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
req.rs
use crate::codec::*; use crate::endpoint::Endpoint; use crate::error::*; use crate::transport::AcceptStopHandle; use crate::util::{Peer, PeerIdentity}; use crate::*; use crate::{SocketType, ZmqResult}; use async_trait::async_trait; use bytes::Bytes; use crossbeam::queue::SegQueue; use dashmap::DashMap; use futures::{SinkExt, StreamExt}; use std::collections::HashMap; use std::sync::Arc; struct ReqSocketBackend { pub(crate) peers: DashMap<PeerIdentity, Peer>, pub(crate) round_robin: SegQueue<PeerIdentity>, socket_monitor: Mutex<Option<mpsc::Sender<SocketEvent>>>, socket_options: SocketOptions, } pub struct ReqSocket { backend: Arc<ReqSocketBackend>, current_request: Option<PeerIdentity>, binds: HashMap<Endpoint, AcceptStopHandle>, } impl Drop for ReqSocket { fn drop(&mut self) { self.backend.shutdown(); } } #[async_trait] impl SocketSend for ReqSocket { async fn send(&mut self, mut message: ZmqMessage) -> ZmqResult<()> { if self.current_request.is_some() { return Err(ZmqError::ReturnToSender { reason: "Unable to send message. Request already in progress", message, }); } // In normal scenario this will always be only 1 iteration // There can be special case when peer has disconnected and his id is still in // RR queue This happens because SegQueue don't have an api to delete // items from queue. So in such case we'll just pop item and skip it if // we don't have a matching peer in peers map loop { let next_peer_id = match self.backend.round_robin.pop() { Ok(peer) => peer, Err(_) => { return Err(ZmqError::ReturnToSender { reason: "Not connected to peers. Unable to send messages", message, }) } }; match self.backend.peers.get_mut(&next_peer_id) { Some(mut peer) => { self.backend.round_robin.push(next_peer_id.clone()); message.push_front(Bytes::new()); peer.send_queue.send(Message::Message(message)).await?; self.current_request = Some(next_peer_id); return Ok(()); } None => continue, } } } } #[async_trait] impl SocketRecv for ReqSocket { async fn recv(&mut self) -> ZmqResult<ZmqMessage> { match self.current_request.take() { Some(peer_id) => { if let Some(mut peer) = self.backend.peers.get_mut(&peer_id) { let message = peer.recv_queue.next().await; match message { Some(Ok(Message::Message(mut m))) => { assert!(m.len() > 1); assert!(m.pop_front().unwrap().is_empty()); // Ensure that we have delimeter as first part Ok(m) } Some(_) => todo!(), None => Err(ZmqError::NoMessage), } } else { Err(ZmqError::Other("Server disconnected")) } } None => Err(ZmqError::Other("Unable to recv. No request in progress")), } } } #[async_trait] impl Socket for ReqSocket { fn with_options(options: SocketOptions) -> Self { Self { backend: Arc::new(ReqSocketBackend { peers: DashMap::new(), round_robin: SegQueue::new(), socket_monitor: Mutex::new(None), socket_options: options, }), current_request: None, binds: HashMap::new(), } } fn backend(&self) -> Arc<dyn MultiPeerBackend> { self.backend.clone() } fn binds(&mut self) -> &mut HashMap<Endpoint, AcceptStopHandle> { &mut self.binds } fn monitor(&mut self) -> mpsc::Receiver<SocketEvent> { let (sender, receiver) = mpsc::channel(1024); self.backend.socket_monitor.lock().replace(sender); receiver } } #[async_trait] impl MultiPeerBackend for ReqSocketBackend { async fn peer_connected(self: Arc<Self>, peer_id: &PeerIdentity, io: FramedIo) { let (recv_queue, send_queue) = io.into_parts(); self.peers.insert( peer_id.clone(), Peer { _identity: peer_id.clone(), send_queue, recv_queue, }, ); self.round_robin.push(peer_id.clone()); } fn peer_disconnected(&self, peer_id: &PeerIdentity) { self.peers.remove(peer_id); } } impl SocketBackend for ReqSocketBackend { fn socket_type(&self) -> SocketType
fn socket_options(&self) -> &SocketOptions { &self.socket_options } fn shutdown(&self) { self.peers.clear(); } fn monitor(&self) -> &Mutex<Option<mpsc::Sender<SocketEvent>>> { &self.socket_monitor } }
{ SocketType::REQ }
identifier_body
req.rs
use crate::codec::*; use crate::endpoint::Endpoint; use crate::error::*; use crate::transport::AcceptStopHandle; use crate::util::{Peer, PeerIdentity}; use crate::*; use crate::{SocketType, ZmqResult}; use async_trait::async_trait; use bytes::Bytes; use crossbeam::queue::SegQueue; use dashmap::DashMap; use futures::{SinkExt, StreamExt}; use std::collections::HashMap; use std::sync::Arc; struct ReqSocketBackend { pub(crate) peers: DashMap<PeerIdentity, Peer>, pub(crate) round_robin: SegQueue<PeerIdentity>, socket_monitor: Mutex<Option<mpsc::Sender<SocketEvent>>>, socket_options: SocketOptions, } pub struct
{ backend: Arc<ReqSocketBackend>, current_request: Option<PeerIdentity>, binds: HashMap<Endpoint, AcceptStopHandle>, } impl Drop for ReqSocket { fn drop(&mut self) { self.backend.shutdown(); } } #[async_trait] impl SocketSend for ReqSocket { async fn send(&mut self, mut message: ZmqMessage) -> ZmqResult<()> { if self.current_request.is_some() { return Err(ZmqError::ReturnToSender { reason: "Unable to send message. Request already in progress", message, }); } // In normal scenario this will always be only 1 iteration // There can be special case when peer has disconnected and his id is still in // RR queue This happens because SegQueue don't have an api to delete // items from queue. So in such case we'll just pop item and skip it if // we don't have a matching peer in peers map loop { let next_peer_id = match self.backend.round_robin.pop() { Ok(peer) => peer, Err(_) => { return Err(ZmqError::ReturnToSender { reason: "Not connected to peers. Unable to send messages", message, }) } }; match self.backend.peers.get_mut(&next_peer_id) { Some(mut peer) => { self.backend.round_robin.push(next_peer_id.clone()); message.push_front(Bytes::new()); peer.send_queue.send(Message::Message(message)).await?; self.current_request = Some(next_peer_id); return Ok(()); } None => continue, } } } } #[async_trait] impl SocketRecv for ReqSocket { async fn recv(&mut self) -> ZmqResult<ZmqMessage> { match self.current_request.take() { Some(peer_id) => { if let Some(mut peer) = self.backend.peers.get_mut(&peer_id) { let message = peer.recv_queue.next().await; match message { Some(Ok(Message::Message(mut m))) => { assert!(m.len() > 1); assert!(m.pop_front().unwrap().is_empty()); // Ensure that we have delimeter as first part Ok(m) } Some(_) => todo!(), None => Err(ZmqError::NoMessage), } } else { Err(ZmqError::Other("Server disconnected")) } } None => Err(ZmqError::Other("Unable to recv. No request in progress")), } } } #[async_trait] impl Socket for ReqSocket { fn with_options(options: SocketOptions) -> Self { Self { backend: Arc::new(ReqSocketBackend { peers: DashMap::new(), round_robin: SegQueue::new(), socket_monitor: Mutex::new(None), socket_options: options, }), current_request: None, binds: HashMap::new(), } } fn backend(&self) -> Arc<dyn MultiPeerBackend> { self.backend.clone() } fn binds(&mut self) -> &mut HashMap<Endpoint, AcceptStopHandle> { &mut self.binds } fn monitor(&mut self) -> mpsc::Receiver<SocketEvent> { let (sender, receiver) = mpsc::channel(1024); self.backend.socket_monitor.lock().replace(sender); receiver } } #[async_trait] impl MultiPeerBackend for ReqSocketBackend { async fn peer_connected(self: Arc<Self>, peer_id: &PeerIdentity, io: FramedIo) { let (recv_queue, send_queue) = io.into_parts(); self.peers.insert( peer_id.clone(), Peer { _identity: peer_id.clone(), send_queue, recv_queue, }, ); self.round_robin.push(peer_id.clone()); } fn peer_disconnected(&self, peer_id: &PeerIdentity) { self.peers.remove(peer_id); } } impl SocketBackend for ReqSocketBackend { fn socket_type(&self) -> SocketType { SocketType::REQ } fn socket_options(&self) -> &SocketOptions { &self.socket_options } fn shutdown(&self) { self.peers.clear(); } fn monitor(&self) -> &Mutex<Option<mpsc::Sender<SocketEvent>>> { &self.socket_monitor } }
ReqSocket
identifier_name
element_data.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::flow::inline::InlineLevelBox; use crate::flow::BlockLevelBox; use atomic_refcell::AtomicRefCell; use servo_arc::Arc; #[derive(Default)] pub(crate) struct LayoutDataForElement { pub(super) self_box: Arc<AtomicRefCell<Option<LayoutBox>>>, pub(super) pseudo_elements: Option<Box<PseudoElementBoxes>>, } #[derive(Default)] pub(super) struct PseudoElementBoxes { pub before: Arc<AtomicRefCell<Option<LayoutBox>>>, pub after: Arc<AtomicRefCell<Option<LayoutBox>>>, } pub(super) enum LayoutBox { DisplayContents,
BlockLevel(Arc<BlockLevelBox>), InlineLevel(Arc<InlineLevelBox>), }
random_line_split
element_data.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::flow::inline::InlineLevelBox; use crate::flow::BlockLevelBox; use atomic_refcell::AtomicRefCell; use servo_arc::Arc; #[derive(Default)] pub(crate) struct
{ pub(super) self_box: Arc<AtomicRefCell<Option<LayoutBox>>>, pub(super) pseudo_elements: Option<Box<PseudoElementBoxes>>, } #[derive(Default)] pub(super) struct PseudoElementBoxes { pub before: Arc<AtomicRefCell<Option<LayoutBox>>>, pub after: Arc<AtomicRefCell<Option<LayoutBox>>>, } pub(super) enum LayoutBox { DisplayContents, BlockLevel(Arc<BlockLevelBox>), InlineLevel(Arc<InlineLevelBox>), }
LayoutDataForElement
identifier_name
lookahead.rs
use bit_set::{self, BitSet}; use collections::Collection; use lr1::core::*; use lr1::tls::Lr1Tls; use std::fmt::{Debug, Error, Formatter}; use std::hash::Hash; use grammar::repr::*; pub trait Lookahead: Clone + Debug + Eq + Ord + Hash + Collection<Item = Self> { fn fmt_as_item_suffix(&self, fmt: &mut Formatter) -> Result<(), Error>; fn conflicts<'grammar>(this_state: &State<'grammar, Self>) -> Vec<Conflict<'grammar, Self>>; } #[derive(Copy, Clone, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)] pub struct Nil; impl Collection for Nil { type Item = Nil; fn push(&mut self, _: Nil) -> bool { false } } impl Lookahead for Nil { fn fmt_as_item_suffix(&self, _fmt: &mut Formatter) -> Result<(), Error> { Ok(()) } fn conflicts<'grammar>(this_state: &State<'grammar, Self>) -> Vec<Conflict<'grammar, Self>> { let index = this_state.index; let mut conflicts = vec![]; for (terminal, &next_state) in &this_state.shifts { conflicts.extend( this_state .reductions .iter() .map(|&(_, production)| Conflict { state: index, lookahead: Nil, production: production, action: Action::Shift(terminal.clone(), next_state), }), ); } if this_state.reductions.len() > 1 { for &(_, production) in &this_state.reductions[1..] { let other_production = this_state.reductions[0].1; conflicts.push(Conflict { state: index, lookahead: Nil, production: production, action: Action::Reduce(other_production), }); } } conflicts } } /// I have semi-arbitrarily decided to use the term "token" to mean /// either one of the terminals of our language, or else the /// pseudo-symbol EOF that represents "end of input". #[derive(Clone, Hash, PartialEq, Eq, PartialOrd, Ord)] pub enum Token { EOF, Error, Terminal(TerminalString), } impl Lookahead for TokenSet { fn fmt_as_item_suffix(&self, fmt: &mut Formatter) -> Result<(), Error> { write!(fmt, " {:?}", self) } fn conflicts<'grammar>(this_state: &State<'grammar, Self>) -> Vec<Conflict<'grammar, Self>> { let mut conflicts = vec![]; for (terminal, &next_state) in &this_state.shifts { let token = Token::Terminal(terminal.clone()); let inconsistent = this_state.reductions.iter().filter_map( |&(ref reduce_tokens, production)| { if reduce_tokens.contains(&token) { Some(production) } else { None } }, ); let set = TokenSet::from(token.clone()); for production in inconsistent { conflicts.push(Conflict { state: this_state.index, lookahead: set.clone(), production: production, action: Action::Shift(terminal.clone(), next_state), }); } } let len = this_state.reductions.len(); for i in 0..len { for j in i + 1..len { let &(ref i_tokens, i_production) = &this_state.reductions[i]; let &(ref j_tokens, j_production) = &this_state.reductions[j]; if i_tokens.is_disjoint(j_tokens) { continue; } conflicts.push(Conflict { state: this_state.index, lookahead: i_tokens.intersection(j_tokens), production: i_production, action: Action::Reduce(j_production), }); } } conflicts } } impl Token { pub fn unwrap_terminal(&self) -> &TerminalString { match *self { Token::Terminal(ref t) => t, Token::EOF | Token::Error => { panic!("`unwrap_terminal()` invoked but with EOF or Error") } } } } #[derive(Clone, Default, Hash, PartialEq, Eq, PartialOrd, Ord)] pub struct TokenSet { bit_set: BitSet<u32>, } fn with<OP, RET>(op: OP) -> RET where OP: FnOnce(&TerminalSet) -> RET, { Lr1Tls::with(op) } impl TokenSet { pub fn new() -> Self { with(|terminals| TokenSet { bit_set: BitSet::with_capacity(terminals.all.len() + 2), }) } /// A TokenSet containing all possible terminals + EOF. pub fn all() -> Self { let mut s = TokenSet::new(); with(|terminals| { for i in 0..terminals.all.len() { s.bit_set.insert(i); } s.insert_eof(); }); s } pub fn eof() -> Self { let mut set = TokenSet::new(); set.insert_eof(); set } fn eof_bit(&self) -> usize { with(|terminals| terminals.all.len()) } fn bit(&self, lookahead: &Token) -> usize { match *lookahead { Token::EOF => self.eof_bit(), Token::Error => self.eof_bit() + 1, Token::Terminal(ref t) => with(|terminals| terminals.bits[t]), } } pub fn len(&self) -> usize { self.bit_set.len() } pub fn insert(&mut self, lookahead: Token) -> bool { let bit = self.bit(&lookahead); self.bit_set.insert(bit) } pub fn insert_eof(&mut self) -> bool { let bit = self.eof_bit(); self.bit_set.insert(bit) } pub fn union_with(&mut self, set: &TokenSet) -> bool { let len = self.len(); self.bit_set.union_with(&set.bit_set); self.len()!= len } pub fn intersection(&self, set: &TokenSet) -> TokenSet { let mut bit_set = self.bit_set.clone(); bit_set.intersect_with(&set.bit_set); TokenSet { bit_set: bit_set } } pub fn contains(&self, token: &Token) -> bool { self.bit_set.contains(self.bit(token)) } pub fn contains_eof(&self) -> bool { self.bit_set.contains(self.eof_bit()) } /// If this set contains EOF, removes it from the set and returns /// true. Otherwise, returns false. pub fn take_eof(&mut self) -> bool { let eof_bit = self.eof_bit(); let contains_eof = self.bit_set.contains(eof_bit); self.bit_set.remove(eof_bit); contains_eof } pub fn is_disjoint(&self, other: &TokenSet) -> bool { self.bit_set.is_disjoint(&other.bit_set) } pub fn is_intersecting(&self, other: &TokenSet) -> bool { !self.is_disjoint(other) } pub fn iter<'iter>(&'iter self) -> TokenSetIter<'iter> { TokenSetIter { bit_set: self.bit_set.iter(), } } } pub struct TokenSetIter<'iter> { bit_set: bit_set::Iter<'iter, u32>, } impl<'iter> Iterator for TokenSetIter<'iter> { type Item = Token; fn next(&mut self) -> Option<Token> { self.bit_set.next().map(|bit| { with(|terminals| { if bit == terminals.all.len() + 1 { Token::Error } else if bit == terminals.all.len() { Token::EOF } else
}) }) } } impl<'debug> Debug for TokenSet { fn fmt(&self, fmt: &mut Formatter) -> Result<(), Error> { let terminals: Vec<_> = self.iter().collect(); Debug::fmt(&terminals, fmt) } } impl<'iter> IntoIterator for &'iter TokenSet { type IntoIter = TokenSetIter<'iter>; type Item = Token; fn into_iter(self) -> Self::IntoIter { self.iter() } } impl Collection for TokenSet { type Item = TokenSet; fn push(&mut self, item: TokenSet) -> bool { self.union_with(&item) } } impl From<Token> for TokenSet { fn from(token: Token) -> Self { let mut set = TokenSet::new(); set.insert(token); set } }
{ Token::Terminal(terminals.all[bit].clone()) }
conditional_block
lookahead.rs
use bit_set::{self, BitSet}; use collections::Collection; use lr1::core::*; use lr1::tls::Lr1Tls; use std::fmt::{Debug, Error, Formatter}; use std::hash::Hash; use grammar::repr::*; pub trait Lookahead: Clone + Debug + Eq + Ord + Hash + Collection<Item = Self> { fn fmt_as_item_suffix(&self, fmt: &mut Formatter) -> Result<(), Error>; fn conflicts<'grammar>(this_state: &State<'grammar, Self>) -> Vec<Conflict<'grammar, Self>>; } #[derive(Copy, Clone, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)] pub struct Nil; impl Collection for Nil { type Item = Nil; fn push(&mut self, _: Nil) -> bool { false } } impl Lookahead for Nil { fn fmt_as_item_suffix(&self, _fmt: &mut Formatter) -> Result<(), Error> { Ok(()) } fn conflicts<'grammar>(this_state: &State<'grammar, Self>) -> Vec<Conflict<'grammar, Self>> { let index = this_state.index; let mut conflicts = vec![]; for (terminal, &next_state) in &this_state.shifts { conflicts.extend( this_state .reductions .iter() .map(|&(_, production)| Conflict { state: index, lookahead: Nil, production: production, action: Action::Shift(terminal.clone(), next_state), }), ); } if this_state.reductions.len() > 1 { for &(_, production) in &this_state.reductions[1..] { let other_production = this_state.reductions[0].1; conflicts.push(Conflict { state: index, lookahead: Nil, production: production, action: Action::Reduce(other_production), }); } } conflicts } } /// I have semi-arbitrarily decided to use the term "token" to mean /// either one of the terminals of our language, or else the /// pseudo-symbol EOF that represents "end of input". #[derive(Clone, Hash, PartialEq, Eq, PartialOrd, Ord)] pub enum Token { EOF, Error, Terminal(TerminalString), } impl Lookahead for TokenSet { fn fmt_as_item_suffix(&self, fmt: &mut Formatter) -> Result<(), Error> { write!(fmt, " {:?}", self) } fn conflicts<'grammar>(this_state: &State<'grammar, Self>) -> Vec<Conflict<'grammar, Self>> { let mut conflicts = vec![]; for (terminal, &next_state) in &this_state.shifts { let token = Token::Terminal(terminal.clone()); let inconsistent = this_state.reductions.iter().filter_map( |&(ref reduce_tokens, production)| { if reduce_tokens.contains(&token) { Some(production) } else { None } }, ); let set = TokenSet::from(token.clone()); for production in inconsistent { conflicts.push(Conflict { state: this_state.index, lookahead: set.clone(), production: production, action: Action::Shift(terminal.clone(), next_state), }); } } let len = this_state.reductions.len(); for i in 0..len { for j in i + 1..len { let &(ref i_tokens, i_production) = &this_state.reductions[i]; let &(ref j_tokens, j_production) = &this_state.reductions[j]; if i_tokens.is_disjoint(j_tokens) { continue; } conflicts.push(Conflict { state: this_state.index, lookahead: i_tokens.intersection(j_tokens), production: i_production, action: Action::Reduce(j_production), }); } } conflicts } } impl Token { pub fn unwrap_terminal(&self) -> &TerminalString { match *self { Token::Terminal(ref t) => t, Token::EOF | Token::Error => { panic!("`unwrap_terminal()` invoked but with EOF or Error") } } } } #[derive(Clone, Default, Hash, PartialEq, Eq, PartialOrd, Ord)] pub struct TokenSet { bit_set: BitSet<u32>, } fn with<OP, RET>(op: OP) -> RET where OP: FnOnce(&TerminalSet) -> RET, { Lr1Tls::with(op) } impl TokenSet { pub fn new() -> Self { with(|terminals| TokenSet { bit_set: BitSet::with_capacity(terminals.all.len() + 2), }) } /// A TokenSet containing all possible terminals + EOF. pub fn all() -> Self { let mut s = TokenSet::new(); with(|terminals| { for i in 0..terminals.all.len() { s.bit_set.insert(i); } s.insert_eof(); }); s } pub fn eof() -> Self { let mut set = TokenSet::new(); set.insert_eof(); set } fn eof_bit(&self) -> usize { with(|terminals| terminals.all.len()) } fn bit(&self, lookahead: &Token) -> usize { match *lookahead { Token::EOF => self.eof_bit(), Token::Error => self.eof_bit() + 1, Token::Terminal(ref t) => with(|terminals| terminals.bits[t]), } } pub fn len(&self) -> usize { self.bit_set.len() } pub fn insert(&mut self, lookahead: Token) -> bool { let bit = self.bit(&lookahead); self.bit_set.insert(bit) } pub fn insert_eof(&mut self) -> bool { let bit = self.eof_bit(); self.bit_set.insert(bit) } pub fn union_with(&mut self, set: &TokenSet) -> bool { let len = self.len(); self.bit_set.union_with(&set.bit_set); self.len()!= len } pub fn intersection(&self, set: &TokenSet) -> TokenSet { let mut bit_set = self.bit_set.clone(); bit_set.intersect_with(&set.bit_set); TokenSet { bit_set: bit_set } } pub fn contains(&self, token: &Token) -> bool { self.bit_set.contains(self.bit(token)) } pub fn contains_eof(&self) -> bool { self.bit_set.contains(self.eof_bit()) } /// If this set contains EOF, removes it from the set and returns /// true. Otherwise, returns false. pub fn take_eof(&mut self) -> bool { let eof_bit = self.eof_bit(); let contains_eof = self.bit_set.contains(eof_bit); self.bit_set.remove(eof_bit); contains_eof } pub fn is_disjoint(&self, other: &TokenSet) -> bool { self.bit_set.is_disjoint(&other.bit_set) } pub fn
(&self, other: &TokenSet) -> bool { !self.is_disjoint(other) } pub fn iter<'iter>(&'iter self) -> TokenSetIter<'iter> { TokenSetIter { bit_set: self.bit_set.iter(), } } } pub struct TokenSetIter<'iter> { bit_set: bit_set::Iter<'iter, u32>, } impl<'iter> Iterator for TokenSetIter<'iter> { type Item = Token; fn next(&mut self) -> Option<Token> { self.bit_set.next().map(|bit| { with(|terminals| { if bit == terminals.all.len() + 1 { Token::Error } else if bit == terminals.all.len() { Token::EOF } else { Token::Terminal(terminals.all[bit].clone()) } }) }) } } impl<'debug> Debug for TokenSet { fn fmt(&self, fmt: &mut Formatter) -> Result<(), Error> { let terminals: Vec<_> = self.iter().collect(); Debug::fmt(&terminals, fmt) } } impl<'iter> IntoIterator for &'iter TokenSet { type IntoIter = TokenSetIter<'iter>; type Item = Token; fn into_iter(self) -> Self::IntoIter { self.iter() } } impl Collection for TokenSet { type Item = TokenSet; fn push(&mut self, item: TokenSet) -> bool { self.union_with(&item) } } impl From<Token> for TokenSet { fn from(token: Token) -> Self { let mut set = TokenSet::new(); set.insert(token); set } }
is_intersecting
identifier_name
lookahead.rs
use bit_set::{self, BitSet}; use collections::Collection; use lr1::core::*; use lr1::tls::Lr1Tls; use std::fmt::{Debug, Error, Formatter}; use std::hash::Hash; use grammar::repr::*; pub trait Lookahead: Clone + Debug + Eq + Ord + Hash + Collection<Item = Self> { fn fmt_as_item_suffix(&self, fmt: &mut Formatter) -> Result<(), Error>; fn conflicts<'grammar>(this_state: &State<'grammar, Self>) -> Vec<Conflict<'grammar, Self>>; } #[derive(Copy, Clone, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)] pub struct Nil; impl Collection for Nil { type Item = Nil; fn push(&mut self, _: Nil) -> bool { false } } impl Lookahead for Nil { fn fmt_as_item_suffix(&self, _fmt: &mut Formatter) -> Result<(), Error> { Ok(()) } fn conflicts<'grammar>(this_state: &State<'grammar, Self>) -> Vec<Conflict<'grammar, Self>> { let index = this_state.index; let mut conflicts = vec![]; for (terminal, &next_state) in &this_state.shifts { conflicts.extend( this_state .reductions .iter() .map(|&(_, production)| Conflict { state: index, lookahead: Nil, production: production, action: Action::Shift(terminal.clone(), next_state), }), ); } if this_state.reductions.len() > 1 { for &(_, production) in &this_state.reductions[1..] { let other_production = this_state.reductions[0].1; conflicts.push(Conflict { state: index, lookahead: Nil, production: production, action: Action::Reduce(other_production), }); } } conflicts } } /// I have semi-arbitrarily decided to use the term "token" to mean /// either one of the terminals of our language, or else the /// pseudo-symbol EOF that represents "end of input". #[derive(Clone, Hash, PartialEq, Eq, PartialOrd, Ord)] pub enum Token { EOF, Error, Terminal(TerminalString), } impl Lookahead for TokenSet { fn fmt_as_item_suffix(&self, fmt: &mut Formatter) -> Result<(), Error> { write!(fmt, " {:?}", self) } fn conflicts<'grammar>(this_state: &State<'grammar, Self>) -> Vec<Conflict<'grammar, Self>> { let mut conflicts = vec![]; for (terminal, &next_state) in &this_state.shifts { let token = Token::Terminal(terminal.clone()); let inconsistent = this_state.reductions.iter().filter_map( |&(ref reduce_tokens, production)| { if reduce_tokens.contains(&token) { Some(production) } else { None } }, ); let set = TokenSet::from(token.clone()); for production in inconsistent { conflicts.push(Conflict { state: this_state.index, lookahead: set.clone(), production: production, action: Action::Shift(terminal.clone(), next_state), }); } } let len = this_state.reductions.len(); for i in 0..len { for j in i + 1..len { let &(ref i_tokens, i_production) = &this_state.reductions[i]; let &(ref j_tokens, j_production) = &this_state.reductions[j]; if i_tokens.is_disjoint(j_tokens) { continue; } conflicts.push(Conflict { state: this_state.index, lookahead: i_tokens.intersection(j_tokens), production: i_production, action: Action::Reduce(j_production), }); } } conflicts } } impl Token { pub fn unwrap_terminal(&self) -> &TerminalString { match *self { Token::Terminal(ref t) => t, Token::EOF | Token::Error => { panic!("`unwrap_terminal()` invoked but with EOF or Error") } } } } #[derive(Clone, Default, Hash, PartialEq, Eq, PartialOrd, Ord)] pub struct TokenSet { bit_set: BitSet<u32>, } fn with<OP, RET>(op: OP) -> RET where OP: FnOnce(&TerminalSet) -> RET, { Lr1Tls::with(op) } impl TokenSet { pub fn new() -> Self { with(|terminals| TokenSet { bit_set: BitSet::with_capacity(terminals.all.len() + 2), }) } /// A TokenSet containing all possible terminals + EOF. pub fn all() -> Self { let mut s = TokenSet::new(); with(|terminals| { for i in 0..terminals.all.len() { s.bit_set.insert(i); } s.insert_eof(); }); s } pub fn eof() -> Self { let mut set = TokenSet::new(); set.insert_eof(); set } fn eof_bit(&self) -> usize { with(|terminals| terminals.all.len()) } fn bit(&self, lookahead: &Token) -> usize { match *lookahead { Token::EOF => self.eof_bit(), Token::Error => self.eof_bit() + 1, Token::Terminal(ref t) => with(|terminals| terminals.bits[t]), } } pub fn len(&self) -> usize { self.bit_set.len() } pub fn insert(&mut self, lookahead: Token) -> bool { let bit = self.bit(&lookahead); self.bit_set.insert(bit) } pub fn insert_eof(&mut self) -> bool { let bit = self.eof_bit(); self.bit_set.insert(bit) } pub fn union_with(&mut self, set: &TokenSet) -> bool { let len = self.len(); self.bit_set.union_with(&set.bit_set); self.len()!= len } pub fn intersection(&self, set: &TokenSet) -> TokenSet
pub fn contains(&self, token: &Token) -> bool { self.bit_set.contains(self.bit(token)) } pub fn contains_eof(&self) -> bool { self.bit_set.contains(self.eof_bit()) } /// If this set contains EOF, removes it from the set and returns /// true. Otherwise, returns false. pub fn take_eof(&mut self) -> bool { let eof_bit = self.eof_bit(); let contains_eof = self.bit_set.contains(eof_bit); self.bit_set.remove(eof_bit); contains_eof } pub fn is_disjoint(&self, other: &TokenSet) -> bool { self.bit_set.is_disjoint(&other.bit_set) } pub fn is_intersecting(&self, other: &TokenSet) -> bool { !self.is_disjoint(other) } pub fn iter<'iter>(&'iter self) -> TokenSetIter<'iter> { TokenSetIter { bit_set: self.bit_set.iter(), } } } pub struct TokenSetIter<'iter> { bit_set: bit_set::Iter<'iter, u32>, } impl<'iter> Iterator for TokenSetIter<'iter> { type Item = Token; fn next(&mut self) -> Option<Token> { self.bit_set.next().map(|bit| { with(|terminals| { if bit == terminals.all.len() + 1 { Token::Error } else if bit == terminals.all.len() { Token::EOF } else { Token::Terminal(terminals.all[bit].clone()) } }) }) } } impl<'debug> Debug for TokenSet { fn fmt(&self, fmt: &mut Formatter) -> Result<(), Error> { let terminals: Vec<_> = self.iter().collect(); Debug::fmt(&terminals, fmt) } } impl<'iter> IntoIterator for &'iter TokenSet { type IntoIter = TokenSetIter<'iter>; type Item = Token; fn into_iter(self) -> Self::IntoIter { self.iter() } } impl Collection for TokenSet { type Item = TokenSet; fn push(&mut self, item: TokenSet) -> bool { self.union_with(&item) } } impl From<Token> for TokenSet { fn from(token: Token) -> Self { let mut set = TokenSet::new(); set.insert(token); set } }
{ let mut bit_set = self.bit_set.clone(); bit_set.intersect_with(&set.bit_set); TokenSet { bit_set: bit_set } }
identifier_body
lookahead.rs
use bit_set::{self, BitSet}; use collections::Collection; use lr1::core::*; use lr1::tls::Lr1Tls; use std::fmt::{Debug, Error, Formatter}; use std::hash::Hash; use grammar::repr::*; pub trait Lookahead: Clone + Debug + Eq + Ord + Hash + Collection<Item = Self> { fn fmt_as_item_suffix(&self, fmt: &mut Formatter) -> Result<(), Error>; fn conflicts<'grammar>(this_state: &State<'grammar, Self>) -> Vec<Conflict<'grammar, Self>>; } #[derive(Copy, Clone, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)] pub struct Nil; impl Collection for Nil { type Item = Nil; fn push(&mut self, _: Nil) -> bool { false } } impl Lookahead for Nil { fn fmt_as_item_suffix(&self, _fmt: &mut Formatter) -> Result<(), Error> { Ok(()) }
let mut conflicts = vec![]; for (terminal, &next_state) in &this_state.shifts { conflicts.extend( this_state .reductions .iter() .map(|&(_, production)| Conflict { state: index, lookahead: Nil, production: production, action: Action::Shift(terminal.clone(), next_state), }), ); } if this_state.reductions.len() > 1 { for &(_, production) in &this_state.reductions[1..] { let other_production = this_state.reductions[0].1; conflicts.push(Conflict { state: index, lookahead: Nil, production: production, action: Action::Reduce(other_production), }); } } conflicts } } /// I have semi-arbitrarily decided to use the term "token" to mean /// either one of the terminals of our language, or else the /// pseudo-symbol EOF that represents "end of input". #[derive(Clone, Hash, PartialEq, Eq, PartialOrd, Ord)] pub enum Token { EOF, Error, Terminal(TerminalString), } impl Lookahead for TokenSet { fn fmt_as_item_suffix(&self, fmt: &mut Formatter) -> Result<(), Error> { write!(fmt, " {:?}", self) } fn conflicts<'grammar>(this_state: &State<'grammar, Self>) -> Vec<Conflict<'grammar, Self>> { let mut conflicts = vec![]; for (terminal, &next_state) in &this_state.shifts { let token = Token::Terminal(terminal.clone()); let inconsistent = this_state.reductions.iter().filter_map( |&(ref reduce_tokens, production)| { if reduce_tokens.contains(&token) { Some(production) } else { None } }, ); let set = TokenSet::from(token.clone()); for production in inconsistent { conflicts.push(Conflict { state: this_state.index, lookahead: set.clone(), production: production, action: Action::Shift(terminal.clone(), next_state), }); } } let len = this_state.reductions.len(); for i in 0..len { for j in i + 1..len { let &(ref i_tokens, i_production) = &this_state.reductions[i]; let &(ref j_tokens, j_production) = &this_state.reductions[j]; if i_tokens.is_disjoint(j_tokens) { continue; } conflicts.push(Conflict { state: this_state.index, lookahead: i_tokens.intersection(j_tokens), production: i_production, action: Action::Reduce(j_production), }); } } conflicts } } impl Token { pub fn unwrap_terminal(&self) -> &TerminalString { match *self { Token::Terminal(ref t) => t, Token::EOF | Token::Error => { panic!("`unwrap_terminal()` invoked but with EOF or Error") } } } } #[derive(Clone, Default, Hash, PartialEq, Eq, PartialOrd, Ord)] pub struct TokenSet { bit_set: BitSet<u32>, } fn with<OP, RET>(op: OP) -> RET where OP: FnOnce(&TerminalSet) -> RET, { Lr1Tls::with(op) } impl TokenSet { pub fn new() -> Self { with(|terminals| TokenSet { bit_set: BitSet::with_capacity(terminals.all.len() + 2), }) } /// A TokenSet containing all possible terminals + EOF. pub fn all() -> Self { let mut s = TokenSet::new(); with(|terminals| { for i in 0..terminals.all.len() { s.bit_set.insert(i); } s.insert_eof(); }); s } pub fn eof() -> Self { let mut set = TokenSet::new(); set.insert_eof(); set } fn eof_bit(&self) -> usize { with(|terminals| terminals.all.len()) } fn bit(&self, lookahead: &Token) -> usize { match *lookahead { Token::EOF => self.eof_bit(), Token::Error => self.eof_bit() + 1, Token::Terminal(ref t) => with(|terminals| terminals.bits[t]), } } pub fn len(&self) -> usize { self.bit_set.len() } pub fn insert(&mut self, lookahead: Token) -> bool { let bit = self.bit(&lookahead); self.bit_set.insert(bit) } pub fn insert_eof(&mut self) -> bool { let bit = self.eof_bit(); self.bit_set.insert(bit) } pub fn union_with(&mut self, set: &TokenSet) -> bool { let len = self.len(); self.bit_set.union_with(&set.bit_set); self.len()!= len } pub fn intersection(&self, set: &TokenSet) -> TokenSet { let mut bit_set = self.bit_set.clone(); bit_set.intersect_with(&set.bit_set); TokenSet { bit_set: bit_set } } pub fn contains(&self, token: &Token) -> bool { self.bit_set.contains(self.bit(token)) } pub fn contains_eof(&self) -> bool { self.bit_set.contains(self.eof_bit()) } /// If this set contains EOF, removes it from the set and returns /// true. Otherwise, returns false. pub fn take_eof(&mut self) -> bool { let eof_bit = self.eof_bit(); let contains_eof = self.bit_set.contains(eof_bit); self.bit_set.remove(eof_bit); contains_eof } pub fn is_disjoint(&self, other: &TokenSet) -> bool { self.bit_set.is_disjoint(&other.bit_set) } pub fn is_intersecting(&self, other: &TokenSet) -> bool { !self.is_disjoint(other) } pub fn iter<'iter>(&'iter self) -> TokenSetIter<'iter> { TokenSetIter { bit_set: self.bit_set.iter(), } } } pub struct TokenSetIter<'iter> { bit_set: bit_set::Iter<'iter, u32>, } impl<'iter> Iterator for TokenSetIter<'iter> { type Item = Token; fn next(&mut self) -> Option<Token> { self.bit_set.next().map(|bit| { with(|terminals| { if bit == terminals.all.len() + 1 { Token::Error } else if bit == terminals.all.len() { Token::EOF } else { Token::Terminal(terminals.all[bit].clone()) } }) }) } } impl<'debug> Debug for TokenSet { fn fmt(&self, fmt: &mut Formatter) -> Result<(), Error> { let terminals: Vec<_> = self.iter().collect(); Debug::fmt(&terminals, fmt) } } impl<'iter> IntoIterator for &'iter TokenSet { type IntoIter = TokenSetIter<'iter>; type Item = Token; fn into_iter(self) -> Self::IntoIter { self.iter() } } impl Collection for TokenSet { type Item = TokenSet; fn push(&mut self, item: TokenSet) -> bool { self.union_with(&item) } } impl From<Token> for TokenSet { fn from(token: Token) -> Self { let mut set = TokenSet::new(); set.insert(token); set } }
fn conflicts<'grammar>(this_state: &State<'grammar, Self>) -> Vec<Conflict<'grammar, Self>> { let index = this_state.index;
random_line_split
nif.rs
use proc_macro2::{Span, TokenStream}; use quote::{quote, ToTokens}; use syn::punctuated::Punctuated; use syn::token::Comma; pub fn transcoder_decorator(args: syn::AttributeArgs, fun: syn::ItemFn) -> TokenStream { let sig = &fun.sig; let name = &sig.ident; let inputs = &sig.inputs; validate_attributes(args.clone()); let flags = schedule_flag(args.to_owned()); let function = fun.to_owned().into_token_stream(); let arity = arity(inputs.clone()); let decoded_terms = extract_inputs(inputs.clone()); let argument_names = create_function_params(inputs.clone()); let erl_func_name = extract_attr_value(args, "name") .map(|ref n| syn::Ident::new(n, Span::call_site())) .unwrap_or_else(|| name.clone()); quote! { #[allow(non_camel_case_types)] pub struct #name; impl rustler::Nif for #name { const NAME: *const u8 = concat!(stringify!(#erl_func_name), "\0").as_ptr() as *const u8; const ARITY: u32 = #arity; const FLAGS: u32 = #flags as u32; const RAW_FUNC: unsafe extern "C" fn( nif_env: rustler::codegen_runtime::NIF_ENV, argc: rustler::codegen_runtime::c_int, argv: *const rustler::codegen_runtime::NIF_TERM ) -> rustler::codegen_runtime::NIF_TERM = { unsafe extern "C" fn nif_func( nif_env: rustler::codegen_runtime::NIF_ENV, argc: rustler::codegen_runtime::c_int, argv: *const rustler::codegen_runtime::NIF_TERM ) -> rustler::codegen_runtime::NIF_TERM { let lifetime = (); let env = rustler::Env::new(&lifetime, nif_env); let terms = std::slice::from_raw_parts(argv, argc as usize) .iter() .map(|term| rustler::Term::new(env, *term)) .collect::<Vec<rustler::Term>>(); fn wrapper<'a>( env: rustler::Env<'a>, args: &[rustler::Term<'a>] ) -> rustler::codegen_runtime::NifReturned { let result: std::thread::Result<_> = std::panic::catch_unwind(move || { #decoded_terms #function Ok(#name(#argument_names)) }); rustler::codegen_runtime::handle_nif_result(result, env) } wrapper(env, &terms).apply(env) } nif_func }; const FUNC: rustler::codegen_runtime::DEF_NIF_FUNC = rustler::codegen_runtime::DEF_NIF_FUNC { arity: Self::ARITY, flags: Self::FLAGS, function: Self::RAW_FUNC, name: Self::NAME }; } } } fn schedule_flag(args: syn::AttributeArgs) -> TokenStream { let mut tokens = TokenStream::new(); let valid = ["DirtyCpu", "DirtyIo", "Normal"]; let flag = match extract_attr_value(args, "schedule") { Some(value) => { if valid.contains(&value.as_str()) { syn::Ident::new(value.as_str(), Span::call_site()) } else { panic!("Invalid schedule option `{}`", value); } } None => syn::Ident::new("Normal", Span::call_site()), }; tokens.extend(quote! { rustler::SchedulerFlags::#flag }); tokens } fn extract_attr_value(args: syn::AttributeArgs, name: &str) -> Option<String> { use syn::{Lit, Meta, MetaNameValue, NestedMeta}; for arg in args.iter() { if let NestedMeta::Meta(Meta::NameValue(MetaNameValue { path, lit,.. })) = arg { if path.is_ident(name) { if let Lit::Str(lit) = lit { return Some(lit.value()); } } } } None } fn extract_inputs(inputs: Punctuated<syn::FnArg, Comma>) -> TokenStream { let mut tokens = TokenStream::new(); let mut idx: usize = 0; for item in inputs.iter() { if let syn::FnArg::Typed(ref typed) = item { let name = &typed.pat; match &*typed.ty { syn::Type::Reference(typ) => { let decoder = quote! { let #name: #typ = match args[#idx].decode() { Ok(value) => value, Err(err) => return Err(err) }; }; tokens.extend(decoder); } syn::Type::Path(syn::TypePath { path,.. }) => { let typ = &typed.ty; let ident = path.segments.last().unwrap().ident.to_string(); match ident.as_ref() { "Env" => { continue; } "Term" => { let arg = quote! { let #name: #typ = args[#idx]; }; tokens.extend(arg); } _ => { let decoder = quote! { let #name: #typ = match args[#idx].decode() { Ok(value) => value, Err(err) => return Err(err) }; }; tokens.extend(decoder); } } } other => { panic!("unsupported input given: {:?}", other); } } } else { panic!("unsupported input given: {:?}", stringify!(&item)); }; idx += 1; } tokens } fn create_function_params(inputs: Punctuated<syn::FnArg, Comma>) -> TokenStream { let mut tokens = TokenStream::new(); for item in inputs.iter() { let name = if let syn::FnArg::Typed(ref typed) = item { &typed.pat } else { panic!("unsupported input given: {:?}", stringify!(&item)); }; tokens.extend(quote!(#name,)); } tokens } fn arity(inputs: Punctuated<syn::FnArg, Comma>) -> u32 { let mut arity: u32 = 0;
if i == 0 && ident == "Env" { continue; } if ident == "Env" { panic!("Env must be the first argument in NIF functions"); } }; } else { panic!("unsupported input given: {:?}", stringify!(&item)); }; arity += 1; } arity } fn validate_attributes(args: syn::AttributeArgs) { use syn::{Meta, MetaNameValue, NestedMeta}; let known_attrs = ["schedule", "name"]; for arg in args.iter() { if let NestedMeta::Meta(Meta::NameValue(MetaNameValue { path,.. })) = arg { if known_attrs.iter().all(|known|!path.is_ident(known)) { match path.get_ident() { Some(path) => panic!( "Unknown attribute '{}'. Allowed attributes: {:?}", path, known_attrs ), None => panic!( "Cannot parse attribute. Allowed attributes: {:?}", known_attrs ), } } } } }
for (i, item) in inputs.iter().enumerate() { if let syn::FnArg::Typed(ref typed) = item { if let syn::Type::Path(syn::TypePath { path, .. }) = &*typed.ty { let ident = path.segments.last().unwrap().ident.to_string();
random_line_split
nif.rs
use proc_macro2::{Span, TokenStream}; use quote::{quote, ToTokens}; use syn::punctuated::Punctuated; use syn::token::Comma; pub fn transcoder_decorator(args: syn::AttributeArgs, fun: syn::ItemFn) -> TokenStream { let sig = &fun.sig; let name = &sig.ident; let inputs = &sig.inputs; validate_attributes(args.clone()); let flags = schedule_flag(args.to_owned()); let function = fun.to_owned().into_token_stream(); let arity = arity(inputs.clone()); let decoded_terms = extract_inputs(inputs.clone()); let argument_names = create_function_params(inputs.clone()); let erl_func_name = extract_attr_value(args, "name") .map(|ref n| syn::Ident::new(n, Span::call_site())) .unwrap_or_else(|| name.clone()); quote! { #[allow(non_camel_case_types)] pub struct #name; impl rustler::Nif for #name { const NAME: *const u8 = concat!(stringify!(#erl_func_name), "\0").as_ptr() as *const u8; const ARITY: u32 = #arity; const FLAGS: u32 = #flags as u32; const RAW_FUNC: unsafe extern "C" fn( nif_env: rustler::codegen_runtime::NIF_ENV, argc: rustler::codegen_runtime::c_int, argv: *const rustler::codegen_runtime::NIF_TERM ) -> rustler::codegen_runtime::NIF_TERM = { unsafe extern "C" fn nif_func( nif_env: rustler::codegen_runtime::NIF_ENV, argc: rustler::codegen_runtime::c_int, argv: *const rustler::codegen_runtime::NIF_TERM ) -> rustler::codegen_runtime::NIF_TERM { let lifetime = (); let env = rustler::Env::new(&lifetime, nif_env); let terms = std::slice::from_raw_parts(argv, argc as usize) .iter() .map(|term| rustler::Term::new(env, *term)) .collect::<Vec<rustler::Term>>(); fn wrapper<'a>( env: rustler::Env<'a>, args: &[rustler::Term<'a>] ) -> rustler::codegen_runtime::NifReturned { let result: std::thread::Result<_> = std::panic::catch_unwind(move || { #decoded_terms #function Ok(#name(#argument_names)) }); rustler::codegen_runtime::handle_nif_result(result, env) } wrapper(env, &terms).apply(env) } nif_func }; const FUNC: rustler::codegen_runtime::DEF_NIF_FUNC = rustler::codegen_runtime::DEF_NIF_FUNC { arity: Self::ARITY, flags: Self::FLAGS, function: Self::RAW_FUNC, name: Self::NAME }; } } } fn schedule_flag(args: syn::AttributeArgs) -> TokenStream { let mut tokens = TokenStream::new(); let valid = ["DirtyCpu", "DirtyIo", "Normal"]; let flag = match extract_attr_value(args, "schedule") { Some(value) => { if valid.contains(&value.as_str()) { syn::Ident::new(value.as_str(), Span::call_site()) } else { panic!("Invalid schedule option `{}`", value); } } None => syn::Ident::new("Normal", Span::call_site()), }; tokens.extend(quote! { rustler::SchedulerFlags::#flag }); tokens } fn extract_attr_value(args: syn::AttributeArgs, name: &str) -> Option<String>
fn extract_inputs(inputs: Punctuated<syn::FnArg, Comma>) -> TokenStream { let mut tokens = TokenStream::new(); let mut idx: usize = 0; for item in inputs.iter() { if let syn::FnArg::Typed(ref typed) = item { let name = &typed.pat; match &*typed.ty { syn::Type::Reference(typ) => { let decoder = quote! { let #name: #typ = match args[#idx].decode() { Ok(value) => value, Err(err) => return Err(err) }; }; tokens.extend(decoder); } syn::Type::Path(syn::TypePath { path,.. }) => { let typ = &typed.ty; let ident = path.segments.last().unwrap().ident.to_string(); match ident.as_ref() { "Env" => { continue; } "Term" => { let arg = quote! { let #name: #typ = args[#idx]; }; tokens.extend(arg); } _ => { let decoder = quote! { let #name: #typ = match args[#idx].decode() { Ok(value) => value, Err(err) => return Err(err) }; }; tokens.extend(decoder); } } } other => { panic!("unsupported input given: {:?}", other); } } } else { panic!("unsupported input given: {:?}", stringify!(&item)); }; idx += 1; } tokens } fn create_function_params(inputs: Punctuated<syn::FnArg, Comma>) -> TokenStream { let mut tokens = TokenStream::new(); for item in inputs.iter() { let name = if let syn::FnArg::Typed(ref typed) = item { &typed.pat } else { panic!("unsupported input given: {:?}", stringify!(&item)); }; tokens.extend(quote!(#name,)); } tokens } fn arity(inputs: Punctuated<syn::FnArg, Comma>) -> u32 { let mut arity: u32 = 0; for (i, item) in inputs.iter().enumerate() { if let syn::FnArg::Typed(ref typed) = item { if let syn::Type::Path(syn::TypePath { path,.. }) = &*typed.ty { let ident = path.segments.last().unwrap().ident.to_string(); if i == 0 && ident == "Env" { continue; } if ident == "Env" { panic!("Env must be the first argument in NIF functions"); } }; } else { panic!("unsupported input given: {:?}", stringify!(&item)); }; arity += 1; } arity } fn validate_attributes(args: syn::AttributeArgs) { use syn::{Meta, MetaNameValue, NestedMeta}; let known_attrs = ["schedule", "name"]; for arg in args.iter() { if let NestedMeta::Meta(Meta::NameValue(MetaNameValue { path,.. })) = arg { if known_attrs.iter().all(|known|!path.is_ident(known)) { match path.get_ident() { Some(path) => panic!( "Unknown attribute '{}'. Allowed attributes: {:?}", path, known_attrs ), None => panic!( "Cannot parse attribute. Allowed attributes: {:?}", known_attrs ), } } } } }
{ use syn::{Lit, Meta, MetaNameValue, NestedMeta}; for arg in args.iter() { if let NestedMeta::Meta(Meta::NameValue(MetaNameValue { path, lit, .. })) = arg { if path.is_ident(name) { if let Lit::Str(lit) = lit { return Some(lit.value()); } } } } None }
identifier_body
nif.rs
use proc_macro2::{Span, TokenStream}; use quote::{quote, ToTokens}; use syn::punctuated::Punctuated; use syn::token::Comma; pub fn transcoder_decorator(args: syn::AttributeArgs, fun: syn::ItemFn) -> TokenStream { let sig = &fun.sig; let name = &sig.ident; let inputs = &sig.inputs; validate_attributes(args.clone()); let flags = schedule_flag(args.to_owned()); let function = fun.to_owned().into_token_stream(); let arity = arity(inputs.clone()); let decoded_terms = extract_inputs(inputs.clone()); let argument_names = create_function_params(inputs.clone()); let erl_func_name = extract_attr_value(args, "name") .map(|ref n| syn::Ident::new(n, Span::call_site())) .unwrap_or_else(|| name.clone()); quote! { #[allow(non_camel_case_types)] pub struct #name; impl rustler::Nif for #name { const NAME: *const u8 = concat!(stringify!(#erl_func_name), "\0").as_ptr() as *const u8; const ARITY: u32 = #arity; const FLAGS: u32 = #flags as u32; const RAW_FUNC: unsafe extern "C" fn( nif_env: rustler::codegen_runtime::NIF_ENV, argc: rustler::codegen_runtime::c_int, argv: *const rustler::codegen_runtime::NIF_TERM ) -> rustler::codegen_runtime::NIF_TERM = { unsafe extern "C" fn nif_func( nif_env: rustler::codegen_runtime::NIF_ENV, argc: rustler::codegen_runtime::c_int, argv: *const rustler::codegen_runtime::NIF_TERM ) -> rustler::codegen_runtime::NIF_TERM { let lifetime = (); let env = rustler::Env::new(&lifetime, nif_env); let terms = std::slice::from_raw_parts(argv, argc as usize) .iter() .map(|term| rustler::Term::new(env, *term)) .collect::<Vec<rustler::Term>>(); fn wrapper<'a>( env: rustler::Env<'a>, args: &[rustler::Term<'a>] ) -> rustler::codegen_runtime::NifReturned { let result: std::thread::Result<_> = std::panic::catch_unwind(move || { #decoded_terms #function Ok(#name(#argument_names)) }); rustler::codegen_runtime::handle_nif_result(result, env) } wrapper(env, &terms).apply(env) } nif_func }; const FUNC: rustler::codegen_runtime::DEF_NIF_FUNC = rustler::codegen_runtime::DEF_NIF_FUNC { arity: Self::ARITY, flags: Self::FLAGS, function: Self::RAW_FUNC, name: Self::NAME }; } } } fn schedule_flag(args: syn::AttributeArgs) -> TokenStream { let mut tokens = TokenStream::new(); let valid = ["DirtyCpu", "DirtyIo", "Normal"]; let flag = match extract_attr_value(args, "schedule") { Some(value) => { if valid.contains(&value.as_str()) { syn::Ident::new(value.as_str(), Span::call_site()) } else { panic!("Invalid schedule option `{}`", value); } } None => syn::Ident::new("Normal", Span::call_site()), }; tokens.extend(quote! { rustler::SchedulerFlags::#flag }); tokens } fn extract_attr_value(args: syn::AttributeArgs, name: &str) -> Option<String> { use syn::{Lit, Meta, MetaNameValue, NestedMeta}; for arg in args.iter() { if let NestedMeta::Meta(Meta::NameValue(MetaNameValue { path, lit,.. })) = arg { if path.is_ident(name) { if let Lit::Str(lit) = lit { return Some(lit.value()); } } } } None } fn extract_inputs(inputs: Punctuated<syn::FnArg, Comma>) -> TokenStream { let mut tokens = TokenStream::new(); let mut idx: usize = 0; for item in inputs.iter() { if let syn::FnArg::Typed(ref typed) = item { let name = &typed.pat; match &*typed.ty { syn::Type::Reference(typ) => { let decoder = quote! { let #name: #typ = match args[#idx].decode() { Ok(value) => value, Err(err) => return Err(err) }; }; tokens.extend(decoder); } syn::Type::Path(syn::TypePath { path,.. }) => { let typ = &typed.ty; let ident = path.segments.last().unwrap().ident.to_string(); match ident.as_ref() { "Env" => { continue; } "Term" => { let arg = quote! { let #name: #typ = args[#idx]; }; tokens.extend(arg); } _ => { let decoder = quote! { let #name: #typ = match args[#idx].decode() { Ok(value) => value, Err(err) => return Err(err) }; }; tokens.extend(decoder); } } } other => { panic!("unsupported input given: {:?}", other); } } } else { panic!("unsupported input given: {:?}", stringify!(&item)); }; idx += 1; } tokens } fn
(inputs: Punctuated<syn::FnArg, Comma>) -> TokenStream { let mut tokens = TokenStream::new(); for item in inputs.iter() { let name = if let syn::FnArg::Typed(ref typed) = item { &typed.pat } else { panic!("unsupported input given: {:?}", stringify!(&item)); }; tokens.extend(quote!(#name,)); } tokens } fn arity(inputs: Punctuated<syn::FnArg, Comma>) -> u32 { let mut arity: u32 = 0; for (i, item) in inputs.iter().enumerate() { if let syn::FnArg::Typed(ref typed) = item { if let syn::Type::Path(syn::TypePath { path,.. }) = &*typed.ty { let ident = path.segments.last().unwrap().ident.to_string(); if i == 0 && ident == "Env" { continue; } if ident == "Env" { panic!("Env must be the first argument in NIF functions"); } }; } else { panic!("unsupported input given: {:?}", stringify!(&item)); }; arity += 1; } arity } fn validate_attributes(args: syn::AttributeArgs) { use syn::{Meta, MetaNameValue, NestedMeta}; let known_attrs = ["schedule", "name"]; for arg in args.iter() { if let NestedMeta::Meta(Meta::NameValue(MetaNameValue { path,.. })) = arg { if known_attrs.iter().all(|known|!path.is_ident(known)) { match path.get_ident() { Some(path) => panic!( "Unknown attribute '{}'. Allowed attributes: {:?}", path, known_attrs ), None => panic!( "Cannot parse attribute. Allowed attributes: {:?}", known_attrs ), } } } } }
create_function_params
identifier_name
addrinfo.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use libc::c_int; use libc; use std::mem; use std::ptr::{null, null_mut}; use std::rt::task::BlockedTask; use std::rt::rtio; use net; use super::{Loop, UvError, Request, wait_until_woken_after, wakeup}; use uvll; pub struct Addrinfo { handle: *const libc::addrinfo, } struct Ctx { slot: Option<BlockedTask>, status: c_int, addrinfo: Option<Addrinfo>, } pub struct GetAddrInfoRequest; impl GetAddrInfoRequest { pub fn run(loop_: &Loop, node: Option<&str>, service: Option<&str>, hints: Option<rtio::AddrinfoHint>) -> Result<Vec<rtio::AddrinfoInfo>, UvError> { assert!(node.is_some() || service.is_some()); let (_c_node, c_node_ptr) = match node { Some(n) => { let c_node = n.to_c_str(); let c_node_ptr = c_node.as_ptr(); (Some(c_node), c_node_ptr) } None => (None, null()) }; let (_c_service, c_service_ptr) = match service { Some(s) => { let c_service = s.to_c_str(); let c_service_ptr = c_service.as_ptr(); (Some(c_service), c_service_ptr) } None => (None, null()) }; let hint = hints.map(|hint| { libc::addrinfo { ai_flags: 0, ai_family: hint.family as c_int, ai_socktype: 0, ai_protocol: 0, ai_addrlen: 0, ai_canonname: null_mut(), ai_addr: null_mut(), ai_next: null_mut(), } }); let hint_ptr = hint.as_ref().map_or(null(), |x| { x as *const libc::addrinfo }); let mut req = Request::new(uvll::UV_GETADDRINFO); return match unsafe { uvll::uv_getaddrinfo(loop_.handle, req.handle, getaddrinfo_cb, c_node_ptr, c_service_ptr, hint_ptr) } { 0 => { req.defuse(); // uv callback now owns this request let mut cx = Ctx { slot: None, status: 0, addrinfo: None }; wait_until_woken_after(&mut cx.slot, loop_, || { req.set_data(&mut cx); }); match cx.status { 0 => Ok(accum_addrinfo(cx.addrinfo.as_ref().unwrap())), n => Err(UvError(n)) } } n => Err(UvError(n)) }; extern fn getaddrinfo_cb(req: *mut uvll::uv_getaddrinfo_t, status: c_int, res: *const libc::addrinfo) { let req = Request::wrap(req); assert!(status!= uvll::ECANCELED); let cx: &mut Ctx = unsafe { req.get_data() }; cx.status = status; cx.addrinfo = Some(Addrinfo { handle: res }); wakeup(&mut cx.slot); } } }
fn drop(&mut self) { unsafe { uvll::uv_freeaddrinfo(self.handle as *mut _) } } } // Traverse the addrinfo linked list, producing a vector of Rust socket addresses pub fn accum_addrinfo(addr: &Addrinfo) -> Vec<rtio::AddrinfoInfo> { unsafe { let mut addr = addr.handle; let mut addrs = Vec::new(); loop { let rustaddr = net::sockaddr_to_addr(mem::transmute((*addr).ai_addr), (*addr).ai_addrlen as uint); addrs.push(rtio::AddrinfoInfo { address: rustaddr, family: (*addr).ai_family as uint, socktype: 0, protocol: 0, flags: 0, }); if (*addr).ai_next.is_not_null() { addr = (*addr).ai_next as *const _; } else { break; } } addrs } }
impl Drop for Addrinfo {
random_line_split
addrinfo.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use libc::c_int; use libc; use std::mem; use std::ptr::{null, null_mut}; use std::rt::task::BlockedTask; use std::rt::rtio; use net; use super::{Loop, UvError, Request, wait_until_woken_after, wakeup}; use uvll; pub struct Addrinfo { handle: *const libc::addrinfo, } struct Ctx { slot: Option<BlockedTask>, status: c_int, addrinfo: Option<Addrinfo>, } pub struct GetAddrInfoRequest; impl GetAddrInfoRequest { pub fn run(loop_: &Loop, node: Option<&str>, service: Option<&str>, hints: Option<rtio::AddrinfoHint>) -> Result<Vec<rtio::AddrinfoInfo>, UvError>
let hint = hints.map(|hint| { libc::addrinfo { ai_flags: 0, ai_family: hint.family as c_int, ai_socktype: 0, ai_protocol: 0, ai_addrlen: 0, ai_canonname: null_mut(), ai_addr: null_mut(), ai_next: null_mut(), } }); let hint_ptr = hint.as_ref().map_or(null(), |x| { x as *const libc::addrinfo }); let mut req = Request::new(uvll::UV_GETADDRINFO); return match unsafe { uvll::uv_getaddrinfo(loop_.handle, req.handle, getaddrinfo_cb, c_node_ptr, c_service_ptr, hint_ptr) } { 0 => { req.defuse(); // uv callback now owns this request let mut cx = Ctx { slot: None, status: 0, addrinfo: None }; wait_until_woken_after(&mut cx.slot, loop_, || { req.set_data(&mut cx); }); match cx.status { 0 => Ok(accum_addrinfo(cx.addrinfo.as_ref().unwrap())), n => Err(UvError(n)) } } n => Err(UvError(n)) }; extern fn getaddrinfo_cb(req: *mut uvll::uv_getaddrinfo_t, status: c_int, res: *const libc::addrinfo) { let req = Request::wrap(req); assert!(status!= uvll::ECANCELED); let cx: &mut Ctx = unsafe { req.get_data() }; cx.status = status; cx.addrinfo = Some(Addrinfo { handle: res }); wakeup(&mut cx.slot); } } } impl Drop for Addrinfo { fn drop(&mut self) { unsafe { uvll::uv_freeaddrinfo(self.handle as *mut _) } } } // Traverse the addrinfo linked list, producing a vector of Rust socket addresses pub fn accum_addrinfo(addr: &Addrinfo) -> Vec<rtio::AddrinfoInfo> { unsafe { let mut addr = addr.handle; let mut addrs = Vec::new(); loop { let rustaddr = net::sockaddr_to_addr(mem::transmute((*addr).ai_addr), (*addr).ai_addrlen as uint); addrs.push(rtio::AddrinfoInfo { address: rustaddr, family: (*addr).ai_family as uint, socktype: 0, protocol: 0, flags: 0, }); if (*addr).ai_next.is_not_null() { addr = (*addr).ai_next as *const _; } else { break; } } addrs } }
{ assert!(node.is_some() || service.is_some()); let (_c_node, c_node_ptr) = match node { Some(n) => { let c_node = n.to_c_str(); let c_node_ptr = c_node.as_ptr(); (Some(c_node), c_node_ptr) } None => (None, null()) }; let (_c_service, c_service_ptr) = match service { Some(s) => { let c_service = s.to_c_str(); let c_service_ptr = c_service.as_ptr(); (Some(c_service), c_service_ptr) } None => (None, null()) };
identifier_body
addrinfo.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use libc::c_int; use libc; use std::mem; use std::ptr::{null, null_mut}; use std::rt::task::BlockedTask; use std::rt::rtio; use net; use super::{Loop, UvError, Request, wait_until_woken_after, wakeup}; use uvll; pub struct Addrinfo { handle: *const libc::addrinfo, } struct Ctx { slot: Option<BlockedTask>, status: c_int, addrinfo: Option<Addrinfo>, } pub struct GetAddrInfoRequest; impl GetAddrInfoRequest { pub fn run(loop_: &Loop, node: Option<&str>, service: Option<&str>, hints: Option<rtio::AddrinfoHint>) -> Result<Vec<rtio::AddrinfoInfo>, UvError> { assert!(node.is_some() || service.is_some()); let (_c_node, c_node_ptr) = match node { Some(n) => { let c_node = n.to_c_str(); let c_node_ptr = c_node.as_ptr(); (Some(c_node), c_node_ptr) } None => (None, null()) }; let (_c_service, c_service_ptr) = match service { Some(s) => { let c_service = s.to_c_str(); let c_service_ptr = c_service.as_ptr(); (Some(c_service), c_service_ptr) } None => (None, null()) }; let hint = hints.map(|hint| { libc::addrinfo { ai_flags: 0, ai_family: hint.family as c_int, ai_socktype: 0, ai_protocol: 0, ai_addrlen: 0, ai_canonname: null_mut(), ai_addr: null_mut(), ai_next: null_mut(), } }); let hint_ptr = hint.as_ref().map_or(null(), |x| { x as *const libc::addrinfo }); let mut req = Request::new(uvll::UV_GETADDRINFO); return match unsafe { uvll::uv_getaddrinfo(loop_.handle, req.handle, getaddrinfo_cb, c_node_ptr, c_service_ptr, hint_ptr) } { 0 => { req.defuse(); // uv callback now owns this request let mut cx = Ctx { slot: None, status: 0, addrinfo: None }; wait_until_woken_after(&mut cx.slot, loop_, || { req.set_data(&mut cx); }); match cx.status { 0 => Ok(accum_addrinfo(cx.addrinfo.as_ref().unwrap())), n => Err(UvError(n)) } } n => Err(UvError(n)) }; extern fn
(req: *mut uvll::uv_getaddrinfo_t, status: c_int, res: *const libc::addrinfo) { let req = Request::wrap(req); assert!(status!= uvll::ECANCELED); let cx: &mut Ctx = unsafe { req.get_data() }; cx.status = status; cx.addrinfo = Some(Addrinfo { handle: res }); wakeup(&mut cx.slot); } } } impl Drop for Addrinfo { fn drop(&mut self) { unsafe { uvll::uv_freeaddrinfo(self.handle as *mut _) } } } // Traverse the addrinfo linked list, producing a vector of Rust socket addresses pub fn accum_addrinfo(addr: &Addrinfo) -> Vec<rtio::AddrinfoInfo> { unsafe { let mut addr = addr.handle; let mut addrs = Vec::new(); loop { let rustaddr = net::sockaddr_to_addr(mem::transmute((*addr).ai_addr), (*addr).ai_addrlen as uint); addrs.push(rtio::AddrinfoInfo { address: rustaddr, family: (*addr).ai_family as uint, socktype: 0, protocol: 0, flags: 0, }); if (*addr).ai_next.is_not_null() { addr = (*addr).ai_next as *const _; } else { break; } } addrs } }
getaddrinfo_cb
identifier_name
basic_shape.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/. */ //! CSS handling for the [`basic-shape`](https://drafts.csswg.org/css-shapes/#typedef-basic-shape) //! types that are generic over their `ToCss` implementations. use std::fmt; use style_traits::{HasViewportPercentage, ToCss}; use values::computed::ComputedValueAsSpecified; use values::generics::border::BorderRadius; use values::generics::position::Position; use values::generics::rect::Rect; use values::specified::url::SpecifiedUrl; /// A clipping shape, for `clip-path`. pub type ClippingShape<BasicShape> = ShapeSource<BasicShape, GeometryBox>; /// https://drafts.fxtf.org/css-masking-1/#typedef-geometry-box #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] #[derive(Clone, Copy, Debug, PartialEq)] pub enum GeometryBox { FillBox, StrokeBox, ViewBox, ShapeBox(ShapeBox), } impl ComputedValueAsSpecified for GeometryBox {} /// A float area shape, for `shape-outside`. pub type FloatAreaShape<BasicShape> = ShapeSource<BasicShape, ShapeBox>; // https://drafts.csswg.org/css-shapes-1/#typedef-shape-box define_css_keyword_enum!(ShapeBox: "margin-box" => MarginBox, "border-box" => BorderBox, "padding-box" => PaddingBox, "content-box" => ContentBox ); add_impls_for_keyword_enum!(ShapeBox); /// A shape source, for some reference box. #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] #[derive(Clone, Debug, PartialEq, ToComputedValue)] pub enum ShapeSource<BasicShape, ReferenceBox> { Url(SpecifiedUrl), Shape(BasicShape, Option<ReferenceBox>), Box(ReferenceBox), None, } #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] #[derive(Clone, Debug, PartialEq, ToComputedValue, ToCss)] pub enum BasicShape<H, V, LengthOrPercentage> { Inset(InsetRect<LengthOrPercentage>), Circle(Circle<H, V, LengthOrPercentage>), Ellipse(Ellipse<H, V, LengthOrPercentage>), Polygon(Polygon<LengthOrPercentage>), } /// https://drafts.csswg.org/css-shapes/#funcdef-inset #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] #[derive(Clone, Debug, PartialEq, ToComputedValue)] pub struct InsetRect<LengthOrPercentage> { pub rect: Rect<LengthOrPercentage>, pub round: Option<BorderRadius<LengthOrPercentage>>, } /// https://drafts.csswg.org/css-shapes/#funcdef-circle #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] #[derive(Clone, Copy, Debug, PartialEq, ToComputedValue)] pub struct Circle<H, V, LengthOrPercentage> { pub position: Position<H, V>, pub radius: ShapeRadius<LengthOrPercentage>, } /// https://drafts.csswg.org/css-shapes/#funcdef-ellipse #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] #[derive(Clone, Copy, Debug, PartialEq, ToComputedValue)] pub struct Ellipse<H, V, LengthOrPercentage> { pub position: Position<H, V>, pub semiaxis_x: ShapeRadius<LengthOrPercentage>, pub semiaxis_y: ShapeRadius<LengthOrPercentage>, } /// https://drafts.csswg.org/css-shapes/#typedef-shape-radius #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] #[derive(Clone, Copy, Debug, PartialEq, ToComputedValue)] pub enum ShapeRadius<LengthOrPercentage> { Length(LengthOrPercentage), ClosestSide, FarthestSide, } #[cfg_attr(feature = "servo", derive(HeapSizeOf))] #[derive(Clone, Debug, PartialEq, ToComputedValue)] /// A generic type for representing the `polygon()` function /// /// https://drafts.csswg.org/css-shapes/#funcdef-polygon pub struct Polygon<LengthOrPercentage> { /// The filling rule for a polygon. pub fill: FillRule, /// A collection of (x, y) coordinates to draw the polygon. pub coordinates: Vec<(LengthOrPercentage, LengthOrPercentage)>, } // https://drafts.csswg.org/css-shapes/#typedef-fill-rule // NOTE: Basic shapes spec says that these are the only two values, however // https://www.w3.org/TR/SVG/painting.html#FillRuleProperty // says that it can also be `inherit` define_css_keyword_enum!(FillRule: "nonzero" => NonZero, "evenodd" => EvenOdd ); add_impls_for_keyword_enum!(FillRule); impl<B, T> HasViewportPercentage for ShapeSource<B, T> { #[inline] fn has_viewport_percentage(&self) -> bool { false } } impl<B: ToCss, T: ToCss> ToCss for ShapeSource<B, T> { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { ShapeSource::Url(ref url) => url.to_css(dest), ShapeSource::Shape(ref shape, Some(ref ref_box)) => { shape.to_css(dest)?; dest.write_str(" ")?; ref_box.to_css(dest) }, ShapeSource::Shape(ref shape, None) => shape.to_css(dest), ShapeSource::Box(ref val) => val.to_css(dest), ShapeSource::None => dest.write_str("none"), } } } impl ToCss for GeometryBox { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { GeometryBox::FillBox => dest.write_str("fill-box"), GeometryBox::StrokeBox => dest.write_str("stroke-box"), GeometryBox::ViewBox => dest.write_str("view-box"), GeometryBox::ShapeBox(s) => s.to_css(dest), } } } impl<L> ToCss for InsetRect<L> where L: ToCss + PartialEq { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { dest.write_str("inset(")?; self.rect.to_css(dest)?; if let Some(ref radius) = self.round { dest.write_str(" round ")?; radius.to_css(dest)?; } dest.write_str(")") } } impl<L> Default for ShapeRadius<L> { #[inline] fn
() -> Self { ShapeRadius::ClosestSide } } impl<L: ToCss> ToCss for ShapeRadius<L> { #[inline] fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { ShapeRadius::Length(ref lop) => lop.to_css(dest), ShapeRadius::ClosestSide => dest.write_str("closest-side"), ShapeRadius::FarthestSide => dest.write_str("farthest-side"), } } } impl<L: ToCss> ToCss for Polygon<L> { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { dest.write_str("polygon(")?; if self.fill!= FillRule::default() { self.fill.to_css(dest)?; dest.write_str(", ")?; } for (i, coord) in self.coordinates.iter().enumerate() { if i > 0 { dest.write_str(", ")?; } coord.0.to_css(dest)?; dest.write_str(" ")?; coord.1.to_css(dest)?; } dest.write_str(")") } } impl Default for FillRule { #[inline] fn default() -> Self { FillRule::NonZero } }
default
identifier_name
basic_shape.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/. */ //! CSS handling for the [`basic-shape`](https://drafts.csswg.org/css-shapes/#typedef-basic-shape) //! types that are generic over their `ToCss` implementations. use std::fmt; use style_traits::{HasViewportPercentage, ToCss}; use values::computed::ComputedValueAsSpecified; use values::generics::border::BorderRadius; use values::generics::position::Position; use values::generics::rect::Rect; use values::specified::url::SpecifiedUrl; /// A clipping shape, for `clip-path`. pub type ClippingShape<BasicShape> = ShapeSource<BasicShape, GeometryBox>; /// https://drafts.fxtf.org/css-masking-1/#typedef-geometry-box #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] #[derive(Clone, Copy, Debug, PartialEq)] pub enum GeometryBox { FillBox, StrokeBox, ViewBox, ShapeBox(ShapeBox), } impl ComputedValueAsSpecified for GeometryBox {} /// A float area shape, for `shape-outside`.
"margin-box" => MarginBox, "border-box" => BorderBox, "padding-box" => PaddingBox, "content-box" => ContentBox ); add_impls_for_keyword_enum!(ShapeBox); /// A shape source, for some reference box. #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] #[derive(Clone, Debug, PartialEq, ToComputedValue)] pub enum ShapeSource<BasicShape, ReferenceBox> { Url(SpecifiedUrl), Shape(BasicShape, Option<ReferenceBox>), Box(ReferenceBox), None, } #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] #[derive(Clone, Debug, PartialEq, ToComputedValue, ToCss)] pub enum BasicShape<H, V, LengthOrPercentage> { Inset(InsetRect<LengthOrPercentage>), Circle(Circle<H, V, LengthOrPercentage>), Ellipse(Ellipse<H, V, LengthOrPercentage>), Polygon(Polygon<LengthOrPercentage>), } /// https://drafts.csswg.org/css-shapes/#funcdef-inset #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] #[derive(Clone, Debug, PartialEq, ToComputedValue)] pub struct InsetRect<LengthOrPercentage> { pub rect: Rect<LengthOrPercentage>, pub round: Option<BorderRadius<LengthOrPercentage>>, } /// https://drafts.csswg.org/css-shapes/#funcdef-circle #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] #[derive(Clone, Copy, Debug, PartialEq, ToComputedValue)] pub struct Circle<H, V, LengthOrPercentage> { pub position: Position<H, V>, pub radius: ShapeRadius<LengthOrPercentage>, } /// https://drafts.csswg.org/css-shapes/#funcdef-ellipse #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] #[derive(Clone, Copy, Debug, PartialEq, ToComputedValue)] pub struct Ellipse<H, V, LengthOrPercentage> { pub position: Position<H, V>, pub semiaxis_x: ShapeRadius<LengthOrPercentage>, pub semiaxis_y: ShapeRadius<LengthOrPercentage>, } /// https://drafts.csswg.org/css-shapes/#typedef-shape-radius #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] #[derive(Clone, Copy, Debug, PartialEq, ToComputedValue)] pub enum ShapeRadius<LengthOrPercentage> { Length(LengthOrPercentage), ClosestSide, FarthestSide, } #[cfg_attr(feature = "servo", derive(HeapSizeOf))] #[derive(Clone, Debug, PartialEq, ToComputedValue)] /// A generic type for representing the `polygon()` function /// /// https://drafts.csswg.org/css-shapes/#funcdef-polygon pub struct Polygon<LengthOrPercentage> { /// The filling rule for a polygon. pub fill: FillRule, /// A collection of (x, y) coordinates to draw the polygon. pub coordinates: Vec<(LengthOrPercentage, LengthOrPercentage)>, } // https://drafts.csswg.org/css-shapes/#typedef-fill-rule // NOTE: Basic shapes spec says that these are the only two values, however // https://www.w3.org/TR/SVG/painting.html#FillRuleProperty // says that it can also be `inherit` define_css_keyword_enum!(FillRule: "nonzero" => NonZero, "evenodd" => EvenOdd ); add_impls_for_keyword_enum!(FillRule); impl<B, T> HasViewportPercentage for ShapeSource<B, T> { #[inline] fn has_viewport_percentage(&self) -> bool { false } } impl<B: ToCss, T: ToCss> ToCss for ShapeSource<B, T> { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { ShapeSource::Url(ref url) => url.to_css(dest), ShapeSource::Shape(ref shape, Some(ref ref_box)) => { shape.to_css(dest)?; dest.write_str(" ")?; ref_box.to_css(dest) }, ShapeSource::Shape(ref shape, None) => shape.to_css(dest), ShapeSource::Box(ref val) => val.to_css(dest), ShapeSource::None => dest.write_str("none"), } } } impl ToCss for GeometryBox { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { GeometryBox::FillBox => dest.write_str("fill-box"), GeometryBox::StrokeBox => dest.write_str("stroke-box"), GeometryBox::ViewBox => dest.write_str("view-box"), GeometryBox::ShapeBox(s) => s.to_css(dest), } } } impl<L> ToCss for InsetRect<L> where L: ToCss + PartialEq { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { dest.write_str("inset(")?; self.rect.to_css(dest)?; if let Some(ref radius) = self.round { dest.write_str(" round ")?; radius.to_css(dest)?; } dest.write_str(")") } } impl<L> Default for ShapeRadius<L> { #[inline] fn default() -> Self { ShapeRadius::ClosestSide } } impl<L: ToCss> ToCss for ShapeRadius<L> { #[inline] fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { ShapeRadius::Length(ref lop) => lop.to_css(dest), ShapeRadius::ClosestSide => dest.write_str("closest-side"), ShapeRadius::FarthestSide => dest.write_str("farthest-side"), } } } impl<L: ToCss> ToCss for Polygon<L> { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { dest.write_str("polygon(")?; if self.fill!= FillRule::default() { self.fill.to_css(dest)?; dest.write_str(", ")?; } for (i, coord) in self.coordinates.iter().enumerate() { if i > 0 { dest.write_str(", ")?; } coord.0.to_css(dest)?; dest.write_str(" ")?; coord.1.to_css(dest)?; } dest.write_str(")") } } impl Default for FillRule { #[inline] fn default() -> Self { FillRule::NonZero } }
pub type FloatAreaShape<BasicShape> = ShapeSource<BasicShape, ShapeBox>; // https://drafts.csswg.org/css-shapes-1/#typedef-shape-box define_css_keyword_enum!(ShapeBox:
random_line_split
handle.rs
// Copyright 2020 The Tink-Rust Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// //! Handle wrapper for keysets. use crate::{utils::wrap_err, TinkError}; use std::sync::Arc; use tink_proto::{key_data::KeyMaterialType, prost::Message, Keyset, KeysetInfo}; /// `Handle` provides access to a [`Keyset`] protobuf, to limit the exposure /// of actual protocol buffers that hold sensitive key material. pub struct Handle { ks: Keyset, } impl Handle { /// Create a keyset handle that contains a single fresh key generated according /// to the given [`KeyTemplate`](tink_proto::KeyTemplate). pub fn new(kt: &tink_proto::KeyTemplate) -> Result<Self, TinkError> { let mut ksm = super::Manager::new(); ksm.rotate(kt) .map_err(|e| wrap_err("keyset::Handle: cannot generate new keyset", e))?; ksm.handle() .map_err(|e| wrap_err("keyset::Handle: cannot get keyset handle", e)) } /// Create a new instance of [`Handle`] using the given [`Keyset`] which does not contain any /// secret key material. pub fn new_with_no_secrets(ks: Keyset) -> Result<Self, TinkError> { let h = Handle { ks: validate_keyset(ks)?, }; if h.has_secrets()? { // If you need to do this, you have to use `tink_core::keyset::insecure::read()` // instead. return Err("importing unencrypted secret key material is forbidden".into()); } Ok(h) } /// Attempt to create a [`Handle`] from an encrypted keyset obtained via a /// [`Reader`](crate::keyset::Reader). pub fn read<T>(reader: &mut T, master_key: Box<dyn crate::Aead>) -> Result<Self, TinkError> where T: crate::keyset::Reader, { Self::read_with_associated_data(reader, master_key, &[]) } /// Attempt to create a [`Handle`] from an encrypted keyset obtained via a /// [`Reader`](crate::keyset::Reader) using the provided associated data. pub fn read_with_associated_data<T>( reader: &mut T, master_key: Box<dyn crate::Aead>, associated_data: &[u8], ) -> Result<Self, TinkError> where T: crate::keyset::Reader, { let encrypted_keyset = reader.read_encrypted()?; let ks = decrypt(&encrypted_keyset, master_key, associated_data)?; Ok(Handle { ks: validate_keyset(ks)?, }) } /// Attempt to create a [`Handle`] from a keyset obtained via a /// [`Reader`](crate::keyset::Reader). pub fn read_with_no_secrets<T>(reader: &mut T) -> Result<Self, TinkError> where T: crate::keyset::Reader, { let ks = reader.read()?; Handle::new_with_no_secrets(ks) } /// Return a [`Handle`] of the public keys if the managed keyset contains private keys. pub fn public(&self) -> Result<Self, TinkError> { let priv_keys = &self.ks.key; let mut pub_keys = Vec::with_capacity(priv_keys.len()); for priv_key in priv_keys { let priv_key_data = priv_key .key_data .as_ref() .ok_or_else(|| TinkError::new("keyset::Handle: invalid keyset"))?; let pub_key_data = public_key_data(priv_key_data).map_err(|e| wrap_err("keyset::Handle", e))?; pub_keys.push(tink_proto::keyset::Key { key_data: Some(pub_key_data), status: priv_key.status, key_id: priv_key.key_id, output_prefix_type: priv_key.output_prefix_type, }); } let ks = Keyset { primary_key_id: self.ks.primary_key_id, key: pub_keys, }; Ok(Handle { ks }) } /// Encrypts and writes the enclosed [`Keyset`]. pub fn write<T>( &self, writer: &mut T, master_key: Box<dyn crate::Aead>, ) -> Result<(), TinkError> where T: super::Writer, { self.write_with_associated_data(writer, master_key, &[]) } /// Encrypts and writes the enclosed [`Keyset`] using the provided associated data. pub fn write_with_associated_data<T>( &self, writer: &mut T, master_key: Box<dyn crate::Aead>, associated_data: &[u8], ) -> Result<(), TinkError> where T: super::Writer, { let encrypted = encrypt(&self.ks, master_key, associated_data)?; writer.write_encrypted(&encrypted) } /// Export the keyset in `h` to the given [`Writer`](super::Writer) returning an error if the /// keyset contains secret key material. pub fn write_with_no_secrets<T>(&self, w: &mut T) -> Result<(), TinkError> where T: super::Writer, { if self.has_secrets()? { Err("exporting unencrypted secret key material is forbidden".into()) } else { w.write(&self.ks) } } /// Create a set of primitives corresponding to the keys with status=ENABLED in the keyset of /// the given keyset [`Handle`], assuming all the corresponding key managers are present (keys /// with status!=ENABLED are skipped). /// /// The returned set is usually later "wrapped" into a class that implements the corresponding /// [`Primitive`](crate::Primitive) interface. pub fn primitives(&self) -> Result<crate::primitiveset::PrimitiveSet, TinkError> { self.primitives_with_key_manager(None) } /// Create a set of primitives corresponding to the keys with status=ENABLED in the keyset of /// the given keyset [`Handle`], using the given key manager (instead of registered key /// managers) for keys supported by it. Keys not supported by the key manager are handled /// by matching registered key managers (if present), and keys with status!=ENABLED are /// skipped. /// /// This enables custom treatment of keys, for example providing extra context (e.g. credentials /// for accessing keys managed by a KMS), or gathering custom monitoring/profiling /// information. /// /// The returned set is usually later "wrapped" into a class that implements the corresponding /// [`Primitive`](crate::Primitive)-interface. pub fn primitives_with_key_manager( &self, km: Option<Arc<dyn crate::registry::KeyManager>>, ) -> Result<crate::primitiveset::PrimitiveSet, TinkError> { super::validate(&self.ks) .map_err(|e| wrap_err("primitives_with_key_manager: invalid keyset", e))?; let mut primitive_set = crate::primitiveset::PrimitiveSet::new(); for key in &self.ks.key { if key.status!= tink_proto::KeyStatusType::Enabled as i32 { continue; } let key_data = key .key_data .as_ref() .ok_or_else(|| TinkError::new("primitives_with_key_manager: no key_data"))?; let primitive = match &km { Some(km) if km.does_support(&key_data.type_url) => km.primitive(&key_data.value), Some(_) | None => crate::registry::primitive_from_key_data(key_data), } .map_err(|e| { wrap_err( "primitives_with_key_manager: cannot get primitive from key", e, ) })?; let entry = primitive_set .add(primitive, key) .map_err(|e| wrap_err("primitives_with_key_manager: cannot add primitive", e))?; if key.key_id == self.ks.primary_key_id { primitive_set.primary = Some(entry.clone()); } } Ok(primitive_set) } /// Check if the keyset handle contains any key material considered secret. Both symmetric keys /// and the private key of an asymmetric crypto system are considered secret keys. Also /// returns true when encountering any errors. fn has_secrets(&self) -> Result<bool, TinkError> { let mut result = false; for k in &self.ks.key { match &k.key_data { None => return Err("invalid keyset".into()), Some(kd) => match KeyMaterialType::from_i32(kd.key_material_type) { Some(KeyMaterialType::UnknownKeymaterial) => result = true, Some(KeyMaterialType::Symmetric) => result = true, Some(KeyMaterialType::AsymmetricPrivate) => result = true, Some(KeyMaterialType::AsymmetricPublic) => {} Some(KeyMaterialType::Remote) => {} None => return Err("invalid key material type".into()), }, } } Ok(result) } /// Return [`KeysetInfo`] representation of the managed keyset. The result does not /// contain any sensitive key material. pub fn keyset_info(&self) -> KeysetInfo { get_keyset_info(&self.ks) } /// Consume the `Handle` and return the enclosed [`Keyset`]. pub(crate) fn into_inner(self) -> Keyset { self.ks } /// Return a copy of the enclosed [`Keyset`]; for internal /// use only. #[cfg(feature = "insecure")] #[cfg_attr(docsrs, doc(cfg(feature = "insecure")))] pub(crate) fn clone_keyset(&self) -> Keyset { self.ks.clone() } /// Create a `Handle` from a [`Keyset`]. Implemented as a standalone method rather than /// as an `impl` of the `From` trait so visibility can be restricted. pub(crate) fn from_keyset(ks: Keyset) -> Result<Self, TinkError> { Ok(Handle { ks: validate_keyset(ks)?, }) } } /// Check that a [`Keyset`] is valid. fn validate_keyset(ks: Keyset) -> Result<Keyset, TinkError> { for k in &ks.key { match &k.key_data { None if k.status == tink_proto::KeyStatusType::Destroyed as i32 => {} None => return Err("invalid keyset".into()), Some(kd) => match KeyMaterialType::from_i32(kd.key_material_type) { Some(_) => {} None => return Err("invalid key material type".into()), }, } } Ok(ks) } /// Extract the public key data corresponding to private key data. fn public_key_data(priv_key_data: &tink_proto::KeyData) -> Result<tink_proto::KeyData, TinkError> { if priv_key_data.key_material_type != tink_proto::key_data::KeyMaterialType::AsymmetricPrivate as i32 { return Err("keyset::Handle: keyset contains a non-private key".into()); } let km = crate::registry::get_key_manager(&priv_key_data.type_url)?; if!km.supports_private_keys() { return Err(format!( "keyset::Handle: {} does not belong to a KeyManager that handles private keys", priv_key_data.type_url ) .into()); } km.public_key_data(&priv_key_data.value) } /// Decrypt a keyset with a master key. fn decrypt( encrypted_keyset: &tink_proto::EncryptedKeyset, master_key: Box<dyn crate::Aead>,
let decrypted = master_key .decrypt(&encrypted_keyset.encrypted_keyset, associated_data) .map_err(|e| wrap_err("keyset::Handle: decryption failed", e))?; Keyset::decode(&decrypted[..]).map_err(|_| TinkError::new("keyset::Handle:: invalid keyset")) } /// Encrypt a keyset with a master key. fn encrypt( keyset: &Keyset, master_key: Box<dyn crate::Aead>, associated_data: &[u8], ) -> Result<tink_proto::EncryptedKeyset, TinkError> { let mut serialized_keyset = vec![]; keyset .encode(&mut serialized_keyset) .map_err(|e| wrap_err("keyset::Handle: invalid keyset", e))?; let encrypted = master_key .encrypt(&serialized_keyset, associated_data) .map_err(|e| wrap_err("keyset::Handle: encrypted failed", e))?; Ok(tink_proto::EncryptedKeyset { encrypted_keyset: encrypted, keyset_info: Some(get_keyset_info(keyset)), }) } /// Return a [`KeysetInfo`] from a [`Keyset`] protobuf. fn get_keyset_info(keyset: &Keyset) -> KeysetInfo { let n_key = keyset.key.len(); let mut key_infos = Vec::with_capacity(n_key); for key in &keyset.key { key_infos.push(get_key_info(key)); } KeysetInfo { primary_key_id: keyset.primary_key_id, key_info: key_infos, } } /// Return a [`KeyInfo`](tink_proto::keyset_info::KeyInfo) from a /// [`Key`](tink_proto::keyset::Key) protobuf. fn get_key_info(key: &tink_proto::keyset::Key) -> tink_proto::keyset_info::KeyInfo { tink_proto::keyset_info::KeyInfo { type_url: match &key.key_data { Some(kd) => kd.type_url.clone(), None => "".to_string(), }, status: key.status, key_id: key.key_id, output_prefix_type: key.output_prefix_type, } } impl std::fmt::Debug for Handle { /// Return a string representation of the managed keyset. /// The result does not contain any sensitive key material. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{:?}", get_keyset_info(&self.ks)) } }
associated_data: &[u8], ) -> Result<Keyset, TinkError> {
random_line_split
handle.rs
// Copyright 2020 The Tink-Rust Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// //! Handle wrapper for keysets. use crate::{utils::wrap_err, TinkError}; use std::sync::Arc; use tink_proto::{key_data::KeyMaterialType, prost::Message, Keyset, KeysetInfo}; /// `Handle` provides access to a [`Keyset`] protobuf, to limit the exposure /// of actual protocol buffers that hold sensitive key material. pub struct Handle { ks: Keyset, } impl Handle { /// Create a keyset handle that contains a single fresh key generated according /// to the given [`KeyTemplate`](tink_proto::KeyTemplate). pub fn new(kt: &tink_proto::KeyTemplate) -> Result<Self, TinkError> { let mut ksm = super::Manager::new(); ksm.rotate(kt) .map_err(|e| wrap_err("keyset::Handle: cannot generate new keyset", e))?; ksm.handle() .map_err(|e| wrap_err("keyset::Handle: cannot get keyset handle", e)) } /// Create a new instance of [`Handle`] using the given [`Keyset`] which does not contain any /// secret key material. pub fn new_with_no_secrets(ks: Keyset) -> Result<Self, TinkError> { let h = Handle { ks: validate_keyset(ks)?, }; if h.has_secrets()? { // If you need to do this, you have to use `tink_core::keyset::insecure::read()` // instead. return Err("importing unencrypted secret key material is forbidden".into()); } Ok(h) } /// Attempt to create a [`Handle`] from an encrypted keyset obtained via a /// [`Reader`](crate::keyset::Reader). pub fn read<T>(reader: &mut T, master_key: Box<dyn crate::Aead>) -> Result<Self, TinkError> where T: crate::keyset::Reader, { Self::read_with_associated_data(reader, master_key, &[]) } /// Attempt to create a [`Handle`] from an encrypted keyset obtained via a /// [`Reader`](crate::keyset::Reader) using the provided associated data. pub fn read_with_associated_data<T>( reader: &mut T, master_key: Box<dyn crate::Aead>, associated_data: &[u8], ) -> Result<Self, TinkError> where T: crate::keyset::Reader, { let encrypted_keyset = reader.read_encrypted()?; let ks = decrypt(&encrypted_keyset, master_key, associated_data)?; Ok(Handle { ks: validate_keyset(ks)?, }) } /// Attempt to create a [`Handle`] from a keyset obtained via a /// [`Reader`](crate::keyset::Reader). pub fn read_with_no_secrets<T>(reader: &mut T) -> Result<Self, TinkError> where T: crate::keyset::Reader, { let ks = reader.read()?; Handle::new_with_no_secrets(ks) } /// Return a [`Handle`] of the public keys if the managed keyset contains private keys. pub fn public(&self) -> Result<Self, TinkError> { let priv_keys = &self.ks.key; let mut pub_keys = Vec::with_capacity(priv_keys.len()); for priv_key in priv_keys { let priv_key_data = priv_key .key_data .as_ref() .ok_or_else(|| TinkError::new("keyset::Handle: invalid keyset"))?; let pub_key_data = public_key_data(priv_key_data).map_err(|e| wrap_err("keyset::Handle", e))?; pub_keys.push(tink_proto::keyset::Key { key_data: Some(pub_key_data), status: priv_key.status, key_id: priv_key.key_id, output_prefix_type: priv_key.output_prefix_type, }); } let ks = Keyset { primary_key_id: self.ks.primary_key_id, key: pub_keys, }; Ok(Handle { ks }) } /// Encrypts and writes the enclosed [`Keyset`]. pub fn write<T>( &self, writer: &mut T, master_key: Box<dyn crate::Aead>, ) -> Result<(), TinkError> where T: super::Writer, { self.write_with_associated_data(writer, master_key, &[]) } /// Encrypts and writes the enclosed [`Keyset`] using the provided associated data. pub fn write_with_associated_data<T>( &self, writer: &mut T, master_key: Box<dyn crate::Aead>, associated_data: &[u8], ) -> Result<(), TinkError> where T: super::Writer, { let encrypted = encrypt(&self.ks, master_key, associated_data)?; writer.write_encrypted(&encrypted) } /// Export the keyset in `h` to the given [`Writer`](super::Writer) returning an error if the /// keyset contains secret key material. pub fn write_with_no_secrets<T>(&self, w: &mut T) -> Result<(), TinkError> where T: super::Writer, { if self.has_secrets()? { Err("exporting unencrypted secret key material is forbidden".into()) } else { w.write(&self.ks) } } /// Create a set of primitives corresponding to the keys with status=ENABLED in the keyset of /// the given keyset [`Handle`], assuming all the corresponding key managers are present (keys /// with status!=ENABLED are skipped). /// /// The returned set is usually later "wrapped" into a class that implements the corresponding /// [`Primitive`](crate::Primitive) interface. pub fn primitives(&self) -> Result<crate::primitiveset::PrimitiveSet, TinkError> { self.primitives_with_key_manager(None) } /// Create a set of primitives corresponding to the keys with status=ENABLED in the keyset of /// the given keyset [`Handle`], using the given key manager (instead of registered key /// managers) for keys supported by it. Keys not supported by the key manager are handled /// by matching registered key managers (if present), and keys with status!=ENABLED are /// skipped. /// /// This enables custom treatment of keys, for example providing extra context (e.g. credentials /// for accessing keys managed by a KMS), or gathering custom monitoring/profiling /// information. /// /// The returned set is usually later "wrapped" into a class that implements the corresponding /// [`Primitive`](crate::Primitive)-interface. pub fn primitives_with_key_manager( &self, km: Option<Arc<dyn crate::registry::KeyManager>>, ) -> Result<crate::primitiveset::PrimitiveSet, TinkError> { super::validate(&self.ks) .map_err(|e| wrap_err("primitives_with_key_manager: invalid keyset", e))?; let mut primitive_set = crate::primitiveset::PrimitiveSet::new(); for key in &self.ks.key { if key.status!= tink_proto::KeyStatusType::Enabled as i32 { continue; } let key_data = key .key_data .as_ref() .ok_or_else(|| TinkError::new("primitives_with_key_manager: no key_data"))?; let primitive = match &km { Some(km) if km.does_support(&key_data.type_url) => km.primitive(&key_data.value), Some(_) | None => crate::registry::primitive_from_key_data(key_data), } .map_err(|e| { wrap_err( "primitives_with_key_manager: cannot get primitive from key", e, ) })?; let entry = primitive_set .add(primitive, key) .map_err(|e| wrap_err("primitives_with_key_manager: cannot add primitive", e))?; if key.key_id == self.ks.primary_key_id { primitive_set.primary = Some(entry.clone()); } } Ok(primitive_set) } /// Check if the keyset handle contains any key material considered secret. Both symmetric keys /// and the private key of an asymmetric crypto system are considered secret keys. Also /// returns true when encountering any errors. fn has_secrets(&self) -> Result<bool, TinkError> { let mut result = false; for k in &self.ks.key { match &k.key_data { None => return Err("invalid keyset".into()), Some(kd) => match KeyMaterialType::from_i32(kd.key_material_type) { Some(KeyMaterialType::UnknownKeymaterial) => result = true, Some(KeyMaterialType::Symmetric) => result = true, Some(KeyMaterialType::AsymmetricPrivate) => result = true, Some(KeyMaterialType::AsymmetricPublic) => {} Some(KeyMaterialType::Remote) => {} None => return Err("invalid key material type".into()), }, } } Ok(result) } /// Return [`KeysetInfo`] representation of the managed keyset. The result does not /// contain any sensitive key material. pub fn keyset_info(&self) -> KeysetInfo { get_keyset_info(&self.ks) } /// Consume the `Handle` and return the enclosed [`Keyset`]. pub(crate) fn into_inner(self) -> Keyset { self.ks } /// Return a copy of the enclosed [`Keyset`]; for internal /// use only. #[cfg(feature = "insecure")] #[cfg_attr(docsrs, doc(cfg(feature = "insecure")))] pub(crate) fn clone_keyset(&self) -> Keyset
/// Create a `Handle` from a [`Keyset`]. Implemented as a standalone method rather than /// as an `impl` of the `From` trait so visibility can be restricted. pub(crate) fn from_keyset(ks: Keyset) -> Result<Self, TinkError> { Ok(Handle { ks: validate_keyset(ks)?, }) } } /// Check that a [`Keyset`] is valid. fn validate_keyset(ks: Keyset) -> Result<Keyset, TinkError> { for k in &ks.key { match &k.key_data { None if k.status == tink_proto::KeyStatusType::Destroyed as i32 => {} None => return Err("invalid keyset".into()), Some(kd) => match KeyMaterialType::from_i32(kd.key_material_type) { Some(_) => {} None => return Err("invalid key material type".into()), }, } } Ok(ks) } /// Extract the public key data corresponding to private key data. fn public_key_data(priv_key_data: &tink_proto::KeyData) -> Result<tink_proto::KeyData, TinkError> { if priv_key_data.key_material_type != tink_proto::key_data::KeyMaterialType::AsymmetricPrivate as i32 { return Err("keyset::Handle: keyset contains a non-private key".into()); } let km = crate::registry::get_key_manager(&priv_key_data.type_url)?; if!km.supports_private_keys() { return Err(format!( "keyset::Handle: {} does not belong to a KeyManager that handles private keys", priv_key_data.type_url ) .into()); } km.public_key_data(&priv_key_data.value) } /// Decrypt a keyset with a master key. fn decrypt( encrypted_keyset: &tink_proto::EncryptedKeyset, master_key: Box<dyn crate::Aead>, associated_data: &[u8], ) -> Result<Keyset, TinkError> { let decrypted = master_key .decrypt(&encrypted_keyset.encrypted_keyset, associated_data) .map_err(|e| wrap_err("keyset::Handle: decryption failed", e))?; Keyset::decode(&decrypted[..]).map_err(|_| TinkError::new("keyset::Handle:: invalid keyset")) } /// Encrypt a keyset with a master key. fn encrypt( keyset: &Keyset, master_key: Box<dyn crate::Aead>, associated_data: &[u8], ) -> Result<tink_proto::EncryptedKeyset, TinkError> { let mut serialized_keyset = vec![]; keyset .encode(&mut serialized_keyset) .map_err(|e| wrap_err("keyset::Handle: invalid keyset", e))?; let encrypted = master_key .encrypt(&serialized_keyset, associated_data) .map_err(|e| wrap_err("keyset::Handle: encrypted failed", e))?; Ok(tink_proto::EncryptedKeyset { encrypted_keyset: encrypted, keyset_info: Some(get_keyset_info(keyset)), }) } /// Return a [`KeysetInfo`] from a [`Keyset`] protobuf. fn get_keyset_info(keyset: &Keyset) -> KeysetInfo { let n_key = keyset.key.len(); let mut key_infos = Vec::with_capacity(n_key); for key in &keyset.key { key_infos.push(get_key_info(key)); } KeysetInfo { primary_key_id: keyset.primary_key_id, key_info: key_infos, } } /// Return a [`KeyInfo`](tink_proto::keyset_info::KeyInfo) from a /// [`Key`](tink_proto::keyset::Key) protobuf. fn get_key_info(key: &tink_proto::keyset::Key) -> tink_proto::keyset_info::KeyInfo { tink_proto::keyset_info::KeyInfo { type_url: match &key.key_data { Some(kd) => kd.type_url.clone(), None => "".to_string(), }, status: key.status, key_id: key.key_id, output_prefix_type: key.output_prefix_type, } } impl std::fmt::Debug for Handle { /// Return a string representation of the managed keyset. /// The result does not contain any sensitive key material. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{:?}", get_keyset_info(&self.ks)) } }
{ self.ks.clone() }
identifier_body
handle.rs
// Copyright 2020 The Tink-Rust Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// //! Handle wrapper for keysets. use crate::{utils::wrap_err, TinkError}; use std::sync::Arc; use tink_proto::{key_data::KeyMaterialType, prost::Message, Keyset, KeysetInfo}; /// `Handle` provides access to a [`Keyset`] protobuf, to limit the exposure /// of actual protocol buffers that hold sensitive key material. pub struct Handle { ks: Keyset, } impl Handle { /// Create a keyset handle that contains a single fresh key generated according /// to the given [`KeyTemplate`](tink_proto::KeyTemplate). pub fn
(kt: &tink_proto::KeyTemplate) -> Result<Self, TinkError> { let mut ksm = super::Manager::new(); ksm.rotate(kt) .map_err(|e| wrap_err("keyset::Handle: cannot generate new keyset", e))?; ksm.handle() .map_err(|e| wrap_err("keyset::Handle: cannot get keyset handle", e)) } /// Create a new instance of [`Handle`] using the given [`Keyset`] which does not contain any /// secret key material. pub fn new_with_no_secrets(ks: Keyset) -> Result<Self, TinkError> { let h = Handle { ks: validate_keyset(ks)?, }; if h.has_secrets()? { // If you need to do this, you have to use `tink_core::keyset::insecure::read()` // instead. return Err("importing unencrypted secret key material is forbidden".into()); } Ok(h) } /// Attempt to create a [`Handle`] from an encrypted keyset obtained via a /// [`Reader`](crate::keyset::Reader). pub fn read<T>(reader: &mut T, master_key: Box<dyn crate::Aead>) -> Result<Self, TinkError> where T: crate::keyset::Reader, { Self::read_with_associated_data(reader, master_key, &[]) } /// Attempt to create a [`Handle`] from an encrypted keyset obtained via a /// [`Reader`](crate::keyset::Reader) using the provided associated data. pub fn read_with_associated_data<T>( reader: &mut T, master_key: Box<dyn crate::Aead>, associated_data: &[u8], ) -> Result<Self, TinkError> where T: crate::keyset::Reader, { let encrypted_keyset = reader.read_encrypted()?; let ks = decrypt(&encrypted_keyset, master_key, associated_data)?; Ok(Handle { ks: validate_keyset(ks)?, }) } /// Attempt to create a [`Handle`] from a keyset obtained via a /// [`Reader`](crate::keyset::Reader). pub fn read_with_no_secrets<T>(reader: &mut T) -> Result<Self, TinkError> where T: crate::keyset::Reader, { let ks = reader.read()?; Handle::new_with_no_secrets(ks) } /// Return a [`Handle`] of the public keys if the managed keyset contains private keys. pub fn public(&self) -> Result<Self, TinkError> { let priv_keys = &self.ks.key; let mut pub_keys = Vec::with_capacity(priv_keys.len()); for priv_key in priv_keys { let priv_key_data = priv_key .key_data .as_ref() .ok_or_else(|| TinkError::new("keyset::Handle: invalid keyset"))?; let pub_key_data = public_key_data(priv_key_data).map_err(|e| wrap_err("keyset::Handle", e))?; pub_keys.push(tink_proto::keyset::Key { key_data: Some(pub_key_data), status: priv_key.status, key_id: priv_key.key_id, output_prefix_type: priv_key.output_prefix_type, }); } let ks = Keyset { primary_key_id: self.ks.primary_key_id, key: pub_keys, }; Ok(Handle { ks }) } /// Encrypts and writes the enclosed [`Keyset`]. pub fn write<T>( &self, writer: &mut T, master_key: Box<dyn crate::Aead>, ) -> Result<(), TinkError> where T: super::Writer, { self.write_with_associated_data(writer, master_key, &[]) } /// Encrypts and writes the enclosed [`Keyset`] using the provided associated data. pub fn write_with_associated_data<T>( &self, writer: &mut T, master_key: Box<dyn crate::Aead>, associated_data: &[u8], ) -> Result<(), TinkError> where T: super::Writer, { let encrypted = encrypt(&self.ks, master_key, associated_data)?; writer.write_encrypted(&encrypted) } /// Export the keyset in `h` to the given [`Writer`](super::Writer) returning an error if the /// keyset contains secret key material. pub fn write_with_no_secrets<T>(&self, w: &mut T) -> Result<(), TinkError> where T: super::Writer, { if self.has_secrets()? { Err("exporting unencrypted secret key material is forbidden".into()) } else { w.write(&self.ks) } } /// Create a set of primitives corresponding to the keys with status=ENABLED in the keyset of /// the given keyset [`Handle`], assuming all the corresponding key managers are present (keys /// with status!=ENABLED are skipped). /// /// The returned set is usually later "wrapped" into a class that implements the corresponding /// [`Primitive`](crate::Primitive) interface. pub fn primitives(&self) -> Result<crate::primitiveset::PrimitiveSet, TinkError> { self.primitives_with_key_manager(None) } /// Create a set of primitives corresponding to the keys with status=ENABLED in the keyset of /// the given keyset [`Handle`], using the given key manager (instead of registered key /// managers) for keys supported by it. Keys not supported by the key manager are handled /// by matching registered key managers (if present), and keys with status!=ENABLED are /// skipped. /// /// This enables custom treatment of keys, for example providing extra context (e.g. credentials /// for accessing keys managed by a KMS), or gathering custom monitoring/profiling /// information. /// /// The returned set is usually later "wrapped" into a class that implements the corresponding /// [`Primitive`](crate::Primitive)-interface. pub fn primitives_with_key_manager( &self, km: Option<Arc<dyn crate::registry::KeyManager>>, ) -> Result<crate::primitiveset::PrimitiveSet, TinkError> { super::validate(&self.ks) .map_err(|e| wrap_err("primitives_with_key_manager: invalid keyset", e))?; let mut primitive_set = crate::primitiveset::PrimitiveSet::new(); for key in &self.ks.key { if key.status!= tink_proto::KeyStatusType::Enabled as i32 { continue; } let key_data = key .key_data .as_ref() .ok_or_else(|| TinkError::new("primitives_with_key_manager: no key_data"))?; let primitive = match &km { Some(km) if km.does_support(&key_data.type_url) => km.primitive(&key_data.value), Some(_) | None => crate::registry::primitive_from_key_data(key_data), } .map_err(|e| { wrap_err( "primitives_with_key_manager: cannot get primitive from key", e, ) })?; let entry = primitive_set .add(primitive, key) .map_err(|e| wrap_err("primitives_with_key_manager: cannot add primitive", e))?; if key.key_id == self.ks.primary_key_id { primitive_set.primary = Some(entry.clone()); } } Ok(primitive_set) } /// Check if the keyset handle contains any key material considered secret. Both symmetric keys /// and the private key of an asymmetric crypto system are considered secret keys. Also /// returns true when encountering any errors. fn has_secrets(&self) -> Result<bool, TinkError> { let mut result = false; for k in &self.ks.key { match &k.key_data { None => return Err("invalid keyset".into()), Some(kd) => match KeyMaterialType::from_i32(kd.key_material_type) { Some(KeyMaterialType::UnknownKeymaterial) => result = true, Some(KeyMaterialType::Symmetric) => result = true, Some(KeyMaterialType::AsymmetricPrivate) => result = true, Some(KeyMaterialType::AsymmetricPublic) => {} Some(KeyMaterialType::Remote) => {} None => return Err("invalid key material type".into()), }, } } Ok(result) } /// Return [`KeysetInfo`] representation of the managed keyset. The result does not /// contain any sensitive key material. pub fn keyset_info(&self) -> KeysetInfo { get_keyset_info(&self.ks) } /// Consume the `Handle` and return the enclosed [`Keyset`]. pub(crate) fn into_inner(self) -> Keyset { self.ks } /// Return a copy of the enclosed [`Keyset`]; for internal /// use only. #[cfg(feature = "insecure")] #[cfg_attr(docsrs, doc(cfg(feature = "insecure")))] pub(crate) fn clone_keyset(&self) -> Keyset { self.ks.clone() } /// Create a `Handle` from a [`Keyset`]. Implemented as a standalone method rather than /// as an `impl` of the `From` trait so visibility can be restricted. pub(crate) fn from_keyset(ks: Keyset) -> Result<Self, TinkError> { Ok(Handle { ks: validate_keyset(ks)?, }) } } /// Check that a [`Keyset`] is valid. fn validate_keyset(ks: Keyset) -> Result<Keyset, TinkError> { for k in &ks.key { match &k.key_data { None if k.status == tink_proto::KeyStatusType::Destroyed as i32 => {} None => return Err("invalid keyset".into()), Some(kd) => match KeyMaterialType::from_i32(kd.key_material_type) { Some(_) => {} None => return Err("invalid key material type".into()), }, } } Ok(ks) } /// Extract the public key data corresponding to private key data. fn public_key_data(priv_key_data: &tink_proto::KeyData) -> Result<tink_proto::KeyData, TinkError> { if priv_key_data.key_material_type != tink_proto::key_data::KeyMaterialType::AsymmetricPrivate as i32 { return Err("keyset::Handle: keyset contains a non-private key".into()); } let km = crate::registry::get_key_manager(&priv_key_data.type_url)?; if!km.supports_private_keys() { return Err(format!( "keyset::Handle: {} does not belong to a KeyManager that handles private keys", priv_key_data.type_url ) .into()); } km.public_key_data(&priv_key_data.value) } /// Decrypt a keyset with a master key. fn decrypt( encrypted_keyset: &tink_proto::EncryptedKeyset, master_key: Box<dyn crate::Aead>, associated_data: &[u8], ) -> Result<Keyset, TinkError> { let decrypted = master_key .decrypt(&encrypted_keyset.encrypted_keyset, associated_data) .map_err(|e| wrap_err("keyset::Handle: decryption failed", e))?; Keyset::decode(&decrypted[..]).map_err(|_| TinkError::new("keyset::Handle:: invalid keyset")) } /// Encrypt a keyset with a master key. fn encrypt( keyset: &Keyset, master_key: Box<dyn crate::Aead>, associated_data: &[u8], ) -> Result<tink_proto::EncryptedKeyset, TinkError> { let mut serialized_keyset = vec![]; keyset .encode(&mut serialized_keyset) .map_err(|e| wrap_err("keyset::Handle: invalid keyset", e))?; let encrypted = master_key .encrypt(&serialized_keyset, associated_data) .map_err(|e| wrap_err("keyset::Handle: encrypted failed", e))?; Ok(tink_proto::EncryptedKeyset { encrypted_keyset: encrypted, keyset_info: Some(get_keyset_info(keyset)), }) } /// Return a [`KeysetInfo`] from a [`Keyset`] protobuf. fn get_keyset_info(keyset: &Keyset) -> KeysetInfo { let n_key = keyset.key.len(); let mut key_infos = Vec::with_capacity(n_key); for key in &keyset.key { key_infos.push(get_key_info(key)); } KeysetInfo { primary_key_id: keyset.primary_key_id, key_info: key_infos, } } /// Return a [`KeyInfo`](tink_proto::keyset_info::KeyInfo) from a /// [`Key`](tink_proto::keyset::Key) protobuf. fn get_key_info(key: &tink_proto::keyset::Key) -> tink_proto::keyset_info::KeyInfo { tink_proto::keyset_info::KeyInfo { type_url: match &key.key_data { Some(kd) => kd.type_url.clone(), None => "".to_string(), }, status: key.status, key_id: key.key_id, output_prefix_type: key.output_prefix_type, } } impl std::fmt::Debug for Handle { /// Return a string representation of the managed keyset. /// The result does not contain any sensitive key material. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{:?}", get_keyset_info(&self.ks)) } }
new
identifier_name
uniformbuffergl.rs
// Copyright (c) 2016-2018 Bruce Stenning. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS // OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED // AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. use std::os::raw::*; use std::mem; use graphics::uniformbuffer::*; use algebra::matrix::Mat4; use algebra::vector::Vec3; use gl; use gl::types::*; pub struct UniformBufferGl { pub underlying: UniformBufferBacking, pub ubo_handle: GLuint, } impl UniformBufferGl { /// Constructor /// /// data: Raw data for the uniform buffer /// ubo_handle: The UBO object handle pub fn new(data: &UniformBufferBacking, ubo_handle: GLuint) -> UniformBufferGl { UniformBufferGl { underlying: data.clone(), ubo_handle: ubo_handle, } } /// Return the uniform buffer object handle pub fn get_handle(&self) -> GLuint { self.ubo_handle } } impl UniformBuffer for UniformBufferGl { /// Synchronise the accumulated contents of the buffer with the graphics API fn synchronise(&self) { unsafe { gl::BindBuffer(gl::UNIFORM_BUFFER, self.ubo_handle); let src: *const c_void = mem::transmute(self.underlying.bytes.as_ptr()); gl::BufferSubData( gl::UNIFORM_BUFFER, 0, self.underlying.bytes.len() as isize, src, ); gl::BindBuffer(gl::UNIFORM_BUFFER, 0); } } /// Set a integer in part of the memory put aside for the named uniform buffer /// /// uniform_name: The name of the uniform whose value should be set /// value: The value to set for the uniform fn set_int(&mut self, uniform_name: &str, value: i32) { self.underlying.set_int(uniform_name, value); } /// Set a floating point in part of the memory put aside for the named uniform buffer /// /// uniform_name: The name of the uniform whose value should be set /// value: The value to set for the uniform fn set_float(&mut self, uniform_name: &str, value: f32) { self.underlying.set_float(uniform_name, value); } /// Set a 3-component vector in part of the memory put aside for the named uniform buffer /// /// uniform_name: The name of the uniform whose value should be set /// value: The value to set for the uniform fn set_vec3(&mut self, uniform_name: &str, value: &Vec3<f32>)
/// Set a 4x4-component matrix in part of the memory put aside for the named uniform buffer /// /// uniform_name: The name of the uniform whose value should be set /// value: The value to set for the uniform fn set_matrix(&mut self, uniform_name: &str, value: &Mat4<f32>) { self.underlying.set_matrix(uniform_name, value); } /// Set a floating point vector in part of the memory put aside for the named uniform buffer /// /// uniform_name: The name of the uniform whose value should be set /// value: The vector to set for the uniform fn set_float_vector(&mut self, uniform_name: &str, value: &Vec<f32>) { self.underlying.set_float_vector(uniform_name, value); } }
{ self.underlying.set_vec3(uniform_name, value); }
identifier_body
uniformbuffergl.rs
// Copyright (c) 2016-2018 Bruce Stenning. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS // OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED // AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. use std::os::raw::*; use std::mem; use graphics::uniformbuffer::*; use algebra::matrix::Mat4; use algebra::vector::Vec3; use gl; use gl::types::*; pub struct UniformBufferGl { pub underlying: UniformBufferBacking, pub ubo_handle: GLuint, }
pub fn new(data: &UniformBufferBacking, ubo_handle: GLuint) -> UniformBufferGl { UniformBufferGl { underlying: data.clone(), ubo_handle: ubo_handle, } } /// Return the uniform buffer object handle pub fn get_handle(&self) -> GLuint { self.ubo_handle } } impl UniformBuffer for UniformBufferGl { /// Synchronise the accumulated contents of the buffer with the graphics API fn synchronise(&self) { unsafe { gl::BindBuffer(gl::UNIFORM_BUFFER, self.ubo_handle); let src: *const c_void = mem::transmute(self.underlying.bytes.as_ptr()); gl::BufferSubData( gl::UNIFORM_BUFFER, 0, self.underlying.bytes.len() as isize, src, ); gl::BindBuffer(gl::UNIFORM_BUFFER, 0); } } /// Set a integer in part of the memory put aside for the named uniform buffer /// /// uniform_name: The name of the uniform whose value should be set /// value: The value to set for the uniform fn set_int(&mut self, uniform_name: &str, value: i32) { self.underlying.set_int(uniform_name, value); } /// Set a floating point in part of the memory put aside for the named uniform buffer /// /// uniform_name: The name of the uniform whose value should be set /// value: The value to set for the uniform fn set_float(&mut self, uniform_name: &str, value: f32) { self.underlying.set_float(uniform_name, value); } /// Set a 3-component vector in part of the memory put aside for the named uniform buffer /// /// uniform_name: The name of the uniform whose value should be set /// value: The value to set for the uniform fn set_vec3(&mut self, uniform_name: &str, value: &Vec3<f32>) { self.underlying.set_vec3(uniform_name, value); } /// Set a 4x4-component matrix in part of the memory put aside for the named uniform buffer /// /// uniform_name: The name of the uniform whose value should be set /// value: The value to set for the uniform fn set_matrix(&mut self, uniform_name: &str, value: &Mat4<f32>) { self.underlying.set_matrix(uniform_name, value); } /// Set a floating point vector in part of the memory put aside for the named uniform buffer /// /// uniform_name: The name of the uniform whose value should be set /// value: The vector to set for the uniform fn set_float_vector(&mut self, uniform_name: &str, value: &Vec<f32>) { self.underlying.set_float_vector(uniform_name, value); } }
impl UniformBufferGl { /// Constructor /// /// data: Raw data for the uniform buffer /// ubo_handle: The UBO object handle
random_line_split
uniformbuffergl.rs
// Copyright (c) 2016-2018 Bruce Stenning. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS // OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED // AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. use std::os::raw::*; use std::mem; use graphics::uniformbuffer::*; use algebra::matrix::Mat4; use algebra::vector::Vec3; use gl; use gl::types::*; pub struct UniformBufferGl { pub underlying: UniformBufferBacking, pub ubo_handle: GLuint, } impl UniformBufferGl { /// Constructor /// /// data: Raw data for the uniform buffer /// ubo_handle: The UBO object handle pub fn new(data: &UniformBufferBacking, ubo_handle: GLuint) -> UniformBufferGl { UniformBufferGl { underlying: data.clone(), ubo_handle: ubo_handle, } } /// Return the uniform buffer object handle pub fn get_handle(&self) -> GLuint { self.ubo_handle } } impl UniformBuffer for UniformBufferGl { /// Synchronise the accumulated contents of the buffer with the graphics API fn synchronise(&self) { unsafe { gl::BindBuffer(gl::UNIFORM_BUFFER, self.ubo_handle); let src: *const c_void = mem::transmute(self.underlying.bytes.as_ptr()); gl::BufferSubData( gl::UNIFORM_BUFFER, 0, self.underlying.bytes.len() as isize, src, ); gl::BindBuffer(gl::UNIFORM_BUFFER, 0); } } /// Set a integer in part of the memory put aside for the named uniform buffer /// /// uniform_name: The name of the uniform whose value should be set /// value: The value to set for the uniform fn set_int(&mut self, uniform_name: &str, value: i32) { self.underlying.set_int(uniform_name, value); } /// Set a floating point in part of the memory put aside for the named uniform buffer /// /// uniform_name: The name of the uniform whose value should be set /// value: The value to set for the uniform fn set_float(&mut self, uniform_name: &str, value: f32) { self.underlying.set_float(uniform_name, value); } /// Set a 3-component vector in part of the memory put aside for the named uniform buffer /// /// uniform_name: The name of the uniform whose value should be set /// value: The value to set for the uniform fn set_vec3(&mut self, uniform_name: &str, value: &Vec3<f32>) { self.underlying.set_vec3(uniform_name, value); } /// Set a 4x4-component matrix in part of the memory put aside for the named uniform buffer /// /// uniform_name: The name of the uniform whose value should be set /// value: The value to set for the uniform fn set_matrix(&mut self, uniform_name: &str, value: &Mat4<f32>) { self.underlying.set_matrix(uniform_name, value); } /// Set a floating point vector in part of the memory put aside for the named uniform buffer /// /// uniform_name: The name of the uniform whose value should be set /// value: The vector to set for the uniform fn
(&mut self, uniform_name: &str, value: &Vec<f32>) { self.underlying.set_float_vector(uniform_name, value); } }
set_float_vector
identifier_name
problem-0002.rs
/// Problem 2 /// /// Each new term in the Fibonacci sequence is generated by adding the previous /// two terms. By starting with 1 and 2, the first 10 terms will be: /// /// 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,... /// /// By considering the terms in the Fibonacci sequence whose values do not /// exceed four million, find the sum of the even-valued terms. fn main() { println!("Problem 2"); let mut fib_a: u32 = 1; let mut fib_b: u32 = 2; let mut sum_even: u32 = 2; loop { let fib_c: u32 = fib_a + fib_b; if fib_c > 4000000 { break } if (fib_c % 2) == 0
fib_a = fib_b; fib_b = fib_c; } println!("Answer: {}", sum_even); }
{ sum_even += fib_c; }
conditional_block
problem-0002.rs
/// Problem 2 /// /// Each new term in the Fibonacci sequence is generated by adding the previous /// two terms. By starting with 1 and 2, the first 10 terms will be: /// /// 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,... /// /// By considering the terms in the Fibonacci sequence whose values do not /// exceed four million, find the sum of the even-valued terms. fn main() { println!("Problem 2"); let mut fib_a: u32 = 1; let mut fib_b: u32 = 2; let mut sum_even: u32 = 2; loop { let fib_c: u32 = fib_a + fib_b; if fib_c > 4000000 { break } if (fib_c % 2) == 0 { sum_even += fib_c;
} println!("Answer: {}", sum_even); }
} fib_a = fib_b; fib_b = fib_c;
random_line_split
problem-0002.rs
/// Problem 2 /// /// Each new term in the Fibonacci sequence is generated by adding the previous /// two terms. By starting with 1 and 2, the first 10 terms will be: /// /// 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,... /// /// By considering the terms in the Fibonacci sequence whose values do not /// exceed four million, find the sum of the even-valued terms. fn main()
{ println!("Problem 2"); let mut fib_a: u32 = 1; let mut fib_b: u32 = 2; let mut sum_even: u32 = 2; loop { let fib_c: u32 = fib_a + fib_b; if fib_c > 4000000 { break } if (fib_c % 2) == 0 { sum_even += fib_c; } fib_a = fib_b; fib_b = fib_c; } println!("Answer: {}", sum_even); }
identifier_body
problem-0002.rs
/// Problem 2 /// /// Each new term in the Fibonacci sequence is generated by adding the previous /// two terms. By starting with 1 and 2, the first 10 terms will be: /// /// 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,... /// /// By considering the terms in the Fibonacci sequence whose values do not /// exceed four million, find the sum of the even-valued terms. fn
() { println!("Problem 2"); let mut fib_a: u32 = 1; let mut fib_b: u32 = 2; let mut sum_even: u32 = 2; loop { let fib_c: u32 = fib_a + fib_b; if fib_c > 4000000 { break } if (fib_c % 2) == 0 { sum_even += fib_c; } fib_a = fib_b; fib_b = fib_c; } println!("Answer: {}", sum_even); }
main
identifier_name
markdown.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. use collections::HashSet; use std::{str, io}; use std::strbuf::StrBuf; use getopts; use testing; use html::escape::Escape; use html::markdown::{MarkdownWithToc, find_testable_code, reset_headers}; use test::Collector; fn load_string(input: &Path) -> io::IoResult<Option<~str>> { let mut f = try!(io::File::open(input)); let d = try!(f.read_to_end()); Ok(str::from_utf8(d.as_slice()).map(|s| s.to_owned())) } macro_rules! load_or_return { ($input: expr, $cant_read: expr, $not_utf8: expr) => { { let input = Path::new($input); match load_string(&input) { Err(e) => { let _ = writeln!(&mut io::stderr(), "error reading `{}`: {}", input.display(), e); return $cant_read; } Ok(None) => { let _ = writeln!(&mut io::stderr(), "error reading `{}`: not UTF-8", input.display()); return $not_utf8; } Ok(Some(s)) => s } } } } /// Separate any lines at the start of the file that begin with `%`. fn extract_leading_metadata<'a>(s: &'a str) -> (Vec<&'a str>, &'a str) { let mut metadata = Vec::new(); for line in s.lines() { if line.starts_with("%") { // remove %<whitespace> metadata.push(line.slice_from(1).trim_left()) } else { let line_start_byte = s.subslice_offset(line); return (metadata, s.slice_from(line_start_byte)); } } // if we're here, then all lines were metadata % lines. (metadata, "") } fn load_external_files(names: &[~str]) -> Option<~str> { let mut out = StrBuf::new(); for name in names.iter() { out.push_str(load_or_return!(name.as_slice(), None, None)); out.push_char('\n'); } Some(out.into_owned()) } /// Render `input` (e.g. "foo.md") into an HTML file in `output` /// (e.g. output = "bar" => "bar/foo.html"). pub fn render(input: &str, mut output: Path, matches: &getopts::Matches) -> int { let input_p = Path::new(input); output.push(input_p.filestem().unwrap()); output.set_extension("html"); let mut css = StrBuf::new(); for name in matches.opt_strs("markdown-css").iter() { let s = format!("<link rel=\"stylesheet\" type=\"text/css\" href=\"{}\">\n", name); css.push_str(s) } let input_str = load_or_return!(input, 1, 2); let (in_header, before_content, after_content) = match (load_external_files(matches.opt_strs("markdown-in-header") .as_slice()), load_external_files(matches.opt_strs("markdown-before-content") .as_slice()), load_external_files(matches.opt_strs("markdown-after-content") .as_slice())) { (Some(a), Some(b), Some(c)) => (a,b,c), _ => return 3 }; let mut out = match io::File::create(&output) { Err(e) => { let _ = writeln!(&mut io::stderr(), "error opening `{}` for writing: {}", output.display(), e); return 4; } Ok(f) => f }; let (metadata, text) = extract_leading_metadata(input_str); if metadata.len() == 0 { let _ = writeln!(&mut io::stderr(), "invalid markdown file: expecting initial line with `%...TITLE...`"); return 5; } let title = metadata.get(0).as_slice(); reset_headers(); let err = write!( &mut out, r#"<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="generator" content="rustdoc"> <title>{title}</title> {css} {in_header} </head> <body> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> {before_content} <h1 class="title">{title}</h1> {text} {after_content} </body> </html>"#, title = Escape(title), css = css, in_header = in_header, before_content = before_content, text = MarkdownWithToc(text), after_content = after_content); match err { Err(e) => { let _ = writeln!(&mut io::stderr(), "error writing to `{}`: {}", output.display(), e); 6 } Ok(_) => 0 } } /// Run any tests/code examples in the markdown file `input`. pub fn
(input: &str, libs: HashSet<Path>, mut test_args: Vec<~str>) -> int { let input_str = load_or_return!(input, 1, 2); let mut collector = Collector::new(input.to_owned(), libs, true, true); find_testable_code(input_str, &mut collector); test_args.unshift(~"rustdoctest"); testing::test_main(test_args.as_slice(), collector.tests); 0 }
test
identifier_name
markdown.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. use collections::HashSet; use std::{str, io}; use std::strbuf::StrBuf; use getopts; use testing; use html::escape::Escape; use html::markdown::{MarkdownWithToc, find_testable_code, reset_headers}; use test::Collector; fn load_string(input: &Path) -> io::IoResult<Option<~str>> { let mut f = try!(io::File::open(input)); let d = try!(f.read_to_end()); Ok(str::from_utf8(d.as_slice()).map(|s| s.to_owned())) } macro_rules! load_or_return { ($input: expr, $cant_read: expr, $not_utf8: expr) => { { let input = Path::new($input); match load_string(&input) { Err(e) => { let _ = writeln!(&mut io::stderr(), "error reading `{}`: {}", input.display(), e); return $cant_read; } Ok(None) => { let _ = writeln!(&mut io::stderr(), "error reading `{}`: not UTF-8", input.display()); return $not_utf8; } Ok(Some(s)) => s } } } } /// Separate any lines at the start of the file that begin with `%`. fn extract_leading_metadata<'a>(s: &'a str) -> (Vec<&'a str>, &'a str) { let mut metadata = Vec::new(); for line in s.lines() { if line.starts_with("%") { // remove %<whitespace> metadata.push(line.slice_from(1).trim_left()) } else { let line_start_byte = s.subslice_offset(line); return (metadata, s.slice_from(line_start_byte)); } } // if we're here, then all lines were metadata % lines. (metadata, "") } fn load_external_files(names: &[~str]) -> Option<~str> { let mut out = StrBuf::new(); for name in names.iter() { out.push_str(load_or_return!(name.as_slice(), None, None)); out.push_char('\n'); } Some(out.into_owned()) }
output.push(input_p.filestem().unwrap()); output.set_extension("html"); let mut css = StrBuf::new(); for name in matches.opt_strs("markdown-css").iter() { let s = format!("<link rel=\"stylesheet\" type=\"text/css\" href=\"{}\">\n", name); css.push_str(s) } let input_str = load_or_return!(input, 1, 2); let (in_header, before_content, after_content) = match (load_external_files(matches.opt_strs("markdown-in-header") .as_slice()), load_external_files(matches.opt_strs("markdown-before-content") .as_slice()), load_external_files(matches.opt_strs("markdown-after-content") .as_slice())) { (Some(a), Some(b), Some(c)) => (a,b,c), _ => return 3 }; let mut out = match io::File::create(&output) { Err(e) => { let _ = writeln!(&mut io::stderr(), "error opening `{}` for writing: {}", output.display(), e); return 4; } Ok(f) => f }; let (metadata, text) = extract_leading_metadata(input_str); if metadata.len() == 0 { let _ = writeln!(&mut io::stderr(), "invalid markdown file: expecting initial line with `%...TITLE...`"); return 5; } let title = metadata.get(0).as_slice(); reset_headers(); let err = write!( &mut out, r#"<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="generator" content="rustdoc"> <title>{title}</title> {css} {in_header} </head> <body> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> {before_content} <h1 class="title">{title}</h1> {text} {after_content} </body> </html>"#, title = Escape(title), css = css, in_header = in_header, before_content = before_content, text = MarkdownWithToc(text), after_content = after_content); match err { Err(e) => { let _ = writeln!(&mut io::stderr(), "error writing to `{}`: {}", output.display(), e); 6 } Ok(_) => 0 } } /// Run any tests/code examples in the markdown file `input`. pub fn test(input: &str, libs: HashSet<Path>, mut test_args: Vec<~str>) -> int { let input_str = load_or_return!(input, 1, 2); let mut collector = Collector::new(input.to_owned(), libs, true, true); find_testable_code(input_str, &mut collector); test_args.unshift(~"rustdoctest"); testing::test_main(test_args.as_slice(), collector.tests); 0 }
/// Render `input` (e.g. "foo.md") into an HTML file in `output` /// (e.g. output = "bar" => "bar/foo.html"). pub fn render(input: &str, mut output: Path, matches: &getopts::Matches) -> int { let input_p = Path::new(input);
random_line_split
markdown.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. use collections::HashSet; use std::{str, io}; use std::strbuf::StrBuf; use getopts; use testing; use html::escape::Escape; use html::markdown::{MarkdownWithToc, find_testable_code, reset_headers}; use test::Collector; fn load_string(input: &Path) -> io::IoResult<Option<~str>> { let mut f = try!(io::File::open(input)); let d = try!(f.read_to_end()); Ok(str::from_utf8(d.as_slice()).map(|s| s.to_owned())) } macro_rules! load_or_return { ($input: expr, $cant_read: expr, $not_utf8: expr) => { { let input = Path::new($input); match load_string(&input) { Err(e) => { let _ = writeln!(&mut io::stderr(), "error reading `{}`: {}", input.display(), e); return $cant_read; } Ok(None) => { let _ = writeln!(&mut io::stderr(), "error reading `{}`: not UTF-8", input.display()); return $not_utf8; } Ok(Some(s)) => s } } } } /// Separate any lines at the start of the file that begin with `%`. fn extract_leading_metadata<'a>(s: &'a str) -> (Vec<&'a str>, &'a str) { let mut metadata = Vec::new(); for line in s.lines() { if line.starts_with("%") { // remove %<whitespace> metadata.push(line.slice_from(1).trim_left()) } else { let line_start_byte = s.subslice_offset(line); return (metadata, s.slice_from(line_start_byte)); } } // if we're here, then all lines were metadata % lines. (metadata, "") } fn load_external_files(names: &[~str]) -> Option<~str> { let mut out = StrBuf::new(); for name in names.iter() { out.push_str(load_or_return!(name.as_slice(), None, None)); out.push_char('\n'); } Some(out.into_owned()) } /// Render `input` (e.g. "foo.md") into an HTML file in `output` /// (e.g. output = "bar" => "bar/foo.html"). pub fn render(input: &str, mut output: Path, matches: &getopts::Matches) -> int { let input_p = Path::new(input); output.push(input_p.filestem().unwrap()); output.set_extension("html"); let mut css = StrBuf::new(); for name in matches.opt_strs("markdown-css").iter() { let s = format!("<link rel=\"stylesheet\" type=\"text/css\" href=\"{}\">\n", name); css.push_str(s) } let input_str = load_or_return!(input, 1, 2); let (in_header, before_content, after_content) = match (load_external_files(matches.opt_strs("markdown-in-header") .as_slice()), load_external_files(matches.opt_strs("markdown-before-content") .as_slice()), load_external_files(matches.opt_strs("markdown-after-content") .as_slice())) { (Some(a), Some(b), Some(c)) => (a,b,c), _ => return 3 }; let mut out = match io::File::create(&output) { Err(e) =>
Ok(f) => f }; let (metadata, text) = extract_leading_metadata(input_str); if metadata.len() == 0 { let _ = writeln!(&mut io::stderr(), "invalid markdown file: expecting initial line with `%...TITLE...`"); return 5; } let title = metadata.get(0).as_slice(); reset_headers(); let err = write!( &mut out, r#"<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="generator" content="rustdoc"> <title>{title}</title> {css} {in_header} </head> <body> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> {before_content} <h1 class="title">{title}</h1> {text} {after_content} </body> </html>"#, title = Escape(title), css = css, in_header = in_header, before_content = before_content, text = MarkdownWithToc(text), after_content = after_content); match err { Err(e) => { let _ = writeln!(&mut io::stderr(), "error writing to `{}`: {}", output.display(), e); 6 } Ok(_) => 0 } } /// Run any tests/code examples in the markdown file `input`. pub fn test(input: &str, libs: HashSet<Path>, mut test_args: Vec<~str>) -> int { let input_str = load_or_return!(input, 1, 2); let mut collector = Collector::new(input.to_owned(), libs, true, true); find_testable_code(input_str, &mut collector); test_args.unshift(~"rustdoctest"); testing::test_main(test_args.as_slice(), collector.tests); 0 }
{ let _ = writeln!(&mut io::stderr(), "error opening `{}` for writing: {}", output.display(), e); return 4; }
conditional_block
markdown.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. use collections::HashSet; use std::{str, io}; use std::strbuf::StrBuf; use getopts; use testing; use html::escape::Escape; use html::markdown::{MarkdownWithToc, find_testable_code, reset_headers}; use test::Collector; fn load_string(input: &Path) -> io::IoResult<Option<~str>> { let mut f = try!(io::File::open(input)); let d = try!(f.read_to_end()); Ok(str::from_utf8(d.as_slice()).map(|s| s.to_owned())) } macro_rules! load_or_return { ($input: expr, $cant_read: expr, $not_utf8: expr) => { { let input = Path::new($input); match load_string(&input) { Err(e) => { let _ = writeln!(&mut io::stderr(), "error reading `{}`: {}", input.display(), e); return $cant_read; } Ok(None) => { let _ = writeln!(&mut io::stderr(), "error reading `{}`: not UTF-8", input.display()); return $not_utf8; } Ok(Some(s)) => s } } } } /// Separate any lines at the start of the file that begin with `%`. fn extract_leading_metadata<'a>(s: &'a str) -> (Vec<&'a str>, &'a str)
fn load_external_files(names: &[~str]) -> Option<~str> { let mut out = StrBuf::new(); for name in names.iter() { out.push_str(load_or_return!(name.as_slice(), None, None)); out.push_char('\n'); } Some(out.into_owned()) } /// Render `input` (e.g. "foo.md") into an HTML file in `output` /// (e.g. output = "bar" => "bar/foo.html"). pub fn render(input: &str, mut output: Path, matches: &getopts::Matches) -> int { let input_p = Path::new(input); output.push(input_p.filestem().unwrap()); output.set_extension("html"); let mut css = StrBuf::new(); for name in matches.opt_strs("markdown-css").iter() { let s = format!("<link rel=\"stylesheet\" type=\"text/css\" href=\"{}\">\n", name); css.push_str(s) } let input_str = load_or_return!(input, 1, 2); let (in_header, before_content, after_content) = match (load_external_files(matches.opt_strs("markdown-in-header") .as_slice()), load_external_files(matches.opt_strs("markdown-before-content") .as_slice()), load_external_files(matches.opt_strs("markdown-after-content") .as_slice())) { (Some(a), Some(b), Some(c)) => (a,b,c), _ => return 3 }; let mut out = match io::File::create(&output) { Err(e) => { let _ = writeln!(&mut io::stderr(), "error opening `{}` for writing: {}", output.display(), e); return 4; } Ok(f) => f }; let (metadata, text) = extract_leading_metadata(input_str); if metadata.len() == 0 { let _ = writeln!(&mut io::stderr(), "invalid markdown file: expecting initial line with `%...TITLE...`"); return 5; } let title = metadata.get(0).as_slice(); reset_headers(); let err = write!( &mut out, r#"<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="generator" content="rustdoc"> <title>{title}</title> {css} {in_header} </head> <body> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> {before_content} <h1 class="title">{title}</h1> {text} {after_content} </body> </html>"#, title = Escape(title), css = css, in_header = in_header, before_content = before_content, text = MarkdownWithToc(text), after_content = after_content); match err { Err(e) => { let _ = writeln!(&mut io::stderr(), "error writing to `{}`: {}", output.display(), e); 6 } Ok(_) => 0 } } /// Run any tests/code examples in the markdown file `input`. pub fn test(input: &str, libs: HashSet<Path>, mut test_args: Vec<~str>) -> int { let input_str = load_or_return!(input, 1, 2); let mut collector = Collector::new(input.to_owned(), libs, true, true); find_testable_code(input_str, &mut collector); test_args.unshift(~"rustdoctest"); testing::test_main(test_args.as_slice(), collector.tests); 0 }
{ let mut metadata = Vec::new(); for line in s.lines() { if line.starts_with("%") { // remove %<whitespace> metadata.push(line.slice_from(1).trim_left()) } else { let line_start_byte = s.subslice_offset(line); return (metadata, s.slice_from(line_start_byte)); } } // if we're here, then all lines were metadata % lines. (metadata, "") }
identifier_body
linkhack.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/. */ // Some crumminess to make sure we link correctly #[cfg(target_os = "linux")] #[link(name = "pthread")] #[link(name = "js_static")] #[link(name = "stdc++")] #[link(name = "z")] extern { } #[cfg(target_os = "macos")]
#[link(name = "js_static")] #[link(name = "stdc++")] #[link(name = "z")] extern { } //Avoid hard linking with stdc++ in android ndk cross toolchain //It is hard to find location of android system libs in this rust source file //and also we need to size down for mobile app packaging #[cfg(target_os = "android")] #[link(name = "js_static")] #[link(name = "stdc++")] #[link(name = "z")] extern { }
random_line_split
token.rs
Literals */ LIT_INT(i64, ast::int_ty), LIT_UINT(u64, ast::uint_ty), LIT_INT_UNSUFFIXED(i64), LIT_FLOAT(ast::ident, ast::float_ty), LIT_FLOAT_UNSUFFIXED(ast::ident), LIT_STR(ast::ident), /* Name components */ // an identifier contains an "is_mod_name" boolean, // indicating whether :: follows this token with no // whitespace in between. IDENT(ast::ident, bool), UNDERSCORE, LIFETIME(ast::ident), /* For interpolation */ INTERPOLATED(nonterminal), DOC_COMMENT(ast::ident), EOF, } #[deriving(Encodable, Decodable, Eq, IterBytes)] /// For interpolation during macro expansion. pub enum nonterminal { nt_item(@ast::item), nt_block(ast::blk), nt_stmt(@ast::stmt), nt_pat( @ast::pat), nt_expr(@ast::expr), nt_ty( ast::Ty), nt_ident(ast::ident, bool), nt_path( ast::Path), nt_tt( @ast::token_tree), //needs @ed to break a circularity nt_matchers(~[ast::matcher]) } pub fn
(o: binop) -> ~str { match o { PLUS => ~"+", MINUS => ~"-", STAR => ~"*", SLASH => ~"/", PERCENT => ~"%", CARET => ~"^", AND => ~"&", OR => ~"|", SHL => ~"<<", SHR => ~">>" } } pub fn to_str(in: @ident_interner, t: &Token) -> ~str { match *t { EQ => ~"=", LT => ~"<", LE => ~"<=", EQEQ => ~"==", NE => ~"!=", GE => ~">=", GT => ~">", NOT => ~"!", TILDE => ~"~", OROR => ~"||", ANDAND => ~"&&", BINOP(op) => binop_to_str(op), BINOPEQ(op) => binop_to_str(op) + "=", /* Structural symbols */ AT => ~"@", DOT => ~".", DOTDOT => ~"..", COMMA => ~",", SEMI => ~";", COLON => ~":", MOD_SEP => ~"::", RARROW => ~"->", LARROW => ~"<-", DARROW => ~"<->", FAT_ARROW => ~"=>", LPAREN => ~"(", RPAREN => ~")", LBRACKET => ~"[", RBRACKET => ~"]", LBRACE => ~"{", RBRACE => ~"}", POUND => ~"#", DOLLAR => ~"$", /* Literals */ LIT_INT(c, ast::ty_char) => { let mut res = ~"'"; do (c as char).escape_default |c| { res.push_char(c); } res.push_char('\''); res } LIT_INT(i, t) => { i.to_str() + ast_util::int_ty_to_str(t) } LIT_UINT(u, t) => { u.to_str() + ast_util::uint_ty_to_str(t) } LIT_INT_UNSUFFIXED(i) => { i.to_str() } LIT_FLOAT(ref s, t) => { let mut body = ident_to_str(s).to_owned(); if body.ends_with(".") { body.push_char('0'); // `10.f` is not a float literal } body + ast_util::float_ty_to_str(t) } LIT_FLOAT_UNSUFFIXED(ref s) => { let mut body = ident_to_str(s).to_owned(); if body.ends_with(".") { body.push_char('0'); // `10.f` is not a float literal } body } LIT_STR(ref s) => { fmt!("\"%s\"", ident_to_str(s).escape_default()) } /* Name components */ IDENT(s, _) => in.get(s.name).to_owned(), LIFETIME(s) => fmt!("'%s", in.get(s.name)), UNDERSCORE => ~"_", /* Other */ DOC_COMMENT(ref s) => ident_to_str(s).to_owned(), EOF => ~"<eof>", INTERPOLATED(ref nt) => { match nt { &nt_expr(e) => ::print::pprust::expr_to_str(e, in), _ => { ~"an interpolated " + match (*nt) { nt_item(*) => ~"item", nt_block(*) => ~"block", nt_stmt(*) => ~"statement", nt_pat(*) => ~"pattern", nt_expr(*) => fail!("should have been handled above"), nt_ty(*) => ~"type", nt_ident(*) => ~"identifier", nt_path(*) => ~"path", nt_tt(*) => ~"tt", nt_matchers(*) => ~"matcher sequence" } } } } } } pub fn can_begin_expr(t: &Token) -> bool { match *t { LPAREN => true, LBRACE => true, LBRACKET => true, IDENT(_, _) => true, UNDERSCORE => true, TILDE => true, LIT_INT(_, _) => true, LIT_UINT(_, _) => true, LIT_INT_UNSUFFIXED(_) => true, LIT_FLOAT(_, _) => true, LIT_FLOAT_UNSUFFIXED(_) => true, LIT_STR(_) => true, POUND => true, AT => true, NOT => true, BINOP(MINUS) => true, BINOP(STAR) => true, BINOP(AND) => true, BINOP(OR) => true, // in lambda syntax OROR => true, // in lambda syntax MOD_SEP => true, INTERPOLATED(nt_expr(*)) | INTERPOLATED(nt_ident(*)) | INTERPOLATED(nt_block(*)) | INTERPOLATED(nt_path(*)) => true, _ => false } } /// what's the opposite delimiter? pub fn flip_delimiter(t: &token::Token) -> token::Token { match *t { LPAREN => RPAREN, LBRACE => RBRACE, LBRACKET => RBRACKET, RPAREN => LPAREN, RBRACE => LBRACE, RBRACKET => LBRACKET, _ => fail!() } } pub fn is_lit(t: &Token) -> bool { match *t { LIT_INT(_, _) => true, LIT_UINT(_, _) => true, LIT_INT_UNSUFFIXED(_) => true, LIT_FLOAT(_, _) => true, LIT_FLOAT_UNSUFFIXED(_) => true, LIT_STR(_) => true, _ => false } } pub fn is_ident(t: &Token) -> bool { match *t { IDENT(_, _) => true, _ => false } } pub fn is_ident_or_path(t: &Token) -> bool { match *t { IDENT(_, _) | INTERPOLATED(nt_path(*)) => true, _ => false } } pub fn is_plain_ident(t: &Token) -> bool { match *t { IDENT(_, false) => true, _ => false } } pub fn is_bar(t: &Token) -> bool { match *t { BINOP(OR) | OROR => true, _ => false } } pub mod special_idents { use ast::ident; pub static underscore : ident = ident { name: 0, ctxt: 0}; pub static anon : ident = ident { name: 1, ctxt: 0}; pub static invalid : ident = ident { name: 2, ctxt: 0}; // '' pub static unary : ident = ident { name: 3, ctxt: 0}; pub static not_fn : ident = ident { name: 4, ctxt: 0}; pub static idx_fn : ident = ident { name: 5, ctxt: 0}; pub static unary_minus_fn : ident = ident { name: 6, ctxt: 0}; pub static clownshoes_extensions : ident = ident { name: 7, ctxt: 0}; pub static self_ : ident = ident { name: 8, ctxt: 0}; //'self' /* for matcher NTs */ pub static item : ident = ident { name: 9, ctxt: 0}; pub static block : ident = ident { name: 10, ctxt: 0}; pub static stmt : ident = ident { name: 11, ctxt: 0}; pub static pat : ident = ident { name: 12, ctxt: 0}; pub static expr : ident = ident { name: 13, ctxt: 0}; pub static ty : ident = ident { name: 14, ctxt: 0}; pub static ident : ident = ident { name: 15, ctxt: 0}; pub static path : ident = ident { name: 16, ctxt: 0}; pub static tt : ident = ident { name: 17, ctxt: 0}; pub static matchers : ident = ident { name: 18, ctxt: 0}; pub static str : ident = ident { name: 19, ctxt: 0}; // for the type /* outside of libsyntax */ pub static arg : ident = ident { name: 20, ctxt: 0}; pub static descrim : ident = ident { name: 21, ctxt: 0}; pub static clownshoe_abi : ident = ident { name: 22, ctxt: 0}; pub static clownshoe_stack_shim : ident = ident { name: 23, ctxt: 0}; pub static main : ident = ident { name: 24, ctxt: 0}; pub static opaque : ident = ident { name: 25, ctxt: 0}; pub static blk : ident = ident { name: 26, ctxt: 0}; pub static statik : ident = ident { name: 27, ctxt: 0}; pub static clownshoes_foreign_mod: ident = ident { name: 28, ctxt: 0}; pub static unnamed_field: ident = ident { name: 29, ctxt: 0}; pub static c_abi: ident = ident { name: 30, ctxt: 0}; pub static type_self: ident = ident { name: 31, ctxt: 0}; // `Self` } /** * Maps a token to a record specifying the corresponding binary * operator */ pub fn token_to_binop(tok: Token) -> Option<ast::binop> { match tok { BINOP(STAR) => Some(ast::mul), BINOP(SLASH) => Some(ast::div), BINOP(PERCENT) => Some(ast::rem), BINOP(PLUS) => Some(ast::add), BINOP(MINUS) => Some(ast::subtract), BINOP(SHL) => Some(ast::shl), BINOP(SHR) => Some(ast::shr), BINOP(AND) => Some(ast::bitand), BINOP(CARET) => Some(ast::bitxor), BINOP(OR) => Some(ast::bitor), LT => Some(ast::lt), LE => Some(ast::le), GE => Some(ast::ge), GT => Some(ast::gt), EQEQ => Some(ast::eq), NE => Some(ast::ne), ANDAND => Some(ast::and), OROR => Some(ast::or), _ => None } } pub struct ident_interner { priv interner: StrInterner, } impl ident_interner { pub fn intern(&self, val: &str) -> Name { self.interner.intern(val) } pub fn gensym(&self, val: &str) -> Name { self.interner.gensym(val) } pub fn get(&self, idx: Name) -> @str { self.interner.get(idx) } // is this really something that should be exposed? pub fn len(&self) -> uint { self.interner.len() } pub fn find_equiv<Q:Hash + IterBytes + Equiv<@str>>(&self, val: &Q) -> Option<Name> { self.interner.find_equiv(val) } } // return a fresh interner, preloaded with special identifiers. fn mk_fresh_ident_interner() -> @ident_interner { // the indices here must correspond to the numbers in // special_idents. let init_vec = ~[ "_", // 0 "anon", // 1 "", // 2 "unary", // 3 "!", // 4 "[]", // 5 "unary-", // 6 "__extensions__", // 7 "self", // 8 "item", // 9 "block", // 10 "stmt", // 11 "pat", // 12 "expr", // 13 "ty", // 14 "ident", // 15 "path", // 16 "tt", // 17 "matchers", // 18 "str", // 19 "arg", // 20 "descrim", // 21 "__rust_abi", // 22 "__rust_stack_shim", // 23 "main", // 24 "<opaque>", // 25 "blk", // 26 "static", // 27 "__foreign_mod__", // 28 "__field__", // 29 "C", // 30 "Self", // 31 "as", // 32 "break", // 33 "const", // 34 "copy", // 35 "do", // 36 "else", // 37 "enum", // 38 "extern", // 39 "false", // 40 "fn", // 41 "for", // 42 "if", // 43 "impl", // 44 "let", // 45 "__log", // 46 "loop", // 47 "match", // 48 "mod", // 49 "mut", // 50 "once", // 51 "priv", // 52 "pub", // 53 "pure", // 54 "ref", // 55 "return", // 56 "static", // 27 -- also a special ident "self", // 8 -- also a special ident "struct", // 57 "super", // 58 "true", // 59 "trait", // 60 "type", // 61 "unsafe", // 62 "use", // 63 "while", // 64 "be", // 65 ]; @ident_interner { interner: interner::StrInterner::prefill(init_vec) } } // if an interner exists in TLS, return it. Otherwise, prepare a // fresh one. pub fn get_ident_interner() -> @ident_interner { #[cfg(not(stage0))] static key: local_data::Key<@@::parse::token::ident_interner> = &local_data::Key; #[cfg(stage0)] fn key(_: @@::parse::token::ident_interner) {} match local_data::get(key, |k| k.map(|&k| *k)) { Some(interner) => *interner, None => { let interner = mk_fresh_ident_interner(); local_data::set(key, @interner); interner } } } /* for when we don't care about the contents; doesn't interact with TLD or serialization */ pub fn mk_fake_ident_interner() -> @ident_interner { @ident_interner { interner: interner::StrInterner::new() } } // maps a string to its interned representation pub fn intern(str : &str) -> Name { let interner = get_ident_interner(); interner.intern(str) } // gensyms a new uint, using the current interner pub fn gensym(str : &str) -> Name { let interner = get_ident_interner(); interner.gensym(str) } // map an interned representation back to a string pub fn interner_get(name : Name) -> @str { get_ident_interner().get(name) } // maps an identifier to the string that it corresponds to pub fn ident_to_str(id : &ast::ident) -> @str { interner_get(id.name) } // maps a string to an identifier with an empty syntax context pub fn str_to_ident(str : &str) -> ast::ident { ast::new_ident(intern(str)) } // maps a string to a gensym'ed identifier pub fn gensym_ident(str : &str) -> ast::ident { ast::new_ident(gensym(str)) } // create a fresh name. In principle, this is just a // gensym, but for debugging purposes, you'd like the // resulting name to have a suggestive stringify, without // paying the cost of guaranteeing that the name is // truly unique. I'm going to try to strike a balance // by using a gensym with a name that has a random number // at the end. So, the gensym guarantees the uniqueness, // and the int helps to avoid confusion. pub fn fresh_name(src_name : &str) -> Name { let num = rand::rng().gen_uint_range(0,0xffff); gensym(fmt!("%s_%u",src_name,num)) } /** * All the valid words that have meaning in the Rust language. * * Rust keywords are either'strict' or'reserved'. Strict keywords may not * appear as identifiers at all. Reserved keywords are not used anywhere in * the language and may not appear as identifiers. */ pub mod keywords { use ast::ident; pub enum Keyword { // Strict keywords As, Break, Const, Copy, Do, Else, Enum, Extern, False, Fn, For, If, Impl, Let, __Log, Loop, Match, Mod, Mut, Once, Priv, Pub, Pure, Ref, Return, Static, Self, Struct, Super, True, Trait, Type, Unsafe, Use, While, // Reserved keywords Be, } impl Keyword { pub fn to_ident(&self) -> ident { match *self { As => ident { name: 32, ctxt: 0 }, Break => ident { name: 33, ctxt: 0 }, Const => ident { name: 34, ctxt: 0 }, Copy => ident { name: 35, ctxt: 0 }, Do => ident { name: 36, ctxt: 0 }, Else => ident { name: 37, ctxt: 0 }, Enum => ident { name: 38, ctxt: 0 }, Extern => ident { name: 39, ctxt: 0 }, False => ident { name: 40, ctxt: 0 }, Fn => ident { name: 41, ctxt
binop_to_str
identifier_name
token.rs
LBRACE => ~"{", RBRACE => ~"}", POUND => ~"#", DOLLAR => ~"$", /* Literals */ LIT_INT(c, ast::ty_char) => { let mut res = ~"'"; do (c as char).escape_default |c| { res.push_char(c); } res.push_char('\''); res } LIT_INT(i, t) => { i.to_str() + ast_util::int_ty_to_str(t) } LIT_UINT(u, t) => { u.to_str() + ast_util::uint_ty_to_str(t) } LIT_INT_UNSUFFIXED(i) => { i.to_str() } LIT_FLOAT(ref s, t) => { let mut body = ident_to_str(s).to_owned(); if body.ends_with(".") { body.push_char('0'); // `10.f` is not a float literal } body + ast_util::float_ty_to_str(t) } LIT_FLOAT_UNSUFFIXED(ref s) => { let mut body = ident_to_str(s).to_owned(); if body.ends_with(".") { body.push_char('0'); // `10.f` is not a float literal } body } LIT_STR(ref s) => { fmt!("\"%s\"", ident_to_str(s).escape_default()) } /* Name components */ IDENT(s, _) => in.get(s.name).to_owned(), LIFETIME(s) => fmt!("'%s", in.get(s.name)), UNDERSCORE => ~"_", /* Other */ DOC_COMMENT(ref s) => ident_to_str(s).to_owned(), EOF => ~"<eof>", INTERPOLATED(ref nt) => { match nt { &nt_expr(e) => ::print::pprust::expr_to_str(e, in), _ => { ~"an interpolated " + match (*nt) { nt_item(*) => ~"item", nt_block(*) => ~"block", nt_stmt(*) => ~"statement", nt_pat(*) => ~"pattern", nt_expr(*) => fail!("should have been handled above"), nt_ty(*) => ~"type", nt_ident(*) => ~"identifier", nt_path(*) => ~"path", nt_tt(*) => ~"tt", nt_matchers(*) => ~"matcher sequence" } } } } } } pub fn can_begin_expr(t: &Token) -> bool { match *t { LPAREN => true, LBRACE => true, LBRACKET => true, IDENT(_, _) => true, UNDERSCORE => true, TILDE => true, LIT_INT(_, _) => true, LIT_UINT(_, _) => true, LIT_INT_UNSUFFIXED(_) => true, LIT_FLOAT(_, _) => true, LIT_FLOAT_UNSUFFIXED(_) => true, LIT_STR(_) => true, POUND => true, AT => true, NOT => true, BINOP(MINUS) => true, BINOP(STAR) => true, BINOP(AND) => true, BINOP(OR) => true, // in lambda syntax OROR => true, // in lambda syntax MOD_SEP => true, INTERPOLATED(nt_expr(*)) | INTERPOLATED(nt_ident(*)) | INTERPOLATED(nt_block(*)) | INTERPOLATED(nt_path(*)) => true, _ => false } } /// what's the opposite delimiter? pub fn flip_delimiter(t: &token::Token) -> token::Token { match *t { LPAREN => RPAREN, LBRACE => RBRACE, LBRACKET => RBRACKET, RPAREN => LPAREN, RBRACE => LBRACE, RBRACKET => LBRACKET, _ => fail!() } } pub fn is_lit(t: &Token) -> bool { match *t { LIT_INT(_, _) => true, LIT_UINT(_, _) => true, LIT_INT_UNSUFFIXED(_) => true, LIT_FLOAT(_, _) => true, LIT_FLOAT_UNSUFFIXED(_) => true, LIT_STR(_) => true, _ => false } } pub fn is_ident(t: &Token) -> bool { match *t { IDENT(_, _) => true, _ => false } } pub fn is_ident_or_path(t: &Token) -> bool { match *t { IDENT(_, _) | INTERPOLATED(nt_path(*)) => true, _ => false } } pub fn is_plain_ident(t: &Token) -> bool { match *t { IDENT(_, false) => true, _ => false } } pub fn is_bar(t: &Token) -> bool { match *t { BINOP(OR) | OROR => true, _ => false } } pub mod special_idents { use ast::ident; pub static underscore : ident = ident { name: 0, ctxt: 0}; pub static anon : ident = ident { name: 1, ctxt: 0}; pub static invalid : ident = ident { name: 2, ctxt: 0}; // '' pub static unary : ident = ident { name: 3, ctxt: 0}; pub static not_fn : ident = ident { name: 4, ctxt: 0}; pub static idx_fn : ident = ident { name: 5, ctxt: 0}; pub static unary_minus_fn : ident = ident { name: 6, ctxt: 0}; pub static clownshoes_extensions : ident = ident { name: 7, ctxt: 0}; pub static self_ : ident = ident { name: 8, ctxt: 0}; //'self' /* for matcher NTs */ pub static item : ident = ident { name: 9, ctxt: 0}; pub static block : ident = ident { name: 10, ctxt: 0}; pub static stmt : ident = ident { name: 11, ctxt: 0}; pub static pat : ident = ident { name: 12, ctxt: 0}; pub static expr : ident = ident { name: 13, ctxt: 0}; pub static ty : ident = ident { name: 14, ctxt: 0}; pub static ident : ident = ident { name: 15, ctxt: 0}; pub static path : ident = ident { name: 16, ctxt: 0}; pub static tt : ident = ident { name: 17, ctxt: 0}; pub static matchers : ident = ident { name: 18, ctxt: 0}; pub static str : ident = ident { name: 19, ctxt: 0}; // for the type /* outside of libsyntax */ pub static arg : ident = ident { name: 20, ctxt: 0}; pub static descrim : ident = ident { name: 21, ctxt: 0}; pub static clownshoe_abi : ident = ident { name: 22, ctxt: 0}; pub static clownshoe_stack_shim : ident = ident { name: 23, ctxt: 0}; pub static main : ident = ident { name: 24, ctxt: 0}; pub static opaque : ident = ident { name: 25, ctxt: 0}; pub static blk : ident = ident { name: 26, ctxt: 0}; pub static statik : ident = ident { name: 27, ctxt: 0}; pub static clownshoes_foreign_mod: ident = ident { name: 28, ctxt: 0}; pub static unnamed_field: ident = ident { name: 29, ctxt: 0}; pub static c_abi: ident = ident { name: 30, ctxt: 0}; pub static type_self: ident = ident { name: 31, ctxt: 0}; // `Self` } /** * Maps a token to a record specifying the corresponding binary * operator */ pub fn token_to_binop(tok: Token) -> Option<ast::binop> { match tok { BINOP(STAR) => Some(ast::mul), BINOP(SLASH) => Some(ast::div), BINOP(PERCENT) => Some(ast::rem), BINOP(PLUS) => Some(ast::add), BINOP(MINUS) => Some(ast::subtract), BINOP(SHL) => Some(ast::shl), BINOP(SHR) => Some(ast::shr), BINOP(AND) => Some(ast::bitand), BINOP(CARET) => Some(ast::bitxor), BINOP(OR) => Some(ast::bitor), LT => Some(ast::lt), LE => Some(ast::le), GE => Some(ast::ge), GT => Some(ast::gt), EQEQ => Some(ast::eq), NE => Some(ast::ne), ANDAND => Some(ast::and), OROR => Some(ast::or), _ => None } } pub struct ident_interner { priv interner: StrInterner, } impl ident_interner { pub fn intern(&self, val: &str) -> Name { self.interner.intern(val) } pub fn gensym(&self, val: &str) -> Name { self.interner.gensym(val) } pub fn get(&self, idx: Name) -> @str { self.interner.get(idx) } // is this really something that should be exposed? pub fn len(&self) -> uint { self.interner.len() } pub fn find_equiv<Q:Hash + IterBytes + Equiv<@str>>(&self, val: &Q) -> Option<Name> { self.interner.find_equiv(val) } } // return a fresh interner, preloaded with special identifiers. fn mk_fresh_ident_interner() -> @ident_interner { // the indices here must correspond to the numbers in // special_idents. let init_vec = ~[ "_", // 0 "anon", // 1 "", // 2 "unary", // 3 "!", // 4 "[]", // 5 "unary-", // 6 "__extensions__", // 7 "self", // 8 "item", // 9 "block", // 10 "stmt", // 11 "pat", // 12 "expr", // 13 "ty", // 14 "ident", // 15 "path", // 16 "tt", // 17 "matchers", // 18 "str", // 19 "arg", // 20 "descrim", // 21 "__rust_abi", // 22 "__rust_stack_shim", // 23 "main", // 24 "<opaque>", // 25 "blk", // 26 "static", // 27 "__foreign_mod__", // 28 "__field__", // 29 "C", // 30 "Self", // 31 "as", // 32 "break", // 33 "const", // 34 "copy", // 35 "do", // 36 "else", // 37 "enum", // 38 "extern", // 39 "false", // 40 "fn", // 41 "for", // 42 "if", // 43 "impl", // 44 "let", // 45 "__log", // 46 "loop", // 47 "match", // 48 "mod", // 49 "mut", // 50 "once", // 51 "priv", // 52 "pub", // 53 "pure", // 54 "ref", // 55 "return", // 56 "static", // 27 -- also a special ident "self", // 8 -- also a special ident "struct", // 57 "super", // 58 "true", // 59 "trait", // 60 "type", // 61 "unsafe", // 62 "use", // 63 "while", // 64 "be", // 65 ]; @ident_interner { interner: interner::StrInterner::prefill(init_vec) } } // if an interner exists in TLS, return it. Otherwise, prepare a // fresh one. pub fn get_ident_interner() -> @ident_interner { #[cfg(not(stage0))] static key: local_data::Key<@@::parse::token::ident_interner> = &local_data::Key; #[cfg(stage0)] fn key(_: @@::parse::token::ident_interner) {} match local_data::get(key, |k| k.map(|&k| *k)) { Some(interner) => *interner, None => { let interner = mk_fresh_ident_interner(); local_data::set(key, @interner); interner } } } /* for when we don't care about the contents; doesn't interact with TLD or serialization */ pub fn mk_fake_ident_interner() -> @ident_interner { @ident_interner { interner: interner::StrInterner::new() } } // maps a string to its interned representation pub fn intern(str : &str) -> Name { let interner = get_ident_interner(); interner.intern(str) } // gensyms a new uint, using the current interner pub fn gensym(str : &str) -> Name { let interner = get_ident_interner(); interner.gensym(str) } // map an interned representation back to a string pub fn interner_get(name : Name) -> @str { get_ident_interner().get(name) } // maps an identifier to the string that it corresponds to pub fn ident_to_str(id : &ast::ident) -> @str { interner_get(id.name) } // maps a string to an identifier with an empty syntax context pub fn str_to_ident(str : &str) -> ast::ident { ast::new_ident(intern(str)) } // maps a string to a gensym'ed identifier pub fn gensym_ident(str : &str) -> ast::ident { ast::new_ident(gensym(str)) } // create a fresh name. In principle, this is just a // gensym, but for debugging purposes, you'd like the // resulting name to have a suggestive stringify, without // paying the cost of guaranteeing that the name is // truly unique. I'm going to try to strike a balance // by using a gensym with a name that has a random number // at the end. So, the gensym guarantees the uniqueness, // and the int helps to avoid confusion. pub fn fresh_name(src_name : &str) -> Name { let num = rand::rng().gen_uint_range(0,0xffff); gensym(fmt!("%s_%u",src_name,num)) } /** * All the valid words that have meaning in the Rust language. * * Rust keywords are either'strict' or'reserved'. Strict keywords may not * appear as identifiers at all. Reserved keywords are not used anywhere in * the language and may not appear as identifiers. */ pub mod keywords { use ast::ident; pub enum Keyword { // Strict keywords As, Break, Const, Copy, Do, Else, Enum, Extern, False, Fn, For, If, Impl, Let, __Log, Loop, Match, Mod, Mut, Once, Priv, Pub, Pure, Ref, Return, Static, Self, Struct, Super, True, Trait, Type, Unsafe, Use, While, // Reserved keywords Be, } impl Keyword { pub fn to_ident(&self) -> ident { match *self { As => ident { name: 32, ctxt: 0 }, Break => ident { name: 33, ctxt: 0 }, Const => ident { name: 34, ctxt: 0 }, Copy => ident { name: 35, ctxt: 0 }, Do => ident { name: 36, ctxt: 0 }, Else => ident { name: 37, ctxt: 0 }, Enum => ident { name: 38, ctxt: 0 }, Extern => ident { name: 39, ctxt: 0 }, False => ident { name: 40, ctxt: 0 }, Fn => ident { name: 41, ctxt: 0 }, For => ident { name: 42, ctxt: 0 }, If => ident { name: 43, ctxt: 0 }, Impl => ident { name: 44, ctxt: 0 }, Let => ident { name: 45, ctxt: 0 }, __Log => ident { name: 46, ctxt: 0 }, Loop => ident { name: 47, ctxt: 0 }, Match => ident { name: 48, ctxt: 0 }, Mod => ident { name: 49, ctxt: 0 }, Mut => ident { name: 50, ctxt: 0 }, Once => ident { name: 51, ctxt: 0 }, Priv => ident { name: 52, ctxt: 0 }, Pub => ident { name: 53, ctxt: 0 }, Pure => ident { name: 54, ctxt: 0 }, Ref => ident { name: 55, ctxt: 0 }, Return => ident { name: 56, ctxt: 0 }, Static => ident { name: 27, ctxt: 0 }, Self => ident { name: 8, ctxt: 0 }, Struct => ident { name: 57, ctxt: 0 }, Super => ident { name: 58, ctxt: 0 }, True => ident { name: 59, ctxt: 0 }, Trait => ident { name: 60, ctxt: 0 }, Type => ident { name: 61, ctxt: 0 }, Unsafe => ident { name: 62, ctxt: 0 }, Use => ident { name: 63, ctxt: 0 }, While => ident { name: 64, ctxt: 0 }, Be => ident { name: 65, ctxt: 0 }, } } } } pub fn is_keyword(kw: keywords::Keyword, tok: &Token) -> bool { match *tok { token::IDENT(sid, false) => { kw.to_ident().name == sid.name } _ => { false } } } pub fn is_any_keyword(tok: &Token) -> bool
{ match *tok { token::IDENT(sid, false) => match sid.name { 8 | 27 | 32 .. 65 => true, _ => false, }, _ => false } }
identifier_body
token.rs
/* Literals */ LIT_INT(i64, ast::int_ty), LIT_UINT(u64, ast::uint_ty), LIT_INT_UNSUFFIXED(i64), LIT_FLOAT(ast::ident, ast::float_ty), LIT_FLOAT_UNSUFFIXED(ast::ident), LIT_STR(ast::ident), /* Name components */ // an identifier contains an "is_mod_name" boolean, // indicating whether :: follows this token with no // whitespace in between. IDENT(ast::ident, bool), UNDERSCORE, LIFETIME(ast::ident), /* For interpolation */ INTERPOLATED(nonterminal), DOC_COMMENT(ast::ident), EOF, } #[deriving(Encodable, Decodable, Eq, IterBytes)] /// For interpolation during macro expansion. pub enum nonterminal { nt_item(@ast::item), nt_block(ast::blk), nt_stmt(@ast::stmt), nt_pat( @ast::pat), nt_expr(@ast::expr), nt_ty( ast::Ty), nt_ident(ast::ident, bool), nt_path( ast::Path), nt_tt( @ast::token_tree), //needs @ed to break a circularity nt_matchers(~[ast::matcher]) } pub fn binop_to_str(o: binop) -> ~str { match o { PLUS => ~"+", MINUS => ~"-", STAR => ~"*", SLASH => ~"/", PERCENT => ~"%", CARET => ~"^", AND => ~"&", OR => ~"|", SHL => ~"<<", SHR => ~">>" } } pub fn to_str(in: @ident_interner, t: &Token) -> ~str { match *t { EQ => ~"=", LT => ~"<", LE => ~"<=", EQEQ => ~"==", NE => ~"!=", GE => ~">=", GT => ~">", NOT => ~"!", TILDE => ~"~", OROR => ~"||", ANDAND => ~"&&", BINOP(op) => binop_to_str(op), BINOPEQ(op) => binop_to_str(op) + "=", /* Structural symbols */ AT => ~"@", DOT => ~".", DOTDOT => ~"..", COMMA => ~",", SEMI => ~";", COLON => ~":", MOD_SEP => ~"::", RARROW => ~"->", LARROW => ~"<-", DARROW => ~"<->", FAT_ARROW => ~"=>", LPAREN => ~"(", RPAREN => ~")", LBRACKET => ~"[", RBRACKET => ~"]", LBRACE => ~"{", RBRACE => ~"}", POUND => ~"#", DOLLAR => ~"$", /* Literals */ LIT_INT(c, ast::ty_char) => { let mut res = ~"'"; do (c as char).escape_default |c| { res.push_char(c); } res.push_char('\''); res } LIT_INT(i, t) => { i.to_str() + ast_util::int_ty_to_str(t) } LIT_UINT(u, t) => { u.to_str() + ast_util::uint_ty_to_str(t) } LIT_INT_UNSUFFIXED(i) => { i.to_str() } LIT_FLOAT(ref s, t) => { let mut body = ident_to_str(s).to_owned(); if body.ends_with(".") { body.push_char('0'); // `10.f` is not a float literal } body + ast_util::float_ty_to_str(t) } LIT_FLOAT_UNSUFFIXED(ref s) => { let mut body = ident_to_str(s).to_owned(); if body.ends_with(".") { body.push_char('0'); // `10.f` is not a float literal } body } LIT_STR(ref s) => { fmt!("\"%s\"", ident_to_str(s).escape_default()) } /* Name components */ IDENT(s, _) => in.get(s.name).to_owned(), LIFETIME(s) => fmt!("'%s", in.get(s.name)), UNDERSCORE => ~"_", /* Other */ DOC_COMMENT(ref s) => ident_to_str(s).to_owned(), EOF => ~"<eof>", INTERPOLATED(ref nt) => { match nt { &nt_expr(e) => ::print::pprust::expr_to_str(e, in), _ => { ~"an interpolated " + match (*nt) { nt_item(*) => ~"item", nt_block(*) => ~"block", nt_stmt(*) => ~"statement", nt_pat(*) => ~"pattern", nt_expr(*) => fail!("should have been handled above"), nt_ty(*) => ~"type", nt_ident(*) => ~"identifier", nt_path(*) => ~"path", nt_tt(*) => ~"tt", nt_matchers(*) => ~"matcher sequence" } } } } } } pub fn can_begin_expr(t: &Token) -> bool { match *t { LPAREN => true, LBRACE => true, LBRACKET => true, IDENT(_, _) => true, UNDERSCORE => true, TILDE => true, LIT_INT(_, _) => true, LIT_UINT(_, _) => true, LIT_INT_UNSUFFIXED(_) => true, LIT_FLOAT(_, _) => true, LIT_FLOAT_UNSUFFIXED(_) => true, LIT_STR(_) => true, POUND => true, AT => true, NOT => true, BINOP(MINUS) => true, BINOP(STAR) => true, BINOP(AND) => true, BINOP(OR) => true, // in lambda syntax OROR => true, // in lambda syntax MOD_SEP => true, INTERPOLATED(nt_expr(*)) | INTERPOLATED(nt_ident(*)) | INTERPOLATED(nt_block(*)) | INTERPOLATED(nt_path(*)) => true, _ => false } } /// what's the opposite delimiter? pub fn flip_delimiter(t: &token::Token) -> token::Token { match *t { LPAREN => RPAREN, LBRACE => RBRACE, LBRACKET => RBRACKET, RPAREN => LPAREN, RBRACE => LBRACE, RBRACKET => LBRACKET, _ => fail!() } } pub fn is_lit(t: &Token) -> bool { match *t { LIT_INT(_, _) => true, LIT_UINT(_, _) => true, LIT_INT_UNSUFFIXED(_) => true, LIT_FLOAT(_, _) => true, LIT_FLOAT_UNSUFFIXED(_) => true, LIT_STR(_) => true, _ => false } } pub fn is_ident(t: &Token) -> bool { match *t { IDENT(_, _) => true, _ => false } } pub fn is_ident_or_path(t: &Token) -> bool { match *t { IDENT(_, _) | INTERPOLATED(nt_path(*)) => true, _ => false } } pub fn is_plain_ident(t: &Token) -> bool { match *t { IDENT(_, false) => true, _ => false } } pub fn is_bar(t: &Token) -> bool { match *t { BINOP(OR) | OROR => true, _ => false } } pub mod special_idents { use ast::ident; pub static underscore : ident = ident { name: 0, ctxt: 0}; pub static anon : ident = ident { name: 1, ctxt: 0}; pub static invalid : ident = ident { name: 2, ctxt: 0}; // '' pub static unary : ident = ident { name: 3, ctxt: 0}; pub static not_fn : ident = ident { name: 4, ctxt: 0}; pub static idx_fn : ident = ident { name: 5, ctxt: 0}; pub static unary_minus_fn : ident = ident { name: 6, ctxt: 0}; pub static clownshoes_extensions : ident = ident { name: 7, ctxt: 0}; pub static self_ : ident = ident { name: 8, ctxt: 0}; //'self' /* for matcher NTs */ pub static item : ident = ident { name: 9, ctxt: 0}; pub static block : ident = ident { name: 10, ctxt: 0}; pub static stmt : ident = ident { name: 11, ctxt: 0}; pub static pat : ident = ident { name: 12, ctxt: 0}; pub static expr : ident = ident { name: 13, ctxt: 0}; pub static ty : ident = ident { name: 14, ctxt: 0}; pub static ident : ident = ident { name: 15, ctxt: 0}; pub static path : ident = ident { name: 16, ctxt: 0}; pub static tt : ident = ident { name: 17, ctxt: 0}; pub static matchers : ident = ident { name: 18, ctxt: 0}; pub static str : ident = ident { name: 19, ctxt: 0}; // for the type /* outside of libsyntax */ pub static arg : ident = ident { name: 20, ctxt: 0}; pub static descrim : ident = ident { name: 21, ctxt: 0}; pub static clownshoe_abi : ident = ident { name: 22, ctxt: 0}; pub static clownshoe_stack_shim : ident = ident { name: 23, ctxt: 0}; pub static main : ident = ident { name: 24, ctxt: 0}; pub static opaque : ident = ident { name: 25, ctxt: 0}; pub static blk : ident = ident { name: 26, ctxt: 0}; pub static statik : ident = ident { name: 27, ctxt: 0}; pub static clownshoes_foreign_mod: ident = ident { name: 28, ctxt: 0}; pub static unnamed_field: ident = ident { name: 29, ctxt: 0}; pub static c_abi: ident = ident { name: 30, ctxt: 0}; pub static type_self: ident = ident { name: 31, ctxt: 0}; // `Self` } /** * Maps a token to a record specifying the corresponding binary * operator */ pub fn token_to_binop(tok: Token) -> Option<ast::binop> { match tok { BINOP(STAR) => Some(ast::mul), BINOP(SLASH) => Some(ast::div), BINOP(PERCENT) => Some(ast::rem), BINOP(PLUS) => Some(ast::add), BINOP(MINUS) => Some(ast::subtract), BINOP(SHL) => Some(ast::shl), BINOP(SHR) => Some(ast::shr), BINOP(AND) => Some(ast::bitand), BINOP(CARET) => Some(ast::bitxor), BINOP(OR) => Some(ast::bitor), LT => Some(ast::lt), LE => Some(ast::le), GE => Some(ast::ge), GT => Some(ast::gt), EQEQ => Some(ast::eq), NE => Some(ast::ne), ANDAND => Some(ast::and), OROR => Some(ast::or), _ => None } } pub struct ident_interner { priv interner: StrInterner, } impl ident_interner { pub fn intern(&self, val: &str) -> Name { self.interner.intern(val) } pub fn gensym(&self, val: &str) -> Name { self.interner.gensym(val) } pub fn get(&self, idx: Name) -> @str { self.interner.get(idx) } // is this really something that should be exposed? pub fn len(&self) -> uint { self.interner.len() } pub fn find_equiv<Q:Hash + IterBytes + Equiv<@str>>(&self, val: &Q) -> Option<Name> { self.interner.find_equiv(val) } } // return a fresh interner, preloaded with special identifiers. fn mk_fresh_ident_interner() -> @ident_interner { // the indices here must correspond to the numbers in // special_idents. let init_vec = ~[ "_", // 0 "anon", // 1 "", // 2 "unary", // 3 "!", // 4 "[]", // 5 "unary-", // 6 "__extensions__", // 7 "self", // 8 "item", // 9 "block", // 10 "stmt", // 11 "pat", // 12 "expr", // 13 "ty", // 14
"tt", // 17 "matchers", // 18 "str", // 19 "arg", // 20 "descrim", // 21 "__rust_abi", // 22 "__rust_stack_shim", // 23 "main", // 24 "<opaque>", // 25 "blk", // 26 "static", // 27 "__foreign_mod__", // 28 "__field__", // 29 "C", // 30 "Self", // 31 "as", // 32 "break", // 33 "const", // 34 "copy", // 35 "do", // 36 "else", // 37 "enum", // 38 "extern", // 39 "false", // 40 "fn", // 41 "for", // 42 "if", // 43 "impl", // 44 "let", // 45 "__log", // 46 "loop", // 47 "match", // 48 "mod", // 49 "mut", // 50 "once", // 51 "priv", // 52 "pub", // 53 "pure", // 54 "ref", // 55 "return", // 56 "static", // 27 -- also a special ident "self", // 8 -- also a special ident "struct", // 57 "super", // 58 "true", // 59 "trait", // 60 "type", // 61 "unsafe", // 62 "use", // 63 "while", // 64 "be", // 65 ]; @ident_interner { interner: interner::StrInterner::prefill(init_vec) } } // if an interner exists in TLS, return it. Otherwise, prepare a // fresh one. pub fn get_ident_interner() -> @ident_interner { #[cfg(not(stage0))] static key: local_data::Key<@@::parse::token::ident_interner> = &local_data::Key; #[cfg(stage0)] fn key(_: @@::parse::token::ident_interner) {} match local_data::get(key, |k| k.map(|&k| *k)) { Some(interner) => *interner, None => { let interner = mk_fresh_ident_interner(); local_data::set(key, @interner); interner } } } /* for when we don't care about the contents; doesn't interact with TLD or serialization */ pub fn mk_fake_ident_interner() -> @ident_interner { @ident_interner { interner: interner::StrInterner::new() } } // maps a string to its interned representation pub fn intern(str : &str) -> Name { let interner = get_ident_interner(); interner.intern(str) } // gensyms a new uint, using the current interner pub fn gensym(str : &str) -> Name { let interner = get_ident_interner(); interner.gensym(str) } // map an interned representation back to a string pub fn interner_get(name : Name) -> @str { get_ident_interner().get(name) } // maps an identifier to the string that it corresponds to pub fn ident_to_str(id : &ast::ident) -> @str { interner_get(id.name) } // maps a string to an identifier with an empty syntax context pub fn str_to_ident(str : &str) -> ast::ident { ast::new_ident(intern(str)) } // maps a string to a gensym'ed identifier pub fn gensym_ident(str : &str) -> ast::ident { ast::new_ident(gensym(str)) } // create a fresh name. In principle, this is just a // gensym, but for debugging purposes, you'd like the // resulting name to have a suggestive stringify, without // paying the cost of guaranteeing that the name is // truly unique. I'm going to try to strike a balance // by using a gensym with a name that has a random number // at the end. So, the gensym guarantees the uniqueness, // and the int helps to avoid confusion. pub fn fresh_name(src_name : &str) -> Name { let num = rand::rng().gen_uint_range(0,0xffff); gensym(fmt!("%s_%u",src_name,num)) } /** * All the valid words that have meaning in the Rust language. * * Rust keywords are either'strict' or'reserved'. Strict keywords may not * appear as identifiers at all. Reserved keywords are not used anywhere in * the language and may not appear as identifiers. */ pub mod keywords { use ast::ident; pub enum Keyword { // Strict keywords As, Break, Const, Copy, Do, Else, Enum, Extern, False, Fn, For, If, Impl, Let, __Log, Loop, Match, Mod, Mut, Once, Priv, Pub, Pure, Ref, Return, Static, Self, Struct, Super, True, Trait, Type, Unsafe, Use, While, // Reserved keywords Be, } impl Keyword { pub fn to_ident(&self) -> ident { match *self { As => ident { name: 32, ctxt: 0 }, Break => ident { name: 33, ctxt: 0 }, Const => ident { name: 34, ctxt: 0 }, Copy => ident { name: 35, ctxt: 0 }, Do => ident { name: 36, ctxt: 0 }, Else => ident { name: 37, ctxt: 0 }, Enum => ident { name: 38, ctxt: 0 }, Extern => ident { name: 39, ctxt: 0 }, False => ident { name: 40, ctxt: 0 }, Fn => ident { name: 41, ctxt: 0
"ident", // 15 "path", // 16
random_line_split
admin_sockets.rs
// Copyright 2017 LambdaStack All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #![cfg(target_os = "linux")] use std::str; use std::io::{Read, Write, Cursor}; use std::os::unix::net::UnixStream; use std::net::Shutdown; use error::{RadosError, RadosResult}; use byteorder::{BigEndian, ReadBytesExt}; /// This is a helper function that builds a raw command from the actual command. You just pass /// in a command like "help". The returned `String` will be a JSON String. pub fn
(cmd: &str, socket: &str) -> RadosResult<String> { let raw_cmd = format!("{{\"{}\": \"{}\"}}", "prefix", cmd); admin_socket_raw_command(&raw_cmd, socket) } /// This function supports a raw command in the format of something like: `{"prefix": "help"}`. /// The returned `String` will be a JSON String. #[allow(unused_variables)] pub fn admin_socket_raw_command(cmd: &str, socket: &str) -> RadosResult<String> { let mut output = String::new(); let mut buffer = vec![0;4]; // Should return 4 bytes with size or indicator. let cmd = &format!("{}\0", cmd); // Terminator so don't add one to commands. let mut stream = try!(UnixStream::connect(socket)); let wb = try!(stream.write(cmd.as_bytes())); let ret_val = try!(stream.read(&mut buffer)); if ret_val < 4 { try!(stream.shutdown(Shutdown::Both)); return Err(RadosError::new("Admin socket: Invalid command or socket did not return any data".to_string())); } // The first 4 bytes are Big Endian unsigned int let mut rdr = Cursor::new(buffer); let len = rdr.read_u32::<BigEndian>().unwrap(); // Not currently using the len but may... let rb = try!(stream.read_to_string(&mut output)); try!(stream.shutdown(Shutdown::Both)); Ok(output) }
admin_socket_command
identifier_name
admin_sockets.rs
// Copyright 2017 LambdaStack All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #![cfg(target_os = "linux")] use std::str; use std::io::{Read, Write, Cursor}; use std::os::unix::net::UnixStream; use std::net::Shutdown; use error::{RadosError, RadosResult}; use byteorder::{BigEndian, ReadBytesExt}; /// This is a helper function that builds a raw command from the actual command. You just pass /// in a command like "help". The returned `String` will be a JSON String. pub fn admin_socket_command(cmd: &str, socket: &str) -> RadosResult<String> { let raw_cmd = format!("{{\"{}\": \"{}\"}}", "prefix", cmd); admin_socket_raw_command(&raw_cmd, socket) } /// This function supports a raw command in the format of something like: `{"prefix": "help"}`. /// The returned `String` will be a JSON String. #[allow(unused_variables)] pub fn admin_socket_raw_command(cmd: &str, socket: &str) -> RadosResult<String> { let mut output = String::new(); let mut buffer = vec![0;4]; // Should return 4 bytes with size or indicator. let cmd = &format!("{}\0", cmd); // Terminator so don't add one to commands. let mut stream = try!(UnixStream::connect(socket)); let wb = try!(stream.write(cmd.as_bytes())); let ret_val = try!(stream.read(&mut buffer)); if ret_val < 4 { try!(stream.shutdown(Shutdown::Both)); return Err(RadosError::new("Admin socket: Invalid command or socket did not return any data".to_string())); } // The first 4 bytes are Big Endian unsigned int let mut rdr = Cursor::new(buffer); let len = rdr.read_u32::<BigEndian>().unwrap(); // Not currently using the len but may... let rb = try!(stream.read_to_string(&mut output)); try!(stream.shutdown(Shutdown::Both)); Ok(output) }
// // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS,
random_line_split
admin_sockets.rs
// Copyright 2017 LambdaStack All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #![cfg(target_os = "linux")] use std::str; use std::io::{Read, Write, Cursor}; use std::os::unix::net::UnixStream; use std::net::Shutdown; use error::{RadosError, RadosResult}; use byteorder::{BigEndian, ReadBytesExt}; /// This is a helper function that builds a raw command from the actual command. You just pass /// in a command like "help". The returned `String` will be a JSON String. pub fn admin_socket_command(cmd: &str, socket: &str) -> RadosResult<String> { let raw_cmd = format!("{{\"{}\": \"{}\"}}", "prefix", cmd); admin_socket_raw_command(&raw_cmd, socket) } /// This function supports a raw command in the format of something like: `{"prefix": "help"}`. /// The returned `String` will be a JSON String. #[allow(unused_variables)] pub fn admin_socket_raw_command(cmd: &str, socket: &str) -> RadosResult<String> { let mut output = String::new(); let mut buffer = vec![0;4]; // Should return 4 bytes with size or indicator. let cmd = &format!("{}\0", cmd); // Terminator so don't add one to commands. let mut stream = try!(UnixStream::connect(socket)); let wb = try!(stream.write(cmd.as_bytes())); let ret_val = try!(stream.read(&mut buffer)); if ret_val < 4
// The first 4 bytes are Big Endian unsigned int let mut rdr = Cursor::new(buffer); let len = rdr.read_u32::<BigEndian>().unwrap(); // Not currently using the len but may... let rb = try!(stream.read_to_string(&mut output)); try!(stream.shutdown(Shutdown::Both)); Ok(output) }
{ try!(stream.shutdown(Shutdown::Both)); return Err(RadosError::new("Admin socket: Invalid command or socket did not return any data".to_string())); }
conditional_block
admin_sockets.rs
// Copyright 2017 LambdaStack All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #![cfg(target_os = "linux")] use std::str; use std::io::{Read, Write, Cursor}; use std::os::unix::net::UnixStream; use std::net::Shutdown; use error::{RadosError, RadosResult}; use byteorder::{BigEndian, ReadBytesExt}; /// This is a helper function that builds a raw command from the actual command. You just pass /// in a command like "help". The returned `String` will be a JSON String. pub fn admin_socket_command(cmd: &str, socket: &str) -> RadosResult<String>
/// This function supports a raw command in the format of something like: `{"prefix": "help"}`. /// The returned `String` will be a JSON String. #[allow(unused_variables)] pub fn admin_socket_raw_command(cmd: &str, socket: &str) -> RadosResult<String> { let mut output = String::new(); let mut buffer = vec![0;4]; // Should return 4 bytes with size or indicator. let cmd = &format!("{}\0", cmd); // Terminator so don't add one to commands. let mut stream = try!(UnixStream::connect(socket)); let wb = try!(stream.write(cmd.as_bytes())); let ret_val = try!(stream.read(&mut buffer)); if ret_val < 4 { try!(stream.shutdown(Shutdown::Both)); return Err(RadosError::new("Admin socket: Invalid command or socket did not return any data".to_string())); } // The first 4 bytes are Big Endian unsigned int let mut rdr = Cursor::new(buffer); let len = rdr.read_u32::<BigEndian>().unwrap(); // Not currently using the len but may... let rb = try!(stream.read_to_string(&mut output)); try!(stream.shutdown(Shutdown::Both)); Ok(output) }
{ let raw_cmd = format!("{{\"{}\": \"{}\"}}", "prefix", cmd); admin_socket_raw_command(&raw_cmd, socket) }
identifier_body
small_objects_stress.rs
extern crate stopwatch; use stopwatch::Stopwatch; extern crate mo_gc; use mo_gc::{GcThread, GcRoot, Trace, StatsLogger}; const THING_SIZE: usize = 8; const THING_COUNT: i64 = 2500000; struct Thing { _data: [u64; THING_SIZE], } impl Thing { fn new() -> Thing { Thing { _data: [0; THING_SIZE] } } } unsafe impl Trace for Thing {} fn app() { let sw = Stopwatch::start_new(); for _ in 0..THING_COUNT { let _new = GcRoot::new(Thing::new()); } let per_second = (THING_COUNT * 1000) / sw.elapsed_ms(); println!("app allocated {} objects at {} objects per second", THING_COUNT, per_second); println!("app finished in {}ms", sw.elapsed_ms()); } fn main()
{ let gc = GcThread::spawn_gc(); let app_handle1 = gc.spawn(|| app()); let app_handle2 = gc.spawn(|| app()); let logger = gc.join().expect("gc failed"); logger.dump_to_stdout(); app_handle1.join().expect("app failed"); app_handle2.join().expect("app failed"); }
identifier_body
small_objects_stress.rs
extern crate stopwatch; use stopwatch::Stopwatch; extern crate mo_gc; use mo_gc::{GcThread, GcRoot, Trace, StatsLogger}; const THING_SIZE: usize = 8; const THING_COUNT: i64 = 2500000; struct Thing { _data: [u64; THING_SIZE], } impl Thing { fn new() -> Thing { Thing { _data: [0; THING_SIZE] } } } unsafe impl Trace for Thing {} fn
() { let sw = Stopwatch::start_new(); for _ in 0..THING_COUNT { let _new = GcRoot::new(Thing::new()); } let per_second = (THING_COUNT * 1000) / sw.elapsed_ms(); println!("app allocated {} objects at {} objects per second", THING_COUNT, per_second); println!("app finished in {}ms", sw.elapsed_ms()); } fn main() { let gc = GcThread::spawn_gc(); let app_handle1 = gc.spawn(|| app()); let app_handle2 = gc.spawn(|| app()); let logger = gc.join().expect("gc failed"); logger.dump_to_stdout(); app_handle1.join().expect("app failed"); app_handle2.join().expect("app failed"); }
app
identifier_name
small_objects_stress.rs
extern crate stopwatch; use stopwatch::Stopwatch; extern crate mo_gc; use mo_gc::{GcThread, GcRoot, Trace, StatsLogger}; const THING_SIZE: usize = 8; const THING_COUNT: i64 = 2500000; struct Thing { _data: [u64; THING_SIZE], } impl Thing { fn new() -> Thing { Thing { _data: [0; THING_SIZE] } } } unsafe impl Trace for Thing {} fn app() { let sw = Stopwatch::start_new(); for _ in 0..THING_COUNT { let _new = GcRoot::new(Thing::new()); } let per_second = (THING_COUNT * 1000) / sw.elapsed_ms(); println!("app allocated {} objects at {} objects per second", THING_COUNT, per_second); println!("app finished in {}ms", sw.elapsed_ms()); } fn main() { let gc = GcThread::spawn_gc(); let app_handle1 = gc.spawn(|| app()); let app_handle2 = gc.spawn(|| app()); let logger = gc.join().expect("gc failed"); logger.dump_to_stdout(); app_handle1.join().expect("app failed"); app_handle2.join().expect("app failed");
}
random_line_split
illegal-proc-macro-derive-use.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. extern crate proc_macro; #[proc_macro_derive(Foo)] //~^ ERROR: only usable with crates of the `proc-macro` crate type pub fn
(a: proc_macro::TokenStream) -> proc_macro::TokenStream { a } // Issue #37590 #[proc_macro_derive(Foo)] //~^ ERROR: the `#[proc_macro_derive]` attribute may only be used on bare functions pub struct Foo { } fn main() {}
foo
identifier_name
illegal-proc-macro-derive-use.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms.
a } // Issue #37590 #[proc_macro_derive(Foo)] //~^ ERROR: the `#[proc_macro_derive]` attribute may only be used on bare functions pub struct Foo { } fn main() {}
extern crate proc_macro; #[proc_macro_derive(Foo)] //~^ ERROR: only usable with crates of the `proc-macro` crate type pub fn foo(a: proc_macro::TokenStream) -> proc_macro::TokenStream {
random_line_split
illegal-proc-macro-derive-use.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. extern crate proc_macro; #[proc_macro_derive(Foo)] //~^ ERROR: only usable with crates of the `proc-macro` crate type pub fn foo(a: proc_macro::TokenStream) -> proc_macro::TokenStream
// Issue #37590 #[proc_macro_derive(Foo)] //~^ ERROR: the `#[proc_macro_derive]` attribute may only be used on bare functions pub struct Foo { } fn main() {}
{ a }
identifier_body
window.rs
use error::Result; use error::Error::Sdl as SdlError; use sdl2::Sdl; use sdl2::video::Window as SdlWindow; use sdl2::video::{gl_attr, GLProfile, GLContext}; use libc::c_void; use gl; use sdl2; const WINDOW_TITLE: &'static str = "Rusty Doom v0.0.7 - Toggle mouse with backtick key (`))"; const OPENGL_DEPTH_SIZE: u8 = 24; pub struct Window { window: SdlWindow, width: u32, height: u32, _context: GLContext, } impl Window { pub fn new(sdl: &Sdl, width: u32, height: u32) -> Result<Window> { gl_attr::set_context_profile(GLProfile::Core); gl_attr::set_context_major_version(gl::platform::GL_MAJOR_VERSION); gl_attr::set_context_minor_version(gl::platform::GL_MINOR_VERSION); gl_attr::set_depth_size(OPENGL_DEPTH_SIZE); gl_attr::set_double_buffer(true); let window = try!(sdl.window(WINDOW_TITLE, width as u32, height as u32) .position_centered() .opengl() .build() .map_err(SdlError)); let context = try!(window.gl_create_context().map_err(SdlError)); sdl2::clear_error(); gl::load_with(|name| { sdl2::video::gl_get_proc_address(name) as *const c_void }); let mut vao_id = 0; check_gl_unsafe!(gl::GenVertexArrays(1, &mut vao_id)); check_gl_unsafe!(gl::BindVertexArray(vao_id)); check_gl_unsafe!(gl::ClearColor(0.06, 0.07, 0.09, 0.0)); check_gl_unsafe!(gl::Enable(gl::DEPTH_TEST)); check_gl_unsafe!(gl::DepthFunc(gl::LESS)); Ok(Window { window: window, width: width, height: height, _context: context, }) } pub fn aspect_ratio(&self) -> f32 { self.width as f32 / self.height as f32 } pub fn swap_buffers(&self) { self.window.gl_swap_window(); } pub fn clear(&self)
}
{ check_gl_unsafe!(gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT)); }
identifier_body
window.rs
use error::Result; use error::Error::Sdl as SdlError; use sdl2::Sdl; use sdl2::video::Window as SdlWindow; use sdl2::video::{gl_attr, GLProfile, GLContext}; use libc::c_void; use gl; use sdl2; const WINDOW_TITLE: &'static str = "Rusty Doom v0.0.7 - Toggle mouse with backtick key (`))"; const OPENGL_DEPTH_SIZE: u8 = 24; pub struct Window { window: SdlWindow, width: u32, height: u32, _context: GLContext, } impl Window { pub fn new(sdl: &Sdl, width: u32, height: u32) -> Result<Window> { gl_attr::set_context_profile(GLProfile::Core); gl_attr::set_context_major_version(gl::platform::GL_MAJOR_VERSION);
let window = try!(sdl.window(WINDOW_TITLE, width as u32, height as u32) .position_centered() .opengl() .build() .map_err(SdlError)); let context = try!(window.gl_create_context().map_err(SdlError)); sdl2::clear_error(); gl::load_with(|name| { sdl2::video::gl_get_proc_address(name) as *const c_void }); let mut vao_id = 0; check_gl_unsafe!(gl::GenVertexArrays(1, &mut vao_id)); check_gl_unsafe!(gl::BindVertexArray(vao_id)); check_gl_unsafe!(gl::ClearColor(0.06, 0.07, 0.09, 0.0)); check_gl_unsafe!(gl::Enable(gl::DEPTH_TEST)); check_gl_unsafe!(gl::DepthFunc(gl::LESS)); Ok(Window { window: window, width: width, height: height, _context: context, }) } pub fn aspect_ratio(&self) -> f32 { self.width as f32 / self.height as f32 } pub fn swap_buffers(&self) { self.window.gl_swap_window(); } pub fn clear(&self) { check_gl_unsafe!(gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT)); } }
gl_attr::set_context_minor_version(gl::platform::GL_MINOR_VERSION); gl_attr::set_depth_size(OPENGL_DEPTH_SIZE); gl_attr::set_double_buffer(true);
random_line_split
window.rs
use error::Result; use error::Error::Sdl as SdlError; use sdl2::Sdl; use sdl2::video::Window as SdlWindow; use sdl2::video::{gl_attr, GLProfile, GLContext}; use libc::c_void; use gl; use sdl2; const WINDOW_TITLE: &'static str = "Rusty Doom v0.0.7 - Toggle mouse with backtick key (`))"; const OPENGL_DEPTH_SIZE: u8 = 24; pub struct Window { window: SdlWindow, width: u32, height: u32, _context: GLContext, } impl Window { pub fn new(sdl: &Sdl, width: u32, height: u32) -> Result<Window> { gl_attr::set_context_profile(GLProfile::Core); gl_attr::set_context_major_version(gl::platform::GL_MAJOR_VERSION); gl_attr::set_context_minor_version(gl::platform::GL_MINOR_VERSION); gl_attr::set_depth_size(OPENGL_DEPTH_SIZE); gl_attr::set_double_buffer(true); let window = try!(sdl.window(WINDOW_TITLE, width as u32, height as u32) .position_centered() .opengl() .build() .map_err(SdlError)); let context = try!(window.gl_create_context().map_err(SdlError)); sdl2::clear_error(); gl::load_with(|name| { sdl2::video::gl_get_proc_address(name) as *const c_void }); let mut vao_id = 0; check_gl_unsafe!(gl::GenVertexArrays(1, &mut vao_id)); check_gl_unsafe!(gl::BindVertexArray(vao_id)); check_gl_unsafe!(gl::ClearColor(0.06, 0.07, 0.09, 0.0)); check_gl_unsafe!(gl::Enable(gl::DEPTH_TEST)); check_gl_unsafe!(gl::DepthFunc(gl::LESS)); Ok(Window { window: window, width: width, height: height, _context: context, }) } pub fn
(&self) -> f32 { self.width as f32 / self.height as f32 } pub fn swap_buffers(&self) { self.window.gl_swap_window(); } pub fn clear(&self) { check_gl_unsafe!(gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT)); } }
aspect_ratio
identifier_name
dinputd.rs
DEFINE_GUID!{IID_IDirectInputEffectDriver, 0x02538130, 0x898f, 0x11d0, 0x9a, 0xd0, 0x00, 0xa0, 0xc9, 0xa0, 0x6e, 0x35} DEFINE_GUID!{IID_IDirectInputJoyConfig, 0x1de12ab1, 0xc9f5, 0x11cf, 0xbf, 0xc7, 0x44, 0x45, 0x53, 0x54, 0x00, 0x00} DEFINE_GUID!{IID_IDirectInputPIDDriver, 0xeec6993a, 0xb3fd, 0x11d2, 0xa9, 0x16, 0x00, 0xc0, 0x4f, 0xb9, 0x86, 0x38} DEFINE_GUID!{IID_IDirectInputJoyConfig8, 0xeb0d7dfa, 0x1990, 0x4f27, 0xb4, 0xd6, 0xed, 0xf2, 0xee, 0xc4, 0xa4, 0x4c} DEFINE_GUID!{GUID_KeyboardClass, 0x4d36e96b, 0xe325, 0x11ce, 0xbf, 0xc1, 0x08, 0x00, 0x2b, 0xe1, 0x03, 0x18} DEFINE_GUID!{GUID_MediaClass, 0x4d36e96c, 0xe325, 0x11ce, 0xbf, 0xc1, 0x08, 0x00, 0x2b, 0xe1, 0x03, 0x18} DEFINE_GUID!{GUID_MouseClass, 0x4d36e96f, 0xe325, 0x11ce, 0xbf, 0xc1, 0x08, 0x00, 0x2b, 0xe1, 0x03, 0x18} DEFINE_GUID!{GUID_HIDClass, 0x745a17a0, 0x74d3, 0x11d0, 0xb6, 0xfe, 0x00, 0xa0, 0xc9, 0x0f, 0x57, 0xda}
// 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. // All files in the project carrying such notice may not be copied, modified, or distributed // except according to those terms.
random_line_split
engine.rs
use std::thread; use std::collections::HashMap; use std::intrinsics::type_name; use std::mem; use std::ptr::{self, Unique}; use std::sync::{Arc, Barrier, Mutex}; use std::time::Duration; use bootstrap::input::ScanCode; use bootstrap::window::Window; use bootstrap::window::Message::*; use bootstrap::time::Timer; use bs_audio; use polygon::{Renderer, RendererBuilder}; use singleton::Singleton; use stopwatch::{Collector, Stopwatch}; use scene::*; use resource::ResourceManager; use ecs::*; use component::*; use debug_draw::DebugDraw; pub const TARGET_FRAME_TIME_SECONDS: f32 = 1.0 / 60.0; pub const TARGET_FRAME_TIME_MS: f32 = TARGET_FRAME_TIME_SECONDS * 1000.0; static mut INSTANCE: *mut Engine = ptr::null_mut(); pub struct Engine { renderer: Mutex<Box<Renderer>>, window: Window, resource_manager: Box<ResourceManager>, systems: HashMap<SystemId, Box<System>>, debug_systems: HashMap<SystemId, Box<System>>, // TODO: Replace explicit update ordering with something more automatic (e.g. dependency hierarchy). audio_update: Box<System>, alarm_update: Box<System>, collision_update: Box<System>, scene: Scene, debug_draw: DebugDraw, close: bool, debug_pause: bool, } impl Engine { /// Starts the engine's main loop, blocking until the game shuts down. /// /// This function starts the engine's internal update loop which handles the details of /// processing input from the OS, invoking game code, and rendering each frame. This function /// blocks until the engine recieves a message to being the shutdown process, at which point it /// will end the update loop and perform any necessary shutdown and cleanup procedures. Once /// those have completed this function will return. /// /// Panics if the engine hasn't been created yet. pub fn start() { let instance = unsafe { debug_assert!(!INSTANCE.is_null(), "Cannot retrieve Engine instance because none exists"); &mut *INSTANCE }; // Run main loop. instance.main_loop(); // Perform cleanup. unsafe { Engine::destroy_instance(); } } /// Retrieves a reference to current scene. /// /// Panics if the engine hasn't been created yet. pub fn scene<'a>() -> &'a Scene { let instance = Engine::instance(); &instance.scene } /// Retrieves a reference to the resource manager. /// /// TODO: The resource manager should probably be a singleton too since it's already setup to /// be used through shared references. pub fn resource_manager<'a>() -> &'a ResourceManager { let instance = Engine::instance(); &*instance.resource_manager } pub fn renderer<F, T>(func: F) -> T where F: FnOnce(&mut Renderer) -> T, { let instance = Engine::instance(); let mut renderer = instance.renderer.lock().expect("Could not acquire lock on renderer mutex"); func(&mut **renderer) } pub fn window() -> &'static Window { &Engine::instance().window } fn main_loop(&mut self) { let timer = Timer::new(); let mut collector = Collector::new().unwrap(); loop { let _stopwatch = Stopwatch::new("loop"); let start_time = timer.now(); self.update(); self.draw(); if self.close { println!("shutting down engine"); break; } if!cfg!(feature="timing") && timer.elapsed_ms(start_time) > TARGET_FRAME_TIME_MS { println!( "WARNING: Missed frame time. Frame time: {}ms, target frame time: {}ms", timer.elapsed_ms(start_time), TARGET_FRAME_TIME_MS); } // Wait for target frame time. let mut remaining_time_ms = TARGET_FRAME_TIME_MS - timer.elapsed_ms(start_time); while remaining_time_ms > 1.0 { thread::sleep(Duration::from_millis(remaining_time_ms as u64)); remaining_time_ms = TARGET_FRAME_TIME_MS - timer.elapsed_ms(start_time); } while remaining_time_ms > 0.0 { remaining_time_ms = TARGET_FRAME_TIME_MS - timer.elapsed_ms(start_time); } // TODO: Don't flip buffers until end of frame time? }; collector.flush_to_file("stopwatch.csv"); } fn update(&mut self) { let _stopwatch = Stopwatch::new("update"); let scene = &mut self.scene; scene.input.clear(); // TODO: Make this an iterator to simplify this loop. while let Some(message) = self.window.next_message() { match message { Activate => (), Close => self.close = true, Destroy => (), Paint => (), // Handle inputs. KeyDown(_) | KeyUp(_) | MouseMove(_, _) | MousePos(_, _) | MouseButtonPressed(_) | MouseButtonReleased(_) | MouseWheel(_) => scene.input.push_input(message), } } // TODO: More efficient handling of debug pause (i.e. something that doesn't have any // overhead when doing a release build). if!self.debug_pause || scene.input.key_pressed(ScanCode::F11) { self.debug_draw.clear_buffer(); self.alarm_update.update(scene, TARGET_FRAME_TIME_SECONDS); // Update systems. for (_, system) in self.systems.iter_mut() { system.update(scene, TARGET_FRAME_TIME_SECONDS); } // Update component managers. scene.update_managers(); } // Update debug systems always forever. for (_, system) in self.debug_systems.iter_mut() { system.update(scene, TARGET_FRAME_TIME_SECONDS); } // NOTE: Transform update used to go here. if!self.debug_pause || scene.input.key_pressed(ScanCode::F11) { self.collision_update.update(scene, TARGET_FRAME_TIME_SECONDS); self.audio_update.update(scene, TARGET_FRAME_TIME_SECONDS); } if scene.input.key_pressed(ScanCode::F9) { self.debug_pause =!self.debug_pause; } if scene.input.key_pressed(ScanCode::F11) { self.debug_pause = true; } } #[cfg(not(feature="no-draw"))] fn draw(&mut self) { let _stopwatch = Stopwatch::new("draw"); self.renderer .lock() .expect("Unable to acquire lock on renderer mutex for drawing") .draw(); } #[cfg(feature="no-draw")] fn draw(&mut self) {} } unsafe impl Singleton for Engine { /// Creates the instance of the singleton. fn set_instance(engine: Engine) { assert!(unsafe { INSTANCE.is_null() }, "Cannot create more than one Engine instance"); let boxed_engine = Box::new(engine); unsafe { INSTANCE = Box::into_raw(boxed_engine); } } /// Retrieves an immutable reference to the singleton instance. /// /// This function is unsafe because there is no way of know fn instance() -> &'static Self { unsafe { debug_assert!(!INSTANCE.is_null(), "Cannot retrieve Engine instance because none exists"); &*INSTANCE
} } /// Destroys the instance of the singleton. unsafe fn destroy_instance() { let ptr = mem::replace(&mut INSTANCE, ptr::null_mut()); Box::from_raw(ptr); } } pub struct EngineBuilder { systems: HashMap<SystemId, Box<System>>, debug_systems: HashMap<SystemId, Box<System>>, managers: ManagerMap, max_workers: usize, } /// A builder for configuring the components and systems registered with the game engine. /// /// Component managers and systems cannot be changed once the engine has been instantiated so they /// must be provided all together when the instance is created. `EngineBuilder` provides an /// interface for gathering all managers and systems to be provided to the engine. impl EngineBuilder { /// Creates a new `EngineBuilder` object. pub fn new() -> EngineBuilder { let mut builder = EngineBuilder { systems: HashMap::new(), debug_systems: HashMap::new(), managers: ManagerMap::new(), max_workers: 1, }; // Register internal component managers. builder.register_component::<Transform>(); builder.register_component::<Camera>(); builder.register_component::<Light>(); builder.register_component::<Mesh>(); builder.register_component::<AudioSource>(); builder.register_component::<AlarmId>(); builder.register_component::<Collider>(); builder } /// Consumes the builder and creates the `Engine` instance. /// /// No `Engine` object is returned because this method instantiates the engine singleton. pub fn build(self) { let engine = { let window = { let mut window = unsafe { mem::uninitialized() }; let mut out = unsafe { Unique::new(&mut window as *mut _) }; let barrier = Arc::new(Barrier::new(2)); let barrier_clone = barrier.clone(); thread::spawn(move || { let mut window = Window::new("gunship game").unwrap(); let mut message_pump = window.message_pump(); // write data out to `window` without dropping the old (uninitialized) value. unsafe { ptr::write(out.get_mut(), window); } // Sync with barrier_clone.wait(); message_pump.run(); }); // Wait until window thread finishe creating the window. barrier.wait(); window }; let mut renderer = RendererBuilder::new(&window).build(); let debug_draw = DebugDraw::new(&mut *renderer); let resource_manager = Box::new(ResourceManager::new()); let audio_source = match bs_audio::init() { Ok(audio_source) => audio_source, Err(error) => { // TODO: Rather than panicking, create a null audio system and keep running. panic!("Error while initialzing audio subsystem: {}", error) }, }; Engine { window: window, renderer: Mutex::new(renderer), resource_manager: resource_manager, systems: self.systems, debug_systems: self.debug_systems, audio_update: Box::new(AudioSystem), alarm_update: Box::new(alarm_update), collision_update: Box::new(CollisionSystem::new()), scene: Scene::new(audio_source, self.managers), debug_draw: debug_draw, close: false, debug_pause: false, } }; // Init aysnc subsystem. ::async::init(); ::async::start_workers(self.max_workers); Engine::set_instance(engine); run!(Engine::start()); } pub fn max_workers(&mut self, workers: usize) -> &mut EngineBuilder { assert!(workers > 0, "There must be at least one worker for the engine to run"); self.max_workers = workers; self } /// Registers the manager for the specified component type. /// /// Defers internally to `register_manager()`. pub fn register_component<T: Component>(&mut self) -> &mut EngineBuilder { T::Manager::register(self); self } /// Registers the specified manager with the engine. /// /// Defers internally to `ComponentManager::register()`. pub fn register_manager<T: ComponentManager>(&mut self, manager: T) -> &mut EngineBuilder { let manager_id = ManagerId::of::<T>(); assert!( !self.managers.contains_key(&manager_id), "Manager {} with ID {:?} already registered", unsafe { type_name::<T>() }, &manager_id); // Box the manager as a trait object to construct the data and vtable pointers. let boxed_manager = Box::new(manager); // Add the manager to the type map and the component id to the component map. self.managers.insert(manager_id, boxed_manager); self } /// Registers the system with the engine. pub fn register_system<T: System>(&mut self, system: T) -> &mut EngineBuilder { let system_id = SystemId::of::<T>(); assert!( !self.systems.contains_key(&system_id), "System {} with ID {:?} already registered", unsafe { type_name::<T>() }, &system_id); self.systems.insert(system_id, Box::new(system)); self } /// Registers the debug system with the engine. pub fn register_debug_system<T: System>(&mut self, system: T) -> &mut EngineBuilder { let system_id = SystemId::of::<T>(); assert!( !self.debug_systems.contains_key(&system_id), "System {} with ID {:?} already registered", unsafe { type_name::<T>() }, &system_id); self.debug_systems.insert(system_id, Box::new(system)); self } }
random_line_split
engine.rs
use std::thread; use std::collections::HashMap; use std::intrinsics::type_name; use std::mem; use std::ptr::{self, Unique}; use std::sync::{Arc, Barrier, Mutex}; use std::time::Duration; use bootstrap::input::ScanCode; use bootstrap::window::Window; use bootstrap::window::Message::*; use bootstrap::time::Timer; use bs_audio; use polygon::{Renderer, RendererBuilder}; use singleton::Singleton; use stopwatch::{Collector, Stopwatch}; use scene::*; use resource::ResourceManager; use ecs::*; use component::*; use debug_draw::DebugDraw; pub const TARGET_FRAME_TIME_SECONDS: f32 = 1.0 / 60.0; pub const TARGET_FRAME_TIME_MS: f32 = TARGET_FRAME_TIME_SECONDS * 1000.0; static mut INSTANCE: *mut Engine = ptr::null_mut(); pub struct Engine { renderer: Mutex<Box<Renderer>>, window: Window, resource_manager: Box<ResourceManager>, systems: HashMap<SystemId, Box<System>>, debug_systems: HashMap<SystemId, Box<System>>, // TODO: Replace explicit update ordering with something more automatic (e.g. dependency hierarchy). audio_update: Box<System>, alarm_update: Box<System>, collision_update: Box<System>, scene: Scene, debug_draw: DebugDraw, close: bool, debug_pause: bool, } impl Engine { /// Starts the engine's main loop, blocking until the game shuts down. /// /// This function starts the engine's internal update loop which handles the details of /// processing input from the OS, invoking game code, and rendering each frame. This function /// blocks until the engine recieves a message to being the shutdown process, at which point it /// will end the update loop and perform any necessary shutdown and cleanup procedures. Once /// those have completed this function will return. /// /// Panics if the engine hasn't been created yet. pub fn start() { let instance = unsafe { debug_assert!(!INSTANCE.is_null(), "Cannot retrieve Engine instance because none exists"); &mut *INSTANCE }; // Run main loop. instance.main_loop(); // Perform cleanup. unsafe { Engine::destroy_instance(); } } /// Retrieves a reference to current scene. /// /// Panics if the engine hasn't been created yet. pub fn scene<'a>() -> &'a Scene { let instance = Engine::instance(); &instance.scene } /// Retrieves a reference to the resource manager. /// /// TODO: The resource manager should probably be a singleton too since it's already setup to /// be used through shared references. pub fn resource_manager<'a>() -> &'a ResourceManager { let instance = Engine::instance(); &*instance.resource_manager } pub fn renderer<F, T>(func: F) -> T where F: FnOnce(&mut Renderer) -> T, { let instance = Engine::instance(); let mut renderer = instance.renderer.lock().expect("Could not acquire lock on renderer mutex"); func(&mut **renderer) } pub fn window() -> &'static Window { &Engine::instance().window } fn main_loop(&mut self) { let timer = Timer::new(); let mut collector = Collector::new().unwrap(); loop { let _stopwatch = Stopwatch::new("loop"); let start_time = timer.now(); self.update(); self.draw(); if self.close { println!("shutting down engine"); break; } if!cfg!(feature="timing") && timer.elapsed_ms(start_time) > TARGET_FRAME_TIME_MS { println!( "WARNING: Missed frame time. Frame time: {}ms, target frame time: {}ms", timer.elapsed_ms(start_time), TARGET_FRAME_TIME_MS); } // Wait for target frame time. let mut remaining_time_ms = TARGET_FRAME_TIME_MS - timer.elapsed_ms(start_time); while remaining_time_ms > 1.0 { thread::sleep(Duration::from_millis(remaining_time_ms as u64)); remaining_time_ms = TARGET_FRAME_TIME_MS - timer.elapsed_ms(start_time); } while remaining_time_ms > 0.0 { remaining_time_ms = TARGET_FRAME_TIME_MS - timer.elapsed_ms(start_time); } // TODO: Don't flip buffers until end of frame time? }; collector.flush_to_file("stopwatch.csv"); } fn update(&mut self) { let _stopwatch = Stopwatch::new("update"); let scene = &mut self.scene; scene.input.clear(); // TODO: Make this an iterator to simplify this loop. while let Some(message) = self.window.next_message() { match message { Activate => (), Close => self.close = true, Destroy => (), Paint => (), // Handle inputs. KeyDown(_) | KeyUp(_) | MouseMove(_, _) | MousePos(_, _) | MouseButtonPressed(_) | MouseButtonReleased(_) | MouseWheel(_) => scene.input.push_input(message), } } // TODO: More efficient handling of debug pause (i.e. something that doesn't have any // overhead when doing a release build). if!self.debug_pause || scene.input.key_pressed(ScanCode::F11) { self.debug_draw.clear_buffer(); self.alarm_update.update(scene, TARGET_FRAME_TIME_SECONDS); // Update systems. for (_, system) in self.systems.iter_mut() { system.update(scene, TARGET_FRAME_TIME_SECONDS); } // Update component managers. scene.update_managers(); } // Update debug systems always forever. for (_, system) in self.debug_systems.iter_mut() { system.update(scene, TARGET_FRAME_TIME_SECONDS); } // NOTE: Transform update used to go here. if!self.debug_pause || scene.input.key_pressed(ScanCode::F11) { self.collision_update.update(scene, TARGET_FRAME_TIME_SECONDS); self.audio_update.update(scene, TARGET_FRAME_TIME_SECONDS); } if scene.input.key_pressed(ScanCode::F9) { self.debug_pause =!self.debug_pause; } if scene.input.key_pressed(ScanCode::F11) { self.debug_pause = true; } } #[cfg(not(feature="no-draw"))] fn draw(&mut self) { let _stopwatch = Stopwatch::new("draw"); self.renderer .lock() .expect("Unable to acquire lock on renderer mutex for drawing") .draw(); } #[cfg(feature="no-draw")] fn draw(&mut self) {} } unsafe impl Singleton for Engine { /// Creates the instance of the singleton. fn
(engine: Engine) { assert!(unsafe { INSTANCE.is_null() }, "Cannot create more than one Engine instance"); let boxed_engine = Box::new(engine); unsafe { INSTANCE = Box::into_raw(boxed_engine); } } /// Retrieves an immutable reference to the singleton instance. /// /// This function is unsafe because there is no way of know fn instance() -> &'static Self { unsafe { debug_assert!(!INSTANCE.is_null(), "Cannot retrieve Engine instance because none exists"); &*INSTANCE } } /// Destroys the instance of the singleton. unsafe fn destroy_instance() { let ptr = mem::replace(&mut INSTANCE, ptr::null_mut()); Box::from_raw(ptr); } } pub struct EngineBuilder { systems: HashMap<SystemId, Box<System>>, debug_systems: HashMap<SystemId, Box<System>>, managers: ManagerMap, max_workers: usize, } /// A builder for configuring the components and systems registered with the game engine. /// /// Component managers and systems cannot be changed once the engine has been instantiated so they /// must be provided all together when the instance is created. `EngineBuilder` provides an /// interface for gathering all managers and systems to be provided to the engine. impl EngineBuilder { /// Creates a new `EngineBuilder` object. pub fn new() -> EngineBuilder { let mut builder = EngineBuilder { systems: HashMap::new(), debug_systems: HashMap::new(), managers: ManagerMap::new(), max_workers: 1, }; // Register internal component managers. builder.register_component::<Transform>(); builder.register_component::<Camera>(); builder.register_component::<Light>(); builder.register_component::<Mesh>(); builder.register_component::<AudioSource>(); builder.register_component::<AlarmId>(); builder.register_component::<Collider>(); builder } /// Consumes the builder and creates the `Engine` instance. /// /// No `Engine` object is returned because this method instantiates the engine singleton. pub fn build(self) { let engine = { let window = { let mut window = unsafe { mem::uninitialized() }; let mut out = unsafe { Unique::new(&mut window as *mut _) }; let barrier = Arc::new(Barrier::new(2)); let barrier_clone = barrier.clone(); thread::spawn(move || { let mut window = Window::new("gunship game").unwrap(); let mut message_pump = window.message_pump(); // write data out to `window` without dropping the old (uninitialized) value. unsafe { ptr::write(out.get_mut(), window); } // Sync with barrier_clone.wait(); message_pump.run(); }); // Wait until window thread finishe creating the window. barrier.wait(); window }; let mut renderer = RendererBuilder::new(&window).build(); let debug_draw = DebugDraw::new(&mut *renderer); let resource_manager = Box::new(ResourceManager::new()); let audio_source = match bs_audio::init() { Ok(audio_source) => audio_source, Err(error) => { // TODO: Rather than panicking, create a null audio system and keep running. panic!("Error while initialzing audio subsystem: {}", error) }, }; Engine { window: window, renderer: Mutex::new(renderer), resource_manager: resource_manager, systems: self.systems, debug_systems: self.debug_systems, audio_update: Box::new(AudioSystem), alarm_update: Box::new(alarm_update), collision_update: Box::new(CollisionSystem::new()), scene: Scene::new(audio_source, self.managers), debug_draw: debug_draw, close: false, debug_pause: false, } }; // Init aysnc subsystem. ::async::init(); ::async::start_workers(self.max_workers); Engine::set_instance(engine); run!(Engine::start()); } pub fn max_workers(&mut self, workers: usize) -> &mut EngineBuilder { assert!(workers > 0, "There must be at least one worker for the engine to run"); self.max_workers = workers; self } /// Registers the manager for the specified component type. /// /// Defers internally to `register_manager()`. pub fn register_component<T: Component>(&mut self) -> &mut EngineBuilder { T::Manager::register(self); self } /// Registers the specified manager with the engine. /// /// Defers internally to `ComponentManager::register()`. pub fn register_manager<T: ComponentManager>(&mut self, manager: T) -> &mut EngineBuilder { let manager_id = ManagerId::of::<T>(); assert!( !self.managers.contains_key(&manager_id), "Manager {} with ID {:?} already registered", unsafe { type_name::<T>() }, &manager_id); // Box the manager as a trait object to construct the data and vtable pointers. let boxed_manager = Box::new(manager); // Add the manager to the type map and the component id to the component map. self.managers.insert(manager_id, boxed_manager); self } /// Registers the system with the engine. pub fn register_system<T: System>(&mut self, system: T) -> &mut EngineBuilder { let system_id = SystemId::of::<T>(); assert!( !self.systems.contains_key(&system_id), "System {} with ID {:?} already registered", unsafe { type_name::<T>() }, &system_id); self.systems.insert(system_id, Box::new(system)); self } /// Registers the debug system with the engine. pub fn register_debug_system<T: System>(&mut self, system: T) -> &mut EngineBuilder { let system_id = SystemId::of::<T>(); assert!( !self.debug_systems.contains_key(&system_id), "System {} with ID {:?} already registered", unsafe { type_name::<T>() }, &system_id); self.debug_systems.insert(system_id, Box::new(system)); self } }
set_instance
identifier_name
engine.rs
use std::thread; use std::collections::HashMap; use std::intrinsics::type_name; use std::mem; use std::ptr::{self, Unique}; use std::sync::{Arc, Barrier, Mutex}; use std::time::Duration; use bootstrap::input::ScanCode; use bootstrap::window::Window; use bootstrap::window::Message::*; use bootstrap::time::Timer; use bs_audio; use polygon::{Renderer, RendererBuilder}; use singleton::Singleton; use stopwatch::{Collector, Stopwatch}; use scene::*; use resource::ResourceManager; use ecs::*; use component::*; use debug_draw::DebugDraw; pub const TARGET_FRAME_TIME_SECONDS: f32 = 1.0 / 60.0; pub const TARGET_FRAME_TIME_MS: f32 = TARGET_FRAME_TIME_SECONDS * 1000.0; static mut INSTANCE: *mut Engine = ptr::null_mut(); pub struct Engine { renderer: Mutex<Box<Renderer>>, window: Window, resource_manager: Box<ResourceManager>, systems: HashMap<SystemId, Box<System>>, debug_systems: HashMap<SystemId, Box<System>>, // TODO: Replace explicit update ordering with something more automatic (e.g. dependency hierarchy). audio_update: Box<System>, alarm_update: Box<System>, collision_update: Box<System>, scene: Scene, debug_draw: DebugDraw, close: bool, debug_pause: bool, } impl Engine { /// Starts the engine's main loop, blocking until the game shuts down. /// /// This function starts the engine's internal update loop which handles the details of /// processing input from the OS, invoking game code, and rendering each frame. This function /// blocks until the engine recieves a message to being the shutdown process, at which point it /// will end the update loop and perform any necessary shutdown and cleanup procedures. Once /// those have completed this function will return. /// /// Panics if the engine hasn't been created yet. pub fn start() { let instance = unsafe { debug_assert!(!INSTANCE.is_null(), "Cannot retrieve Engine instance because none exists"); &mut *INSTANCE }; // Run main loop. instance.main_loop(); // Perform cleanup. unsafe { Engine::destroy_instance(); } } /// Retrieves a reference to current scene. /// /// Panics if the engine hasn't been created yet. pub fn scene<'a>() -> &'a Scene { let instance = Engine::instance(); &instance.scene } /// Retrieves a reference to the resource manager. /// /// TODO: The resource manager should probably be a singleton too since it's already setup to /// be used through shared references. pub fn resource_manager<'a>() -> &'a ResourceManager { let instance = Engine::instance(); &*instance.resource_manager } pub fn renderer<F, T>(func: F) -> T where F: FnOnce(&mut Renderer) -> T, { let instance = Engine::instance(); let mut renderer = instance.renderer.lock().expect("Could not acquire lock on renderer mutex"); func(&mut **renderer) } pub fn window() -> &'static Window { &Engine::instance().window } fn main_loop(&mut self) { let timer = Timer::new(); let mut collector = Collector::new().unwrap(); loop { let _stopwatch = Stopwatch::new("loop"); let start_time = timer.now(); self.update(); self.draw(); if self.close { println!("shutting down engine"); break; } if!cfg!(feature="timing") && timer.elapsed_ms(start_time) > TARGET_FRAME_TIME_MS { println!( "WARNING: Missed frame time. Frame time: {}ms, target frame time: {}ms", timer.elapsed_ms(start_time), TARGET_FRAME_TIME_MS); } // Wait for target frame time. let mut remaining_time_ms = TARGET_FRAME_TIME_MS - timer.elapsed_ms(start_time); while remaining_time_ms > 1.0 { thread::sleep(Duration::from_millis(remaining_time_ms as u64)); remaining_time_ms = TARGET_FRAME_TIME_MS - timer.elapsed_ms(start_time); } while remaining_time_ms > 0.0 { remaining_time_ms = TARGET_FRAME_TIME_MS - timer.elapsed_ms(start_time); } // TODO: Don't flip buffers until end of frame time? }; collector.flush_to_file("stopwatch.csv"); } fn update(&mut self) { let _stopwatch = Stopwatch::new("update"); let scene = &mut self.scene; scene.input.clear(); // TODO: Make this an iterator to simplify this loop. while let Some(message) = self.window.next_message() { match message { Activate => (), Close => self.close = true, Destroy => (), Paint => (), // Handle inputs. KeyDown(_) | KeyUp(_) | MouseMove(_, _) | MousePos(_, _) | MouseButtonPressed(_) | MouseButtonReleased(_) | MouseWheel(_) => scene.input.push_input(message), } } // TODO: More efficient handling of debug pause (i.e. something that doesn't have any // overhead when doing a release build). if!self.debug_pause || scene.input.key_pressed(ScanCode::F11) { self.debug_draw.clear_buffer(); self.alarm_update.update(scene, TARGET_FRAME_TIME_SECONDS); // Update systems. for (_, system) in self.systems.iter_mut() { system.update(scene, TARGET_FRAME_TIME_SECONDS); } // Update component managers. scene.update_managers(); } // Update debug systems always forever. for (_, system) in self.debug_systems.iter_mut() { system.update(scene, TARGET_FRAME_TIME_SECONDS); } // NOTE: Transform update used to go here. if!self.debug_pause || scene.input.key_pressed(ScanCode::F11) { self.collision_update.update(scene, TARGET_FRAME_TIME_SECONDS); self.audio_update.update(scene, TARGET_FRAME_TIME_SECONDS); } if scene.input.key_pressed(ScanCode::F9) { self.debug_pause =!self.debug_pause; } if scene.input.key_pressed(ScanCode::F11) { self.debug_pause = true; } } #[cfg(not(feature="no-draw"))] fn draw(&mut self) { let _stopwatch = Stopwatch::new("draw"); self.renderer .lock() .expect("Unable to acquire lock on renderer mutex for drawing") .draw(); } #[cfg(feature="no-draw")] fn draw(&mut self)
} unsafe impl Singleton for Engine { /// Creates the instance of the singleton. fn set_instance(engine: Engine) { assert!(unsafe { INSTANCE.is_null() }, "Cannot create more than one Engine instance"); let boxed_engine = Box::new(engine); unsafe { INSTANCE = Box::into_raw(boxed_engine); } } /// Retrieves an immutable reference to the singleton instance. /// /// This function is unsafe because there is no way of know fn instance() -> &'static Self { unsafe { debug_assert!(!INSTANCE.is_null(), "Cannot retrieve Engine instance because none exists"); &*INSTANCE } } /// Destroys the instance of the singleton. unsafe fn destroy_instance() { let ptr = mem::replace(&mut INSTANCE, ptr::null_mut()); Box::from_raw(ptr); } } pub struct EngineBuilder { systems: HashMap<SystemId, Box<System>>, debug_systems: HashMap<SystemId, Box<System>>, managers: ManagerMap, max_workers: usize, } /// A builder for configuring the components and systems registered with the game engine. /// /// Component managers and systems cannot be changed once the engine has been instantiated so they /// must be provided all together when the instance is created. `EngineBuilder` provides an /// interface for gathering all managers and systems to be provided to the engine. impl EngineBuilder { /// Creates a new `EngineBuilder` object. pub fn new() -> EngineBuilder { let mut builder = EngineBuilder { systems: HashMap::new(), debug_systems: HashMap::new(), managers: ManagerMap::new(), max_workers: 1, }; // Register internal component managers. builder.register_component::<Transform>(); builder.register_component::<Camera>(); builder.register_component::<Light>(); builder.register_component::<Mesh>(); builder.register_component::<AudioSource>(); builder.register_component::<AlarmId>(); builder.register_component::<Collider>(); builder } /// Consumes the builder and creates the `Engine` instance. /// /// No `Engine` object is returned because this method instantiates the engine singleton. pub fn build(self) { let engine = { let window = { let mut window = unsafe { mem::uninitialized() }; let mut out = unsafe { Unique::new(&mut window as *mut _) }; let barrier = Arc::new(Barrier::new(2)); let barrier_clone = barrier.clone(); thread::spawn(move || { let mut window = Window::new("gunship game").unwrap(); let mut message_pump = window.message_pump(); // write data out to `window` without dropping the old (uninitialized) value. unsafe { ptr::write(out.get_mut(), window); } // Sync with barrier_clone.wait(); message_pump.run(); }); // Wait until window thread finishe creating the window. barrier.wait(); window }; let mut renderer = RendererBuilder::new(&window).build(); let debug_draw = DebugDraw::new(&mut *renderer); let resource_manager = Box::new(ResourceManager::new()); let audio_source = match bs_audio::init() { Ok(audio_source) => audio_source, Err(error) => { // TODO: Rather than panicking, create a null audio system and keep running. panic!("Error while initialzing audio subsystem: {}", error) }, }; Engine { window: window, renderer: Mutex::new(renderer), resource_manager: resource_manager, systems: self.systems, debug_systems: self.debug_systems, audio_update: Box::new(AudioSystem), alarm_update: Box::new(alarm_update), collision_update: Box::new(CollisionSystem::new()), scene: Scene::new(audio_source, self.managers), debug_draw: debug_draw, close: false, debug_pause: false, } }; // Init aysnc subsystem. ::async::init(); ::async::start_workers(self.max_workers); Engine::set_instance(engine); run!(Engine::start()); } pub fn max_workers(&mut self, workers: usize) -> &mut EngineBuilder { assert!(workers > 0, "There must be at least one worker for the engine to run"); self.max_workers = workers; self } /// Registers the manager for the specified component type. /// /// Defers internally to `register_manager()`. pub fn register_component<T: Component>(&mut self) -> &mut EngineBuilder { T::Manager::register(self); self } /// Registers the specified manager with the engine. /// /// Defers internally to `ComponentManager::register()`. pub fn register_manager<T: ComponentManager>(&mut self, manager: T) -> &mut EngineBuilder { let manager_id = ManagerId::of::<T>(); assert!( !self.managers.contains_key(&manager_id), "Manager {} with ID {:?} already registered", unsafe { type_name::<T>() }, &manager_id); // Box the manager as a trait object to construct the data and vtable pointers. let boxed_manager = Box::new(manager); // Add the manager to the type map and the component id to the component map. self.managers.insert(manager_id, boxed_manager); self } /// Registers the system with the engine. pub fn register_system<T: System>(&mut self, system: T) -> &mut EngineBuilder { let system_id = SystemId::of::<T>(); assert!( !self.systems.contains_key(&system_id), "System {} with ID {:?} already registered", unsafe { type_name::<T>() }, &system_id); self.systems.insert(system_id, Box::new(system)); self } /// Registers the debug system with the engine. pub fn register_debug_system<T: System>(&mut self, system: T) -> &mut EngineBuilder { let system_id = SystemId::of::<T>(); assert!( !self.debug_systems.contains_key(&system_id), "System {} with ID {:?} already registered", unsafe { type_name::<T>() }, &system_id); self.debug_systems.insert(system_id, Box::new(system)); self } }
{}
identifier_body
ac97.rs
use alloc::boxed::Box; use core::{cmp, ptr, mem}; use common::memory; use schemes::{Resource, ResourceSeek, Url}; use common::time::{self, Duration}; use drivers::pci::config::PciConfig; use drivers::io::{Io, Pio}; use schemes::{Result, KScheme}; use syscall::{Error, EBADF}; #[repr(packed)] struct BD { ptr: u32, samples: u32, } struct AC97Resource { audio: usize, bus_master: usize, } impl Resource for AC97Resource { fn dup(&self) -> Result<Box<Resource>> { Ok(box AC97Resource { audio: self.audio, bus_master: self.bus_master, }) } fn url(&self) -> Url { Url::from_str("audio:") } fn read(&mut self, _: &mut [u8]) -> Result<usize> { Err(Error::new(EBADF)) } fn write(&mut self, buf: &[u8]) -> Result<usize> { unsafe { let audio = self.audio as u16; let mut master_volume = Pio::<u16>::new(audio + 2); let mut pcm_volume = Pio::<u16>::new(audio + 0x18); master_volume.write(0x808); pcm_volume.write(0x808); let bus_master = self.bus_master as u16; let mut po_bdbar = Pio::<u32>::new(bus_master + 0x10); let po_civ = Pio::<u8>::new(bus_master + 0x14); let mut po_lvi = Pio::<u8>::new(bus_master + 0x15); let mut po_cr = Pio::<u8>::new(bus_master + 0x1B); loop { if po_cr.read() & 1 == 0 { break; } Duration::new(0, 10 * time::NANOS_PER_MILLI).sleep(); } po_cr.write(0); let mut bdl = po_bdbar.read() as *mut BD; if bdl as usize == 0 { bdl = memory::alloc(32 * mem::size_of::<BD>()) as *mut BD; po_bdbar.write(bdl as u32); } for i in 0..32 { ptr::write(bdl.offset(i), BD { ptr: 0, samples: 0, }); } let mut wait = false; let mut position = 0; let mut lvi = po_lvi.read(); let start_lvi; if lvi == 0 { start_lvi = 31; } else { start_lvi = lvi - 1; } lvi += 1; if lvi >= 32 { lvi = 0; } loop { while wait { if po_civ.read()!= lvi as u8 { break; } Duration::new(0, 10 * time::NANOS_PER_MILLI).sleep(); } debug!("{} / {}: {} / {}\n", po_civ.read(), lvi as usize, position, buf.len()); let bytes = cmp::min(65534 * 2, (buf.len() - position + 1)); let samples = bytes / 2; ptr::write(bdl.offset(lvi as isize), BD { ptr: buf.as_ptr().offset(position as isize) as u32, samples: (samples & 0xFFFF) as u32, }); position += bytes; if position >= buf.len() { break; } lvi += 1; if lvi >= 32 { lvi = 0; } if lvi == start_lvi { po_lvi.write(start_lvi); po_cr.write(1); wait = true; } } po_lvi.write(lvi); po_cr.write(1); loop { if po_civ.read() == lvi { po_cr.write(0); break; } Duration::new(0, 10 * time::NANOS_PER_MILLI).sleep(); } debug!("Finished {} / {}\n", po_civ.read(), lvi); } Ok(buf.len()) } fn seek(&mut self, _: ResourceSeek) -> Result<usize> { Err(Error::new(EBADF)) } fn
(&mut self) -> Result<()> { Err(Error::new(EBADF)) } } pub struct AC97 { pub audio: usize, pub bus_master: usize, pub irq: u8, } impl KScheme for AC97 { fn scheme(&self) -> &str { "audio" } fn open(&mut self, _: &Url, _: usize) -> Result<Box<Resource>> { Ok(box AC97Resource { audio: self.audio, bus_master: self.bus_master, }) } fn on_irq(&mut self, irq: u8) { if irq == self.irq { // d("AC97 IRQ\n"); } } fn on_poll(&mut self) {} } impl AC97 { pub unsafe fn new(mut pci: PciConfig) -> Box<AC97> { pci.flag(4, 4, true); // Bus mastering let module = box AC97 { audio: pci.read(0x10) as usize & 0xFFFFFFF0, bus_master: pci.read(0x14) as usize & 0xFFFFFFF0, irq: pci.read(0x3C) as u8 & 0xF, }; debug!("AC97 on: {:X}, {:X}, IRQ: {:X}\n", module.audio, module.bus_master, module.irq); module } }
sync
identifier_name
ac97.rs
use alloc::boxed::Box; use core::{cmp, ptr, mem}; use common::memory; use schemes::{Resource, ResourceSeek, Url}; use common::time::{self, Duration}; use drivers::pci::config::PciConfig; use drivers::io::{Io, Pio}; use schemes::{Result, KScheme}; use syscall::{Error, EBADF}; #[repr(packed)] struct BD { ptr: u32, samples: u32, } struct AC97Resource { audio: usize, bus_master: usize, } impl Resource for AC97Resource { fn dup(&self) -> Result<Box<Resource>> { Ok(box AC97Resource { audio: self.audio, bus_master: self.bus_master, }) } fn url(&self) -> Url { Url::from_str("audio:") } fn read(&mut self, _: &mut [u8]) -> Result<usize> { Err(Error::new(EBADF)) } fn write(&mut self, buf: &[u8]) -> Result<usize> { unsafe { let audio = self.audio as u16; let mut master_volume = Pio::<u16>::new(audio + 2); let mut pcm_volume = Pio::<u16>::new(audio + 0x18); master_volume.write(0x808); pcm_volume.write(0x808); let bus_master = self.bus_master as u16; let mut po_bdbar = Pio::<u32>::new(bus_master + 0x10); let po_civ = Pio::<u8>::new(bus_master + 0x14); let mut po_lvi = Pio::<u8>::new(bus_master + 0x15); let mut po_cr = Pio::<u8>::new(bus_master + 0x1B); loop { if po_cr.read() & 1 == 0 { break; } Duration::new(0, 10 * time::NANOS_PER_MILLI).sleep(); } po_cr.write(0); let mut bdl = po_bdbar.read() as *mut BD; if bdl as usize == 0 { bdl = memory::alloc(32 * mem::size_of::<BD>()) as *mut BD; po_bdbar.write(bdl as u32); } for i in 0..32 { ptr::write(bdl.offset(i), BD { ptr: 0, samples: 0, }); } let mut wait = false; let mut position = 0; let mut lvi = po_lvi.read(); let start_lvi; if lvi == 0 { start_lvi = 31; } else { start_lvi = lvi - 1; } lvi += 1; if lvi >= 32 { lvi = 0; } loop { while wait { if po_civ.read()!= lvi as u8 { break; } Duration::new(0, 10 * time::NANOS_PER_MILLI).sleep(); } debug!("{} / {}: {} / {}\n", po_civ.read(), lvi as usize, position, buf.len()); let bytes = cmp::min(65534 * 2, (buf.len() - position + 1)); let samples = bytes / 2; ptr::write(bdl.offset(lvi as isize), BD { ptr: buf.as_ptr().offset(position as isize) as u32, samples: (samples & 0xFFFF) as u32, }); position += bytes; if position >= buf.len() { break; } lvi += 1; if lvi >= 32 { lvi = 0; } if lvi == start_lvi { po_lvi.write(start_lvi); po_cr.write(1); wait = true; } } po_lvi.write(lvi); po_cr.write(1); loop { if po_civ.read() == lvi { po_cr.write(0); break; } Duration::new(0, 10 * time::NANOS_PER_MILLI).sleep(); } debug!("Finished {} / {}\n", po_civ.read(), lvi); } Ok(buf.len()) } fn seek(&mut self, _: ResourceSeek) -> Result<usize>
fn sync(&mut self) -> Result<()> { Err(Error::new(EBADF)) } } pub struct AC97 { pub audio: usize, pub bus_master: usize, pub irq: u8, } impl KScheme for AC97 { fn scheme(&self) -> &str { "audio" } fn open(&mut self, _: &Url, _: usize) -> Result<Box<Resource>> { Ok(box AC97Resource { audio: self.audio, bus_master: self.bus_master, }) } fn on_irq(&mut self, irq: u8) { if irq == self.irq { // d("AC97 IRQ\n"); } } fn on_poll(&mut self) {} } impl AC97 { pub unsafe fn new(mut pci: PciConfig) -> Box<AC97> { pci.flag(4, 4, true); // Bus mastering let module = box AC97 { audio: pci.read(0x10) as usize & 0xFFFFFFF0, bus_master: pci.read(0x14) as usize & 0xFFFFFFF0, irq: pci.read(0x3C) as u8 & 0xF, }; debug!("AC97 on: {:X}, {:X}, IRQ: {:X}\n", module.audio, module.bus_master, module.irq); module } }
{ Err(Error::new(EBADF)) }
identifier_body
ac97.rs
use alloc::boxed::Box; use core::{cmp, ptr, mem}; use common::memory; use schemes::{Resource, ResourceSeek, Url}; use common::time::{self, Duration}; use drivers::pci::config::PciConfig; use drivers::io::{Io, Pio}; use schemes::{Result, KScheme}; use syscall::{Error, EBADF}; #[repr(packed)] struct BD { ptr: u32, samples: u32, } struct AC97Resource { audio: usize, bus_master: usize, } impl Resource for AC97Resource { fn dup(&self) -> Result<Box<Resource>> { Ok(box AC97Resource { audio: self.audio, bus_master: self.bus_master, }) } fn url(&self) -> Url { Url::from_str("audio:") } fn read(&mut self, _: &mut [u8]) -> Result<usize> { Err(Error::new(EBADF)) } fn write(&mut self, buf: &[u8]) -> Result<usize> { unsafe { let audio = self.audio as u16; let mut master_volume = Pio::<u16>::new(audio + 2); let mut pcm_volume = Pio::<u16>::new(audio + 0x18); master_volume.write(0x808); pcm_volume.write(0x808); let bus_master = self.bus_master as u16; let mut po_bdbar = Pio::<u32>::new(bus_master + 0x10); let po_civ = Pio::<u8>::new(bus_master + 0x14); let mut po_lvi = Pio::<u8>::new(bus_master + 0x15); let mut po_cr = Pio::<u8>::new(bus_master + 0x1B); loop { if po_cr.read() & 1 == 0 { break; } Duration::new(0, 10 * time::NANOS_PER_MILLI).sleep(); } po_cr.write(0); let mut bdl = po_bdbar.read() as *mut BD; if bdl as usize == 0 { bdl = memory::alloc(32 * mem::size_of::<BD>()) as *mut BD; po_bdbar.write(bdl as u32); } for i in 0..32 { ptr::write(bdl.offset(i), BD { ptr: 0, samples: 0, }); } let mut wait = false; let mut position = 0; let mut lvi = po_lvi.read(); let start_lvi; if lvi == 0 { start_lvi = 31; } else { start_lvi = lvi - 1; } lvi += 1; if lvi >= 32 { lvi = 0; } loop { while wait { if po_civ.read()!= lvi as u8 { break; } Duration::new(0, 10 * time::NANOS_PER_MILLI).sleep(); } debug!("{} / {}: {} / {}\n", po_civ.read(), lvi as usize, position, buf.len()); let bytes = cmp::min(65534 * 2, (buf.len() - position + 1)); let samples = bytes / 2; ptr::write(bdl.offset(lvi as isize), BD { ptr: buf.as_ptr().offset(position as isize) as u32, samples: (samples & 0xFFFF) as u32, }); position += bytes; if position >= buf.len() { break; } lvi += 1; if lvi >= 32 { lvi = 0; } if lvi == start_lvi { po_lvi.write(start_lvi);
po_cr.write(1); wait = true; } } po_lvi.write(lvi); po_cr.write(1); loop { if po_civ.read() == lvi { po_cr.write(0); break; } Duration::new(0, 10 * time::NANOS_PER_MILLI).sleep(); } debug!("Finished {} / {}\n", po_civ.read(), lvi); } Ok(buf.len()) } fn seek(&mut self, _: ResourceSeek) -> Result<usize> { Err(Error::new(EBADF)) } fn sync(&mut self) -> Result<()> { Err(Error::new(EBADF)) } } pub struct AC97 { pub audio: usize, pub bus_master: usize, pub irq: u8, } impl KScheme for AC97 { fn scheme(&self) -> &str { "audio" } fn open(&mut self, _: &Url, _: usize) -> Result<Box<Resource>> { Ok(box AC97Resource { audio: self.audio, bus_master: self.bus_master, }) } fn on_irq(&mut self, irq: u8) { if irq == self.irq { // d("AC97 IRQ\n"); } } fn on_poll(&mut self) {} } impl AC97 { pub unsafe fn new(mut pci: PciConfig) -> Box<AC97> { pci.flag(4, 4, true); // Bus mastering let module = box AC97 { audio: pci.read(0x10) as usize & 0xFFFFFFF0, bus_master: pci.read(0x14) as usize & 0xFFFFFFF0, irq: pci.read(0x3C) as u8 & 0xF, }; debug!("AC97 on: {:X}, {:X}, IRQ: {:X}\n", module.audio, module.bus_master, module.irq); module } }
random_line_split
ac97.rs
use alloc::boxed::Box; use core::{cmp, ptr, mem}; use common::memory; use schemes::{Resource, ResourceSeek, Url}; use common::time::{self, Duration}; use drivers::pci::config::PciConfig; use drivers::io::{Io, Pio}; use schemes::{Result, KScheme}; use syscall::{Error, EBADF}; #[repr(packed)] struct BD { ptr: u32, samples: u32, } struct AC97Resource { audio: usize, bus_master: usize, } impl Resource for AC97Resource { fn dup(&self) -> Result<Box<Resource>> { Ok(box AC97Resource { audio: self.audio, bus_master: self.bus_master, }) } fn url(&self) -> Url { Url::from_str("audio:") } fn read(&mut self, _: &mut [u8]) -> Result<usize> { Err(Error::new(EBADF)) } fn write(&mut self, buf: &[u8]) -> Result<usize> { unsafe { let audio = self.audio as u16; let mut master_volume = Pio::<u16>::new(audio + 2); let mut pcm_volume = Pio::<u16>::new(audio + 0x18); master_volume.write(0x808); pcm_volume.write(0x808); let bus_master = self.bus_master as u16; let mut po_bdbar = Pio::<u32>::new(bus_master + 0x10); let po_civ = Pio::<u8>::new(bus_master + 0x14); let mut po_lvi = Pio::<u8>::new(bus_master + 0x15); let mut po_cr = Pio::<u8>::new(bus_master + 0x1B); loop { if po_cr.read() & 1 == 0 { break; } Duration::new(0, 10 * time::NANOS_PER_MILLI).sleep(); } po_cr.write(0); let mut bdl = po_bdbar.read() as *mut BD; if bdl as usize == 0 { bdl = memory::alloc(32 * mem::size_of::<BD>()) as *mut BD; po_bdbar.write(bdl as u32); } for i in 0..32 { ptr::write(bdl.offset(i), BD { ptr: 0, samples: 0, }); } let mut wait = false; let mut position = 0; let mut lvi = po_lvi.read(); let start_lvi; if lvi == 0 { start_lvi = 31; } else { start_lvi = lvi - 1; } lvi += 1; if lvi >= 32 { lvi = 0; } loop { while wait { if po_civ.read()!= lvi as u8 { break; } Duration::new(0, 10 * time::NANOS_PER_MILLI).sleep(); } debug!("{} / {}: {} / {}\n", po_civ.read(), lvi as usize, position, buf.len()); let bytes = cmp::min(65534 * 2, (buf.len() - position + 1)); let samples = bytes / 2; ptr::write(bdl.offset(lvi as isize), BD { ptr: buf.as_ptr().offset(position as isize) as u32, samples: (samples & 0xFFFF) as u32, }); position += bytes; if position >= buf.len() { break; } lvi += 1; if lvi >= 32
if lvi == start_lvi { po_lvi.write(start_lvi); po_cr.write(1); wait = true; } } po_lvi.write(lvi); po_cr.write(1); loop { if po_civ.read() == lvi { po_cr.write(0); break; } Duration::new(0, 10 * time::NANOS_PER_MILLI).sleep(); } debug!("Finished {} / {}\n", po_civ.read(), lvi); } Ok(buf.len()) } fn seek(&mut self, _: ResourceSeek) -> Result<usize> { Err(Error::new(EBADF)) } fn sync(&mut self) -> Result<()> { Err(Error::new(EBADF)) } } pub struct AC97 { pub audio: usize, pub bus_master: usize, pub irq: u8, } impl KScheme for AC97 { fn scheme(&self) -> &str { "audio" } fn open(&mut self, _: &Url, _: usize) -> Result<Box<Resource>> { Ok(box AC97Resource { audio: self.audio, bus_master: self.bus_master, }) } fn on_irq(&mut self, irq: u8) { if irq == self.irq { // d("AC97 IRQ\n"); } } fn on_poll(&mut self) {} } impl AC97 { pub unsafe fn new(mut pci: PciConfig) -> Box<AC97> { pci.flag(4, 4, true); // Bus mastering let module = box AC97 { audio: pci.read(0x10) as usize & 0xFFFFFFF0, bus_master: pci.read(0x14) as usize & 0xFFFFFFF0, irq: pci.read(0x3C) as u8 & 0xF, }; debug!("AC97 on: {:X}, {:X}, IRQ: {:X}\n", module.audio, module.bus_master, module.irq); module } }
{ lvi = 0; }
conditional_block
local_http_server.rs
use async_graphql::http::{playground_source, GraphQLPlaygroundConfig}; use printspool_auth::AuthContext; use tracing::Instrument; use warp::{Filter, http::Response as HttpResponse, hyper::Method}; use eyre::{ // eyre, Result, // Error, // Context as _, }; #[derive(Debug)] pub struct InternalServerError; impl warp::reject::Reject for InternalServerError {} pub async fn start( db: &crate::Db, schema_builder: crate::AppSchemaBuilder, ) -> Result<()> { if &std::env::var("INSECURE_LOCAL_CONNECTION").unwrap_or("0".to_string()) == "0" { debug!("Secure Connections Only: Insecure local connections are disabled."); futures_util::future::pending::<()>().await; return Ok(()) } debug!("Insecure local connections are enabled"); let port = std::env::var("LOCAL_HTTP_PORT") .unwrap_or("20807".to_string()) .parse() .expect("Invalid $LOCAL_HTTP_PORT"); info!("Playground: http://localhost:{}/playground", port); let auth = AuthContext::local_http_auth(db).await?; let schema = schema_builder .data(auth) .finish(); let graphql_post = async_graphql_warp::graphql(schema.clone()) .and(warp::body::content_length_limit(1024 * 1024 * 1024)) .and_then(move | graphql_tuple, | { let (schema, request): ( crate::AppSchema, async_graphql::Request, ) = graphql_tuple; async move { let root_span = span!( parent: None, tracing::Level::INFO, "query root" ); let result = schema.execute(request) .instrument(root_span) .await; Ok::<async_graphql_warp::Response, warp::Rejection>( async_graphql_warp::Response::from(result) ) } }); let graphql_subscription = async_graphql_warp::graphql_subscription_with_data(schema, |_| async { let data = async_graphql::Data::default(); // let root_span = span!( // parent: None, // tracing::Level::INFO, // "span root" // ); Ok(data) }); let graphql_playground = warp::path("playground").and(warp::get()).map(|| { HttpResponse::builder() .header("content-type", "text/html") .body(playground_source( GraphQLPlaygroundConfig::new("/graphql") .subscription_endpoint("/"), )) }); let is_dev = std::env::var("RUST_ENV") .ok() .map(|rust_env| &rust_env == "development") .unwrap_or(true); if is_dev { let cors = warp::cors() .allow_any_origin() .allow_methods(&[Method::GET, Method::POST, Method::DELETE]) .allow_headers(vec!["authorization", "content-type"]); let cors_route = warp::options() .map(warp::reply); let routes = graphql_playground .or(graphql_post) .or(graphql_subscription) .or(cors_route) .with(cors); warp::serve(routes).run(([0, 0, 0, 0], port)).await; } else { // Disable CORS in production to prevent unauthorized 3D printer access from random websites let routes = graphql_playground .or(graphql_post) .or(graphql_subscription); warp::serve(routes).run(([0, 0, 0, 0], port)).await; } Ok(())
}
random_line_split
local_http_server.rs
use async_graphql::http::{playground_source, GraphQLPlaygroundConfig}; use printspool_auth::AuthContext; use tracing::Instrument; use warp::{Filter, http::Response as HttpResponse, hyper::Method}; use eyre::{ // eyre, Result, // Error, // Context as _, }; #[derive(Debug)] pub struct InternalServerError; impl warp::reject::Reject for InternalServerError {} pub async fn start( db: &crate::Db, schema_builder: crate::AppSchemaBuilder, ) -> Result<()> { if &std::env::var("INSECURE_LOCAL_CONNECTION").unwrap_or("0".to_string()) == "0" { debug!("Secure Connections Only: Insecure local connections are disabled."); futures_util::future::pending::<()>().await; return Ok(()) } debug!("Insecure local connections are enabled"); let port = std::env::var("LOCAL_HTTP_PORT") .unwrap_or("20807".to_string()) .parse() .expect("Invalid $LOCAL_HTTP_PORT"); info!("Playground: http://localhost:{}/playground", port); let auth = AuthContext::local_http_auth(db).await?; let schema = schema_builder .data(auth) .finish(); let graphql_post = async_graphql_warp::graphql(schema.clone()) .and(warp::body::content_length_limit(1024 * 1024 * 1024)) .and_then(move | graphql_tuple, | { let (schema, request): ( crate::AppSchema, async_graphql::Request, ) = graphql_tuple; async move { let root_span = span!( parent: None, tracing::Level::INFO, "query root" ); let result = schema.execute(request) .instrument(root_span) .await; Ok::<async_graphql_warp::Response, warp::Rejection>( async_graphql_warp::Response::from(result) ) } }); let graphql_subscription = async_graphql_warp::graphql_subscription_with_data(schema, |_| async { let data = async_graphql::Data::default(); // let root_span = span!( // parent: None, // tracing::Level::INFO, // "span root" // ); Ok(data) }); let graphql_playground = warp::path("playground").and(warp::get()).map(|| { HttpResponse::builder() .header("content-type", "text/html") .body(playground_source( GraphQLPlaygroundConfig::new("/graphql") .subscription_endpoint("/"), )) }); let is_dev = std::env::var("RUST_ENV") .ok() .map(|rust_env| &rust_env == "development") .unwrap_or(true); if is_dev { let cors = warp::cors() .allow_any_origin() .allow_methods(&[Method::GET, Method::POST, Method::DELETE]) .allow_headers(vec!["authorization", "content-type"]); let cors_route = warp::options() .map(warp::reply); let routes = graphql_playground .or(graphql_post) .or(graphql_subscription) .or(cors_route) .with(cors); warp::serve(routes).run(([0, 0, 0, 0], port)).await; } else
Ok(()) }
{ // Disable CORS in production to prevent unauthorized 3D printer access from random websites let routes = graphql_playground .or(graphql_post) .or(graphql_subscription); warp::serve(routes).run(([0, 0, 0, 0], port)).await; }
conditional_block
local_http_server.rs
use async_graphql::http::{playground_source, GraphQLPlaygroundConfig}; use printspool_auth::AuthContext; use tracing::Instrument; use warp::{Filter, http::Response as HttpResponse, hyper::Method}; use eyre::{ // eyre, Result, // Error, // Context as _, }; #[derive(Debug)] pub struct InternalServerError; impl warp::reject::Reject for InternalServerError {} pub async fn
( db: &crate::Db, schema_builder: crate::AppSchemaBuilder, ) -> Result<()> { if &std::env::var("INSECURE_LOCAL_CONNECTION").unwrap_or("0".to_string()) == "0" { debug!("Secure Connections Only: Insecure local connections are disabled."); futures_util::future::pending::<()>().await; return Ok(()) } debug!("Insecure local connections are enabled"); let port = std::env::var("LOCAL_HTTP_PORT") .unwrap_or("20807".to_string()) .parse() .expect("Invalid $LOCAL_HTTP_PORT"); info!("Playground: http://localhost:{}/playground", port); let auth = AuthContext::local_http_auth(db).await?; let schema = schema_builder .data(auth) .finish(); let graphql_post = async_graphql_warp::graphql(schema.clone()) .and(warp::body::content_length_limit(1024 * 1024 * 1024)) .and_then(move | graphql_tuple, | { let (schema, request): ( crate::AppSchema, async_graphql::Request, ) = graphql_tuple; async move { let root_span = span!( parent: None, tracing::Level::INFO, "query root" ); let result = schema.execute(request) .instrument(root_span) .await; Ok::<async_graphql_warp::Response, warp::Rejection>( async_graphql_warp::Response::from(result) ) } }); let graphql_subscription = async_graphql_warp::graphql_subscription_with_data(schema, |_| async { let data = async_graphql::Data::default(); // let root_span = span!( // parent: None, // tracing::Level::INFO, // "span root" // ); Ok(data) }); let graphql_playground = warp::path("playground").and(warp::get()).map(|| { HttpResponse::builder() .header("content-type", "text/html") .body(playground_source( GraphQLPlaygroundConfig::new("/graphql") .subscription_endpoint("/"), )) }); let is_dev = std::env::var("RUST_ENV") .ok() .map(|rust_env| &rust_env == "development") .unwrap_or(true); if is_dev { let cors = warp::cors() .allow_any_origin() .allow_methods(&[Method::GET, Method::POST, Method::DELETE]) .allow_headers(vec!["authorization", "content-type"]); let cors_route = warp::options() .map(warp::reply); let routes = graphql_playground .or(graphql_post) .or(graphql_subscription) .or(cors_route) .with(cors); warp::serve(routes).run(([0, 0, 0, 0], port)).await; } else { // Disable CORS in production to prevent unauthorized 3D printer access from random websites let routes = graphql_playground .or(graphql_post) .or(graphql_subscription); warp::serve(routes).run(([0, 0, 0, 0], port)).await; } Ok(()) }
start
identifier_name
local_http_server.rs
use async_graphql::http::{playground_source, GraphQLPlaygroundConfig}; use printspool_auth::AuthContext; use tracing::Instrument; use warp::{Filter, http::Response as HttpResponse, hyper::Method}; use eyre::{ // eyre, Result, // Error, // Context as _, }; #[derive(Debug)] pub struct InternalServerError; impl warp::reject::Reject for InternalServerError {} pub async fn start( db: &crate::Db, schema_builder: crate::AppSchemaBuilder, ) -> Result<()>
.finish(); let graphql_post = async_graphql_warp::graphql(schema.clone()) .and(warp::body::content_length_limit(1024 * 1024 * 1024)) .and_then(move | graphql_tuple, | { let (schema, request): ( crate::AppSchema, async_graphql::Request, ) = graphql_tuple; async move { let root_span = span!( parent: None, tracing::Level::INFO, "query root" ); let result = schema.execute(request) .instrument(root_span) .await; Ok::<async_graphql_warp::Response, warp::Rejection>( async_graphql_warp::Response::from(result) ) } }); let graphql_subscription = async_graphql_warp::graphql_subscription_with_data(schema, |_| async { let data = async_graphql::Data::default(); // let root_span = span!( // parent: None, // tracing::Level::INFO, // "span root" // ); Ok(data) }); let graphql_playground = warp::path("playground").and(warp::get()).map(|| { HttpResponse::builder() .header("content-type", "text/html") .body(playground_source( GraphQLPlaygroundConfig::new("/graphql") .subscription_endpoint("/"), )) }); let is_dev = std::env::var("RUST_ENV") .ok() .map(|rust_env| &rust_env == "development") .unwrap_or(true); if is_dev { let cors = warp::cors() .allow_any_origin() .allow_methods(&[Method::GET, Method::POST, Method::DELETE]) .allow_headers(vec!["authorization", "content-type"]); let cors_route = warp::options() .map(warp::reply); let routes = graphql_playground .or(graphql_post) .or(graphql_subscription) .or(cors_route) .with(cors); warp::serve(routes).run(([0, 0, 0, 0], port)).await; } else { // Disable CORS in production to prevent unauthorized 3D printer access from random websites let routes = graphql_playground .or(graphql_post) .or(graphql_subscription); warp::serve(routes).run(([0, 0, 0, 0], port)).await; } Ok(()) }
{ if &std::env::var("INSECURE_LOCAL_CONNECTION").unwrap_or("0".to_string()) == "0" { debug!("Secure Connections Only: Insecure local connections are disabled."); futures_util::future::pending::<()>().await; return Ok(()) } debug!("Insecure local connections are enabled"); let port = std::env::var("LOCAL_HTTP_PORT") .unwrap_or("20807".to_string()) .parse() .expect("Invalid $LOCAL_HTTP_PORT"); info!("Playground: http://localhost:{}/playground", port); let auth = AuthContext::local_http_auth(db).await?; let schema = schema_builder .data(auth)
identifier_body
static-vec-autoref.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. struct T(&'static [int]); static A: T = T(&'static [5, 4, 3]); static B: T = T(&[5, 4, 3]); static C: T = T([5, 4, 3]); pub fn
() { assert_eq!(A[0], 5); assert_eq!(B[1], 4); assert_eq!(C[2], 3); }
main
identifier_name
static-vec-autoref.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at
// <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. struct T(&'static [int]); static A: T = T(&'static [5, 4, 3]); static B: T = T(&[5, 4, 3]); static C: T = T([5, 4, 3]); pub fn main() { assert_eq!(A[0], 5); assert_eq!(B[1], 4); assert_eq!(C[2], 3); }
// 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
random_line_split
static-vec-autoref.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. struct T(&'static [int]); static A: T = T(&'static [5, 4, 3]); static B: T = T(&[5, 4, 3]); static C: T = T([5, 4, 3]); pub fn main()
{ assert_eq!(A[0], 5); assert_eq!(B[1], 4); assert_eq!(C[2], 3); }
identifier_body
cssconditionrule.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::CSSConditionRuleBinding::CSSConditionRuleMethods; use dom::bindings::inheritance::Castable; use dom::bindings::str::DOMString; use dom::cssgroupingrule::CSSGroupingRule; use dom::cssmediarule::CSSMediaRule; use dom::cssstylesheet::CSSStyleSheet; use dom::csssupportsrule::CSSSupportsRule; use dom_struct::dom_struct; use std::sync::Arc; use style::shared_lock::{SharedRwLock, Locked};
pub struct CSSConditionRule { cssgroupingrule: CSSGroupingRule, } impl CSSConditionRule { pub fn new_inherited(parent_stylesheet: &CSSStyleSheet, rules: Arc<Locked<StyleCssRules>>) -> CSSConditionRule { CSSConditionRule { cssgroupingrule: CSSGroupingRule::new_inherited(parent_stylesheet, rules), } } pub fn parent_stylesheet(&self) -> &CSSStyleSheet { self.cssgroupingrule.parent_stylesheet() } pub fn shared_lock(&self) -> &SharedRwLock { self.cssgroupingrule.shared_lock() } } impl CSSConditionRuleMethods for CSSConditionRule { /// https://drafts.csswg.org/css-conditional-3/#dom-cssconditionrule-conditiontext fn ConditionText(&self) -> DOMString { if let Some(rule) = self.downcast::<CSSMediaRule>() { rule.get_condition_text() } else if let Some(rule) = self.downcast::<CSSSupportsRule>() { rule.get_condition_text() } else { unreachable!() } } /// https://drafts.csswg.org/css-conditional-3/#dom-cssconditionrule-conditiontext fn SetConditionText(&self, text: DOMString) { if let Some(rule) = self.downcast::<CSSMediaRule>() { rule.set_condition_text(text) } else if let Some(rule) = self.downcast::<CSSSupportsRule>() { rule.set_condition_text(text) } else { unreachable!() } } }
use style::stylesheets::CssRules as StyleCssRules; #[dom_struct]
random_line_split
cssconditionrule.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::CSSConditionRuleBinding::CSSConditionRuleMethods; use dom::bindings::inheritance::Castable; use dom::bindings::str::DOMString; use dom::cssgroupingrule::CSSGroupingRule; use dom::cssmediarule::CSSMediaRule; use dom::cssstylesheet::CSSStyleSheet; use dom::csssupportsrule::CSSSupportsRule; use dom_struct::dom_struct; use std::sync::Arc; use style::shared_lock::{SharedRwLock, Locked}; use style::stylesheets::CssRules as StyleCssRules; #[dom_struct] pub struct CSSConditionRule { cssgroupingrule: CSSGroupingRule, } impl CSSConditionRule { pub fn new_inherited(parent_stylesheet: &CSSStyleSheet, rules: Arc<Locked<StyleCssRules>>) -> CSSConditionRule { CSSConditionRule { cssgroupingrule: CSSGroupingRule::new_inherited(parent_stylesheet, rules), } } pub fn parent_stylesheet(&self) -> &CSSStyleSheet { self.cssgroupingrule.parent_stylesheet() } pub fn shared_lock(&self) -> &SharedRwLock { self.cssgroupingrule.shared_lock() } } impl CSSConditionRuleMethods for CSSConditionRule { /// https://drafts.csswg.org/css-conditional-3/#dom-cssconditionrule-conditiontext fn
(&self) -> DOMString { if let Some(rule) = self.downcast::<CSSMediaRule>() { rule.get_condition_text() } else if let Some(rule) = self.downcast::<CSSSupportsRule>() { rule.get_condition_text() } else { unreachable!() } } /// https://drafts.csswg.org/css-conditional-3/#dom-cssconditionrule-conditiontext fn SetConditionText(&self, text: DOMString) { if let Some(rule) = self.downcast::<CSSMediaRule>() { rule.set_condition_text(text) } else if let Some(rule) = self.downcast::<CSSSupportsRule>() { rule.set_condition_text(text) } else { unreachable!() } } }
ConditionText
identifier_name
cssconditionrule.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::CSSConditionRuleBinding::CSSConditionRuleMethods; use dom::bindings::inheritance::Castable; use dom::bindings::str::DOMString; use dom::cssgroupingrule::CSSGroupingRule; use dom::cssmediarule::CSSMediaRule; use dom::cssstylesheet::CSSStyleSheet; use dom::csssupportsrule::CSSSupportsRule; use dom_struct::dom_struct; use std::sync::Arc; use style::shared_lock::{SharedRwLock, Locked}; use style::stylesheets::CssRules as StyleCssRules; #[dom_struct] pub struct CSSConditionRule { cssgroupingrule: CSSGroupingRule, } impl CSSConditionRule { pub fn new_inherited(parent_stylesheet: &CSSStyleSheet, rules: Arc<Locked<StyleCssRules>>) -> CSSConditionRule { CSSConditionRule { cssgroupingrule: CSSGroupingRule::new_inherited(parent_stylesheet, rules), } } pub fn parent_stylesheet(&self) -> &CSSStyleSheet
pub fn shared_lock(&self) -> &SharedRwLock { self.cssgroupingrule.shared_lock() } } impl CSSConditionRuleMethods for CSSConditionRule { /// https://drafts.csswg.org/css-conditional-3/#dom-cssconditionrule-conditiontext fn ConditionText(&self) -> DOMString { if let Some(rule) = self.downcast::<CSSMediaRule>() { rule.get_condition_text() } else if let Some(rule) = self.downcast::<CSSSupportsRule>() { rule.get_condition_text() } else { unreachable!() } } /// https://drafts.csswg.org/css-conditional-3/#dom-cssconditionrule-conditiontext fn SetConditionText(&self, text: DOMString) { if let Some(rule) = self.downcast::<CSSMediaRule>() { rule.set_condition_text(text) } else if let Some(rule) = self.downcast::<CSSSupportsRule>() { rule.set_condition_text(text) } else { unreachable!() } } }
{ self.cssgroupingrule.parent_stylesheet() }
identifier_body
monomorphize.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use back::link::exported_name; use driver::session; use llvm::ValueRef; use llvm; use middle::subst; use middle::subst::Subst; use middle::trans::base::{set_llvm_fn_attrs, set_inline_hint}; use middle::trans::base::{trans_enum_variant, push_ctxt, get_item_val}; use middle::trans::base::{trans_fn, decl_internal_rust_fn}; use middle::trans::base; use middle::trans::common::*; use middle::trans::foreign; use middle::ty; use util::ppaux::Repr; use syntax::abi; use syntax::ast; use syntax::ast_map; use syntax::ast_util::{local_def, PostExpansionMethod}; use syntax::attr; use std::hash::{sip, Hash}; pub fn
(ccx: &CrateContext, fn_id: ast::DefId, real_substs: &subst::Substs, ref_id: Option<ast::NodeId>) -> (ValueRef, bool) { debug!("monomorphic_fn(\ fn_id={}, \ real_substs={}, \ ref_id={:?})", fn_id.repr(ccx.tcx()), real_substs.repr(ccx.tcx()), ref_id); assert!(real_substs.types.all(|t| { !ty::type_needs_infer(*t) &&!ty::type_has_params(*t) })); let _icx = push_ctxt("monomorphic_fn"); let hash_id = MonoId { def: fn_id, params: real_substs.types.clone() }; match ccx.monomorphized().borrow().find(&hash_id) { Some(&val) => { debug!("leaving monomorphic fn {}", ty::item_path_str(ccx.tcx(), fn_id)); return (val, false); } None => () } let psubsts = param_substs { substs: (*real_substs).clone(), }; debug!("monomorphic_fn(\ fn_id={}, \ psubsts={}, \ hash_id={:?})", fn_id.repr(ccx.tcx()), psubsts.repr(ccx.tcx()), hash_id); let tpt = ty::lookup_item_type(ccx.tcx(), fn_id); let llitem_ty = tpt.ty; let map_node = session::expect( ccx.sess(), ccx.tcx().map.find(fn_id.node), || { format!("while monomorphizing {:?}, couldn't find it in \ the item map (may have attempted to monomorphize \ an item defined in a different crate?)", fn_id) }); match map_node { ast_map::NodeForeignItem(_) => { if ccx.tcx().map.get_foreign_abi(fn_id.node)!= abi::RustIntrinsic { // Foreign externs don't have to be monomorphized. return (get_item_val(ccx, fn_id.node), true); } } _ => {} } debug!("monomorphic_fn about to subst into {}", llitem_ty.repr(ccx.tcx())); let mono_ty = llitem_ty.subst(ccx.tcx(), real_substs); ccx.stats().n_monos.set(ccx.stats().n_monos.get() + 1); let depth; { let mut monomorphizing = ccx.monomorphizing().borrow_mut(); depth = match monomorphizing.find(&fn_id) { Some(&d) => d, None => 0 }; // Random cut-off -- code that needs to instantiate the same function // recursively more than thirty times can probably safely be assumed // to be causing an infinite expansion. if depth > ccx.sess().recursion_limit.get() { ccx.sess().span_fatal(ccx.tcx().map.span(fn_id.node), "reached the recursion limit during monomorphization"); } monomorphizing.insert(fn_id, depth + 1); } let hash; let s = { let mut state = sip::SipState::new(); hash_id.hash(&mut state); mono_ty.hash(&mut state); hash = format!("h{}", state.result()); ccx.tcx().map.with_path(fn_id.node, |path| { exported_name(path, hash.as_slice()) }) }; debug!("monomorphize_fn mangled to {}", s); // This shouldn't need to option dance. let mut hash_id = Some(hash_id); let mk_lldecl = |abi: abi::Abi| { let lldecl = if abi!= abi::Rust { foreign::decl_rust_fn_with_foreign_abi(ccx, mono_ty, s.as_slice()) } else { decl_internal_rust_fn(ccx, mono_ty, s.as_slice()) }; ccx.monomorphized().borrow_mut().insert(hash_id.take().unwrap(), lldecl); lldecl }; let setup_lldecl = |lldecl, attrs: &[ast::Attribute]| { base::update_linkage(ccx, lldecl, None, base::OriginalTranslation); set_llvm_fn_attrs(attrs, lldecl); let is_first =!ccx.available_monomorphizations().borrow().contains(&s); if is_first { ccx.available_monomorphizations().borrow_mut().insert(s.clone()); } let trans_everywhere = attr::requests_inline(attrs); if trans_everywhere &&!is_first { llvm::SetLinkage(lldecl, llvm::AvailableExternallyLinkage); } // If `true`, then `lldecl` should be given a function body. // Otherwise, it should be left as a declaration of an external // function, with no definition in the current compilation unit. trans_everywhere || is_first }; let lldecl = match map_node { ast_map::NodeItem(i) => { match *i { ast::Item { node: ast::ItemFn(ref decl, _, abi, _, ref body), .. } => { let d = mk_lldecl(abi); let needs_body = setup_lldecl(d, i.attrs.as_slice()); if needs_body { if abi!= abi::Rust { foreign::trans_rust_fn_with_foreign_abi( ccx, &**decl, &**body, [], d, &psubsts, fn_id.node, Some(hash.as_slice())); } else { trans_fn(ccx, &**decl, &**body, d, &psubsts, fn_id.node, []); } } d } _ => { ccx.sess().bug("Can't monomorphize this kind of item") } } } ast_map::NodeVariant(v) => { let parent = ccx.tcx().map.get_parent(fn_id.node); let tvs = ty::enum_variants(ccx.tcx(), local_def(parent)); let this_tv = tvs.iter().find(|tv| { tv.id.node == fn_id.node}).unwrap(); let d = mk_lldecl(abi::Rust); set_inline_hint(d); match v.node.kind { ast::TupleVariantKind(ref args) => { trans_enum_variant(ccx, parent, &*v, args.as_slice(), this_tv.disr_val, &psubsts, d); } ast::StructVariantKind(_) => ccx.sess().bug("can't monomorphize struct variants"), } d } ast_map::NodeImplItem(ii) => { match *ii { ast::MethodImplItem(ref mth) => { let d = mk_lldecl(abi::Rust); let needs_body = setup_lldecl(d, mth.attrs.as_slice()); if needs_body { trans_fn(ccx, mth.pe_fn_decl(), mth.pe_body(), d, &psubsts, mth.id, []); } d } ast::TypeImplItem(_) => { ccx.sess().bug("can't monomorphize an associated type") } } } ast_map::NodeTraitItem(method) => { match *method { ast::ProvidedMethod(ref mth) => { let d = mk_lldecl(abi::Rust); let needs_body = setup_lldecl(d, mth.attrs.as_slice()); if needs_body { trans_fn(ccx, mth.pe_fn_decl(), mth.pe_body(), d, &psubsts, mth.id, []); } d } _ => { ccx.sess().bug(format!("can't monomorphize a {:?}", map_node).as_slice()) } } } ast_map::NodeStructCtor(struct_def) => { let d = mk_lldecl(abi::Rust); set_inline_hint(d); base::trans_tuple_struct(ccx, struct_def.fields.as_slice(), struct_def.ctor_id.expect("ast-mapped tuple struct \ didn't have a ctor id"), &psubsts, d); d } // Ugh -- but this ensures any new variants won't be forgotten ast_map::NodeForeignItem(..) | ast_map::NodeLifetime(..) | ast_map::NodeExpr(..) | ast_map::NodeStmt(..) | ast_map::NodeArg(..) | ast_map::NodeBlock(..) | ast_map::NodePat(..) | ast_map::NodeLocal(..) => { ccx.sess().bug(format!("can't monomorphize a {:?}", map_node).as_slice()) } }; ccx.monomorphizing().borrow_mut().insert(fn_id, depth); debug!("leaving monomorphic fn {}", ty::item_path_str(ccx.tcx(), fn_id)); (lldecl, true) } #[deriving(PartialEq, Eq, Hash)] pub struct MonoId { pub def: ast::DefId, pub params: subst::VecPerParamSpace<ty::t> }
monomorphic_fn
identifier_name
monomorphize.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use back::link::exported_name; use driver::session; use llvm::ValueRef; use llvm; use middle::subst; use middle::subst::Subst; use middle::trans::base::{set_llvm_fn_attrs, set_inline_hint}; use middle::trans::base::{trans_enum_variant, push_ctxt, get_item_val}; use middle::trans::base::{trans_fn, decl_internal_rust_fn}; use middle::trans::base; use middle::trans::common::*; use middle::trans::foreign; use middle::ty; use util::ppaux::Repr; use syntax::abi; use syntax::ast; use syntax::ast_map; use syntax::ast_util::{local_def, PostExpansionMethod}; use syntax::attr; use std::hash::{sip, Hash}; pub fn monomorphic_fn(ccx: &CrateContext, fn_id: ast::DefId, real_substs: &subst::Substs, ref_id: Option<ast::NodeId>) -> (ValueRef, bool)
match ccx.monomorphized().borrow().find(&hash_id) { Some(&val) => { debug!("leaving monomorphic fn {}", ty::item_path_str(ccx.tcx(), fn_id)); return (val, false); } None => () } let psubsts = param_substs { substs: (*real_substs).clone(), }; debug!("monomorphic_fn(\ fn_id={}, \ psubsts={}, \ hash_id={:?})", fn_id.repr(ccx.tcx()), psubsts.repr(ccx.tcx()), hash_id); let tpt = ty::lookup_item_type(ccx.tcx(), fn_id); let llitem_ty = tpt.ty; let map_node = session::expect( ccx.sess(), ccx.tcx().map.find(fn_id.node), || { format!("while monomorphizing {:?}, couldn't find it in \ the item map (may have attempted to monomorphize \ an item defined in a different crate?)", fn_id) }); match map_node { ast_map::NodeForeignItem(_) => { if ccx.tcx().map.get_foreign_abi(fn_id.node)!= abi::RustIntrinsic { // Foreign externs don't have to be monomorphized. return (get_item_val(ccx, fn_id.node), true); } } _ => {} } debug!("monomorphic_fn about to subst into {}", llitem_ty.repr(ccx.tcx())); let mono_ty = llitem_ty.subst(ccx.tcx(), real_substs); ccx.stats().n_monos.set(ccx.stats().n_monos.get() + 1); let depth; { let mut monomorphizing = ccx.monomorphizing().borrow_mut(); depth = match monomorphizing.find(&fn_id) { Some(&d) => d, None => 0 }; // Random cut-off -- code that needs to instantiate the same function // recursively more than thirty times can probably safely be assumed // to be causing an infinite expansion. if depth > ccx.sess().recursion_limit.get() { ccx.sess().span_fatal(ccx.tcx().map.span(fn_id.node), "reached the recursion limit during monomorphization"); } monomorphizing.insert(fn_id, depth + 1); } let hash; let s = { let mut state = sip::SipState::new(); hash_id.hash(&mut state); mono_ty.hash(&mut state); hash = format!("h{}", state.result()); ccx.tcx().map.with_path(fn_id.node, |path| { exported_name(path, hash.as_slice()) }) }; debug!("monomorphize_fn mangled to {}", s); // This shouldn't need to option dance. let mut hash_id = Some(hash_id); let mk_lldecl = |abi: abi::Abi| { let lldecl = if abi!= abi::Rust { foreign::decl_rust_fn_with_foreign_abi(ccx, mono_ty, s.as_slice()) } else { decl_internal_rust_fn(ccx, mono_ty, s.as_slice()) }; ccx.monomorphized().borrow_mut().insert(hash_id.take().unwrap(), lldecl); lldecl }; let setup_lldecl = |lldecl, attrs: &[ast::Attribute]| { base::update_linkage(ccx, lldecl, None, base::OriginalTranslation); set_llvm_fn_attrs(attrs, lldecl); let is_first =!ccx.available_monomorphizations().borrow().contains(&s); if is_first { ccx.available_monomorphizations().borrow_mut().insert(s.clone()); } let trans_everywhere = attr::requests_inline(attrs); if trans_everywhere &&!is_first { llvm::SetLinkage(lldecl, llvm::AvailableExternallyLinkage); } // If `true`, then `lldecl` should be given a function body. // Otherwise, it should be left as a declaration of an external // function, with no definition in the current compilation unit. trans_everywhere || is_first }; let lldecl = match map_node { ast_map::NodeItem(i) => { match *i { ast::Item { node: ast::ItemFn(ref decl, _, abi, _, ref body), .. } => { let d = mk_lldecl(abi); let needs_body = setup_lldecl(d, i.attrs.as_slice()); if needs_body { if abi!= abi::Rust { foreign::trans_rust_fn_with_foreign_abi( ccx, &**decl, &**body, [], d, &psubsts, fn_id.node, Some(hash.as_slice())); } else { trans_fn(ccx, &**decl, &**body, d, &psubsts, fn_id.node, []); } } d } _ => { ccx.sess().bug("Can't monomorphize this kind of item") } } } ast_map::NodeVariant(v) => { let parent = ccx.tcx().map.get_parent(fn_id.node); let tvs = ty::enum_variants(ccx.tcx(), local_def(parent)); let this_tv = tvs.iter().find(|tv| { tv.id.node == fn_id.node}).unwrap(); let d = mk_lldecl(abi::Rust); set_inline_hint(d); match v.node.kind { ast::TupleVariantKind(ref args) => { trans_enum_variant(ccx, parent, &*v, args.as_slice(), this_tv.disr_val, &psubsts, d); } ast::StructVariantKind(_) => ccx.sess().bug("can't monomorphize struct variants"), } d } ast_map::NodeImplItem(ii) => { match *ii { ast::MethodImplItem(ref mth) => { let d = mk_lldecl(abi::Rust); let needs_body = setup_lldecl(d, mth.attrs.as_slice()); if needs_body { trans_fn(ccx, mth.pe_fn_decl(), mth.pe_body(), d, &psubsts, mth.id, []); } d } ast::TypeImplItem(_) => { ccx.sess().bug("can't monomorphize an associated type") } } } ast_map::NodeTraitItem(method) => { match *method { ast::ProvidedMethod(ref mth) => { let d = mk_lldecl(abi::Rust); let needs_body = setup_lldecl(d, mth.attrs.as_slice()); if needs_body { trans_fn(ccx, mth.pe_fn_decl(), mth.pe_body(), d, &psubsts, mth.id, []); } d } _ => { ccx.sess().bug(format!("can't monomorphize a {:?}", map_node).as_slice()) } } } ast_map::NodeStructCtor(struct_def) => { let d = mk_lldecl(abi::Rust); set_inline_hint(d); base::trans_tuple_struct(ccx, struct_def.fields.as_slice(), struct_def.ctor_id.expect("ast-mapped tuple struct \ didn't have a ctor id"), &psubsts, d); d } // Ugh -- but this ensures any new variants won't be forgotten ast_map::NodeForeignItem(..) | ast_map::NodeLifetime(..) | ast_map::NodeExpr(..) | ast_map::NodeStmt(..) | ast_map::NodeArg(..) | ast_map::NodeBlock(..) | ast_map::NodePat(..) | ast_map::NodeLocal(..) => { ccx.sess().bug(format!("can't monomorphize a {:?}", map_node).as_slice()) } }; ccx.monomorphizing().borrow_mut().insert(fn_id, depth); debug!("leaving monomorphic fn {}", ty::item_path_str(ccx.tcx(), fn_id)); (lldecl, true) } #[deriving(PartialEq, Eq, Hash)] pub struct MonoId { pub def: ast::DefId, pub params: subst::VecPerParamSpace<ty::t> }
{ debug!("monomorphic_fn(\ fn_id={}, \ real_substs={}, \ ref_id={:?})", fn_id.repr(ccx.tcx()), real_substs.repr(ccx.tcx()), ref_id); assert!(real_substs.types.all(|t| { !ty::type_needs_infer(*t) && !ty::type_has_params(*t) })); let _icx = push_ctxt("monomorphic_fn"); let hash_id = MonoId { def: fn_id, params: real_substs.types.clone() };
identifier_body
monomorphize.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use back::link::exported_name; use driver::session; use llvm::ValueRef; use llvm; use middle::subst; use middle::subst::Subst; use middle::trans::base::{set_llvm_fn_attrs, set_inline_hint}; use middle::trans::base::{trans_enum_variant, push_ctxt, get_item_val}; use middle::trans::base::{trans_fn, decl_internal_rust_fn}; use middle::trans::base; use middle::trans::common::*; use middle::trans::foreign; use middle::ty; use util::ppaux::Repr; use syntax::abi; use syntax::ast; use syntax::ast_map; use syntax::ast_util::{local_def, PostExpansionMethod}; use syntax::attr; use std::hash::{sip, Hash}; pub fn monomorphic_fn(ccx: &CrateContext, fn_id: ast::DefId, real_substs: &subst::Substs, ref_id: Option<ast::NodeId>) -> (ValueRef, bool) { debug!("monomorphic_fn(\ fn_id={}, \ real_substs={}, \ ref_id={:?})", fn_id.repr(ccx.tcx()), real_substs.repr(ccx.tcx()), ref_id); assert!(real_substs.types.all(|t| { !ty::type_needs_infer(*t) &&!ty::type_has_params(*t) })); let _icx = push_ctxt("monomorphic_fn"); let hash_id = MonoId { def: fn_id, params: real_substs.types.clone() }; match ccx.monomorphized().borrow().find(&hash_id) { Some(&val) => { debug!("leaving monomorphic fn {}", ty::item_path_str(ccx.tcx(), fn_id)); return (val, false); } None => () } let psubsts = param_substs { substs: (*real_substs).clone(), }; debug!("monomorphic_fn(\ fn_id={}, \ psubsts={}, \ hash_id={:?})", fn_id.repr(ccx.tcx()), psubsts.repr(ccx.tcx()), hash_id); let tpt = ty::lookup_item_type(ccx.tcx(), fn_id); let llitem_ty = tpt.ty; let map_node = session::expect( ccx.sess(), ccx.tcx().map.find(fn_id.node), || { format!("while monomorphizing {:?}, couldn't find it in \ the item map (may have attempted to monomorphize \ an item defined in a different crate?)", fn_id) }); match map_node { ast_map::NodeForeignItem(_) => { if ccx.tcx().map.get_foreign_abi(fn_id.node)!= abi::RustIntrinsic { // Foreign externs don't have to be monomorphized. return (get_item_val(ccx, fn_id.node), true); } } _ => {} } debug!("monomorphic_fn about to subst into {}", llitem_ty.repr(ccx.tcx())); let mono_ty = llitem_ty.subst(ccx.tcx(), real_substs); ccx.stats().n_monos.set(ccx.stats().n_monos.get() + 1); let depth; { let mut monomorphizing = ccx.monomorphizing().borrow_mut(); depth = match monomorphizing.find(&fn_id) { Some(&d) => d, None => 0 }; // Random cut-off -- code that needs to instantiate the same function // recursively more than thirty times can probably safely be assumed // to be causing an infinite expansion. if depth > ccx.sess().recursion_limit.get() { ccx.sess().span_fatal(ccx.tcx().map.span(fn_id.node), "reached the recursion limit during monomorphization"); } monomorphizing.insert(fn_id, depth + 1); } let hash; let s = { let mut state = sip::SipState::new(); hash_id.hash(&mut state); mono_ty.hash(&mut state); hash = format!("h{}", state.result()); ccx.tcx().map.with_path(fn_id.node, |path| { exported_name(path, hash.as_slice()) }) }; debug!("monomorphize_fn mangled to {}", s); // This shouldn't need to option dance. let mut hash_id = Some(hash_id); let mk_lldecl = |abi: abi::Abi| { let lldecl = if abi!= abi::Rust { foreign::decl_rust_fn_with_foreign_abi(ccx, mono_ty, s.as_slice()) } else { decl_internal_rust_fn(ccx, mono_ty, s.as_slice()) }; ccx.monomorphized().borrow_mut().insert(hash_id.take().unwrap(), lldecl); lldecl }; let setup_lldecl = |lldecl, attrs: &[ast::Attribute]| { base::update_linkage(ccx, lldecl, None, base::OriginalTranslation); set_llvm_fn_attrs(attrs, lldecl); let is_first =!ccx.available_monomorphizations().borrow().contains(&s); if is_first { ccx.available_monomorphizations().borrow_mut().insert(s.clone()); } let trans_everywhere = attr::requests_inline(attrs); if trans_everywhere &&!is_first { llvm::SetLinkage(lldecl, llvm::AvailableExternallyLinkage); } // If `true`, then `lldecl` should be given a function body. // Otherwise, it should be left as a declaration of an external // function, with no definition in the current compilation unit. trans_everywhere || is_first }; let lldecl = match map_node { ast_map::NodeItem(i) => { match *i { ast::Item { node: ast::ItemFn(ref decl, _, abi, _, ref body), .. } => { let d = mk_lldecl(abi); let needs_body = setup_lldecl(d, i.attrs.as_slice()); if needs_body { if abi!= abi::Rust { foreign::trans_rust_fn_with_foreign_abi( ccx, &**decl, &**body, [], d, &psubsts, fn_id.node, Some(hash.as_slice())); } else { trans_fn(ccx, &**decl, &**body, d, &psubsts, fn_id.node, []); } } d } _ => { ccx.sess().bug("Can't monomorphize this kind of item") } } } ast_map::NodeVariant(v) => { let parent = ccx.tcx().map.get_parent(fn_id.node); let tvs = ty::enum_variants(ccx.tcx(), local_def(parent)); let this_tv = tvs.iter().find(|tv| { tv.id.node == fn_id.node}).unwrap(); let d = mk_lldecl(abi::Rust); set_inline_hint(d); match v.node.kind { ast::TupleVariantKind(ref args) => { trans_enum_variant(ccx, parent, &*v, args.as_slice(), this_tv.disr_val, &psubsts, d); } ast::StructVariantKind(_) => ccx.sess().bug("can't monomorphize struct variants"), } d } ast_map::NodeImplItem(ii) => { match *ii { ast::MethodImplItem(ref mth) => { let d = mk_lldecl(abi::Rust); let needs_body = setup_lldecl(d, mth.attrs.as_slice()); if needs_body { trans_fn(ccx, mth.pe_fn_decl(), mth.pe_body(), d, &psubsts, mth.id, []); } d } ast::TypeImplItem(_) => { ccx.sess().bug("can't monomorphize an associated type") } } } ast_map::NodeTraitItem(method) => { match *method { ast::ProvidedMethod(ref mth) => { let d = mk_lldecl(abi::Rust); let needs_body = setup_lldecl(d, mth.attrs.as_slice()); if needs_body { trans_fn(ccx, mth.pe_fn_decl(), mth.pe_body(), d, &psubsts, mth.id, []); } d } _ => { ccx.sess().bug(format!("can't monomorphize a {:?}", map_node).as_slice()) } } } ast_map::NodeStructCtor(struct_def) => { let d = mk_lldecl(abi::Rust); set_inline_hint(d); base::trans_tuple_struct(ccx, struct_def.fields.as_slice(), struct_def.ctor_id.expect("ast-mapped tuple struct \ didn't have a ctor id"), &psubsts, d); d } // Ugh -- but this ensures any new variants won't be forgotten ast_map::NodeForeignItem(..) | ast_map::NodeLifetime(..) | ast_map::NodeExpr(..) | ast_map::NodeStmt(..) | ast_map::NodeArg(..) | ast_map::NodeBlock(..) | ast_map::NodePat(..) | ast_map::NodeLocal(..) => { ccx.sess().bug(format!("can't monomorphize a {:?}", map_node).as_slice())
debug!("leaving monomorphic fn {}", ty::item_path_str(ccx.tcx(), fn_id)); (lldecl, true) } #[deriving(PartialEq, Eq, Hash)] pub struct MonoId { pub def: ast::DefId, pub params: subst::VecPerParamSpace<ty::t> }
} }; ccx.monomorphizing().borrow_mut().insert(fn_id, depth);
random_line_split
frontmatter.rs
use std::fmt; use cobalt_config::DateTime; use cobalt_config::SourceFormat; use liquid; use serde::Serialize; use super::pagination; use crate::error::Result; #[derive(Debug, Eq, PartialEq, Default, Clone, Serialize)] #[serde(deny_unknown_fields, default)] pub struct Frontmatter { pub permalink: cobalt_config::Permalink, pub slug: kstring::KString, pub title: kstring::KString, pub description: Option<kstring::KString>, pub excerpt: Option<kstring::KString>, pub categories: Vec<kstring::KString>, pub tags: Option<Vec<kstring::KString>>, pub excerpt_separator: kstring::KString, pub published_date: Option<DateTime>, pub format: SourceFormat, pub templated: bool, pub layout: Option<kstring::KString>, pub is_draft: bool, pub weight: i32, pub collection: kstring::KString, pub data: liquid::Object, pub pagination: Option<pagination::PaginationConfig>, } impl Frontmatter { pub fn from_config(config: cobalt_config::Frontmatter) -> Result<Frontmatter> { let cobalt_config::Frontmatter { permalink, slug, title, description, excerpt, categories, tags, excerpt_separator, published_date, format, templated, layout, is_draft, weight, collection, data, pagination, } = config; let collection = collection.unwrap_or_default(); let permalink = permalink.unwrap_or_default(); if let Some(ref tags) = tags { if tags.iter().any(|x| x.trim().is_empty()) { failure::bail!("Empty strings are not allowed in tags"); } } let tags = if tags.as_ref().map(|t| t.len()).unwrap_or(0) == 0 { None } else { tags }; let fm = Frontmatter { pagination: pagination .and_then(|p| pagination::PaginationConfig::from_config(p, &permalink)), permalink, slug: slug.ok_or_else(|| failure::err_msg("No slug"))?, title: title.ok_or_else(|| failure::err_msg("No title"))?, description, excerpt, categories: categories.unwrap_or_else(Vec::new), tags, excerpt_separator: excerpt_separator.unwrap_or_else(|| "\n\n".into()), published_date, format: format.unwrap_or_default(), #[cfg(feature = "preview_unstable")] templated: templated.unwrap_or(false), #[cfg(not(feature = "preview_unstable"))] templated: templated.unwrap_or(true), layout, is_draft: is_draft.unwrap_or(false), weight: weight.unwrap_or(0), collection, data, }; if let Some(pagination) = &fm.pagination { if!pagination::is_date_index_sorted(&pagination.date_index) { failure::bail!("date_index is not correctly sorted: Year > Month > Day..."); } } Ok(fm) } } impl fmt::Display for Frontmatter { fn
(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let converted = serde_yaml::to_string(self).expect("should always be valid"); let subset = converted .strip_prefix("---") .unwrap_or_else(|| converted.as_str()) .trim(); let converted = if subset == "{}" { "" } else { subset }; if converted.is_empty() { Ok(()) } else { write!(f, "{}", converted) } } }
fmt
identifier_name
frontmatter.rs
use std::fmt; use cobalt_config::DateTime; use cobalt_config::SourceFormat; use liquid; use serde::Serialize; use super::pagination; use crate::error::Result; #[derive(Debug, Eq, PartialEq, Default, Clone, Serialize)] #[serde(deny_unknown_fields, default)] pub struct Frontmatter { pub permalink: cobalt_config::Permalink, pub slug: kstring::KString, pub title: kstring::KString, pub description: Option<kstring::KString>, pub excerpt: Option<kstring::KString>, pub categories: Vec<kstring::KString>, pub tags: Option<Vec<kstring::KString>>, pub excerpt_separator: kstring::KString, pub published_date: Option<DateTime>, pub format: SourceFormat, pub templated: bool, pub layout: Option<kstring::KString>, pub is_draft: bool, pub weight: i32, pub collection: kstring::KString, pub data: liquid::Object, pub pagination: Option<pagination::PaginationConfig>, } impl Frontmatter { pub fn from_config(config: cobalt_config::Frontmatter) -> Result<Frontmatter>
let collection = collection.unwrap_or_default(); let permalink = permalink.unwrap_or_default(); if let Some(ref tags) = tags { if tags.iter().any(|x| x.trim().is_empty()) { failure::bail!("Empty strings are not allowed in tags"); } } let tags = if tags.as_ref().map(|t| t.len()).unwrap_or(0) == 0 { None } else { tags }; let fm = Frontmatter { pagination: pagination .and_then(|p| pagination::PaginationConfig::from_config(p, &permalink)), permalink, slug: slug.ok_or_else(|| failure::err_msg("No slug"))?, title: title.ok_or_else(|| failure::err_msg("No title"))?, description, excerpt, categories: categories.unwrap_or_else(Vec::new), tags, excerpt_separator: excerpt_separator.unwrap_or_else(|| "\n\n".into()), published_date, format: format.unwrap_or_default(), #[cfg(feature = "preview_unstable")] templated: templated.unwrap_or(false), #[cfg(not(feature = "preview_unstable"))] templated: templated.unwrap_or(true), layout, is_draft: is_draft.unwrap_or(false), weight: weight.unwrap_or(0), collection, data, }; if let Some(pagination) = &fm.pagination { if!pagination::is_date_index_sorted(&pagination.date_index) { failure::bail!("date_index is not correctly sorted: Year > Month > Day..."); } } Ok(fm) } } impl fmt::Display for Frontmatter { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let converted = serde_yaml::to_string(self).expect("should always be valid"); let subset = converted .strip_prefix("---") .unwrap_or_else(|| converted.as_str()) .trim(); let converted = if subset == "{}" { "" } else { subset }; if converted.is_empty() { Ok(()) } else { write!(f, "{}", converted) } } }
{ let cobalt_config::Frontmatter { permalink, slug, title, description, excerpt, categories, tags, excerpt_separator, published_date, format, templated, layout, is_draft, weight, collection, data, pagination, } = config;
identifier_body
frontmatter.rs
use std::fmt; use cobalt_config::DateTime; use cobalt_config::SourceFormat; use liquid; use serde::Serialize; use super::pagination; use crate::error::Result; #[derive(Debug, Eq, PartialEq, Default, Clone, Serialize)] #[serde(deny_unknown_fields, default)] pub struct Frontmatter { pub permalink: cobalt_config::Permalink, pub slug: kstring::KString, pub title: kstring::KString, pub description: Option<kstring::KString>, pub excerpt: Option<kstring::KString>, pub categories: Vec<kstring::KString>, pub tags: Option<Vec<kstring::KString>>, pub excerpt_separator: kstring::KString, pub published_date: Option<DateTime>, pub format: SourceFormat, pub templated: bool, pub layout: Option<kstring::KString>, pub is_draft: bool, pub weight: i32, pub collection: kstring::KString, pub data: liquid::Object, pub pagination: Option<pagination::PaginationConfig>, } impl Frontmatter { pub fn from_config(config: cobalt_config::Frontmatter) -> Result<Frontmatter> { let cobalt_config::Frontmatter { permalink, slug, title, description, excerpt, categories, tags, excerpt_separator, published_date, format, templated, layout, is_draft, weight, collection, data, pagination, } = config; let collection = collection.unwrap_or_default(); let permalink = permalink.unwrap_or_default(); if let Some(ref tags) = tags { if tags.iter().any(|x| x.trim().is_empty()) { failure::bail!("Empty strings are not allowed in tags"); } } let tags = if tags.as_ref().map(|t| t.len()).unwrap_or(0) == 0 { None } else { tags }; let fm = Frontmatter { pagination: pagination .and_then(|p| pagination::PaginationConfig::from_config(p, &permalink)), permalink, slug: slug.ok_or_else(|| failure::err_msg("No slug"))?, title: title.ok_or_else(|| failure::err_msg("No title"))?, description, excerpt, categories: categories.unwrap_or_else(Vec::new), tags, excerpt_separator: excerpt_separator.unwrap_or_else(|| "\n\n".into()), published_date, format: format.unwrap_or_default(), #[cfg(feature = "preview_unstable")] templated: templated.unwrap_or(false), #[cfg(not(feature = "preview_unstable"))] templated: templated.unwrap_or(true), layout, is_draft: is_draft.unwrap_or(false), weight: weight.unwrap_or(0), collection, data, }; if let Some(pagination) = &fm.pagination { if!pagination::is_date_index_sorted(&pagination.date_index) { failure::bail!("date_index is not correctly sorted: Year > Month > Day..."); } } Ok(fm) } } impl fmt::Display for Frontmatter { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let converted = serde_yaml::to_string(self).expect("should always be valid"); let subset = converted .strip_prefix("---") .unwrap_or_else(|| converted.as_str()) .trim(); let converted = if subset == "{}"
else { subset }; if converted.is_empty() { Ok(()) } else { write!(f, "{}", converted) } } }
{ "" }
conditional_block
frontmatter.rs
use std::fmt; use cobalt_config::DateTime; use cobalt_config::SourceFormat; use liquid; use serde::Serialize; use super::pagination; use crate::error::Result;
pub permalink: cobalt_config::Permalink, pub slug: kstring::KString, pub title: kstring::KString, pub description: Option<kstring::KString>, pub excerpt: Option<kstring::KString>, pub categories: Vec<kstring::KString>, pub tags: Option<Vec<kstring::KString>>, pub excerpt_separator: kstring::KString, pub published_date: Option<DateTime>, pub format: SourceFormat, pub templated: bool, pub layout: Option<kstring::KString>, pub is_draft: bool, pub weight: i32, pub collection: kstring::KString, pub data: liquid::Object, pub pagination: Option<pagination::PaginationConfig>, } impl Frontmatter { pub fn from_config(config: cobalt_config::Frontmatter) -> Result<Frontmatter> { let cobalt_config::Frontmatter { permalink, slug, title, description, excerpt, categories, tags, excerpt_separator, published_date, format, templated, layout, is_draft, weight, collection, data, pagination, } = config; let collection = collection.unwrap_or_default(); let permalink = permalink.unwrap_or_default(); if let Some(ref tags) = tags { if tags.iter().any(|x| x.trim().is_empty()) { failure::bail!("Empty strings are not allowed in tags"); } } let tags = if tags.as_ref().map(|t| t.len()).unwrap_or(0) == 0 { None } else { tags }; let fm = Frontmatter { pagination: pagination .and_then(|p| pagination::PaginationConfig::from_config(p, &permalink)), permalink, slug: slug.ok_or_else(|| failure::err_msg("No slug"))?, title: title.ok_or_else(|| failure::err_msg("No title"))?, description, excerpt, categories: categories.unwrap_or_else(Vec::new), tags, excerpt_separator: excerpt_separator.unwrap_or_else(|| "\n\n".into()), published_date, format: format.unwrap_or_default(), #[cfg(feature = "preview_unstable")] templated: templated.unwrap_or(false), #[cfg(not(feature = "preview_unstable"))] templated: templated.unwrap_or(true), layout, is_draft: is_draft.unwrap_or(false), weight: weight.unwrap_or(0), collection, data, }; if let Some(pagination) = &fm.pagination { if!pagination::is_date_index_sorted(&pagination.date_index) { failure::bail!("date_index is not correctly sorted: Year > Month > Day..."); } } Ok(fm) } } impl fmt::Display for Frontmatter { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let converted = serde_yaml::to_string(self).expect("should always be valid"); let subset = converted .strip_prefix("---") .unwrap_or_else(|| converted.as_str()) .trim(); let converted = if subset == "{}" { "" } else { subset }; if converted.is_empty() { Ok(()) } else { write!(f, "{}", converted) } } }
#[derive(Debug, Eq, PartialEq, Default, Clone, Serialize)] #[serde(deny_unknown_fields, default)] pub struct Frontmatter {
random_line_split
multi.rs
//! //! //! Multi reply info as used in old implementation (minus error mgmt TODO) //! TODO with cached associated trait on info, could merge with error.rs?? use std::marker::PhantomData; use super::super::{ BincErr, RepInfo, Info, ReplyProvider, SymProvider, Peer, }; use bincode::Infinite; use bincode::{ serialize_into as bin_encode, deserialize_from as bin_decode, }; use std::io::{ Write, Read, Result, }; use serde::{ Serialize, Deserialize, Serializer, Deserializer, }; use serde::de::DeserializeOwned; /// Possible multiple reply handling implementation /// Cost of an enum, it is mainly for testing,c #[derive(Serialize,Deserialize,Debug,Clone,PartialEq,Eq)] pub enum MultipleReplyMode { /// do not propagate errors NoHandling, /// send error to peer with designed mode (case where we can know emitter for dest or other error /// handling scheme with possible rendezvous point), TunnelMode is optional and used only for /// case where the reply mode differs from the original tunnelmode TODO remove?? (actually use /// for norep (public) to set origin for dest) KnownDest, /// route for error is included, end of payload should be proxyied. Route, /// route for error is included, end of payload should be proxyied, different route is use /// Same as bitunnel from original implementation OtherRoute, /// Mode for reply payload (use by Route and OtherRoute) RouteReply, // if route is cached (info in local cache), report error with same route CachedRoute, CachedRoute, } /// Error handle info include in frame, also use for reply /// TODO split as ReplyInfo is split /// TODOΒ generic not in tunnel #[derive(Serialize,Deserialize,Debug,Clone)] pub enum MultipleReplyInfo<A> { NoHandling, KnownDest(A), // TODOΒ add reply mode?? TODO address instead of key?? Route, // route headers are to be read afterward, contains sym key /// reply info include in route after content RouteReply(Vec<u8>), // route headers are to be read afterward, contains sym key CachedRoute(Vec<u8>), // contains symkey for peer shadow } // TODO implement Info // TODO next split it (here it is MultiReply whichi is previous enum impl, purpose of refacto is // getting rid of those enum (only if needed) // TODO get TunnelProxy info next_proxy_peer and tunnel id as PeerInfo and not reply info (after full running) // TODO for perf sake should be an enum (at least with the noreply : except for cache impl those // ar null (too bug in tunnelshadoww) :Β the double option is not a good sign too /*pub struct MultipleReplyInfo<E : ExtWrite, P : Peer, TW : TunnelWriterExt> { pub info : MultipleReplyInfo<P>, // reply route should be seen as a reply info : used to write the payload -> TODO redesign this // TODO not TunnelWriterFull in box to share with last pub replyroute : Option<(E,Box<TW>)>, //replyroute : Option<Box<(E,TunnelWriterFull<E,P,TW>)>>, }*/ impl<A : Serialize + DeserializeOwned + Clone + Eq> Info for MultipleReplyInfo<A> { #[inline] fn do_cache (&self) -> bool { match self { &MultipleReplyInfo::CachedRoute(_) => true, _ => false, } } fn write_in_header<W : Write>(&mut self, inw : &mut W) -> Result<()> { bin_encode(inw, self, Infinite).map_err(|e|BincErr(e))?; // if self.info.do_cache() { // write tunnel simkey //let shadsim = <<P as Peer>::Shadow as Shadow>::new_shadow_sim().unwrap(); // let mut buf :Vec<u8> = Vec::new(); // try!(inw.write_all(&self.replykey.as_ref().unwrap()[..])); // try!(self.2.as_mut().unwrap().send_shadow_simkey(&mut inw)); /* let mut cbuf = Cursor::new(buf); println!("one"); try!(self.2.as_mut().unwrap().send_shadow_simkey(&mut cbuf)); let mut t = cbuf.into_inner(); println!("{:?}",t); inw.write_all(&mut t [..]); } else { println!("two");*/ // } Ok(()) } fn write_read_info<W : Write>(&mut self, w : &mut W) -> Result<()> { if let &mut MultipleReplyInfo::RouteReply(ref k) = self { bin_encode(w,k, Infinite).map_err(|e|BincErr(e))?; } Ok(()) } fn read_from_header<R : Read>(r : &mut R) -> Result<Self> {
fn read_read_info<R : Read>(&mut self, r : &mut R) -> Result<()> { // as dest this is called multiple times and thus we redifine it if let &mut MultipleReplyInfo::RouteReply(ref mut k) = self { *k = bin_decode(r, Infinite).map_err(|e|BincErr(e))?; } Ok(()) } } impl<A : Serialize + DeserializeOwned + Clone + Eq> RepInfo for MultipleReplyInfo<A> { #[inline] fn require_additional_payload(&self) -> bool { if let &MultipleReplyInfo::Route = self { true } else {false} } /// TODO remove called once fn get_reply_key(&self) -> Option<&Vec<u8>> { match self { // &MultipleReplyInfo::RouteReply(ref k) => Some(k), &MultipleReplyInfo::CachedRoute(ref k) => Some(k), &MultipleReplyInfo::RouteReply(ref k) => Some(k), _ => None, } } } /// TODO E as explicit limiter named trait for readability pub struct ReplyInfoProvider<P : Peer,SSW,SSR, SP : SymProvider<SSW,SSR>> { pub mode : MultipleReplyMode, // for different reply route pub symprov : SP, pub _p : PhantomData<(P,SSW,SSR)>, } /// TODO macro inherit?? impl<P:Peer,SSW,SSR,SP : SymProvider<SSW,SSR>> SymProvider<SSW,SSR> for ReplyInfoProvider<P,SSW,SSR,SP> { #[inline] fn new_sym_key (&mut self) -> Vec<u8> { self.symprov.new_sym_key() } #[inline] fn new_sym_writer (&mut self, k : Vec<u8>) -> SSW { self.symprov.new_sym_writer(k) } #[inline] fn new_sym_reader (&mut self, k : Vec<u8>) -> SSR { self.symprov.new_sym_reader(k) } } impl<P : Peer,SSW,SSR,SP : SymProvider<SSW,SSR>> ReplyProvider<P, MultipleReplyInfo<<P as Peer>::Address>> for ReplyInfoProvider<P,SSW,SSR,SP> { /// Error infos bases for peers fn new_reply (&mut self, route : &[&P]) -> Vec<MultipleReplyInfo<<P as Peer>::Address>> { let l = route.len(); match self.mode { MultipleReplyMode::NoHandling => vec![MultipleReplyInfo::NoHandling;l-1], MultipleReplyMode::KnownDest => { let mut res = vec![MultipleReplyInfo::NoHandling;l-1]; res[l-2] = MultipleReplyInfo::KnownDest(route[0].get_address().clone()); res }, MultipleReplyMode::OtherRoute => { let mut res = vec![MultipleReplyInfo::NoHandling;l-1]; res[l-2] = MultipleReplyInfo::Route; //res[l-2] = MultipleReplyInfo::Route(self.new_sym_key(route[l-1])); res }, MultipleReplyMode::Route => { let mut res = vec![MultipleReplyInfo::NoHandling;l-1]; //res[l-2] = MultipleReplyInfo::Route(self.new_sym_key(route[l-1])); res[l-2] = MultipleReplyInfo::Route; res }, MultipleReplyMode::RouteReply => { let mut res : Vec<MultipleReplyInfo<_>> = Vec::with_capacity(l-1); for _ in 1..l { res.push(MultipleReplyInfo::RouteReply(self.new_sym_key())) } res }, MultipleReplyMode::CachedRoute => { let mut res : Vec<MultipleReplyInfo<_>> = Vec::with_capacity(l-1); for _ in 1..l { res.push(MultipleReplyInfo::CachedRoute(self.new_sym_key())) } res }, } } } /// specific provider for no rpe pub struct NoMultiRepProvider; impl<P : Peer> ReplyProvider<P, MultipleReplyInfo<<P as Peer>::Address>> for NoMultiRepProvider { #[inline] fn new_reply (&mut self, p : &[&P]) -> Vec<MultipleReplyInfo<<P as Peer>::Address>> { vec![MultipleReplyInfo::NoHandling;p.len()-1] } } impl<SSW,SSR> SymProvider<SSW,SSR> for NoMultiRepProvider { fn new_sym_key (&mut self) -> Vec<u8> { unimplemented!() } fn new_sym_writer (&mut self, _ : Vec<u8>) -> SSW { unimplemented!() } fn new_sym_reader (&mut self, _ : Vec<u8>) -> SSR { unimplemented!() } }
Ok(bin_decode(r, Infinite).map_err(|e|BincErr(e))?) }
identifier_body
multi.rs
//! //! //! Multi reply info as used in old implementation (minus error mgmt TODO) //! TODO with cached associated trait on info, could merge with error.rs?? use std::marker::PhantomData; use super::super::{ BincErr, RepInfo, Info, ReplyProvider, SymProvider, Peer, }; use bincode::Infinite; use bincode::{ serialize_into as bin_encode, deserialize_from as bin_decode, }; use std::io::{ Write, Read, Result, }; use serde::{ Serialize, Deserialize, Serializer, Deserializer, }; use serde::de::DeserializeOwned; /// Possible multiple reply handling implementation /// Cost of an enum, it is mainly for testing,c #[derive(Serialize,Deserialize,Debug,Clone,PartialEq,Eq)] pub enum MultipleReplyMode { /// do not propagate errors NoHandling, /// send error to peer with designed mode (case where we can know emitter for dest or other error /// handling scheme with possible rendezvous point), TunnelMode is optional and used only for /// case where the reply mode differs from the original tunnelmode TODO remove?? (actually use /// for norep (public) to set origin for dest) KnownDest, /// route for error is included, end of payload should be proxyied. Route, /// route for error is included, end of payload should be proxyied, different route is use /// Same as bitunnel from original implementation OtherRoute, /// Mode for reply payload (use by Route and OtherRoute) RouteReply, // if route is cached (info in local cache), report error with same route CachedRoute, CachedRoute, } /// Error handle info include in frame, also use for reply /// TODO split as ReplyInfo is split /// TODOΒ generic not in tunnel #[derive(Serialize,Deserialize,Debug,Clone)] pub enum MultipleReplyInfo<A> { NoHandling, KnownDest(A), // TODOΒ add reply mode?? TODO address instead of key?? Route, // route headers are to be read afterward, contains sym key /// reply info include in route after content RouteReply(Vec<u8>), // route headers are to be read afterward, contains sym key CachedRoute(Vec<u8>), // contains symkey for peer shadow } // TODO implement Info // TODO next split it (here it is MultiReply whichi is previous enum impl, purpose of refacto is // getting rid of those enum (only if needed) // TODO get TunnelProxy info next_proxy_peer and tunnel id as PeerInfo and not reply info (after full running) // TODO for perf sake should be an enum (at least with the noreply : except for cache impl those // ar null (too bug in tunnelshadoww) :Β the double option is not a good sign too /*pub struct MultipleReplyInfo<E : ExtWrite, P : Peer, TW : TunnelWriterExt> { pub info : MultipleReplyInfo<P>, // reply route should be seen as a reply info : used to write the payload -> TODO redesign this // TODO not TunnelWriterFull in box to share with last pub replyroute : Option<(E,Box<TW>)>, //replyroute : Option<Box<(E,TunnelWriterFull<E,P,TW>)>>, }*/ impl<A : Serialize + DeserializeOwned + Clone + Eq> Info for MultipleReplyInfo<A> { #[inline] fn do_cache (&self) -> bool { match self { &MultipleReplyInfo::CachedRoute(_) => true, _ => false, } } fn write_in_header<W : Write>(&mut self, inw : &mut W) -> Result<()> { bin_encode(inw, self, Infinite).map_err(|e|BincErr(e))?; // if self.info.do_cache() { // write tunnel simkey //let shadsim = <<P as Peer>::Shadow as Shadow>::new_shadow_sim().unwrap(); // let mut buf :Vec<u8> = Vec::new(); // try!(inw.write_all(&self.replykey.as_ref().unwrap()[..])); // try!(self.2.as_mut().unwrap().send_shadow_simkey(&mut inw)); /* let mut cbuf = Cursor::new(buf); println!("one"); try!(self.2.as_mut().unwrap().send_shadow_simkey(&mut cbuf)); let mut t = cbuf.into_inner(); println!("{:?}",t); inw.write_all(&mut t [..]); } else { println!("two");*/ // } Ok(()) } fn write_read_info<W : Write>(&mut self, w : &mut W) -> Result<()> { if let &mut MultipleReplyInfo::RouteReply(ref k) = self { bin_encode(w,k, Infinite).map_err(|e|BincErr(e))?; } Ok(()) } fn read_from_header<R : Read>(r : &mut R) -> Result<Self> { Ok(bin_decode(r, Infinite).map_err(|e|BincErr(e))?) } fn read_read_info<R : Read>(&mut self, r : &mut R) -> Result<()> { // as dest this is called multiple times and thus we redifine it if let &mut MultipleReplyInfo::RouteReply(ref mut k) = self { *k = bin_decode(r, Infinite).map_err(|e|BincErr(e))?; } Ok(()) } } impl<A : Serialize + DeserializeOwned + Clone + Eq> RepInfo for MultipleReplyInfo<A> { #[inline] fn require_additional_payload(&self) -> bool { if let &MultipleReplyInfo::Route = self { true } else {false} }
/// TODO remove called once fn get_reply_key(&self) -> Option<&Vec<u8>> { match self { // &MultipleReplyInfo::RouteReply(ref k) => Some(k), &MultipleReplyInfo::CachedRoute(ref k) => Some(k), &MultipleReplyInfo::RouteReply(ref k) => Some(k), _ => None, } } } /// TODO E as explicit limiter named trait for readability pub struct ReplyInfoProvider<P : Peer,SSW,SSR, SP : SymProvider<SSW,SSR>> { pub mode : MultipleReplyMode, // for different reply route pub symprov : SP, pub _p : PhantomData<(P,SSW,SSR)>, } /// TODO macro inherit?? impl<P:Peer,SSW,SSR,SP : SymProvider<SSW,SSR>> SymProvider<SSW,SSR> for ReplyInfoProvider<P,SSW,SSR,SP> { #[inline] fn new_sym_key (&mut self) -> Vec<u8> { self.symprov.new_sym_key() } #[inline] fn new_sym_writer (&mut self, k : Vec<u8>) -> SSW { self.symprov.new_sym_writer(k) } #[inline] fn new_sym_reader (&mut self, k : Vec<u8>) -> SSR { self.symprov.new_sym_reader(k) } } impl<P : Peer,SSW,SSR,SP : SymProvider<SSW,SSR>> ReplyProvider<P, MultipleReplyInfo<<P as Peer>::Address>> for ReplyInfoProvider<P,SSW,SSR,SP> { /// Error infos bases for peers fn new_reply (&mut self, route : &[&P]) -> Vec<MultipleReplyInfo<<P as Peer>::Address>> { let l = route.len(); match self.mode { MultipleReplyMode::NoHandling => vec![MultipleReplyInfo::NoHandling;l-1], MultipleReplyMode::KnownDest => { let mut res = vec![MultipleReplyInfo::NoHandling;l-1]; res[l-2] = MultipleReplyInfo::KnownDest(route[0].get_address().clone()); res }, MultipleReplyMode::OtherRoute => { let mut res = vec![MultipleReplyInfo::NoHandling;l-1]; res[l-2] = MultipleReplyInfo::Route; //res[l-2] = MultipleReplyInfo::Route(self.new_sym_key(route[l-1])); res }, MultipleReplyMode::Route => { let mut res = vec![MultipleReplyInfo::NoHandling;l-1]; //res[l-2] = MultipleReplyInfo::Route(self.new_sym_key(route[l-1])); res[l-2] = MultipleReplyInfo::Route; res }, MultipleReplyMode::RouteReply => { let mut res : Vec<MultipleReplyInfo<_>> = Vec::with_capacity(l-1); for _ in 1..l { res.push(MultipleReplyInfo::RouteReply(self.new_sym_key())) } res }, MultipleReplyMode::CachedRoute => { let mut res : Vec<MultipleReplyInfo<_>> = Vec::with_capacity(l-1); for _ in 1..l { res.push(MultipleReplyInfo::CachedRoute(self.new_sym_key())) } res }, } } } /// specific provider for no rpe pub struct NoMultiRepProvider; impl<P : Peer> ReplyProvider<P, MultipleReplyInfo<<P as Peer>::Address>> for NoMultiRepProvider { #[inline] fn new_reply (&mut self, p : &[&P]) -> Vec<MultipleReplyInfo<<P as Peer>::Address>> { vec![MultipleReplyInfo::NoHandling;p.len()-1] } } impl<SSW,SSR> SymProvider<SSW,SSR> for NoMultiRepProvider { fn new_sym_key (&mut self) -> Vec<u8> { unimplemented!() } fn new_sym_writer (&mut self, _ : Vec<u8>) -> SSW { unimplemented!() } fn new_sym_reader (&mut self, _ : Vec<u8>) -> SSR { unimplemented!() } }
random_line_split
multi.rs
//! //! //! Multi reply info as used in old implementation (minus error mgmt TODO) //! TODO with cached associated trait on info, could merge with error.rs?? use std::marker::PhantomData; use super::super::{ BincErr, RepInfo, Info, ReplyProvider, SymProvider, Peer, }; use bincode::Infinite; use bincode::{ serialize_into as bin_encode, deserialize_from as bin_decode, }; use std::io::{ Write, Read, Result, }; use serde::{ Serialize, Deserialize, Serializer, Deserializer, }; use serde::de::DeserializeOwned; /// Possible multiple reply handling implementation /// Cost of an enum, it is mainly for testing,c #[derive(Serialize,Deserialize,Debug,Clone,PartialEq,Eq)] pub enum MultipleReplyMode { /// do not propagate errors NoHandling, /// send error to peer with designed mode (case where we can know emitter for dest or other error /// handling scheme with possible rendezvous point), TunnelMode is optional and used only for /// case where the reply mode differs from the original tunnelmode TODO remove?? (actually use /// for norep (public) to set origin for dest) KnownDest, /// route for error is included, end of payload should be proxyied. Route, /// route for error is included, end of payload should be proxyied, different route is use /// Same as bitunnel from original implementation OtherRoute, /// Mode for reply payload (use by Route and OtherRoute) RouteReply, // if route is cached (info in local cache), report error with same route CachedRoute, CachedRoute, } /// Error handle info include in frame, also use for reply /// TODO split as ReplyInfo is split /// TODOΒ generic not in tunnel #[derive(Serialize,Deserialize,Debug,Clone)] pub enum MultipleReplyInfo<A> { NoHandling, KnownDest(A), // TODOΒ add reply mode?? TODO address instead of key?? Route, // route headers are to be read afterward, contains sym key /// reply info include in route after content RouteReply(Vec<u8>), // route headers are to be read afterward, contains sym key CachedRoute(Vec<u8>), // contains symkey for peer shadow } // TODO implement Info // TODO next split it (here it is MultiReply whichi is previous enum impl, purpose of refacto is // getting rid of those enum (only if needed) // TODO get TunnelProxy info next_proxy_peer and tunnel id as PeerInfo and not reply info (after full running) // TODO for perf sake should be an enum (at least with the noreply : except for cache impl those // ar null (too bug in tunnelshadoww) :Β the double option is not a good sign too /*pub struct MultipleReplyInfo<E : ExtWrite, P : Peer, TW : TunnelWriterExt> { pub info : MultipleReplyInfo<P>, // reply route should be seen as a reply info : used to write the payload -> TODO redesign this // TODO not TunnelWriterFull in box to share with last pub replyroute : Option<(E,Box<TW>)>, //replyroute : Option<Box<(E,TunnelWriterFull<E,P,TW>)>>, }*/ impl<A : Serialize + DeserializeOwned + Clone + Eq> Info for MultipleReplyInfo<A> { #[inline] fn do_cache (&self) -> bool { match self { &MultipleReplyInfo::CachedRoute(_) => true, _ => false, } } fn write_in_header<W : Write>(&mut self, inw : &mut W) -> Result<()> { bin_encode(inw, self, Infinite).map_err(|e|BincErr(e))?; // if self.info.do_cache() { // write tunnel simkey //let shadsim = <<P as Peer>::Shadow as Shadow>::new_shadow_sim().unwrap(); // let mut buf :Vec<u8> = Vec::new(); // try!(inw.write_all(&self.replykey.as_ref().unwrap()[..])); // try!(self.2.as_mut().unwrap().send_shadow_simkey(&mut inw)); /* let mut cbuf = Cursor::new(buf); println!("one"); try!(self.2.as_mut().unwrap().send_shadow_simkey(&mut cbuf)); let mut t = cbuf.into_inner(); println!("{:?}",t); inw.write_all(&mut t [..]); } else { println!("two");*/ // } Ok(()) } fn write_read_info<W : Write>(&mut self, w : &mut W) -> Result<()> { if let &mut MultipleReplyInfo::RouteReply(ref k) = self { bin_encode(w,k, Infinite).map_err(|e|BincErr(e))?; } Ok(()) } fn read_from_header<R : Read>(r : &mut R) -> Result<Self> { Ok(bin_decode(r, Infinite).map_err(|e|BincErr(e))?) } fn read_read_info<R : Read>(&mut self, r : &mut R) -> Result<()> { // as dest this is called multiple times and thus we redifine it if let &mut MultipleReplyInfo::RouteReply(ref mut k) = self { *k = bin_decode(r, Infinite).map_err(|e|BincErr(e))?; } Ok(()) } } impl<A : Serialize + DeserializeOwned + Clone + Eq> RepInfo for MultipleReplyInfo<A> { #[inline] fn require_additional_payload(&self) -> bool { if let &MultipleReplyInfo::Route = self { true } else {false} } /// TODO remove called once fn get_reply_key(&self) -> Option<&Vec<u8>> { match self { // &MultipleReplyInfo::RouteReply(ref k) => Some(k), &MultipleReplyInfo::CachedRoute(ref k) => Some(k), &MultipleReplyInfo::RouteReply(ref k) => Some(k), _ => None, } } } /// TODO E as explicit limiter named trait for readability pub struct ReplyInfoProvider<P : Peer,SSW,SSR, SP : SymProvider<SSW,SSR>> { pub mode : MultipleReplyMode, // for different reply route pub symprov : SP, pub _p : PhantomData<(P,SSW,SSR)>, } /// TODO macro inherit?? impl<P:Peer,SSW,SSR,SP : SymProvider<SSW,SSR>> SymProvider<SSW,SSR> for ReplyInfoProvider<P,SSW,SSR,SP> { #[inline] fn new_sym_key (&mut self) -> Vec<u8> { self.symprov.new_sym_key() } #[inline] fn new
mut self, k : Vec<u8>) -> SSW { self.symprov.new_sym_writer(k) } #[inline] fn new_sym_reader (&mut self, k : Vec<u8>) -> SSR { self.symprov.new_sym_reader(k) } } impl<P : Peer,SSW,SSR,SP : SymProvider<SSW,SSR>> ReplyProvider<P, MultipleReplyInfo<<P as Peer>::Address>> for ReplyInfoProvider<P,SSW,SSR,SP> { /// Error infos bases for peers fn new_reply (&mut self, route : &[&P]) -> Vec<MultipleReplyInfo<<P as Peer>::Address>> { let l = route.len(); match self.mode { MultipleReplyMode::NoHandling => vec![MultipleReplyInfo::NoHandling;l-1], MultipleReplyMode::KnownDest => { let mut res = vec![MultipleReplyInfo::NoHandling;l-1]; res[l-2] = MultipleReplyInfo::KnownDest(route[0].get_address().clone()); res }, MultipleReplyMode::OtherRoute => { let mut res = vec![MultipleReplyInfo::NoHandling;l-1]; res[l-2] = MultipleReplyInfo::Route; //res[l-2] = MultipleReplyInfo::Route(self.new_sym_key(route[l-1])); res }, MultipleReplyMode::Route => { let mut res = vec![MultipleReplyInfo::NoHandling;l-1]; //res[l-2] = MultipleReplyInfo::Route(self.new_sym_key(route[l-1])); res[l-2] = MultipleReplyInfo::Route; res }, MultipleReplyMode::RouteReply => { let mut res : Vec<MultipleReplyInfo<_>> = Vec::with_capacity(l-1); for _ in 1..l { res.push(MultipleReplyInfo::RouteReply(self.new_sym_key())) } res }, MultipleReplyMode::CachedRoute => { let mut res : Vec<MultipleReplyInfo<_>> = Vec::with_capacity(l-1); for _ in 1..l { res.push(MultipleReplyInfo::CachedRoute(self.new_sym_key())) } res }, } } } /// specific provider for no rpe pub struct NoMultiRepProvider; impl<P : Peer> ReplyProvider<P, MultipleReplyInfo<<P as Peer>::Address>> for NoMultiRepProvider { #[inline] fn new_reply (&mut self, p : &[&P]) -> Vec<MultipleReplyInfo<<P as Peer>::Address>> { vec![MultipleReplyInfo::NoHandling;p.len()-1] } } impl<SSW,SSR> SymProvider<SSW,SSR> for NoMultiRepProvider { fn new_sym_key (&mut self) -> Vec<u8> { unimplemented!() } fn new_sym_writer (&mut self, _ : Vec<u8>) -> SSW { unimplemented!() } fn new_sym_reader (&mut self, _ : Vec<u8>) -> SSR { unimplemented!() } }
_sym_writer (&
identifier_name
common.rs
use num::{Zero, One, Signed, Float}; use math::scalar::{BaseNum, BaseFloat}; use std::ops::{Add, Sub, Mul, Div, Index, Neg}; #[derive(Debug)] pub enum Dimension2 { X = 1, Y = 2, } #[derive(Debug)] pub enum Dimension3 { X = 1, Y = 2, Z = 3, } pub trait ComponentWise where Self: Index<usize>, Self: Index<<Self as ComponentWise>::Dimension> { type Scalar: BaseNum; type Dimension; fn min_component(self) -> Self::Scalar; fn max_component(self) -> Self::Scalar; fn max_dimension(self) -> Self::Dimension; fn min(self, other: Self) -> Self; fn max(self, other: Self) -> Self; } pub trait ComponentWiseSigned: ComponentWise where <Self as ComponentWise>::Scalar: BaseNum + Signed { fn abs(self) -> Self; } pub trait ComponentWiseFloat: ComponentWiseSigned where <Self as ComponentWise>::Scalar: BaseFloat { fn floor(self) -> Self; fn ceil(self) -> Self; } pub trait VectorSpace: Copy + Clone where Self: Zero, Self: Add<Self, Output = Self>, Self: Sub<Self, Output = Self>, Self: Mul<<Self as VectorSpace>::Scalar, Output = Self>, Self: Div<<Self as VectorSpace>::Scalar, Output = Self>, { type Scalar: BaseNum; } pub trait InnerProduct<RHS = Self>: VectorSpace { fn dot(self, other: RHS) -> Self::Scalar; } pub trait CrossProduct<RHS = Self>: VectorSpace { type CrossOutput: VectorSpace; fn cross(self, other: RHS) -> Self::CrossOutput; } pub trait InnerProductSpace: InnerProduct where <Self as VectorSpace>::Scalar: BaseFloat, { fn magnitude(self) -> Self::Scalar { Float::sqrt(self.magnitude_squared()) } fn magnitude_squared(self) -> Self::Scalar { self.dot(self) } fn normalize(self) -> Self { self * (Self::Scalar::one() / self.magnitude()) } } pub trait MetricSpace<RHS = Self>: Copy + Clone { type Scalar: BaseFloat; fn distance(self, other: RHS) -> Self::Scalar { Float::sqrt(self.distance_squared(other)) } fn distance_squared(self, other: RHS) -> Self::Scalar; } pub trait LinearInterpolate: Copy + Clone where Self: Add<Self, Output = Self>, Self: Mul<<Self as LinearInterpolate>::Scalar, Output = Self>, { type Scalar: BaseFloat; fn lerp(self, other: Self, t: Self::Scalar) -> Self { self * (Self::Scalar::one() - t) + other * t } } pub fn dot<T: InnerProduct, U: InnerProduct<T>>(v1: U, v2: T) -> U::Scalar { v1.dot(v2) } pub fn abs_dot<T: InnerProduct, U: InnerProduct<T>>(v1: U, v2: T) -> U::Scalar where U::Scalar: Signed { v1.dot(v2).abs() } pub fn cross<T: CrossProduct, U: CrossProduct<T>>(v1: U, v2: T) -> U::CrossOutput { v1.cross(v2) } pub fn min_component<T: ComponentWise>(v: T) -> T::Scalar { v.min_component() } pub fn max_component<T: ComponentWise>(v: T) -> T::Scalar { v.max_component() } pub fn distance<T: MetricSpace>(v1: T, v2: T) -> T::Scalar { v1.distance(v2) } pub fn distance_squared<T: MetricSpace>(v1: T, v2: T) -> T::Scalar { v1.distance_squared(v2) } pub fn component_wise_min<T: ComponentWise>(v1: T, v2: T) -> T { v1.min(v2) } pub fn component_wise_max<T: ComponentWise>(v1: T, v2: T) -> T { v1.max(v2) } pub fn face_forward<T: InnerProduct, U: InnerProduct<T> + Neg<Output = U>>(v1: U, v2: T) -> U
{ if dot(v1, v2) < U::Scalar::zero() { -v1 } else { v1 } }
identifier_body
common.rs
use num::{Zero, One, Signed, Float}; use math::scalar::{BaseNum, BaseFloat}; use std::ops::{Add, Sub, Mul, Div, Index, Neg}; #[derive(Debug)] pub enum Dimension2 { X = 1, Y = 2, } #[derive(Debug)] pub enum Dimension3 { X = 1, Y = 2, Z = 3, } pub trait ComponentWise where Self: Index<usize>, Self: Index<<Self as ComponentWise>::Dimension> { type Scalar: BaseNum; type Dimension; fn min_component(self) -> Self::Scalar; fn max_component(self) -> Self::Scalar; fn max_dimension(self) -> Self::Dimension; fn min(self, other: Self) -> Self; fn max(self, other: Self) -> Self; } pub trait ComponentWiseSigned: ComponentWise where <Self as ComponentWise>::Scalar: BaseNum + Signed { fn abs(self) -> Self; } pub trait ComponentWiseFloat: ComponentWiseSigned where <Self as ComponentWise>::Scalar: BaseFloat { fn floor(self) -> Self; fn ceil(self) -> Self; } pub trait VectorSpace: Copy + Clone where Self: Zero, Self: Add<Self, Output = Self>, Self: Sub<Self, Output = Self>, Self: Mul<<Self as VectorSpace>::Scalar, Output = Self>, Self: Div<<Self as VectorSpace>::Scalar, Output = Self>, { type Scalar: BaseNum; } pub trait InnerProduct<RHS = Self>: VectorSpace { fn dot(self, other: RHS) -> Self::Scalar; } pub trait CrossProduct<RHS = Self>: VectorSpace { type CrossOutput: VectorSpace; fn cross(self, other: RHS) -> Self::CrossOutput; } pub trait InnerProductSpace: InnerProduct where <Self as VectorSpace>::Scalar: BaseFloat, { fn magnitude(self) -> Self::Scalar { Float::sqrt(self.magnitude_squared()) } fn magnitude_squared(self) -> Self::Scalar { self.dot(self) } fn normalize(self) -> Self { self * (Self::Scalar::one() / self.magnitude()) } } pub trait MetricSpace<RHS = Self>: Copy + Clone { type Scalar: BaseFloat; fn distance(self, other: RHS) -> Self::Scalar { Float::sqrt(self.distance_squared(other)) } fn distance_squared(self, other: RHS) -> Self::Scalar; } pub trait LinearInterpolate: Copy + Clone where Self: Add<Self, Output = Self>, Self: Mul<<Self as LinearInterpolate>::Scalar, Output = Self>, { type Scalar: BaseFloat; fn lerp(self, other: Self, t: Self::Scalar) -> Self { self * (Self::Scalar::one() - t) + other * t } } pub fn dot<T: InnerProduct, U: InnerProduct<T>>(v1: U, v2: T) -> U::Scalar { v1.dot(v2) } pub fn abs_dot<T: InnerProduct, U: InnerProduct<T>>(v1: U, v2: T) -> U::Scalar where U::Scalar: Signed { v1.dot(v2).abs() } pub fn cross<T: CrossProduct, U: CrossProduct<T>>(v1: U, v2: T) -> U::CrossOutput { v1.cross(v2) } pub fn min_component<T: ComponentWise>(v: T) -> T::Scalar { v.min_component() } pub fn max_component<T: ComponentWise>(v: T) -> T::Scalar { v.max_component() } pub fn distance<T: MetricSpace>(v1: T, v2: T) -> T::Scalar { v1.distance(v2) } pub fn distance_squared<T: MetricSpace>(v1: T, v2: T) -> T::Scalar { v1.distance_squared(v2) } pub fn component_wise_min<T: ComponentWise>(v1: T, v2: T) -> T { v1.min(v2) } pub fn component_wise_max<T: ComponentWise>(v1: T, v2: T) -> T { v1.max(v2) } pub fn face_forward<T: InnerProduct, U: InnerProduct<T> + Neg<Output = U>>(v1: U, v2: T) -> U { if dot(v1, v2) < U::Scalar::zero()
else { v1 } }
{ -v1 }
conditional_block
common.rs
use num::{Zero, One, Signed, Float}; use math::scalar::{BaseNum, BaseFloat}; use std::ops::{Add, Sub, Mul, Div, Index, Neg}; #[derive(Debug)] pub enum Dimension2 { X = 1, Y = 2, } #[derive(Debug)] pub enum Dimension3 { X = 1, Y = 2, Z = 3, } pub trait ComponentWise where Self: Index<usize>, Self: Index<<Self as ComponentWise>::Dimension> { type Scalar: BaseNum; type Dimension; fn min_component(self) -> Self::Scalar; fn max_component(self) -> Self::Scalar; fn max_dimension(self) -> Self::Dimension; fn min(self, other: Self) -> Self;
<Self as ComponentWise>::Scalar: BaseNum + Signed { fn abs(self) -> Self; } pub trait ComponentWiseFloat: ComponentWiseSigned where <Self as ComponentWise>::Scalar: BaseFloat { fn floor(self) -> Self; fn ceil(self) -> Self; } pub trait VectorSpace: Copy + Clone where Self: Zero, Self: Add<Self, Output = Self>, Self: Sub<Self, Output = Self>, Self: Mul<<Self as VectorSpace>::Scalar, Output = Self>, Self: Div<<Self as VectorSpace>::Scalar, Output = Self>, { type Scalar: BaseNum; } pub trait InnerProduct<RHS = Self>: VectorSpace { fn dot(self, other: RHS) -> Self::Scalar; } pub trait CrossProduct<RHS = Self>: VectorSpace { type CrossOutput: VectorSpace; fn cross(self, other: RHS) -> Self::CrossOutput; } pub trait InnerProductSpace: InnerProduct where <Self as VectorSpace>::Scalar: BaseFloat, { fn magnitude(self) -> Self::Scalar { Float::sqrt(self.magnitude_squared()) } fn magnitude_squared(self) -> Self::Scalar { self.dot(self) } fn normalize(self) -> Self { self * (Self::Scalar::one() / self.magnitude()) } } pub trait MetricSpace<RHS = Self>: Copy + Clone { type Scalar: BaseFloat; fn distance(self, other: RHS) -> Self::Scalar { Float::sqrt(self.distance_squared(other)) } fn distance_squared(self, other: RHS) -> Self::Scalar; } pub trait LinearInterpolate: Copy + Clone where Self: Add<Self, Output = Self>, Self: Mul<<Self as LinearInterpolate>::Scalar, Output = Self>, { type Scalar: BaseFloat; fn lerp(self, other: Self, t: Self::Scalar) -> Self { self * (Self::Scalar::one() - t) + other * t } } pub fn dot<T: InnerProduct, U: InnerProduct<T>>(v1: U, v2: T) -> U::Scalar { v1.dot(v2) } pub fn abs_dot<T: InnerProduct, U: InnerProduct<T>>(v1: U, v2: T) -> U::Scalar where U::Scalar: Signed { v1.dot(v2).abs() } pub fn cross<T: CrossProduct, U: CrossProduct<T>>(v1: U, v2: T) -> U::CrossOutput { v1.cross(v2) } pub fn min_component<T: ComponentWise>(v: T) -> T::Scalar { v.min_component() } pub fn max_component<T: ComponentWise>(v: T) -> T::Scalar { v.max_component() } pub fn distance<T: MetricSpace>(v1: T, v2: T) -> T::Scalar { v1.distance(v2) } pub fn distance_squared<T: MetricSpace>(v1: T, v2: T) -> T::Scalar { v1.distance_squared(v2) } pub fn component_wise_min<T: ComponentWise>(v1: T, v2: T) -> T { v1.min(v2) } pub fn component_wise_max<T: ComponentWise>(v1: T, v2: T) -> T { v1.max(v2) } pub fn face_forward<T: InnerProduct, U: InnerProduct<T> + Neg<Output = U>>(v1: U, v2: T) -> U { if dot(v1, v2) < U::Scalar::zero() { -v1 } else { v1 } }
fn max(self, other: Self) -> Self; } pub trait ComponentWiseSigned: ComponentWise where
random_line_split
common.rs
use num::{Zero, One, Signed, Float}; use math::scalar::{BaseNum, BaseFloat}; use std::ops::{Add, Sub, Mul, Div, Index, Neg}; #[derive(Debug)] pub enum Dimension2 { X = 1, Y = 2, } #[derive(Debug)] pub enum Dimension3 { X = 1, Y = 2, Z = 3, } pub trait ComponentWise where Self: Index<usize>, Self: Index<<Self as ComponentWise>::Dimension> { type Scalar: BaseNum; type Dimension; fn min_component(self) -> Self::Scalar; fn max_component(self) -> Self::Scalar; fn max_dimension(self) -> Self::Dimension; fn min(self, other: Self) -> Self; fn max(self, other: Self) -> Self; } pub trait ComponentWiseSigned: ComponentWise where <Self as ComponentWise>::Scalar: BaseNum + Signed { fn abs(self) -> Self; } pub trait ComponentWiseFloat: ComponentWiseSigned where <Self as ComponentWise>::Scalar: BaseFloat { fn floor(self) -> Self; fn ceil(self) -> Self; } pub trait VectorSpace: Copy + Clone where Self: Zero, Self: Add<Self, Output = Self>, Self: Sub<Self, Output = Self>, Self: Mul<<Self as VectorSpace>::Scalar, Output = Self>, Self: Div<<Self as VectorSpace>::Scalar, Output = Self>, { type Scalar: BaseNum; } pub trait InnerProduct<RHS = Self>: VectorSpace { fn dot(self, other: RHS) -> Self::Scalar; } pub trait CrossProduct<RHS = Self>: VectorSpace { type CrossOutput: VectorSpace; fn cross(self, other: RHS) -> Self::CrossOutput; } pub trait InnerProductSpace: InnerProduct where <Self as VectorSpace>::Scalar: BaseFloat, { fn magnitude(self) -> Self::Scalar { Float::sqrt(self.magnitude_squared()) } fn magnitude_squared(self) -> Self::Scalar { self.dot(self) } fn normalize(self) -> Self { self * (Self::Scalar::one() / self.magnitude()) } } pub trait MetricSpace<RHS = Self>: Copy + Clone { type Scalar: BaseFloat; fn distance(self, other: RHS) -> Self::Scalar { Float::sqrt(self.distance_squared(other)) } fn distance_squared(self, other: RHS) -> Self::Scalar; } pub trait LinearInterpolate: Copy + Clone where Self: Add<Self, Output = Self>, Self: Mul<<Self as LinearInterpolate>::Scalar, Output = Self>, { type Scalar: BaseFloat; fn
(self, other: Self, t: Self::Scalar) -> Self { self * (Self::Scalar::one() - t) + other * t } } pub fn dot<T: InnerProduct, U: InnerProduct<T>>(v1: U, v2: T) -> U::Scalar { v1.dot(v2) } pub fn abs_dot<T: InnerProduct, U: InnerProduct<T>>(v1: U, v2: T) -> U::Scalar where U::Scalar: Signed { v1.dot(v2).abs() } pub fn cross<T: CrossProduct, U: CrossProduct<T>>(v1: U, v2: T) -> U::CrossOutput { v1.cross(v2) } pub fn min_component<T: ComponentWise>(v: T) -> T::Scalar { v.min_component() } pub fn max_component<T: ComponentWise>(v: T) -> T::Scalar { v.max_component() } pub fn distance<T: MetricSpace>(v1: T, v2: T) -> T::Scalar { v1.distance(v2) } pub fn distance_squared<T: MetricSpace>(v1: T, v2: T) -> T::Scalar { v1.distance_squared(v2) } pub fn component_wise_min<T: ComponentWise>(v1: T, v2: T) -> T { v1.min(v2) } pub fn component_wise_max<T: ComponentWise>(v1: T, v2: T) -> T { v1.max(v2) } pub fn face_forward<T: InnerProduct, U: InnerProduct<T> + Neg<Output = U>>(v1: U, v2: T) -> U { if dot(v1, v2) < U::Scalar::zero() { -v1 } else { v1 } }
lerp
identifier_name
failure.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. #![experimental] use alloc::boxed::Box; use any::{Any, AnyRefExt}; use fmt; use io::{Writer, IoResult}; use kinds::Send; use option::{Some, None}; use result::Ok; use rt::backtrace; use rt::{Stderr, Stdio}; use rustrt::local::Local; use rustrt::task::Task; use str::Str; use string::String; // Defined in this module instead of io::stdio so that the unwinding local_data_key!(pub local_stderr: Box<Writer + Send>) impl Writer for Stdio { fn write(&mut self, bytes: &[u8]) -> IoResult<()> { fn fmt_write<F: fmt::FormatWriter>(f: &mut F, bytes: &[u8]) { let _ = f.write(bytes); } fmt_write(self, bytes); Ok(()) } } pub fn
(obj: &Any + Send, file: &'static str, line: uint) { let msg = match obj.as_ref::<&'static str>() { Some(s) => *s, None => match obj.as_ref::<String>() { Some(s) => s.as_slice(), None => "Box<Any>", } }; let mut err = Stderr; // It is assumed that all reasonable rust code will have a local task at // all times. This means that this `exists` will return true almost all of // the time. There are border cases, however, when the runtime has // *almost* set up the local task, but hasn't quite gotten there yet. In // order to get some better diagnostics, we print on failure and // immediately abort the whole process if there is no local task // available. if!Local::exists(None::<Task>) { let _ = writeln!(&mut err, "failed at '{}', {}:{}", msg, file, line); if backtrace::log_enabled() { let _ = backtrace::write(&mut err); } else { let _ = writeln!(&mut err, "run with `RUST_BACKTRACE=1` to \ see a backtrace"); } return } // Peel the name out of local task so we can print it. We've got to be sure // that the local task is in TLS while we're printing as I/O may occur. let (name, unwinding) = { let mut t = Local::borrow(None::<Task>); (t.name.take(), t.unwinder.unwinding()) }; { let n = name.as_ref().map(|n| n.as_slice()).unwrap_or("<unnamed>"); match local_stderr.replace(None) { Some(mut stderr) => { // FIXME: what to do when the task printing fails? let _ = writeln!(stderr, "task '{}' failed at '{}', {}:{}\n", n, msg, file, line); if backtrace::log_enabled() { let _ = backtrace::write(&mut *stderr); } local_stderr.replace(Some(stderr)); } None => { let _ = writeln!(&mut err, "task '{}' failed at '{}', {}:{}", n, msg, file, line); if backtrace::log_enabled() { let _ = backtrace::write(&mut err); } } } // If this is a double failure, make sure that we printed a backtrace // for this failure. if unwinding &&!backtrace::log_enabled() { let _ = backtrace::write(&mut err); } } Local::borrow(None::<Task>).name = name; }
on_fail
identifier_name
failure.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. #![experimental] use alloc::boxed::Box; use any::{Any, AnyRefExt}; use fmt; use io::{Writer, IoResult}; use kinds::Send; use option::{Some, None}; use result::Ok; use rt::backtrace; use rt::{Stderr, Stdio}; use rustrt::local::Local; use rustrt::task::Task; use str::Str; use string::String; // Defined in this module instead of io::stdio so that the unwinding local_data_key!(pub local_stderr: Box<Writer + Send>) impl Writer for Stdio { fn write(&mut self, bytes: &[u8]) -> IoResult<()>
} pub fn on_fail(obj: &Any + Send, file: &'static str, line: uint) { let msg = match obj.as_ref::<&'static str>() { Some(s) => *s, None => match obj.as_ref::<String>() { Some(s) => s.as_slice(), None => "Box<Any>", } }; let mut err = Stderr; // It is assumed that all reasonable rust code will have a local task at // all times. This means that this `exists` will return true almost all of // the time. There are border cases, however, when the runtime has // *almost* set up the local task, but hasn't quite gotten there yet. In // order to get some better diagnostics, we print on failure and // immediately abort the whole process if there is no local task // available. if!Local::exists(None::<Task>) { let _ = writeln!(&mut err, "failed at '{}', {}:{}", msg, file, line); if backtrace::log_enabled() { let _ = backtrace::write(&mut err); } else { let _ = writeln!(&mut err, "run with `RUST_BACKTRACE=1` to \ see a backtrace"); } return } // Peel the name out of local task so we can print it. We've got to be sure // that the local task is in TLS while we're printing as I/O may occur. let (name, unwinding) = { let mut t = Local::borrow(None::<Task>); (t.name.take(), t.unwinder.unwinding()) }; { let n = name.as_ref().map(|n| n.as_slice()).unwrap_or("<unnamed>"); match local_stderr.replace(None) { Some(mut stderr) => { // FIXME: what to do when the task printing fails? let _ = writeln!(stderr, "task '{}' failed at '{}', {}:{}\n", n, msg, file, line); if backtrace::log_enabled() { let _ = backtrace::write(&mut *stderr); } local_stderr.replace(Some(stderr)); } None => { let _ = writeln!(&mut err, "task '{}' failed at '{}', {}:{}", n, msg, file, line); if backtrace::log_enabled() { let _ = backtrace::write(&mut err); } } } // If this is a double failure, make sure that we printed a backtrace // for this failure. if unwinding &&!backtrace::log_enabled() { let _ = backtrace::write(&mut err); } } Local::borrow(None::<Task>).name = name; }
{ fn fmt_write<F: fmt::FormatWriter>(f: &mut F, bytes: &[u8]) { let _ = f.write(bytes); } fmt_write(self, bytes); Ok(()) }
identifier_body
failure.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. #![experimental] use alloc::boxed::Box; use any::{Any, AnyRefExt}; use fmt; use io::{Writer, IoResult}; use kinds::Send; use option::{Some, None}; use result::Ok; use rt::backtrace; use rt::{Stderr, Stdio}; use rustrt::local::Local;
// Defined in this module instead of io::stdio so that the unwinding local_data_key!(pub local_stderr: Box<Writer + Send>) impl Writer for Stdio { fn write(&mut self, bytes: &[u8]) -> IoResult<()> { fn fmt_write<F: fmt::FormatWriter>(f: &mut F, bytes: &[u8]) { let _ = f.write(bytes); } fmt_write(self, bytes); Ok(()) } } pub fn on_fail(obj: &Any + Send, file: &'static str, line: uint) { let msg = match obj.as_ref::<&'static str>() { Some(s) => *s, None => match obj.as_ref::<String>() { Some(s) => s.as_slice(), None => "Box<Any>", } }; let mut err = Stderr; // It is assumed that all reasonable rust code will have a local task at // all times. This means that this `exists` will return true almost all of // the time. There are border cases, however, when the runtime has // *almost* set up the local task, but hasn't quite gotten there yet. In // order to get some better diagnostics, we print on failure and // immediately abort the whole process if there is no local task // available. if!Local::exists(None::<Task>) { let _ = writeln!(&mut err, "failed at '{}', {}:{}", msg, file, line); if backtrace::log_enabled() { let _ = backtrace::write(&mut err); } else { let _ = writeln!(&mut err, "run with `RUST_BACKTRACE=1` to \ see a backtrace"); } return } // Peel the name out of local task so we can print it. We've got to be sure // that the local task is in TLS while we're printing as I/O may occur. let (name, unwinding) = { let mut t = Local::borrow(None::<Task>); (t.name.take(), t.unwinder.unwinding()) }; { let n = name.as_ref().map(|n| n.as_slice()).unwrap_or("<unnamed>"); match local_stderr.replace(None) { Some(mut stderr) => { // FIXME: what to do when the task printing fails? let _ = writeln!(stderr, "task '{}' failed at '{}', {}:{}\n", n, msg, file, line); if backtrace::log_enabled() { let _ = backtrace::write(&mut *stderr); } local_stderr.replace(Some(stderr)); } None => { let _ = writeln!(&mut err, "task '{}' failed at '{}', {}:{}", n, msg, file, line); if backtrace::log_enabled() { let _ = backtrace::write(&mut err); } } } // If this is a double failure, make sure that we printed a backtrace // for this failure. if unwinding &&!backtrace::log_enabled() { let _ = backtrace::write(&mut err); } } Local::borrow(None::<Task>).name = name; }
use rustrt::task::Task; use str::Str; use string::String;
random_line_split
confirmations.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Types used in Confirmations queue (Trusted Signer) use std::fmt; use serde::{Serialize, Serializer}; use v1::types::{U256, TransactionRequest, RichRawTransaction, H160, H256, H520, Bytes}; use v1::helpers; /// Confirmation waiting in a queue #[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize)] pub struct ConfirmationRequest { /// Id of this confirmation pub id: U256, /// Payload pub payload: ConfirmationPayload, } impl From<helpers::ConfirmationRequest> for ConfirmationRequest { fn from(c: helpers::ConfirmationRequest) -> Self { ConfirmationRequest { id: c.id.into(), payload: c.payload.into(), } } } /// Sign request #[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize)] pub struct SignRequest { /// Address pub address: H160, /// Hash to sign pub hash: H256, } impl From<(H160, H256)> for SignRequest { fn from(tuple: (H160, H256)) -> Self { SignRequest { address: tuple.0, hash: tuple.1, } } } /// Decrypt request #[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize)] pub struct DecryptRequest { /// Address pub address: H160, /// Message to decrypt pub msg: Bytes, } impl From<(H160, Bytes)> for DecryptRequest { fn from(tuple: (H160, Bytes)) -> Self { DecryptRequest { address: tuple.0, msg: tuple.1, } } } /// Confirmation response for particular payload #[derive(Debug, Clone, PartialEq)] pub enum ConfirmationResponse { /// Transaction Hash SendTransaction(H256), /// Transaction RLP SignTransaction(RichRawTransaction), /// Signature Signature(H520), /// Decrypted data Decrypt(Bytes), } impl Serialize for ConfirmationResponse { fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error> where S: Serializer { match *self { ConfirmationResponse::SendTransaction(ref hash) => hash.serialize(serializer), ConfirmationResponse::SignTransaction(ref rlp) => rlp.serialize(serializer), ConfirmationResponse::Signature(ref signature) => signature.serialize(serializer), ConfirmationResponse::Decrypt(ref data) => data.serialize(serializer), } } } /// Confirmation payload, i.e. the thing to be confirmed #[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize)] pub enum ConfirmationPayload { /// Send Transaction #[serde(rename="transaction")] SendTransaction(TransactionRequest), /// Sign Transaction #[serde(rename="transaction")] SignTransaction(TransactionRequest), /// Signature #[serde(rename="sign")] Signature(SignRequest), /// Decryption #[serde(rename="decrypt")] Decrypt(DecryptRequest), } impl From<helpers::ConfirmationPayload> for ConfirmationPayload { fn from(c: helpers::ConfirmationPayload) -> Self { match c { helpers::ConfirmationPayload::SendTransaction(t) => ConfirmationPayload::SendTransaction(t.into()), helpers::ConfirmationPayload::SignTransaction(t) => ConfirmationPayload::SignTransaction(t.into()), helpers::ConfirmationPayload::Signature(address, hash) => ConfirmationPayload::Signature(SignRequest { address: address.into(), hash: hash.into(), }), helpers::ConfirmationPayload::Decrypt(address, msg) => ConfirmationPayload::Decrypt(DecryptRequest { address: address.into(), msg: msg.into(), }), } } } /// Possible modifications to the confirmed transaction sent by `Trusted Signer` #[derive(Debug, PartialEq, Deserialize)] #[serde(deny_unknown_fields)] pub struct TransactionModification { /// Modified gas price #[serde(rename="gasPrice")] pub gas_price: Option<U256>, } /// Represents two possible return values. #[derive(Debug, Clone)] pub enum Either<A, B> where A: fmt::Debug + Clone, B: fmt::Debug + Clone, { /// Primary value Either(A), /// Secondary value Or(B), } impl<A, B> From<A> for Either<A, B> where A: fmt::Debug + Clone, B: fmt::Debug + Clone, { fn from(a: A) -> Self { Either::Either(a) } } impl<A, B> Serialize for Either<A, B> where A: Serialize + fmt::Debug + Clone, B: Serialize + fmt::Debug + Clone, { fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error> where S: Serializer { match *self { Either::Either(ref a) => a.serialize(serializer), Either::Or(ref b) => b.serialize(serializer), } } } #[cfg(test)] mod tests { use std::str::FromStr; use serde_json; use v1::types::U256; use v1::helpers; use super::*; #[test] fn should_serialize_sign_confirmation() { // given let request = helpers::ConfirmationRequest { id: 15.into(), payload: helpers::ConfirmationPayload::Signature(1.into(), 5.into()), };
let res = serde_json::to_string(&ConfirmationRequest::from(request)); let expected = r#"{"id":"0xf","payload":{"sign":{"address":"0x0000000000000000000000000000000000000001","hash":"0x0000000000000000000000000000000000000000000000000000000000000005"}}}"#; // then assert_eq!(res.unwrap(), expected.to_owned()); } #[test] fn should_serialize_transaction_confirmation() { // given let request = helpers::ConfirmationRequest { id: 15.into(), payload: helpers::ConfirmationPayload::SendTransaction(helpers::FilledTransactionRequest { from: 0.into(), to: None, gas: 15_000.into(), gas_price: 10_000.into(), value: 100_000.into(), data: vec![1, 2, 3], nonce: Some(1.into()), }), }; // when let res = serde_json::to_string(&ConfirmationRequest::from(request)); let expected = r#"{"id":"0xf","payload":{"transaction":{"from":"0x0000000000000000000000000000000000000000","to":null,"gasPrice":"0x2710","gas":"0x3a98","value":"0x186a0","data":"0x010203","nonce":"0x1"}}}"#; // then assert_eq!(res.unwrap(), expected.to_owned()); } #[test] fn should_deserialize_modification() { // given let s1 = r#"{ "gasPrice":"0xba43b7400" }"#; let s2 = r#"{}"#; // when let res1: TransactionModification = serde_json::from_str(s1).unwrap(); let res2: TransactionModification = serde_json::from_str(s2).unwrap(); // then assert_eq!(res1, TransactionModification { gas_price: Some(U256::from_str("0ba43b7400").unwrap()), }); assert_eq!(res2, TransactionModification { gas_price: None, }); } }
// when
random_line_split
confirmations.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Types used in Confirmations queue (Trusted Signer) use std::fmt; use serde::{Serialize, Serializer}; use v1::types::{U256, TransactionRequest, RichRawTransaction, H160, H256, H520, Bytes}; use v1::helpers; /// Confirmation waiting in a queue #[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize)] pub struct ConfirmationRequest { /// Id of this confirmation pub id: U256, /// Payload pub payload: ConfirmationPayload, } impl From<helpers::ConfirmationRequest> for ConfirmationRequest { fn from(c: helpers::ConfirmationRequest) -> Self { ConfirmationRequest { id: c.id.into(), payload: c.payload.into(), } } } /// Sign request #[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize)] pub struct SignRequest { /// Address pub address: H160, /// Hash to sign pub hash: H256, } impl From<(H160, H256)> for SignRequest { fn from(tuple: (H160, H256)) -> Self { SignRequest { address: tuple.0, hash: tuple.1, } } } /// Decrypt request #[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize)] pub struct DecryptRequest { /// Address pub address: H160, /// Message to decrypt pub msg: Bytes, } impl From<(H160, Bytes)> for DecryptRequest { fn from(tuple: (H160, Bytes)) -> Self { DecryptRequest { address: tuple.0, msg: tuple.1, } } } /// Confirmation response for particular payload #[derive(Debug, Clone, PartialEq)] pub enum ConfirmationResponse { /// Transaction Hash SendTransaction(H256), /// Transaction RLP SignTransaction(RichRawTransaction), /// Signature Signature(H520), /// Decrypted data Decrypt(Bytes), } impl Serialize for ConfirmationResponse { fn
<S>(&self, serializer: &mut S) -> Result<(), S::Error> where S: Serializer { match *self { ConfirmationResponse::SendTransaction(ref hash) => hash.serialize(serializer), ConfirmationResponse::SignTransaction(ref rlp) => rlp.serialize(serializer), ConfirmationResponse::Signature(ref signature) => signature.serialize(serializer), ConfirmationResponse::Decrypt(ref data) => data.serialize(serializer), } } } /// Confirmation payload, i.e. the thing to be confirmed #[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize)] pub enum ConfirmationPayload { /// Send Transaction #[serde(rename="transaction")] SendTransaction(TransactionRequest), /// Sign Transaction #[serde(rename="transaction")] SignTransaction(TransactionRequest), /// Signature #[serde(rename="sign")] Signature(SignRequest), /// Decryption #[serde(rename="decrypt")] Decrypt(DecryptRequest), } impl From<helpers::ConfirmationPayload> for ConfirmationPayload { fn from(c: helpers::ConfirmationPayload) -> Self { match c { helpers::ConfirmationPayload::SendTransaction(t) => ConfirmationPayload::SendTransaction(t.into()), helpers::ConfirmationPayload::SignTransaction(t) => ConfirmationPayload::SignTransaction(t.into()), helpers::ConfirmationPayload::Signature(address, hash) => ConfirmationPayload::Signature(SignRequest { address: address.into(), hash: hash.into(), }), helpers::ConfirmationPayload::Decrypt(address, msg) => ConfirmationPayload::Decrypt(DecryptRequest { address: address.into(), msg: msg.into(), }), } } } /// Possible modifications to the confirmed transaction sent by `Trusted Signer` #[derive(Debug, PartialEq, Deserialize)] #[serde(deny_unknown_fields)] pub struct TransactionModification { /// Modified gas price #[serde(rename="gasPrice")] pub gas_price: Option<U256>, } /// Represents two possible return values. #[derive(Debug, Clone)] pub enum Either<A, B> where A: fmt::Debug + Clone, B: fmt::Debug + Clone, { /// Primary value Either(A), /// Secondary value Or(B), } impl<A, B> From<A> for Either<A, B> where A: fmt::Debug + Clone, B: fmt::Debug + Clone, { fn from(a: A) -> Self { Either::Either(a) } } impl<A, B> Serialize for Either<A, B> where A: Serialize + fmt::Debug + Clone, B: Serialize + fmt::Debug + Clone, { fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error> where S: Serializer { match *self { Either::Either(ref a) => a.serialize(serializer), Either::Or(ref b) => b.serialize(serializer), } } } #[cfg(test)] mod tests { use std::str::FromStr; use serde_json; use v1::types::U256; use v1::helpers; use super::*; #[test] fn should_serialize_sign_confirmation() { // given let request = helpers::ConfirmationRequest { id: 15.into(), payload: helpers::ConfirmationPayload::Signature(1.into(), 5.into()), }; // when let res = serde_json::to_string(&ConfirmationRequest::from(request)); let expected = r#"{"id":"0xf","payload":{"sign":{"address":"0x0000000000000000000000000000000000000001","hash":"0x0000000000000000000000000000000000000000000000000000000000000005"}}}"#; // then assert_eq!(res.unwrap(), expected.to_owned()); } #[test] fn should_serialize_transaction_confirmation() { // given let request = helpers::ConfirmationRequest { id: 15.into(), payload: helpers::ConfirmationPayload::SendTransaction(helpers::FilledTransactionRequest { from: 0.into(), to: None, gas: 15_000.into(), gas_price: 10_000.into(), value: 100_000.into(), data: vec![1, 2, 3], nonce: Some(1.into()), }), }; // when let res = serde_json::to_string(&ConfirmationRequest::from(request)); let expected = r#"{"id":"0xf","payload":{"transaction":{"from":"0x0000000000000000000000000000000000000000","to":null,"gasPrice":"0x2710","gas":"0x3a98","value":"0x186a0","data":"0x010203","nonce":"0x1"}}}"#; // then assert_eq!(res.unwrap(), expected.to_owned()); } #[test] fn should_deserialize_modification() { // given let s1 = r#"{ "gasPrice":"0xba43b7400" }"#; let s2 = r#"{}"#; // when let res1: TransactionModification = serde_json::from_str(s1).unwrap(); let res2: TransactionModification = serde_json::from_str(s2).unwrap(); // then assert_eq!(res1, TransactionModification { gas_price: Some(U256::from_str("0ba43b7400").unwrap()), }); assert_eq!(res2, TransactionModification { gas_price: None, }); } }
serialize
identifier_name
test_compile.rs
//! Test command for testing the code generator pipeline //! //! The `compile` test command runs each function through the full code generator pipeline use cretonne::binemit; use cretonne::ir; use cretonne; use cretonne::print_errors::pretty_error; use cton_reader::TestCommand; use subtest::{SubTest, Context, Result, run_filecheck}; use std::borrow::Cow; use std::fmt::Write; struct TestCompile; pub fn subtest(parsed: &TestCommand) -> Result<Box<SubTest>> { assert_eq!(parsed.command, "compile"); if!parsed.options.is_empty() { Err(format!("No options allowed on {}", parsed)) } else { Ok(Box::new(TestCompile)) } } impl SubTest for TestCompile { fn name(&self) -> Cow<str> { Cow::from("compile") } fn is_mutating(&self) -> bool { true } fn needs_isa(&self) -> bool { true } fn run(&self, func: Cow<ir::Function>, context: &Context) -> Result<()> { let isa = context.isa.expect("compile needs an ISA"); // Create a compilation context, and drop in the function. let mut comp_ctx = cretonne::Context::new(); comp_ctx.func = func.into_owned(); let code_size = comp_ctx.compile(isa).map_err(|e| { pretty_error(&comp_ctx.func, context.isa, e) })?; dbg!( "Generated {} bytes of code:\n{}", code_size, comp_ctx.func.display(isa) ); // Verify that the returned code size matches the emitted bytes. let mut sink = SizeSink { offset: 0 }; binemit::emit_function( &comp_ctx.func, |func, inst, div, sink| isa.emit_inst(func, inst, div, sink), &mut sink, ); if sink.offset!= code_size { return Err(format!( "Expected code size {}, got {}", code_size, sink.offset )); } // Run final code through filecheck. let mut text = String::new(); write!(&mut text, "{}", &comp_ctx.func.display(Some(isa))) .map_err(|e| e.to_string())?; run_filecheck(&text, context) } } // Code sink that simply counts bytes. struct SizeSink { offset: binemit::CodeOffset, } impl binemit::CodeSink for SizeSink { fn offset(&self) -> binemit::CodeOffset { self.offset } fn put1(&mut self, _: u8) { self.offset += 1; } fn put2(&mut self, _: u16) { self.offset += 2; } fn put4(&mut self, _: u32)
fn put8(&mut self, _: u64) { self.offset += 8; } fn reloc_ebb(&mut self, _reloc: binemit::Reloc, _ebb_offset: binemit::CodeOffset) {} fn reloc_external( &mut self, _reloc: binemit::Reloc, _name: &ir::ExternalName, _addend: binemit::Addend, ) { } fn reloc_jt(&mut self, _reloc: binemit::Reloc, _jt: ir::JumpTable) {} }
{ self.offset += 4; }
identifier_body
test_compile.rs
//! Test command for testing the code generator pipeline //! //! The `compile` test command runs each function through the full code generator pipeline use cretonne::binemit; use cretonne::ir; use cretonne; use cretonne::print_errors::pretty_error; use cton_reader::TestCommand; use subtest::{SubTest, Context, Result, run_filecheck}; use std::borrow::Cow; use std::fmt::Write; struct TestCompile; pub fn subtest(parsed: &TestCommand) -> Result<Box<SubTest>> { assert_eq!(parsed.command, "compile"); if!parsed.options.is_empty()
else { Ok(Box::new(TestCompile)) } } impl SubTest for TestCompile { fn name(&self) -> Cow<str> { Cow::from("compile") } fn is_mutating(&self) -> bool { true } fn needs_isa(&self) -> bool { true } fn run(&self, func: Cow<ir::Function>, context: &Context) -> Result<()> { let isa = context.isa.expect("compile needs an ISA"); // Create a compilation context, and drop in the function. let mut comp_ctx = cretonne::Context::new(); comp_ctx.func = func.into_owned(); let code_size = comp_ctx.compile(isa).map_err(|e| { pretty_error(&comp_ctx.func, context.isa, e) })?; dbg!( "Generated {} bytes of code:\n{}", code_size, comp_ctx.func.display(isa) ); // Verify that the returned code size matches the emitted bytes. let mut sink = SizeSink { offset: 0 }; binemit::emit_function( &comp_ctx.func, |func, inst, div, sink| isa.emit_inst(func, inst, div, sink), &mut sink, ); if sink.offset!= code_size { return Err(format!( "Expected code size {}, got {}", code_size, sink.offset )); } // Run final code through filecheck. let mut text = String::new(); write!(&mut text, "{}", &comp_ctx.func.display(Some(isa))) .map_err(|e| e.to_string())?; run_filecheck(&text, context) } } // Code sink that simply counts bytes. struct SizeSink { offset: binemit::CodeOffset, } impl binemit::CodeSink for SizeSink { fn offset(&self) -> binemit::CodeOffset { self.offset } fn put1(&mut self, _: u8) { self.offset += 1; } fn put2(&mut self, _: u16) { self.offset += 2; } fn put4(&mut self, _: u32) { self.offset += 4; } fn put8(&mut self, _: u64) { self.offset += 8; } fn reloc_ebb(&mut self, _reloc: binemit::Reloc, _ebb_offset: binemit::CodeOffset) {} fn reloc_external( &mut self, _reloc: binemit::Reloc, _name: &ir::ExternalName, _addend: binemit::Addend, ) { } fn reloc_jt(&mut self, _reloc: binemit::Reloc, _jt: ir::JumpTable) {} }
{ Err(format!("No options allowed on {}", parsed)) }
conditional_block
test_compile.rs
//! Test command for testing the code generator pipeline //! //! The `compile` test command runs each function through the full code generator pipeline use cretonne::binemit; use cretonne::ir; use cretonne; use cretonne::print_errors::pretty_error; use cton_reader::TestCommand; use subtest::{SubTest, Context, Result, run_filecheck}; use std::borrow::Cow; use std::fmt::Write; struct TestCompile; pub fn
(parsed: &TestCommand) -> Result<Box<SubTest>> { assert_eq!(parsed.command, "compile"); if!parsed.options.is_empty() { Err(format!("No options allowed on {}", parsed)) } else { Ok(Box::new(TestCompile)) } } impl SubTest for TestCompile { fn name(&self) -> Cow<str> { Cow::from("compile") } fn is_mutating(&self) -> bool { true } fn needs_isa(&self) -> bool { true } fn run(&self, func: Cow<ir::Function>, context: &Context) -> Result<()> { let isa = context.isa.expect("compile needs an ISA"); // Create a compilation context, and drop in the function. let mut comp_ctx = cretonne::Context::new(); comp_ctx.func = func.into_owned(); let code_size = comp_ctx.compile(isa).map_err(|e| { pretty_error(&comp_ctx.func, context.isa, e) })?; dbg!( "Generated {} bytes of code:\n{}", code_size, comp_ctx.func.display(isa) ); // Verify that the returned code size matches the emitted bytes. let mut sink = SizeSink { offset: 0 }; binemit::emit_function( &comp_ctx.func, |func, inst, div, sink| isa.emit_inst(func, inst, div, sink), &mut sink, ); if sink.offset!= code_size { return Err(format!( "Expected code size {}, got {}", code_size, sink.offset )); } // Run final code through filecheck. let mut text = String::new(); write!(&mut text, "{}", &comp_ctx.func.display(Some(isa))) .map_err(|e| e.to_string())?; run_filecheck(&text, context) } } // Code sink that simply counts bytes. struct SizeSink { offset: binemit::CodeOffset, } impl binemit::CodeSink for SizeSink { fn offset(&self) -> binemit::CodeOffset { self.offset } fn put1(&mut self, _: u8) { self.offset += 1; } fn put2(&mut self, _: u16) { self.offset += 2; } fn put4(&mut self, _: u32) { self.offset += 4; } fn put8(&mut self, _: u64) { self.offset += 8; } fn reloc_ebb(&mut self, _reloc: binemit::Reloc, _ebb_offset: binemit::CodeOffset) {} fn reloc_external( &mut self, _reloc: binemit::Reloc, _name: &ir::ExternalName, _addend: binemit::Addend, ) { } fn reloc_jt(&mut self, _reloc: binemit::Reloc, _jt: ir::JumpTable) {} }
subtest
identifier_name
test_compile.rs
//! Test command for testing the code generator pipeline //! //! The `compile` test command runs each function through the full code generator pipeline use cretonne::binemit; use cretonne::ir; use cretonne; use cretonne::print_errors::pretty_error; use cton_reader::TestCommand; use subtest::{SubTest, Context, Result, run_filecheck}; use std::borrow::Cow; use std::fmt::Write; struct TestCompile; pub fn subtest(parsed: &TestCommand) -> Result<Box<SubTest>> { assert_eq!(parsed.command, "compile"); if!parsed.options.is_empty() { Err(format!("No options allowed on {}", parsed)) } else { Ok(Box::new(TestCompile)) } } impl SubTest for TestCompile { fn name(&self) -> Cow<str> { Cow::from("compile") } fn is_mutating(&self) -> bool { true } fn needs_isa(&self) -> bool { true } fn run(&self, func: Cow<ir::Function>, context: &Context) -> Result<()> { let isa = context.isa.expect("compile needs an ISA"); // Create a compilation context, and drop in the function. let mut comp_ctx = cretonne::Context::new(); comp_ctx.func = func.into_owned(); let code_size = comp_ctx.compile(isa).map_err(|e| { pretty_error(&comp_ctx.func, context.isa, e) })?; dbg!( "Generated {} bytes of code:\n{}", code_size, comp_ctx.func.display(isa) ); // Verify that the returned code size matches the emitted bytes. let mut sink = SizeSink { offset: 0 }; binemit::emit_function( &comp_ctx.func, |func, inst, div, sink| isa.emit_inst(func, inst, div, sink), &mut sink, );
"Expected code size {}, got {}", code_size, sink.offset )); } // Run final code through filecheck. let mut text = String::new(); write!(&mut text, "{}", &comp_ctx.func.display(Some(isa))) .map_err(|e| e.to_string())?; run_filecheck(&text, context) } } // Code sink that simply counts bytes. struct SizeSink { offset: binemit::CodeOffset, } impl binemit::CodeSink for SizeSink { fn offset(&self) -> binemit::CodeOffset { self.offset } fn put1(&mut self, _: u8) { self.offset += 1; } fn put2(&mut self, _: u16) { self.offset += 2; } fn put4(&mut self, _: u32) { self.offset += 4; } fn put8(&mut self, _: u64) { self.offset += 8; } fn reloc_ebb(&mut self, _reloc: binemit::Reloc, _ebb_offset: binemit::CodeOffset) {} fn reloc_external( &mut self, _reloc: binemit::Reloc, _name: &ir::ExternalName, _addend: binemit::Addend, ) { } fn reloc_jt(&mut self, _reloc: binemit::Reloc, _jt: ir::JumpTable) {} }
if sink.offset != code_size { return Err(format!(
random_line_split
fragment_buffer.rs
use crate::{buffer::Settings, Cell}; pub use direction::Direction; pub use fragment::Fragment; pub use fragment_tree::FragmentTree; use itertools::Itertools; use std::{ collections::BTreeMap, ops::{Deref, DerefMut}, }; pub mod direction; pub mod fragment; mod fragment_tree; /// Fragment buffer contains the drawing fragments for each cell /// Svg can be converted to fragment buffer /// then from the fragment we can match which characters is best suited for /// a particular set of fragment contained in a cell and then create a stringbuffer. /// The stringbuffer becomes the ascii diagrams /// SVG -> FragmentBuffer -> StringBuffer -> Ascii Diagrams /// /// We can also create a reverse /// Ascii Diagrams -> String Buffer -> Fragment Buffer -> SVG /// /// ```ignore /// 0 1 2 3 4 B C D /// 0β”Œβ”€β”¬β”€β”¬β”€β”¬β”€β” Aβ”Œβ”€β”¬β”€β”¬β”€β”¬β”€β”E /// 1β”œβ”€β”Όβ”€β”Όβ”€β”Όβ”€β”€ β”‚ β”‚ β”‚ β”‚ β”‚ /// 2β”œβ”€β”Όβ”€β”Όβ”€β”Όβ”€β”€ Fβ”œβ”€G─H─I──J /// 3β”œβ”€β”Όβ”€β”Όβ”€β”Όβ”€β”€ β”‚ β”‚ β”‚ β”‚ β”‚ /// 4β”œβ”€β”Όβ”€β”Όβ”€β”Όβ”€β”€ Kβ”œβ”€L─M─N──O /// 5β”œβ”€β”Όβ”€β”Όβ”€β”Όβ”€β”€ β”‚ β”‚ β”‚ β”‚ β”‚ /// 6β”œβ”€β”Όβ”€β”Όβ”€β”Όβ”€β”€ Pβ”œβ”€Q─R─S──T /// 7β”œβ”€β”Όβ”€β”Όβ”€β”Όβ”€β”€ β”‚ β”‚ β”‚ β”‚ β”‚ /// 8β””β”€β”΄β”€β”΄β”€β”΄β”€β”˜ Uβ””β”€β”΄β”€β”΄β”€β”΄β”€β”˜Y /// ``` V W X #[derive(Debug)] pub struct FragmentBuffer(BTreeMap<Cell, Vec<Fragment>>); impl Deref for FragmentBuffer { type Target = BTreeMap<Cell, Vec<Fragment>>; fn deref(&self) -> &Self::Target { &self.0 } } impl DerefMut for FragmentBuffer { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl FragmentBuffer { pub fn new() -> Self { FragmentBuffer(BTreeMap::new()) } /// dump for debugging purpose only /// printling the fragments on this fragment buffer pub fn dump(&self) -> String { let mut
for (cell, shapes) in self.iter() { buff.push_str(&format!("\ncell: {} ", cell)); for shape in shapes { buff.push_str(&format!("\n {}", shape)); } } buff } /// Add a single fragment to this cell pub fn add_fragment_to_cell(&mut self, cell: Cell, fragment: Fragment) { if let Some(existing) = self.get_mut(&cell) { existing.push(fragment); } else { self.insert(cell, vec![fragment]); } self.sort_fragments_in_cell(cell); } /// sort the fragments content in this cell fn sort_fragments_in_cell(&mut self, cell: Cell) { if let Some(fragments) = &mut self.get_mut(&cell) { (*fragments).sort(); } } fn bounds(&self) -> Option<(Cell, Cell)> { let xlimits = self.iter().map(|(cell, _)| cell.x).minmax().into_option(); let ylimits = self.iter().map(|(cell, _)| cell.y).minmax().into_option(); match (xlimits, ylimits) { (Some((min_x, max_x)), Some((min_y, max_y))) => { Some((Cell::new(min_x, min_y), Cell::new(max_x, max_y))) } _ => None, } } pub(crate) fn get_size(&self, settings: &Settings) -> (f32, f32) { let (top_left, bottom_right) = self.bounds().unwrap_or((Cell::new(0, 0), Cell::new(0, 0))); let w = settings.scale * (bottom_right.x + 2) as f32 * Cell::width(); let h = settings.scale * (bottom_right.y + 2) as f32 * Cell::height(); (w, h) } /// add multiple fragments to cell pub fn add_fragments_to_cell(&mut self, cell: Cell, fragments: Vec<Fragment>) { if let Some(existing) = self.get_mut(&cell) { existing.extend(fragments); } else { self.insert(cell, fragments); } self.sort_fragments_in_cell(cell); } pub(crate) fn merge_fragments(&self) -> Vec<Fragment> { let fragments = self.first_pass_merge(); Self::merge_recursive(fragments) } /// merge fragments that can be merged. /// This is only merging the fragments that are in the same /// cell fn first_pass_merge(&self) -> Vec<Fragment> { let mut merged: Vec<Fragment> = vec![]; for (cell, fragments) in self.iter() { for frag in fragments.iter() { //Note: The fragments are calculated with their absolute // parameters and is derived from the cell position let abs_frag = frag.absolute_position(*cell); let had_merged = merged.iter_mut().rev().any(|mfrag| { if mfrag.can_merge(&abs_frag) { if let Some(new_merge) = mfrag.merge(&abs_frag) { *mfrag = new_merge; } else { panic!("Should merged"); } true } else { false } }); if!had_merged { merged.push(abs_frag); } } } merged } fn merge_recursive(fragments: Vec<Fragment>) -> Vec<Fragment> { let original_len = fragments.len(); let merged = Self::second_pass_merge(fragments); if merged.len() < original_len { Self::merge_recursive(merged) } else { merged } } fn second_pass_merge(fragments: Vec<Fragment>) -> Vec<Fragment> { let mut new_fragments: Vec<Fragment> = vec![]; for fragment in fragments.into_iter() { let is_merged = new_fragments.iter_mut().rev().any(|new_frag| { if new_frag.can_merge(&fragment) { *new_frag = new_frag.merge(&fragment).expect("should merge"); true } else { false } }); if!is_merged { new_fragments.push(fragment); } } new_fragments } }
buff = String::new();
identifier_body
fragment_buffer.rs
use crate::{buffer::Settings, Cell}; pub use direction::Direction; pub use fragment::Fragment; pub use fragment_tree::FragmentTree; use itertools::Itertools; use std::{ collections::BTreeMap, ops::{Deref, DerefMut}, }; pub mod direction; pub mod fragment; mod fragment_tree; /// Fragment buffer contains the drawing fragments for each cell /// Svg can be converted to fragment buffer /// then from the fragment we can match which characters is best suited for /// a particular set of fragment contained in a cell and then create a stringbuffer. /// The stringbuffer becomes the ascii diagrams /// SVG -> FragmentBuffer -> StringBuffer -> Ascii Diagrams /// /// We can also create a reverse /// Ascii Diagrams -> String Buffer -> Fragment Buffer -> SVG /// /// ```ignore /// 0 1 2 3 4 B C D /// 0β”Œβ”€β”¬β”€β”¬β”€β”¬β”€β” Aβ”Œβ”€β”¬β”€β”¬β”€β”¬β”€β”E /// 1β”œβ”€β”Όβ”€β”Όβ”€β”Όβ”€β”€ β”‚ β”‚ β”‚ β”‚ β”‚ /// 2β”œβ”€β”Όβ”€β”Όβ”€β”Όβ”€β”€ Fβ”œβ”€G─H─I──J /// 3β”œβ”€β”Όβ”€β”Όβ”€β”Όβ”€β”€ β”‚ β”‚ β”‚ β”‚ β”‚ /// 4β”œβ”€β”Όβ”€β”Όβ”€β”Όβ”€β”€ Kβ”œβ”€L─M─N──O /// 5β”œβ”€β”Όβ”€β”Όβ”€β”Όβ”€β”€ β”‚ β”‚ β”‚ β”‚ β”‚ /// 6β”œβ”€β”Όβ”€β”Όβ”€β”Όβ”€β”€ Pβ”œβ”€Q─R─S──T /// 7β”œβ”€β”Όβ”€β”Όβ”€β”Όβ”€β”€ β”‚ β”‚ β”‚ β”‚ β”‚ /// 8β””β”€β”΄β”€β”΄β”€β”΄β”€β”˜ Uβ””β”€β”΄β”€β”΄β”€β”΄β”€β”˜Y /// ``` V W X #[derive(Debug)] pub struct FragmentBuffer(BTreeMap<Cell, Vec<Fragment>>); impl Deref for FragmentBuffer { type Target = BTreeMap<Cell, Vec<Fragment>>; fn deref(&self) -> &Self::Target { &self.0 } } impl DerefMut for FragmentBuffer { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl FragmentBuffer { pub fn new() -> Self { FragmentBuffer(BTreeMap::new()) } /// dump for debugging purpose only /// printling the fragments on this fragment buffer pub fn dump(&self) -> String { let mut buff = String::new(); for (cell, shapes) in self.iter() { buff.push_str(&format!("\ncell: {} ", cell)); for shape in shapes { buff.push_str(&format!("\n {}", shape)); } } buff } /// Add a single fragment to this cell pub fn add_fragment_to_cell(&mut self, cell: Cell, fragment: Fragment) { if let Some(existing) = self.get_mut(&cell) { existing.push(fragment); } else { self.insert(cell, vec![fragment]); } self.sort_fragments_in_cell(cell); } /// sort the fragments content in this cell fn sort_fragments_in_cell(&mut self, cell: Cell) { if let Some(fragments) = &mut self.get_mut(&cell) { (*fragments).sort(); } } fn bounds(&self) -> Option<(Cell, Cell)> { let xlimits = self.iter().map(|(cell, _)| cell.x).minmax().into_option(); let ylimits = self.iter().map(|(cell, _)| cell.y).minmax().into_option(); match (xlimits, ylimits) { (Some((min_x, max_x)), Some((min_y, max_y))) => { Some((Cell::new(min_x, min_y), Cell::new(max_x, max_y))) } _ => None, } } pub(crate) fn get_size(&self, settings: &Settings) -> (f32, f32) { let (top_left, bottom_right) = self.bounds().unwrap_or((Cell::new(0, 0), Cell::new(0, 0))); let w = settings.scale * (bottom_right.x + 2) as f32 * Cell::width(); let h = settings.scale * (bottom_right.y + 2) as f32 * Cell::height(); (w, h) } /// add multiple fragments to cell pub fn add_fragments_to_cell(&mut self, cell: Cell, fragments: Vec<Fragment>) { if let Some(existing) = self.get_mut(&cell) { existing.extend(fragments); } else { self.insert(cell, fragments); } self.sort_fragments_in_cell(cell); } pub(crate) fn merge_fragments(&self) -> Vec<Fragment> { let fragments = self.first_pass_merge(); Self::merge_recursive(fragments) } /// merge fragments that can be merged. /// This is only merging the fragments that are in the same /// cell fn first_pass_merge(&self) -> Vec<Fragment> { let mut merged: Vec<Fragment> = vec![]; for (cell, fragments) in self.iter() { for frag in fragments.iter() { //Note: The fragments are calculated with their absolute // parameters and is derived from the cell position let abs_frag = frag.absolute_position(*cell); let had_merged = merged.iter_mut().rev().any(|mfrag| { if mfrag.can_merge(&abs_frag) { if let Some(new_merge) = mfrag.merge(&abs_frag) { *mfrag = new_merge; } else { panic!("Should merged"); } true } else { false } }); if!had_merged { merged.push(abs_frag); } } } merged } fn merge_recursive(fragments: Vec<Fragment>) -> Vec<Fragment> { let original_len = fragments.len(); let merged = Self::second_pass_merge(fragments); if merged.len() < original_len { Self::merge_recursive(merged) } else { merged } } fn second_pass_merge(fragments: Vec<Fragment>) -> Vec<Fragment> { let mut new_fragments: Vec<Fragment> = vec![]; for fragment in fragments.into_iter() { let is_merged = new_fragments.iter_mut().rev().any(|new_frag| { if new_frag.can_
{ *new_frag = new_frag.merge(&fragment).expect("should merge"); true } else { false } }); if!is_merged { new_fragments.push(fragment); } } new_fragments } }
merge(&fragment)
identifier_name
fragment_buffer.rs
use crate::{buffer::Settings, Cell}; pub use direction::Direction; pub use fragment::Fragment; pub use fragment_tree::FragmentTree; use itertools::Itertools; use std::{ collections::BTreeMap, ops::{Deref, DerefMut}, }; pub mod direction; pub mod fragment; mod fragment_tree; /// Fragment buffer contains the drawing fragments for each cell /// Svg can be converted to fragment buffer /// then from the fragment we can match which characters is best suited for /// a particular set of fragment contained in a cell and then create a stringbuffer. /// The stringbuffer becomes the ascii diagrams /// SVG -> FragmentBuffer -> StringBuffer -> Ascii Diagrams /// /// We can also create a reverse /// Ascii Diagrams -> String Buffer -> Fragment Buffer -> SVG /// /// ```ignore /// 0 1 2 3 4 B C D /// 0β”Œβ”€β”¬β”€β”¬β”€β”¬β”€β” Aβ”Œβ”€β”¬β”€β”¬β”€β”¬β”€β”E /// 1β”œβ”€β”Όβ”€β”Όβ”€β”Όβ”€β”€ β”‚ β”‚ β”‚ β”‚ β”‚ /// 2β”œβ”€β”Όβ”€β”Όβ”€β”Όβ”€β”€ Fβ”œβ”€G─H─I──J /// 3β”œβ”€β”Όβ”€β”Όβ”€β”Όβ”€β”€ β”‚ β”‚ β”‚ β”‚ β”‚ /// 4β”œβ”€β”Όβ”€β”Όβ”€β”Όβ”€β”€ Kβ”œβ”€L─M─N──O
/// 5β”œβ”€β”Όβ”€β”Όβ”€β”Όβ”€β”€ β”‚ β”‚ β”‚ β”‚ β”‚ /// 6β”œβ”€β”Όβ”€β”Όβ”€β”Όβ”€β”€ Pβ”œβ”€Q─R─S──T /// 7β”œβ”€β”Όβ”€β”Όβ”€β”Όβ”€β”€ β”‚ β”‚ β”‚ β”‚ β”‚ /// 8β””β”€β”΄β”€β”΄β”€β”΄β”€β”˜ Uβ””β”€β”΄β”€β”΄β”€β”΄β”€β”˜Y /// ``` V W X #[derive(Debug)] pub struct FragmentBuffer(BTreeMap<Cell, Vec<Fragment>>); impl Deref for FragmentBuffer { type Target = BTreeMap<Cell, Vec<Fragment>>; fn deref(&self) -> &Self::Target { &self.0 } } impl DerefMut for FragmentBuffer { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl FragmentBuffer { pub fn new() -> Self { FragmentBuffer(BTreeMap::new()) } /// dump for debugging purpose only /// printling the fragments on this fragment buffer pub fn dump(&self) -> String { let mut buff = String::new(); for (cell, shapes) in self.iter() { buff.push_str(&format!("\ncell: {} ", cell)); for shape in shapes { buff.push_str(&format!("\n {}", shape)); } } buff } /// Add a single fragment to this cell pub fn add_fragment_to_cell(&mut self, cell: Cell, fragment: Fragment) { if let Some(existing) = self.get_mut(&cell) { existing.push(fragment); } else { self.insert(cell, vec![fragment]); } self.sort_fragments_in_cell(cell); } /// sort the fragments content in this cell fn sort_fragments_in_cell(&mut self, cell: Cell) { if let Some(fragments) = &mut self.get_mut(&cell) { (*fragments).sort(); } } fn bounds(&self) -> Option<(Cell, Cell)> { let xlimits = self.iter().map(|(cell, _)| cell.x).minmax().into_option(); let ylimits = self.iter().map(|(cell, _)| cell.y).minmax().into_option(); match (xlimits, ylimits) { (Some((min_x, max_x)), Some((min_y, max_y))) => { Some((Cell::new(min_x, min_y), Cell::new(max_x, max_y))) } _ => None, } } pub(crate) fn get_size(&self, settings: &Settings) -> (f32, f32) { let (top_left, bottom_right) = self.bounds().unwrap_or((Cell::new(0, 0), Cell::new(0, 0))); let w = settings.scale * (bottom_right.x + 2) as f32 * Cell::width(); let h = settings.scale * (bottom_right.y + 2) as f32 * Cell::height(); (w, h) } /// add multiple fragments to cell pub fn add_fragments_to_cell(&mut self, cell: Cell, fragments: Vec<Fragment>) { if let Some(existing) = self.get_mut(&cell) { existing.extend(fragments); } else { self.insert(cell, fragments); } self.sort_fragments_in_cell(cell); } pub(crate) fn merge_fragments(&self) -> Vec<Fragment> { let fragments = self.first_pass_merge(); Self::merge_recursive(fragments) } /// merge fragments that can be merged. /// This is only merging the fragments that are in the same /// cell fn first_pass_merge(&self) -> Vec<Fragment> { let mut merged: Vec<Fragment> = vec![]; for (cell, fragments) in self.iter() { for frag in fragments.iter() { //Note: The fragments are calculated with their absolute // parameters and is derived from the cell position let abs_frag = frag.absolute_position(*cell); let had_merged = merged.iter_mut().rev().any(|mfrag| { if mfrag.can_merge(&abs_frag) { if let Some(new_merge) = mfrag.merge(&abs_frag) { *mfrag = new_merge; } else { panic!("Should merged"); } true } else { false } }); if!had_merged { merged.push(abs_frag); } } } merged } fn merge_recursive(fragments: Vec<Fragment>) -> Vec<Fragment> { let original_len = fragments.len(); let merged = Self::second_pass_merge(fragments); if merged.len() < original_len { Self::merge_recursive(merged) } else { merged } } fn second_pass_merge(fragments: Vec<Fragment>) -> Vec<Fragment> { let mut new_fragments: Vec<Fragment> = vec![]; for fragment in fragments.into_iter() { let is_merged = new_fragments.iter_mut().rev().any(|new_frag| { if new_frag.can_merge(&fragment) { *new_frag = new_frag.merge(&fragment).expect("should merge"); true } else { false } }); if!is_merged { new_fragments.push(fragment); } } new_fragments } }
random_line_split
fragment_buffer.rs
use crate::{buffer::Settings, Cell}; pub use direction::Direction; pub use fragment::Fragment; pub use fragment_tree::FragmentTree; use itertools::Itertools; use std::{ collections::BTreeMap, ops::{Deref, DerefMut}, }; pub mod direction; pub mod fragment; mod fragment_tree; /// Fragment buffer contains the drawing fragments for each cell /// Svg can be converted to fragment buffer /// then from the fragment we can match which characters is best suited for /// a particular set of fragment contained in a cell and then create a stringbuffer. /// The stringbuffer becomes the ascii diagrams /// SVG -> FragmentBuffer -> StringBuffer -> Ascii Diagrams /// /// We can also create a reverse /// Ascii Diagrams -> String Buffer -> Fragment Buffer -> SVG /// /// ```ignore /// 0 1 2 3 4 B C D /// 0β”Œβ”€β”¬β”€β”¬β”€β”¬β”€β” Aβ”Œβ”€β”¬β”€β”¬β”€β”¬β”€β”E /// 1β”œβ”€β”Όβ”€β”Όβ”€β”Όβ”€β”€ β”‚ β”‚ β”‚ β”‚ β”‚ /// 2β”œβ”€β”Όβ”€β”Όβ”€β”Όβ”€β”€ Fβ”œβ”€G─H─I──J /// 3β”œβ”€β”Όβ”€β”Όβ”€β”Όβ”€β”€ β”‚ β”‚ β”‚ β”‚ β”‚ /// 4β”œβ”€β”Όβ”€β”Όβ”€β”Όβ”€β”€ Kβ”œβ”€L─M─N──O /// 5β”œβ”€β”Όβ”€β”Όβ”€β”Όβ”€β”€ β”‚ β”‚ β”‚ β”‚ β”‚ /// 6β”œβ”€β”Όβ”€β”Όβ”€β”Όβ”€β”€ Pβ”œβ”€Q─R─S──T /// 7β”œβ”€β”Όβ”€β”Όβ”€β”Όβ”€β”€ β”‚ β”‚ β”‚ β”‚ β”‚ /// 8β””β”€β”΄β”€β”΄β”€β”΄β”€β”˜ Uβ””β”€β”΄β”€β”΄β”€β”΄β”€β”˜Y /// ``` V W X #[derive(Debug)] pub struct FragmentBuffer(BTreeMap<Cell, Vec<Fragment>>); impl Deref for FragmentBuffer { type Target = BTreeMap<Cell, Vec<Fragment>>; fn deref(&self) -> &Self::Target { &self.0 } } impl DerefMut for FragmentBuffer { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl FragmentBuffer { pub fn new() -> Self { FragmentBuffer(BTreeMap::new()) } /// dump for debugging purpose only /// printling the fragments on this fragment buffer pub fn dump(&self) -> String { let mut buff = String::new(); for (cell, shapes) in self.iter() { buff.push_str(&format!("\ncell: {} ", cell)); for shape in shapes { buff.push_str(&format!("\n {}", shape)); } } buff } /// Add a single fragment to this cell pub fn add_fragment_to_cell(&mut self, cell: Cell, fragment: Fragment) { if let Some(existing) = self.get_mut(&cell) { existing.push(fragment); } else { self.insert(cell, vec![fragment]); } self.sort_fragments_in_cell(cell); } /// sort the fragments content in this cell fn sort_fragments_in_cell(&mut self, cell: Cell) { if let Some(fragments) = &mut self.get_mut(&cell) {
nds(&self) -> Option<(Cell, Cell)> { let xlimits = self.iter().map(|(cell, _)| cell.x).minmax().into_option(); let ylimits = self.iter().map(|(cell, _)| cell.y).minmax().into_option(); match (xlimits, ylimits) { (Some((min_x, max_x)), Some((min_y, max_y))) => { Some((Cell::new(min_x, min_y), Cell::new(max_x, max_y))) } _ => None, } } pub(crate) fn get_size(&self, settings: &Settings) -> (f32, f32) { let (top_left, bottom_right) = self.bounds().unwrap_or((Cell::new(0, 0), Cell::new(0, 0))); let w = settings.scale * (bottom_right.x + 2) as f32 * Cell::width(); let h = settings.scale * (bottom_right.y + 2) as f32 * Cell::height(); (w, h) } /// add multiple fragments to cell pub fn add_fragments_to_cell(&mut self, cell: Cell, fragments: Vec<Fragment>) { if let Some(existing) = self.get_mut(&cell) { existing.extend(fragments); } else { self.insert(cell, fragments); } self.sort_fragments_in_cell(cell); } pub(crate) fn merge_fragments(&self) -> Vec<Fragment> { let fragments = self.first_pass_merge(); Self::merge_recursive(fragments) } /// merge fragments that can be merged. /// This is only merging the fragments that are in the same /// cell fn first_pass_merge(&self) -> Vec<Fragment> { let mut merged: Vec<Fragment> = vec![]; for (cell, fragments) in self.iter() { for frag in fragments.iter() { //Note: The fragments are calculated with their absolute // parameters and is derived from the cell position let abs_frag = frag.absolute_position(*cell); let had_merged = merged.iter_mut().rev().any(|mfrag| { if mfrag.can_merge(&abs_frag) { if let Some(new_merge) = mfrag.merge(&abs_frag) { *mfrag = new_merge; } else { panic!("Should merged"); } true } else { false } }); if!had_merged { merged.push(abs_frag); } } } merged } fn merge_recursive(fragments: Vec<Fragment>) -> Vec<Fragment> { let original_len = fragments.len(); let merged = Self::second_pass_merge(fragments); if merged.len() < original_len { Self::merge_recursive(merged) } else { merged } } fn second_pass_merge(fragments: Vec<Fragment>) -> Vec<Fragment> { let mut new_fragments: Vec<Fragment> = vec![]; for fragment in fragments.into_iter() { let is_merged = new_fragments.iter_mut().rev().any(|new_frag| { if new_frag.can_merge(&fragment) { *new_frag = new_frag.merge(&fragment).expect("should merge"); true } else { false } }); if!is_merged { new_fragments.push(fragment); } } new_fragments } }
(*fragments).sort(); } } fn bou
conditional_block
expr-if-box.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[feature(managed_boxes)]; // Tests for if as expressions returning boxed types fn test_box() { let rs = if true { @100 } else { @101 }; assert_eq!(*rs, 100); } fn test_str() { let rs = if true { ~"happy" } else
; assert_eq!(rs, ~"happy"); } pub fn main() { test_box(); test_str(); }
{ ~"sad" }
conditional_block
expr-if-box.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[feature(managed_boxes)];
let rs = if true { @100 } else { @101 }; assert_eq!(*rs, 100); } fn test_str() { let rs = if true { ~"happy" } else { ~"sad" }; assert_eq!(rs, ~"happy"); } pub fn main() { test_box(); test_str(); }
// Tests for if as expressions returning boxed types fn test_box() {
random_line_split
expr-if-box.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[feature(managed_boxes)]; // Tests for if as expressions returning boxed types fn test_box() { let rs = if true { @100 } else { @101 }; assert_eq!(*rs, 100); } fn
() { let rs = if true { ~"happy" } else { ~"sad" }; assert_eq!(rs, ~"happy"); } pub fn main() { test_box(); test_str(); }
test_str
identifier_name
expr-if-box.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[feature(managed_boxes)]; // Tests for if as expressions returning boxed types fn test_box()
fn test_str() { let rs = if true { ~"happy" } else { ~"sad" }; assert_eq!(rs, ~"happy"); } pub fn main() { test_box(); test_str(); }
{ let rs = if true { @100 } else { @101 }; assert_eq!(*rs, 100); }
identifier_body
writer.rs
use interface::fill::fill; use klv::klv::*; use klv::ul::*; use klv::value::*; use klv::value::element::Element; use klv::value::value_data::*; use klv::value::partition::PartitionStatus::*; use std::io::prelude::*; use std::io::Cursor; use serializer::encoder::*; #[derive(Debug, Copy, Clone)] #[repr(C)] pub enum Codec { Jpeg2000, AvcIntra, ProRes, } #[derive(Debug, Copy, Clone)] #[repr(C)] pub enum Wrapping { Frame, Clip, } #[derive(Debug, Clone)] pub struct Stream { pub codec: Codec, pub wrapping: Wrapping } #[derive(Debug, Clone)] pub struct Properties { pub kag_size: Option<u32>, pub streams: Vec<Stream>, } #[derive(Clone)] #[repr(C)] pub struct Writer { pub properties: *mut (), pub handle: *mut (), pub write: extern fn(*mut(), *mut u8, u64) -> bool } impl Writer { pub fn new(handle: *mut(), write: extern fn(*mut(), *mut u8, u64) -> bool) -> Writer { let properties = Properties { kag_size: None, streams: vec![] }; let box_properties = Box::new(properties); let handle_properties = Box::into_raw(box_properties) as *mut _; Writer { properties: handle_properties, handle: handle, write: write, } } pub fn
(&mut self, codec: Codec, wrapping: Wrapping) { let mut properties : Box<Properties> = unsafe{ Box::from_raw(self.properties as *mut Properties) }; properties.streams.push(Stream{ codec: codec, wrapping: wrapping }); self.properties = Box::into_raw(properties) as *mut _; } pub fn dump_header(&mut self) { let properties : Box<Properties> = unsafe{ Box::from_raw(self.properties as *mut Properties) }; let header_klv = Klv { key: Ul::HeaderPartition { status: ClosedAndComplete }, value: Value { elements: vec![ build_element!(Ul::PartitionMajor, uint16 => 1), build_element!(Ul::PartitionMinor, uint16 => 3), build_element!(Ul::PartitionKagSize, uint32 => 512), build_element!(Ul::PartitionThisPartition, uint64 => 0), build_element!(Ul::PartitionPreviousPartition, uint64 => 0), build_element!(Ul::PartitionFooterPartition, uint64 => 131611136), build_element!(Ul::PartitionHeaderByteCount, uint64 => 5120), build_element!(Ul::PartitionIndexByteCount, uint64 => 0), build_element!(Ul::PartitionIndexSid, uint32 => 0), build_element!(Ul::PartitionBodyOffset, uint64 => 0), build_element!(Ul::PartitionBodySid, uint32 => 1), build_element!(Ul::PartitionOperationalPattern, ul => Ul::MxfOP1aSingleItemSinglePackageUniTrackStreamInternal), build_element!(Ul::PartitionEssenceContainers, array_ul => vec![Ul::Essence_Jpeg2000_FrameWrapped]), ] } }; let mut stream = Cursor::new(vec![0; 0]); stream.write(Encoder::serialise(&header_klv).as_ref()).unwrap(); let data = stream.get_mut(); (self.write)(self.handle, data.as_mut_ptr(), data.len() as u64); match properties.kag_size { Some(kag_size) => { fill(&self, data.len(), kag_size as usize); }, None => {}, } let primer_pack_klv = Klv { key: Ul::PrimerPack, value: Value { elements: vec![ build_element!(Ul::Unknown, uint32 => 0), build_element!(Ul::Unknown, uint32 => 18), ] } }; let mut stream = Cursor::new(vec![0; 0]); stream.write(Encoder::serialise(&primer_pack_klv).as_ref()).unwrap(); let data = stream.get_mut(); (self.write)(self.handle, data.as_mut_ptr(), data.len() as u64); self.properties = Box::into_raw(properties) as *mut _; } pub fn wrap(&mut self, data: &Vec<u8>, stream_id: u8) -> bool { let properties : Box<Properties> = unsafe{ Box::from_raw(self.properties as *mut Properties) }; if stream_id as usize >= properties.streams.len() { return false } { let ref stream_properties = &properties.streams[stream_id as usize]; let ul = match (stream_properties.codec, stream_properties.wrapping) { (Codec::Jpeg2000, Wrapping::Frame) => Ul::Jpeg2000FrameWrapped, (Codec::Jpeg2000, Wrapping::Clip) => Ul::Jpeg2000ClipWrapped, (_, _) => unimplemented!(), }; let header_klv = Klv { key: ul, value: Value { elements: vec![ build_element!(Ul::Unknown, unknown => data.to_vec()) ] } }; let mut stream = Cursor::new(vec![0; 0]); stream.write(Encoder::serialise(&header_klv).as_ref()).unwrap(); let data = stream.get_mut(); (self.write)(self.handle, data.as_mut_ptr(), data.len() as u64); } self.properties = Box::into_raw(properties) as *mut _; true } } #[no_mangle] pub extern fn new_writer(handle: *mut(), writer: extern fn(*mut(), *mut u8, u64) -> bool) -> Writer { Writer::new(handle, writer) } #[no_mangle] pub extern fn add_stream(mut writer: Writer, codec: Codec, wrapping: Wrapping) { writer.add_stream(codec, wrapping); } #[no_mangle] pub extern fn dump_header(mut writer: Writer) { writer.dump_header(); } #[no_mangle] pub extern fn wrap(mut writer: Writer, data: *mut u8, size: usize, stream_id: u8) -> bool { unsafe { let mut some_data = Vec::from_raw_parts(data, size, size); writer.wrap(&mut some_data, stream_id) } }
add_stream
identifier_name
writer.rs
use klv::value::element::Element; use klv::value::value_data::*; use klv::value::partition::PartitionStatus::*; use std::io::prelude::*; use std::io::Cursor; use serializer::encoder::*; #[derive(Debug, Copy, Clone)] #[repr(C)] pub enum Codec { Jpeg2000, AvcIntra, ProRes, } #[derive(Debug, Copy, Clone)] #[repr(C)] pub enum Wrapping { Frame, Clip, } #[derive(Debug, Clone)] pub struct Stream { pub codec: Codec, pub wrapping: Wrapping } #[derive(Debug, Clone)] pub struct Properties { pub kag_size: Option<u32>, pub streams: Vec<Stream>, } #[derive(Clone)] #[repr(C)] pub struct Writer { pub properties: *mut (), pub handle: *mut (), pub write: extern fn(*mut(), *mut u8, u64) -> bool } impl Writer { pub fn new(handle: *mut(), write: extern fn(*mut(), *mut u8, u64) -> bool) -> Writer { let properties = Properties { kag_size: None, streams: vec![] }; let box_properties = Box::new(properties); let handle_properties = Box::into_raw(box_properties) as *mut _; Writer { properties: handle_properties, handle: handle, write: write, } } pub fn add_stream(&mut self, codec: Codec, wrapping: Wrapping) { let mut properties : Box<Properties> = unsafe{ Box::from_raw(self.properties as *mut Properties) }; properties.streams.push(Stream{ codec: codec, wrapping: wrapping }); self.properties = Box::into_raw(properties) as *mut _; } pub fn dump_header(&mut self) { let properties : Box<Properties> = unsafe{ Box::from_raw(self.properties as *mut Properties) }; let header_klv = Klv { key: Ul::HeaderPartition { status: ClosedAndComplete }, value: Value { elements: vec![ build_element!(Ul::PartitionMajor, uint16 => 1), build_element!(Ul::PartitionMinor, uint16 => 3), build_element!(Ul::PartitionKagSize, uint32 => 512), build_element!(Ul::PartitionThisPartition, uint64 => 0), build_element!(Ul::PartitionPreviousPartition, uint64 => 0), build_element!(Ul::PartitionFooterPartition, uint64 => 131611136), build_element!(Ul::PartitionHeaderByteCount, uint64 => 5120), build_element!(Ul::PartitionIndexByteCount, uint64 => 0), build_element!(Ul::PartitionIndexSid, uint32 => 0), build_element!(Ul::PartitionBodyOffset, uint64 => 0), build_element!(Ul::PartitionBodySid, uint32 => 1), build_element!(Ul::PartitionOperationalPattern, ul => Ul::MxfOP1aSingleItemSinglePackageUniTrackStreamInternal), build_element!(Ul::PartitionEssenceContainers, array_ul => vec![Ul::Essence_Jpeg2000_FrameWrapped]), ] } }; let mut stream = Cursor::new(vec![0; 0]); stream.write(Encoder::serialise(&header_klv).as_ref()).unwrap(); let data = stream.get_mut(); (self.write)(self.handle, data.as_mut_ptr(), data.len() as u64); match properties.kag_size { Some(kag_size) => { fill(&self, data.len(), kag_size as usize); }, None => {}, } let primer_pack_klv = Klv { key: Ul::PrimerPack, value: Value { elements: vec![ build_element!(Ul::Unknown, uint32 => 0), build_element!(Ul::Unknown, uint32 => 18), ] } }; let mut stream = Cursor::new(vec![0; 0]); stream.write(Encoder::serialise(&primer_pack_klv).as_ref()).unwrap(); let data = stream.get_mut(); (self.write)(self.handle, data.as_mut_ptr(), data.len() as u64); self.properties = Box::into_raw(properties) as *mut _; } pub fn wrap(&mut self, data: &Vec<u8>, stream_id: u8) -> bool { let properties : Box<Properties> = unsafe{ Box::from_raw(self.properties as *mut Properties) }; if stream_id as usize >= properties.streams.len() { return false } { let ref stream_properties = &properties.streams[stream_id as usize]; let ul = match (stream_properties.codec, stream_properties.wrapping) { (Codec::Jpeg2000, Wrapping::Frame) => Ul::Jpeg2000FrameWrapped, (Codec::Jpeg2000, Wrapping::Clip) => Ul::Jpeg2000ClipWrapped, (_, _) => unimplemented!(), }; let header_klv = Klv { key: ul, value: Value { elements: vec![ build_element!(Ul::Unknown, unknown => data.to_vec()) ] } }; let mut stream = Cursor::new(vec![0; 0]); stream.write(Encoder::serialise(&header_klv).as_ref()).unwrap(); let data = stream.get_mut(); (self.write)(self.handle, data.as_mut_ptr(), data.len() as u64); } self.properties = Box::into_raw(properties) as *mut _; true } } #[no_mangle] pub extern fn new_writer(handle: *mut(), writer: extern fn(*mut(), *mut u8, u64) -> bool) -> Writer { Writer::new(handle, writer) } #[no_mangle] pub extern fn add_stream(mut writer: Writer, codec: Codec, wrapping: Wrapping) { writer.add_stream(codec, wrapping); } #[no_mangle] pub extern fn dump_header(mut writer: Writer) { writer.dump_header(); } #[no_mangle] pub extern fn wrap(mut writer: Writer, data: *mut u8, size: usize, stream_id: u8) -> bool { unsafe { let mut some_data = Vec::from_raw_parts(data, size, size); writer.wrap(&mut some_data, stream_id) } }
use interface::fill::fill; use klv::klv::*; use klv::ul::*; use klv::value::*;
random_line_split
writer.rs
use interface::fill::fill; use klv::klv::*; use klv::ul::*; use klv::value::*; use klv::value::element::Element; use klv::value::value_data::*; use klv::value::partition::PartitionStatus::*; use std::io::prelude::*; use std::io::Cursor; use serializer::encoder::*; #[derive(Debug, Copy, Clone)] #[repr(C)] pub enum Codec { Jpeg2000, AvcIntra, ProRes, } #[derive(Debug, Copy, Clone)] #[repr(C)] pub enum Wrapping { Frame, Clip, } #[derive(Debug, Clone)] pub struct Stream { pub codec: Codec, pub wrapping: Wrapping } #[derive(Debug, Clone)] pub struct Properties { pub kag_size: Option<u32>, pub streams: Vec<Stream>, } #[derive(Clone)] #[repr(C)] pub struct Writer { pub properties: *mut (), pub handle: *mut (), pub write: extern fn(*mut(), *mut u8, u64) -> bool } impl Writer { pub fn new(handle: *mut(), write: extern fn(*mut(), *mut u8, u64) -> bool) -> Writer { let properties = Properties { kag_size: None, streams: vec![] }; let box_properties = Box::new(properties); let handle_properties = Box::into_raw(box_properties) as *mut _; Writer { properties: handle_properties, handle: handle, write: write, } } pub fn add_stream(&mut self, codec: Codec, wrapping: Wrapping) { let mut properties : Box<Properties> = unsafe{ Box::from_raw(self.properties as *mut Properties) }; properties.streams.push(Stream{ codec: codec, wrapping: wrapping }); self.properties = Box::into_raw(properties) as *mut _; } pub fn dump_header(&mut self) { let properties : Box<Properties> = unsafe{ Box::from_raw(self.properties as *mut Properties) }; let header_klv = Klv { key: Ul::HeaderPartition { status: ClosedAndComplete }, value: Value { elements: vec![ build_element!(Ul::PartitionMajor, uint16 => 1), build_element!(Ul::PartitionMinor, uint16 => 3), build_element!(Ul::PartitionKagSize, uint32 => 512), build_element!(Ul::PartitionThisPartition, uint64 => 0), build_element!(Ul::PartitionPreviousPartition, uint64 => 0), build_element!(Ul::PartitionFooterPartition, uint64 => 131611136), build_element!(Ul::PartitionHeaderByteCount, uint64 => 5120), build_element!(Ul::PartitionIndexByteCount, uint64 => 0), build_element!(Ul::PartitionIndexSid, uint32 => 0), build_element!(Ul::PartitionBodyOffset, uint64 => 0), build_element!(Ul::PartitionBodySid, uint32 => 1), build_element!(Ul::PartitionOperationalPattern, ul => Ul::MxfOP1aSingleItemSinglePackageUniTrackStreamInternal), build_element!(Ul::PartitionEssenceContainers, array_ul => vec![Ul::Essence_Jpeg2000_FrameWrapped]), ] } }; let mut stream = Cursor::new(vec![0; 0]); stream.write(Encoder::serialise(&header_klv).as_ref()).unwrap(); let data = stream.get_mut(); (self.write)(self.handle, data.as_mut_ptr(), data.len() as u64); match properties.kag_size { Some(kag_size) => { fill(&self, data.len(), kag_size as usize); }, None =>
, } let primer_pack_klv = Klv { key: Ul::PrimerPack, value: Value { elements: vec![ build_element!(Ul::Unknown, uint32 => 0), build_element!(Ul::Unknown, uint32 => 18), ] } }; let mut stream = Cursor::new(vec![0; 0]); stream.write(Encoder::serialise(&primer_pack_klv).as_ref()).unwrap(); let data = stream.get_mut(); (self.write)(self.handle, data.as_mut_ptr(), data.len() as u64); self.properties = Box::into_raw(properties) as *mut _; } pub fn wrap(&mut self, data: &Vec<u8>, stream_id: u8) -> bool { let properties : Box<Properties> = unsafe{ Box::from_raw(self.properties as *mut Properties) }; if stream_id as usize >= properties.streams.len() { return false } { let ref stream_properties = &properties.streams[stream_id as usize]; let ul = match (stream_properties.codec, stream_properties.wrapping) { (Codec::Jpeg2000, Wrapping::Frame) => Ul::Jpeg2000FrameWrapped, (Codec::Jpeg2000, Wrapping::Clip) => Ul::Jpeg2000ClipWrapped, (_, _) => unimplemented!(), }; let header_klv = Klv { key: ul, value: Value { elements: vec![ build_element!(Ul::Unknown, unknown => data.to_vec()) ] } }; let mut stream = Cursor::new(vec![0; 0]); stream.write(Encoder::serialise(&header_klv).as_ref()).unwrap(); let data = stream.get_mut(); (self.write)(self.handle, data.as_mut_ptr(), data.len() as u64); } self.properties = Box::into_raw(properties) as *mut _; true } } #[no_mangle] pub extern fn new_writer(handle: *mut(), writer: extern fn(*mut(), *mut u8, u64) -> bool) -> Writer { Writer::new(handle, writer) } #[no_mangle] pub extern fn add_stream(mut writer: Writer, codec: Codec, wrapping: Wrapping) { writer.add_stream(codec, wrapping); } #[no_mangle] pub extern fn dump_header(mut writer: Writer) { writer.dump_header(); } #[no_mangle] pub extern fn wrap(mut writer: Writer, data: *mut u8, size: usize, stream_id: u8) -> bool { unsafe { let mut some_data = Vec::from_raw_parts(data, size, size); writer.wrap(&mut some_data, stream_id) } }
{}
conditional_block
writer.rs
use interface::fill::fill; use klv::klv::*; use klv::ul::*; use klv::value::*; use klv::value::element::Element; use klv::value::value_data::*; use klv::value::partition::PartitionStatus::*; use std::io::prelude::*; use std::io::Cursor; use serializer::encoder::*; #[derive(Debug, Copy, Clone)] #[repr(C)] pub enum Codec { Jpeg2000, AvcIntra, ProRes, } #[derive(Debug, Copy, Clone)] #[repr(C)] pub enum Wrapping { Frame, Clip, } #[derive(Debug, Clone)] pub struct Stream { pub codec: Codec, pub wrapping: Wrapping } #[derive(Debug, Clone)] pub struct Properties { pub kag_size: Option<u32>, pub streams: Vec<Stream>, } #[derive(Clone)] #[repr(C)] pub struct Writer { pub properties: *mut (), pub handle: *mut (), pub write: extern fn(*mut(), *mut u8, u64) -> bool } impl Writer { pub fn new(handle: *mut(), write: extern fn(*mut(), *mut u8, u64) -> bool) -> Writer { let properties = Properties { kag_size: None, streams: vec![] }; let box_properties = Box::new(properties); let handle_properties = Box::into_raw(box_properties) as *mut _; Writer { properties: handle_properties, handle: handle, write: write, } } pub fn add_stream(&mut self, codec: Codec, wrapping: Wrapping) { let mut properties : Box<Properties> = unsafe{ Box::from_raw(self.properties as *mut Properties) }; properties.streams.push(Stream{ codec: codec, wrapping: wrapping }); self.properties = Box::into_raw(properties) as *mut _; } pub fn dump_header(&mut self) { let properties : Box<Properties> = unsafe{ Box::from_raw(self.properties as *mut Properties) }; let header_klv = Klv { key: Ul::HeaderPartition { status: ClosedAndComplete }, value: Value { elements: vec![ build_element!(Ul::PartitionMajor, uint16 => 1), build_element!(Ul::PartitionMinor, uint16 => 3), build_element!(Ul::PartitionKagSize, uint32 => 512), build_element!(Ul::PartitionThisPartition, uint64 => 0), build_element!(Ul::PartitionPreviousPartition, uint64 => 0), build_element!(Ul::PartitionFooterPartition, uint64 => 131611136), build_element!(Ul::PartitionHeaderByteCount, uint64 => 5120), build_element!(Ul::PartitionIndexByteCount, uint64 => 0), build_element!(Ul::PartitionIndexSid, uint32 => 0), build_element!(Ul::PartitionBodyOffset, uint64 => 0), build_element!(Ul::PartitionBodySid, uint32 => 1), build_element!(Ul::PartitionOperationalPattern, ul => Ul::MxfOP1aSingleItemSinglePackageUniTrackStreamInternal), build_element!(Ul::PartitionEssenceContainers, array_ul => vec![Ul::Essence_Jpeg2000_FrameWrapped]), ] } }; let mut stream = Cursor::new(vec![0; 0]); stream.write(Encoder::serialise(&header_klv).as_ref()).unwrap(); let data = stream.get_mut(); (self.write)(self.handle, data.as_mut_ptr(), data.len() as u64); match properties.kag_size { Some(kag_size) => { fill(&self, data.len(), kag_size as usize); }, None => {}, } let primer_pack_klv = Klv { key: Ul::PrimerPack, value: Value { elements: vec![ build_element!(Ul::Unknown, uint32 => 0), build_element!(Ul::Unknown, uint32 => 18), ] } }; let mut stream = Cursor::new(vec![0; 0]); stream.write(Encoder::serialise(&primer_pack_klv).as_ref()).unwrap(); let data = stream.get_mut(); (self.write)(self.handle, data.as_mut_ptr(), data.len() as u64); self.properties = Box::into_raw(properties) as *mut _; } pub fn wrap(&mut self, data: &Vec<u8>, stream_id: u8) -> bool { let properties : Box<Properties> = unsafe{ Box::from_raw(self.properties as *mut Properties) }; if stream_id as usize >= properties.streams.len() { return false } { let ref stream_properties = &properties.streams[stream_id as usize]; let ul = match (stream_properties.codec, stream_properties.wrapping) { (Codec::Jpeg2000, Wrapping::Frame) => Ul::Jpeg2000FrameWrapped, (Codec::Jpeg2000, Wrapping::Clip) => Ul::Jpeg2000ClipWrapped, (_, _) => unimplemented!(), }; let header_klv = Klv { key: ul, value: Value { elements: vec![ build_element!(Ul::Unknown, unknown => data.to_vec()) ] } }; let mut stream = Cursor::new(vec![0; 0]); stream.write(Encoder::serialise(&header_klv).as_ref()).unwrap(); let data = stream.get_mut(); (self.write)(self.handle, data.as_mut_ptr(), data.len() as u64); } self.properties = Box::into_raw(properties) as *mut _; true } } #[no_mangle] pub extern fn new_writer(handle: *mut(), writer: extern fn(*mut(), *mut u8, u64) -> bool) -> Writer
#[no_mangle] pub extern fn add_stream(mut writer: Writer, codec: Codec, wrapping: Wrapping) { writer.add_stream(codec, wrapping); } #[no_mangle] pub extern fn dump_header(mut writer: Writer) { writer.dump_header(); } #[no_mangle] pub extern fn wrap(mut writer: Writer, data: *mut u8, size: usize, stream_id: u8) -> bool { unsafe { let mut some_data = Vec::from_raw_parts(data, size, size); writer.wrap(&mut some_data, stream_id) } }
{ Writer::new(handle, writer) }
identifier_body