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
ast_clone.rs
use std::str::FromStr; use { proc_macro2::{Span, TokenStream}, syn::{ self, Data, DataEnum, DataStruct, DeriveInput, Field, Fields, FieldsNamed, FieldsUnnamed, Generics, Ident, Variant, }, }; use crate::{ attr, shared::{map_lifetimes, map_type_params, split_for_impl}, }; pub fn derive(input: TokenStream) -> TokenStream { let derive_input = syn::parse2(input).expect("Input is checked by rustc"); let container = attr::Container::from_ast(&derive_input); let DeriveInput { ident, data, generics, .. } = derive_input; let tokens = match data { Data::Struct(ast) => derive_struct(&container, ast, ident, generics), Data::Enum(ast) => derive_enum(&container, ast, ident, generics), Data::Union(_) => panic!("Unions are not supported"), }; tokens.into() } fn derive_struct( container: &attr::Container, ast: DataStruct, ident: Ident, generics: Generics, ) -> TokenStream { let cons = match ast.fields { Fields::Named(FieldsNamed { named,.. }) => gen_struct_cons(&ident, named), Fields::Unnamed(FieldsUnnamed { unnamed,.. }) => gen_tuple_struct_cons(&ident, unnamed), Fields::Unit => quote! { #ident }, }; gen_impl(container, ident, generics, cons) } fn gen_struct_cons<I>(ident: &Ident, fields: I) -> TokenStream where I: IntoIterator<Item = Field>, { // lookup each field by its name and then convert to its type using the Getable // impl of the fields type let field_initializers = fields.into_iter().map(|field| { let field_ty = &field.ty; let ident = field .ident .as_ref() .expect("Struct fields always have names"); quote! { #ident: <#field_ty as gluon_base::ast::AstClone<'ast, Id>>::ast_clone(&self.#ident, arena) } }); quote! { #ident { #(#field_initializers,)* } } } fn gen_tuple_struct_cons<I>(ident: &Ident, fields: I) -> TokenStream where I: IntoIterator<Item = Field>, { let mut fields = fields.into_iter().fuse(); // Treat newtype structs as just their inner type let (first, second) = (fields.next(), fields.next()); match (&first, &second) { (Some(field), None) => { let field_ty = &field.ty; return quote! { #ident ( <#field_ty as gluon_base::ast::AstClone<'__vm, _>>::ast_clone(&self.0, arena) ) }; } _ => (), } // do the lookup using the tag, because tuple structs don't have field names let field_initializers = first .into_iter() .chain(second) .chain(fields) .enumerate() .map(|(idx, field)| { let field_ty = &field.ty; let idx = syn::Index::from(idx); quote! { <#field_ty as gluon_base::ast::AstClone<'__vm, _>>::ast_clone(&self. #idx, arena) } }); quote! { #ident ( #(#field_initializers,)* ) } } fn derive_enum( container: &attr::Container, ast: DataEnum, ident: Ident, generics: Generics, ) -> TokenStream { let cons = { let variants = ast .variants .iter() .enumerate() .map(|(tag, variant)| gen_variant_match(&ident, tag, variant)); // data contains the the data for each field of a variant; the variant of the passed value // is defined by the tag(), which is defined by order of the variants (the first variant is 0) quote! { match self { #(#variants,)* } } }; gen_impl(container, ident, generics, cons) } fn gen_impl( container: &attr::Container, ident: Ident, generics: Generics, clone_impl: TokenStream, ) -> TokenStream { // lifetime bounds like '__vm: 'a, 'a: '__vm (which implies => 'a == '__vm) // writing bounds like this is a lot easier than actually replacing all lifetimes // with '__vm let lifetime_bounds = create_lifetime_bounds(&generics); // generate bounds like T: Getable for every type parameter let ast_clone_bounds = create_ast_clone_bounds(&generics); let (impl_generics, ty_generics, where_clause) = split_for_impl(&generics, &["Id"], &["'ast"]); let dummy_const = Ident::new(&format!("_IMPL_AST_CLONE_FOR_{}", ident), Span::call_site()); let extra_bounds = container.ast_clone_bounds.as_ref().map(|b| { let b = TokenStream::from_str(b).unwrap(); quote! { #b, } }); quote! { #[allow(non_upper_case_globals)] const #dummy_const: () = { use crate as gluon_base; #[automatically_derived] #[allow(unused_attributes, unused_variables)] impl #impl_generics gluon_base::ast::AstClone<'ast, Id> for #ident #ty_generics #where_clause #(#ast_clone_bounds,)* #(#lifetime_bounds),* #extra_bounds Id: Clone { fn ast_clone(&self, arena: gluon_base::ast::ArenaRef<'_, 'ast, Id>) -> Self { #clone_impl } } }; } } fn
(ident: &Ident, _tag: usize, variant: &Variant) -> TokenStream { let variant_ident = &variant.ident; // depending on the type of the variant we need to generate different constructors // for the enum match &variant.fields { Fields::Unit => quote! { #ident::#variant_ident => #ident::#variant_ident }, // both constructors that need to marshall values extract them by using the index // of the field to get the content from Data::get_variant; // the data variable was assigned in the function body above Fields::Unnamed(FieldsUnnamed { unnamed,.. }) => { let fields: Vec<_> = unnamed .iter() .enumerate() .map(|(idx, _field)| syn::Ident::new(&format!("_{}", idx), Span::call_site())) .collect(); let cons = gen_tuple_variant_cons(unnamed.iter().zip(fields.iter())); quote! { #ident::#variant_ident ( #(#fields),* ) => #ident::#variant_ident#cons } } Fields::Named(FieldsNamed { named,.. }) => { let cons = gen_struct_variant_cons(ident, variant_ident, named); let named = named.iter().map(|field| field.ident.as_ref().unwrap()); quote! { #ident::#variant_ident { #(#named),* } => #cons } } } } fn gen_tuple_variant_cons<'a, I>(fields: I) -> TokenStream where I: IntoIterator<Item = (&'a syn::Field, &'a syn::Ident)>, { let fields = fields.into_iter().map(|(field, ident)| { let field_ty = &field.ty; quote! { <#field_ty as gluon_base::ast::AstClone<_>>::ast_clone(#ident, arena) } }); quote! { (#(#fields),*) } } fn gen_struct_variant_cons<'a, I>(ident: &Ident, variant_ident: &Ident, fields: I) -> TokenStream where I: IntoIterator<Item = &'a Field>, { let fields = fields.into_iter().map(|field| { let field_ty = &field.ty; let field_ident = field .ident .as_ref() .expect("Struct fields always have names"); quote! { #field_ident: <#field_ty as gluon_base::ast::AstClone<_>>::ast_clone(#field_ident, arena) } }); quote! { #ident::#variant_ident { #(#fields),* } } } fn create_ast_clone_bounds(generics: &Generics) -> Vec<TokenStream> { map_type_params(generics, |ty| { quote! { #ty: gluon_base::ast::AstClone<'ast, Id> } }) } fn create_lifetime_bounds(generics: &Generics) -> Vec<TokenStream> { map_lifetimes(generics, |_lifetime| { quote! {} }) }
gen_variant_match
identifier_name
mod.rs
use std::iter; use super::super::fundamentals::stacks_and_queues::bag::Bag; use super::super::fundamentals::stacks_and_queues::{Stack, Queue}; use super::super::fundamentals::stacks_and_queues::linked_stack; use super::super::fundamentals::stacks_and_queues::resizing_array_queue::ResizingArrayQueue; #[derive(Clone, Debug)] pub struct Graph { v: usize, e: usize, adj: Vec<Bag<usize>> } impl Graph { pub fn new(v: usize) -> Graph { Graph { v: v, e: 0, adj: iter::repeat(Bag::<usize>::new()).take(v).collect() } } fn validate_vertex(&self, v: usize) { assert!(v < self.v, "vertex is not between 0 and {}", self.v - 1) } pub fn v(&self) -> usize { self.v } pub fn e(&self) -> usize { self.e } pub fn add_edge(&mut self, v: usize, w: usize) { self.validate_vertex(v); self.validate_vertex(w); self.e += 1; self.adj[v].add(w); self.adj[w].add(v); } // FIXME: should this be a global function pub fn degree(&self, v: usize) -> usize { self.validate_vertex(v); self.adj[v].len() } pub fn max_degree(&self) -> usize { (0.. self.v()).map(|v| self.degree(v)).max().unwrap_or(0) } pub fn average_degree(&self) -> f64 { // (0.. self.v()).map(|v| self.degree(v)).sum::<usize>() as f64 / self.v() as f64 2.0 * self.e() as f64 / self.v() as f64 } pub fn number_of_self_loops(&self) -> usize { let mut count = 0; for v in 0.. self.v() { for w in self.adj(v) { if v == w { count += 1; } } } count / 2 } pub fn to_dot(&self) -> String { let mut dot = String::new(); dot.push_str("graph G {\n"); for i in 0.. self.v { dot.push_str(&format!(" {};\n", i)); } for (v, adj) in self.adj.iter().enumerate() { for w in adj.iter() { dot.push_str(&format!(" {} -- {};\n", v, w)); } } dot.push_str("}\n"); dot } pub fn adj(&self, v: usize) -> ::std::vec::IntoIter<usize> { self.adj[v].iter().map(|v| v.clone()).collect::<Vec<usize>>().into_iter() } pub fn dfs<'a>(&'a self, s: usize) -> SearchPaths<'a> { let mut path = SearchPaths::new(self, s); path.dfs(s); path } pub fn bfs<'a>(&'a self, s: usize) -> SearchPaths<'a> { let mut path = SearchPaths::new(self, s); path.bfs(s); path } pub fn cc<'a>(&'a self) -> CC<'a> { CC::new(self) } } pub struct SearchPaths<'a> { graph: &'a Graph, marked: Vec<bool>, edge_to: Vec<Option<usize>>, s: usize } impl<'a> SearchPaths<'a> { fn new<'b>(graph: &'b Graph, s: usize) -> SearchPaths<'b> { let marked = iter::repeat(false).take(graph.v()).collect(); let edge_to = iter::repeat(None).take(graph.v()).collect(); SearchPaths { graph: graph, marked: marked, edge_to: edge_to, s: s } } fn dfs(&mut self, v: usize) { self.marked[v] = true; for w in self.graph.adj(v) { if!self.marked[w] { self.dfs(w); self.edge_to[w] = Some(v); } } } fn bfs(&mut self, s: usize) { let mut q = ResizingArrayQueue::new(); q.enqueue(s); self.marked[s] = true; while!q.is_empty() { let v = q.dequeue().unwrap(); for w in self.graph.adj(v) { if!self.marked[w] { self.edge_to[w] = Some(v); q.enqueue(w); self.marked[w] = true; } } } } pub fn has_path_to(&self, v: usize) -> bool
pub fn path_to(&self, v: usize) -> Option<Vec<usize>> { if!self.has_path_to(v) { None } else { let mut path = linked_stack::LinkedStack::new(); let mut x = v; while x!= self.s { path.push(x); x = self.edge_to[x].unwrap(); } path.push(self.s); Some(path.into_iter().collect()) } } } /// Compute connected components using depth first search. pub struct CC<'a> { graph: &'a Graph, marked: Vec<bool>, id: Vec<Option<usize>>, count: usize, } impl<'a> CC<'a> { fn new<'b>(graph: &'b Graph) -> CC<'b> { let n = graph.v(); let mut cc = CC { graph: graph, marked: iter::repeat(false).take(n).collect(), id: iter::repeat(None).take(n).collect(), count: 0 }; cc.init(); cc } fn init(&mut self) { for v in 0.. self.graph.v() { if!self.marked[v] { self.dfs(v); self.count += 1; } } } pub fn count(&self) -> usize { self.count } pub fn id(&self, v: usize) -> usize { self.id[v].unwrap() } pub fn connected(&self, v: usize, w: usize) -> bool { self.id[v] == self.id[w] } fn dfs(&mut self, v: usize) { self.marked[v] = true; self.id[v] = Some(self.count); for w in self.graph.adj(v) { if!self.marked[w] { self.dfs(w) } } } } #[test] fn test_graph_visit() { let mut g = Graph::new(13); g.add_edge(0, 1); g.add_edge(0, 2); g.add_edge(0, 6); g.add_edge(0, 5); g.add_edge(5, 3); g.add_edge(5, 4); g.add_edge(3, 4); g.add_edge(4, 6); g.add_edge(7, 8); g.add_edge(9, 10); g.add_edge(9, 11); g.add_edge(9, 12); g.add_edge(11, 12); // println!("dot => \n {}", g.to_dot()); assert_eq!(format!("{:?}", g.dfs(0).path_to(3).unwrap()), "[0, 5, 4, 3]"); assert_eq!(format!("{:?}", g.bfs(0).path_to(3).unwrap()), "[0, 5, 3]"); assert_eq!(g.cc().id(4), 0); assert_eq!(g.cc().id(8), 1); assert_eq!(g.cc().id(11), 2); assert!(g.cc().connected(0, 4)); } #[test] fn test_graph() { let mut g = Graph::new(10); g.add_edge(0, 3); g.add_edge(0, 5); g.add_edge(4, 5); g.add_edge(2, 9); g.add_edge(2, 8); g.add_edge(3, 7); g.add_edge(1, 6); g.add_edge(6, 9); g.add_edge(5, 8); // println!("got => \n{}", g.to_dot()); assert_eq!(10, g.v()); assert_eq!(9, g.e()); assert_eq!(3, g.degree(5)); for w in g.adj(5) { assert!(vec![8, 4, 0].contains(&w)); } assert_eq!(g.max_degree(), 3); assert!(g.average_degree() < 2.0); assert_eq!(g.number_of_self_loops(), 0); } #[test] fn test_graph_functions() { let mut g = Graph::new(5); for i in 0.. 5 { for j in 0.. 5 { g.add_edge(i, j); } } assert_eq!(10, g.max_degree()); assert_eq!(5, g.number_of_self_loops()); }
{ self.marked[v] }
identifier_body
mod.rs
use std::iter; use super::super::fundamentals::stacks_and_queues::bag::Bag; use super::super::fundamentals::stacks_and_queues::{Stack, Queue}; use super::super::fundamentals::stacks_and_queues::linked_stack; use super::super::fundamentals::stacks_and_queues::resizing_array_queue::ResizingArrayQueue; #[derive(Clone, Debug)] pub struct Graph { v: usize, e: usize, adj: Vec<Bag<usize>> } impl Graph { pub fn new(v: usize) -> Graph { Graph { v: v, e: 0, adj: iter::repeat(Bag::<usize>::new()).take(v).collect() } } fn validate_vertex(&self, v: usize) { assert!(v < self.v, "vertex is not between 0 and {}", self.v - 1) } pub fn v(&self) -> usize { self.v } pub fn e(&self) -> usize { self.e } pub fn add_edge(&mut self, v: usize, w: usize) { self.validate_vertex(v); self.validate_vertex(w); self.e += 1; self.adj[v].add(w); self.adj[w].add(v); } // FIXME: should this be a global function pub fn degree(&self, v: usize) -> usize { self.validate_vertex(v); self.adj[v].len() } pub fn max_degree(&self) -> usize { (0.. self.v()).map(|v| self.degree(v)).max().unwrap_or(0) } pub fn average_degree(&self) -> f64 { // (0.. self.v()).map(|v| self.degree(v)).sum::<usize>() as f64 / self.v() as f64 2.0 * self.e() as f64 / self.v() as f64 } pub fn number_of_self_loops(&self) -> usize { let mut count = 0; for v in 0.. self.v() { for w in self.adj(v) { if v == w { count += 1; } } } count / 2 } pub fn to_dot(&self) -> String { let mut dot = String::new(); dot.push_str("graph G {\n"); for i in 0.. self.v { dot.push_str(&format!(" {};\n", i)); } for (v, adj) in self.adj.iter().enumerate() { for w in adj.iter() { dot.push_str(&format!(" {} -- {};\n", v, w)); } } dot.push_str("}\n"); dot } pub fn adj(&self, v: usize) -> ::std::vec::IntoIter<usize> { self.adj[v].iter().map(|v| v.clone()).collect::<Vec<usize>>().into_iter() } pub fn dfs<'a>(&'a self, s: usize) -> SearchPaths<'a> { let mut path = SearchPaths::new(self, s); path.dfs(s); path } pub fn bfs<'a>(&'a self, s: usize) -> SearchPaths<'a> { let mut path = SearchPaths::new(self, s); path.bfs(s); path } pub fn cc<'a>(&'a self) -> CC<'a> { CC::new(self) } } pub struct SearchPaths<'a> { graph: &'a Graph, marked: Vec<bool>, edge_to: Vec<Option<usize>>, s: usize } impl<'a> SearchPaths<'a> { fn new<'b>(graph: &'b Graph, s: usize) -> SearchPaths<'b> { let marked = iter::repeat(false).take(graph.v()).collect(); let edge_to = iter::repeat(None).take(graph.v()).collect(); SearchPaths { graph: graph, marked: marked, edge_to: edge_to, s: s } } fn dfs(&mut self, v: usize) { self.marked[v] = true; for w in self.graph.adj(v) { if!self.marked[w]
} } fn bfs(&mut self, s: usize) { let mut q = ResizingArrayQueue::new(); q.enqueue(s); self.marked[s] = true; while!q.is_empty() { let v = q.dequeue().unwrap(); for w in self.graph.adj(v) { if!self.marked[w] { self.edge_to[w] = Some(v); q.enqueue(w); self.marked[w] = true; } } } } pub fn has_path_to(&self, v: usize) -> bool { self.marked[v] } pub fn path_to(&self, v: usize) -> Option<Vec<usize>> { if!self.has_path_to(v) { None } else { let mut path = linked_stack::LinkedStack::new(); let mut x = v; while x!= self.s { path.push(x); x = self.edge_to[x].unwrap(); } path.push(self.s); Some(path.into_iter().collect()) } } } /// Compute connected components using depth first search. pub struct CC<'a> { graph: &'a Graph, marked: Vec<bool>, id: Vec<Option<usize>>, count: usize, } impl<'a> CC<'a> { fn new<'b>(graph: &'b Graph) -> CC<'b> { let n = graph.v(); let mut cc = CC { graph: graph, marked: iter::repeat(false).take(n).collect(), id: iter::repeat(None).take(n).collect(), count: 0 }; cc.init(); cc } fn init(&mut self) { for v in 0.. self.graph.v() { if!self.marked[v] { self.dfs(v); self.count += 1; } } } pub fn count(&self) -> usize { self.count } pub fn id(&self, v: usize) -> usize { self.id[v].unwrap() } pub fn connected(&self, v: usize, w: usize) -> bool { self.id[v] == self.id[w] } fn dfs(&mut self, v: usize) { self.marked[v] = true; self.id[v] = Some(self.count); for w in self.graph.adj(v) { if!self.marked[w] { self.dfs(w) } } } } #[test] fn test_graph_visit() { let mut g = Graph::new(13); g.add_edge(0, 1); g.add_edge(0, 2); g.add_edge(0, 6); g.add_edge(0, 5); g.add_edge(5, 3); g.add_edge(5, 4); g.add_edge(3, 4); g.add_edge(4, 6); g.add_edge(7, 8); g.add_edge(9, 10); g.add_edge(9, 11); g.add_edge(9, 12); g.add_edge(11, 12); // println!("dot => \n {}", g.to_dot()); assert_eq!(format!("{:?}", g.dfs(0).path_to(3).unwrap()), "[0, 5, 4, 3]"); assert_eq!(format!("{:?}", g.bfs(0).path_to(3).unwrap()), "[0, 5, 3]"); assert_eq!(g.cc().id(4), 0); assert_eq!(g.cc().id(8), 1); assert_eq!(g.cc().id(11), 2); assert!(g.cc().connected(0, 4)); } #[test] fn test_graph() { let mut g = Graph::new(10); g.add_edge(0, 3); g.add_edge(0, 5); g.add_edge(4, 5); g.add_edge(2, 9); g.add_edge(2, 8); g.add_edge(3, 7); g.add_edge(1, 6); g.add_edge(6, 9); g.add_edge(5, 8); // println!("got => \n{}", g.to_dot()); assert_eq!(10, g.v()); assert_eq!(9, g.e()); assert_eq!(3, g.degree(5)); for w in g.adj(5) { assert!(vec![8, 4, 0].contains(&w)); } assert_eq!(g.max_degree(), 3); assert!(g.average_degree() < 2.0); assert_eq!(g.number_of_self_loops(), 0); } #[test] fn test_graph_functions() { let mut g = Graph::new(5); for i in 0.. 5 { for j in 0.. 5 { g.add_edge(i, j); } } assert_eq!(10, g.max_degree()); assert_eq!(5, g.number_of_self_loops()); }
{ self.dfs(w); self.edge_to[w] = Some(v); }
conditional_block
mod.rs
use std::iter; use super::super::fundamentals::stacks_and_queues::bag::Bag; use super::super::fundamentals::stacks_and_queues::{Stack, Queue}; use super::super::fundamentals::stacks_and_queues::linked_stack; use super::super::fundamentals::stacks_and_queues::resizing_array_queue::ResizingArrayQueue; #[derive(Clone, Debug)] pub struct Graph { v: usize, e: usize, adj: Vec<Bag<usize>> } impl Graph { pub fn new(v: usize) -> Graph { Graph { v: v, e: 0, adj: iter::repeat(Bag::<usize>::new()).take(v).collect() } } fn validate_vertex(&self, v: usize) { assert!(v < self.v, "vertex is not between 0 and {}", self.v - 1) } pub fn v(&self) -> usize { self.v } pub fn e(&self) -> usize { self.e } pub fn add_edge(&mut self, v: usize, w: usize) { self.validate_vertex(v); self.validate_vertex(w); self.e += 1; self.adj[v].add(w); self.adj[w].add(v); } // FIXME: should this be a global function pub fn
(&self, v: usize) -> usize { self.validate_vertex(v); self.adj[v].len() } pub fn max_degree(&self) -> usize { (0.. self.v()).map(|v| self.degree(v)).max().unwrap_or(0) } pub fn average_degree(&self) -> f64 { // (0.. self.v()).map(|v| self.degree(v)).sum::<usize>() as f64 / self.v() as f64 2.0 * self.e() as f64 / self.v() as f64 } pub fn number_of_self_loops(&self) -> usize { let mut count = 0; for v in 0.. self.v() { for w in self.adj(v) { if v == w { count += 1; } } } count / 2 } pub fn to_dot(&self) -> String { let mut dot = String::new(); dot.push_str("graph G {\n"); for i in 0.. self.v { dot.push_str(&format!(" {};\n", i)); } for (v, adj) in self.adj.iter().enumerate() { for w in adj.iter() { dot.push_str(&format!(" {} -- {};\n", v, w)); } } dot.push_str("}\n"); dot } pub fn adj(&self, v: usize) -> ::std::vec::IntoIter<usize> { self.adj[v].iter().map(|v| v.clone()).collect::<Vec<usize>>().into_iter() } pub fn dfs<'a>(&'a self, s: usize) -> SearchPaths<'a> { let mut path = SearchPaths::new(self, s); path.dfs(s); path } pub fn bfs<'a>(&'a self, s: usize) -> SearchPaths<'a> { let mut path = SearchPaths::new(self, s); path.bfs(s); path } pub fn cc<'a>(&'a self) -> CC<'a> { CC::new(self) } } pub struct SearchPaths<'a> { graph: &'a Graph, marked: Vec<bool>, edge_to: Vec<Option<usize>>, s: usize } impl<'a> SearchPaths<'a> { fn new<'b>(graph: &'b Graph, s: usize) -> SearchPaths<'b> { let marked = iter::repeat(false).take(graph.v()).collect(); let edge_to = iter::repeat(None).take(graph.v()).collect(); SearchPaths { graph: graph, marked: marked, edge_to: edge_to, s: s } } fn dfs(&mut self, v: usize) { self.marked[v] = true; for w in self.graph.adj(v) { if!self.marked[w] { self.dfs(w); self.edge_to[w] = Some(v); } } } fn bfs(&mut self, s: usize) { let mut q = ResizingArrayQueue::new(); q.enqueue(s); self.marked[s] = true; while!q.is_empty() { let v = q.dequeue().unwrap(); for w in self.graph.adj(v) { if!self.marked[w] { self.edge_to[w] = Some(v); q.enqueue(w); self.marked[w] = true; } } } } pub fn has_path_to(&self, v: usize) -> bool { self.marked[v] } pub fn path_to(&self, v: usize) -> Option<Vec<usize>> { if!self.has_path_to(v) { None } else { let mut path = linked_stack::LinkedStack::new(); let mut x = v; while x!= self.s { path.push(x); x = self.edge_to[x].unwrap(); } path.push(self.s); Some(path.into_iter().collect()) } } } /// Compute connected components using depth first search. pub struct CC<'a> { graph: &'a Graph, marked: Vec<bool>, id: Vec<Option<usize>>, count: usize, } impl<'a> CC<'a> { fn new<'b>(graph: &'b Graph) -> CC<'b> { let n = graph.v(); let mut cc = CC { graph: graph, marked: iter::repeat(false).take(n).collect(), id: iter::repeat(None).take(n).collect(), count: 0 }; cc.init(); cc } fn init(&mut self) { for v in 0.. self.graph.v() { if!self.marked[v] { self.dfs(v); self.count += 1; } } } pub fn count(&self) -> usize { self.count } pub fn id(&self, v: usize) -> usize { self.id[v].unwrap() } pub fn connected(&self, v: usize, w: usize) -> bool { self.id[v] == self.id[w] } fn dfs(&mut self, v: usize) { self.marked[v] = true; self.id[v] = Some(self.count); for w in self.graph.adj(v) { if!self.marked[w] { self.dfs(w) } } } } #[test] fn test_graph_visit() { let mut g = Graph::new(13); g.add_edge(0, 1); g.add_edge(0, 2); g.add_edge(0, 6); g.add_edge(0, 5); g.add_edge(5, 3); g.add_edge(5, 4); g.add_edge(3, 4); g.add_edge(4, 6); g.add_edge(7, 8); g.add_edge(9, 10); g.add_edge(9, 11); g.add_edge(9, 12); g.add_edge(11, 12); // println!("dot => \n {}", g.to_dot()); assert_eq!(format!("{:?}", g.dfs(0).path_to(3).unwrap()), "[0, 5, 4, 3]"); assert_eq!(format!("{:?}", g.bfs(0).path_to(3).unwrap()), "[0, 5, 3]"); assert_eq!(g.cc().id(4), 0); assert_eq!(g.cc().id(8), 1); assert_eq!(g.cc().id(11), 2); assert!(g.cc().connected(0, 4)); } #[test] fn test_graph() { let mut g = Graph::new(10); g.add_edge(0, 3); g.add_edge(0, 5); g.add_edge(4, 5); g.add_edge(2, 9); g.add_edge(2, 8); g.add_edge(3, 7); g.add_edge(1, 6); g.add_edge(6, 9); g.add_edge(5, 8); // println!("got => \n{}", g.to_dot()); assert_eq!(10, g.v()); assert_eq!(9, g.e()); assert_eq!(3, g.degree(5)); for w in g.adj(5) { assert!(vec![8, 4, 0].contains(&w)); } assert_eq!(g.max_degree(), 3); assert!(g.average_degree() < 2.0); assert_eq!(g.number_of_self_loops(), 0); } #[test] fn test_graph_functions() { let mut g = Graph::new(5); for i in 0.. 5 { for j in 0.. 5 { g.add_edge(i, j); } } assert_eq!(10, g.max_degree()); assert_eq!(5, g.number_of_self_loops()); }
degree
identifier_name
mod.rs
use std::iter; use super::super::fundamentals::stacks_and_queues::bag::Bag; use super::super::fundamentals::stacks_and_queues::{Stack, Queue}; use super::super::fundamentals::stacks_and_queues::linked_stack; use super::super::fundamentals::stacks_and_queues::resizing_array_queue::ResizingArrayQueue; #[derive(Clone, Debug)] pub struct Graph { v: usize, e: usize, adj: Vec<Bag<usize>> } impl Graph { pub fn new(v: usize) -> Graph { Graph { v: v, e: 0, adj: iter::repeat(Bag::<usize>::new()).take(v).collect() } } fn validate_vertex(&self, v: usize) { assert!(v < self.v, "vertex is not between 0 and {}", self.v - 1) } pub fn v(&self) -> usize { self.v } pub fn e(&self) -> usize {
} pub fn add_edge(&mut self, v: usize, w: usize) { self.validate_vertex(v); self.validate_vertex(w); self.e += 1; self.adj[v].add(w); self.adj[w].add(v); } // FIXME: should this be a global function pub fn degree(&self, v: usize) -> usize { self.validate_vertex(v); self.adj[v].len() } pub fn max_degree(&self) -> usize { (0.. self.v()).map(|v| self.degree(v)).max().unwrap_or(0) } pub fn average_degree(&self) -> f64 { // (0.. self.v()).map(|v| self.degree(v)).sum::<usize>() as f64 / self.v() as f64 2.0 * self.e() as f64 / self.v() as f64 } pub fn number_of_self_loops(&self) -> usize { let mut count = 0; for v in 0.. self.v() { for w in self.adj(v) { if v == w { count += 1; } } } count / 2 } pub fn to_dot(&self) -> String { let mut dot = String::new(); dot.push_str("graph G {\n"); for i in 0.. self.v { dot.push_str(&format!(" {};\n", i)); } for (v, adj) in self.adj.iter().enumerate() { for w in adj.iter() { dot.push_str(&format!(" {} -- {};\n", v, w)); } } dot.push_str("}\n"); dot } pub fn adj(&self, v: usize) -> ::std::vec::IntoIter<usize> { self.adj[v].iter().map(|v| v.clone()).collect::<Vec<usize>>().into_iter() } pub fn dfs<'a>(&'a self, s: usize) -> SearchPaths<'a> { let mut path = SearchPaths::new(self, s); path.dfs(s); path } pub fn bfs<'a>(&'a self, s: usize) -> SearchPaths<'a> { let mut path = SearchPaths::new(self, s); path.bfs(s); path } pub fn cc<'a>(&'a self) -> CC<'a> { CC::new(self) } } pub struct SearchPaths<'a> { graph: &'a Graph, marked: Vec<bool>, edge_to: Vec<Option<usize>>, s: usize } impl<'a> SearchPaths<'a> { fn new<'b>(graph: &'b Graph, s: usize) -> SearchPaths<'b> { let marked = iter::repeat(false).take(graph.v()).collect(); let edge_to = iter::repeat(None).take(graph.v()).collect(); SearchPaths { graph: graph, marked: marked, edge_to: edge_to, s: s } } fn dfs(&mut self, v: usize) { self.marked[v] = true; for w in self.graph.adj(v) { if!self.marked[w] { self.dfs(w); self.edge_to[w] = Some(v); } } } fn bfs(&mut self, s: usize) { let mut q = ResizingArrayQueue::new(); q.enqueue(s); self.marked[s] = true; while!q.is_empty() { let v = q.dequeue().unwrap(); for w in self.graph.adj(v) { if!self.marked[w] { self.edge_to[w] = Some(v); q.enqueue(w); self.marked[w] = true; } } } } pub fn has_path_to(&self, v: usize) -> bool { self.marked[v] } pub fn path_to(&self, v: usize) -> Option<Vec<usize>> { if!self.has_path_to(v) { None } else { let mut path = linked_stack::LinkedStack::new(); let mut x = v; while x!= self.s { path.push(x); x = self.edge_to[x].unwrap(); } path.push(self.s); Some(path.into_iter().collect()) } } } /// Compute connected components using depth first search. pub struct CC<'a> { graph: &'a Graph, marked: Vec<bool>, id: Vec<Option<usize>>, count: usize, } impl<'a> CC<'a> { fn new<'b>(graph: &'b Graph) -> CC<'b> { let n = graph.v(); let mut cc = CC { graph: graph, marked: iter::repeat(false).take(n).collect(), id: iter::repeat(None).take(n).collect(), count: 0 }; cc.init(); cc } fn init(&mut self) { for v in 0.. self.graph.v() { if!self.marked[v] { self.dfs(v); self.count += 1; } } } pub fn count(&self) -> usize { self.count } pub fn id(&self, v: usize) -> usize { self.id[v].unwrap() } pub fn connected(&self, v: usize, w: usize) -> bool { self.id[v] == self.id[w] } fn dfs(&mut self, v: usize) { self.marked[v] = true; self.id[v] = Some(self.count); for w in self.graph.adj(v) { if!self.marked[w] { self.dfs(w) } } } } #[test] fn test_graph_visit() { let mut g = Graph::new(13); g.add_edge(0, 1); g.add_edge(0, 2); g.add_edge(0, 6); g.add_edge(0, 5); g.add_edge(5, 3); g.add_edge(5, 4); g.add_edge(3, 4); g.add_edge(4, 6); g.add_edge(7, 8); g.add_edge(9, 10); g.add_edge(9, 11); g.add_edge(9, 12); g.add_edge(11, 12); // println!("dot => \n {}", g.to_dot()); assert_eq!(format!("{:?}", g.dfs(0).path_to(3).unwrap()), "[0, 5, 4, 3]"); assert_eq!(format!("{:?}", g.bfs(0).path_to(3).unwrap()), "[0, 5, 3]"); assert_eq!(g.cc().id(4), 0); assert_eq!(g.cc().id(8), 1); assert_eq!(g.cc().id(11), 2); assert!(g.cc().connected(0, 4)); } #[test] fn test_graph() { let mut g = Graph::new(10); g.add_edge(0, 3); g.add_edge(0, 5); g.add_edge(4, 5); g.add_edge(2, 9); g.add_edge(2, 8); g.add_edge(3, 7); g.add_edge(1, 6); g.add_edge(6, 9); g.add_edge(5, 8); // println!("got => \n{}", g.to_dot()); assert_eq!(10, g.v()); assert_eq!(9, g.e()); assert_eq!(3, g.degree(5)); for w in g.adj(5) { assert!(vec![8, 4, 0].contains(&w)); } assert_eq!(g.max_degree(), 3); assert!(g.average_degree() < 2.0); assert_eq!(g.number_of_self_loops(), 0); } #[test] fn test_graph_functions() { let mut g = Graph::new(5); for i in 0.. 5 { for j in 0.. 5 { g.add_edge(i, j); } } assert_eq!(10, g.max_degree()); assert_eq!(5, g.number_of_self_loops()); }
self.e
random_line_split
applicable_declarations.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/. */ //! Applicable declarations management. use properties::PropertyDeclarationBlock; use rule_tree::{CascadeLevel, StyleSource}; use servo_arc::Arc; use shared_lock::Locked; use smallvec::SmallVec; use std::fmt::{Debug, self}; use std::mem; /// List of applicable declarations. This is a transient structure that shuttles /// declarations between selector matching and inserting into the rule tree, and /// therefore we want to avoid heap-allocation where possible. /// /// In measurements on wikipedia, we pretty much never have more than 8 applicable /// declarations, so we could consider making this 8 entries instead of 16. /// However, it may depend a lot on workload, and stack space is cheap. pub type ApplicableDeclarationList = SmallVec<[ApplicableDeclarationBlock; 16]>; /// Blink uses 18 bits to store source order, and does not check overflow [1]. /// That's a limit that could be reached in realistic webpages, so we use /// 24 bits and enforce defined behavior in the overflow case. /// /// Note that the value of 24 is also hard-coded into the level() accessor, /// which does a byte-aligned load of the 4th byte. If you change this value /// you'll need to change that as well. /// /// [1] https://cs.chromium.org/chromium/src/third_party/WebKit/Source/core/css/ /// RuleSet.h?l=128&rcl=90140ab80b84d0f889abc253410f44ed54ae04f3 const SOURCE_ORDER_BITS: usize = 24; const SOURCE_ORDER_MASK: u32 = (1 << SOURCE_ORDER_BITS) - 1; const SOURCE_ORDER_MAX: u32 = SOURCE_ORDER_MASK; /// Stores the source order of a block and the cascade level it belongs to. #[cfg_attr(feature = "servo", derive(HeapSizeOf))] #[derive(Clone, Copy, Eq, PartialEq)] struct SourceOrderAndCascadeLevel(u32); impl SourceOrderAndCascadeLevel { fn new(source_order: u32, cascade_level: CascadeLevel) -> SourceOrderAndCascadeLevel { let mut bits = ::std::cmp::min(source_order, SOURCE_ORDER_MAX); bits |= (cascade_level as u8 as u32) << SOURCE_ORDER_BITS; SourceOrderAndCascadeLevel(bits) } fn order(&self) -> u32 { self.0 & SOURCE_ORDER_MASK } fn level(&self) -> CascadeLevel { unsafe { // Transmute rather than shifting so that we're sure the compiler // emits a simple byte-aligned load. let as_bytes: [u8; 4] = mem::transmute(self.0); CascadeLevel::from_byte(as_bytes[3]) } } } impl Debug for SourceOrderAndCascadeLevel { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("SourceOrderAndCascadeLevel") .field("order", &self.order()) .field("level", &self.level()) .finish() } } /// A property declaration together with its precedence among rules of equal /// specificity so that we can sort them. /// /// This represents the declarations in a given declaration block for a given /// importance. #[cfg_attr(feature = "servo", derive(HeapSizeOf))] #[derive(Clone, Debug, PartialEq)] pub struct ApplicableDeclarationBlock { /// The style source, either a style rule, or a property declaration block. #[cfg_attr(feature = "servo", ignore_heap_size_of = "Arc")] pub source: StyleSource, /// The source order of the block, and the cascade level it belongs to. order_and_level: SourceOrderAndCascadeLevel, /// The specificity of the selector this block is represented by. pub specificity: u32, } impl ApplicableDeclarationBlock { /// Constructs an applicable declaration block from a given property /// declaration block and importance. #[inline] pub fn from_declarations(declarations: Arc<Locked<PropertyDeclarationBlock>>, level: CascadeLevel) -> Self { ApplicableDeclarationBlock { source: StyleSource::Declarations(declarations), order_and_level: SourceOrderAndCascadeLevel::new(0, level), specificity: 0, } } /// Constructs an applicable declaration block from the given components #[inline] pub fn new(source: StyleSource, order: u32, level: CascadeLevel, specificity: u32) -> Self { ApplicableDeclarationBlock { source: source, order_and_level: SourceOrderAndCascadeLevel::new(order, level), specificity: specificity, } } /// Returns the source order of the block. #[inline] pub fn source_order(&self) -> u32 { self.order_and_level.order() } /// Returns the cascade level of the block. #[inline] pub fn level(&self) -> CascadeLevel { self.order_and_level.level() } /// Convenience method to consume self and return the source alongside the /// level. #[inline] pub fn order_and_level(self) -> (StyleSource, CascadeLevel) { let level = self.level(); (self.source, level) }
}
random_line_split
applicable_declarations.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/. */ //! Applicable declarations management. use properties::PropertyDeclarationBlock; use rule_tree::{CascadeLevel, StyleSource}; use servo_arc::Arc; use shared_lock::Locked; use smallvec::SmallVec; use std::fmt::{Debug, self}; use std::mem; /// List of applicable declarations. This is a transient structure that shuttles /// declarations between selector matching and inserting into the rule tree, and /// therefore we want to avoid heap-allocation where possible. /// /// In measurements on wikipedia, we pretty much never have more than 8 applicable /// declarations, so we could consider making this 8 entries instead of 16. /// However, it may depend a lot on workload, and stack space is cheap. pub type ApplicableDeclarationList = SmallVec<[ApplicableDeclarationBlock; 16]>; /// Blink uses 18 bits to store source order, and does not check overflow [1]. /// That's a limit that could be reached in realistic webpages, so we use /// 24 bits and enforce defined behavior in the overflow case. /// /// Note that the value of 24 is also hard-coded into the level() accessor, /// which does a byte-aligned load of the 4th byte. If you change this value /// you'll need to change that as well. /// /// [1] https://cs.chromium.org/chromium/src/third_party/WebKit/Source/core/css/ /// RuleSet.h?l=128&rcl=90140ab80b84d0f889abc253410f44ed54ae04f3 const SOURCE_ORDER_BITS: usize = 24; const SOURCE_ORDER_MASK: u32 = (1 << SOURCE_ORDER_BITS) - 1; const SOURCE_ORDER_MAX: u32 = SOURCE_ORDER_MASK; /// Stores the source order of a block and the cascade level it belongs to. #[cfg_attr(feature = "servo", derive(HeapSizeOf))] #[derive(Clone, Copy, Eq, PartialEq)] struct SourceOrderAndCascadeLevel(u32); impl SourceOrderAndCascadeLevel { fn new(source_order: u32, cascade_level: CascadeLevel) -> SourceOrderAndCascadeLevel
fn order(&self) -> u32 { self.0 & SOURCE_ORDER_MASK } fn level(&self) -> CascadeLevel { unsafe { // Transmute rather than shifting so that we're sure the compiler // emits a simple byte-aligned load. let as_bytes: [u8; 4] = mem::transmute(self.0); CascadeLevel::from_byte(as_bytes[3]) } } } impl Debug for SourceOrderAndCascadeLevel { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("SourceOrderAndCascadeLevel") .field("order", &self.order()) .field("level", &self.level()) .finish() } } /// A property declaration together with its precedence among rules of equal /// specificity so that we can sort them. /// /// This represents the declarations in a given declaration block for a given /// importance. #[cfg_attr(feature = "servo", derive(HeapSizeOf))] #[derive(Clone, Debug, PartialEq)] pub struct ApplicableDeclarationBlock { /// The style source, either a style rule, or a property declaration block. #[cfg_attr(feature = "servo", ignore_heap_size_of = "Arc")] pub source: StyleSource, /// The source order of the block, and the cascade level it belongs to. order_and_level: SourceOrderAndCascadeLevel, /// The specificity of the selector this block is represented by. pub specificity: u32, } impl ApplicableDeclarationBlock { /// Constructs an applicable declaration block from a given property /// declaration block and importance. #[inline] pub fn from_declarations(declarations: Arc<Locked<PropertyDeclarationBlock>>, level: CascadeLevel) -> Self { ApplicableDeclarationBlock { source: StyleSource::Declarations(declarations), order_and_level: SourceOrderAndCascadeLevel::new(0, level), specificity: 0, } } /// Constructs an applicable declaration block from the given components #[inline] pub fn new(source: StyleSource, order: u32, level: CascadeLevel, specificity: u32) -> Self { ApplicableDeclarationBlock { source: source, order_and_level: SourceOrderAndCascadeLevel::new(order, level), specificity: specificity, } } /// Returns the source order of the block. #[inline] pub fn source_order(&self) -> u32 { self.order_and_level.order() } /// Returns the cascade level of the block. #[inline] pub fn level(&self) -> CascadeLevel { self.order_and_level.level() } /// Convenience method to consume self and return the source alongside the /// level. #[inline] pub fn order_and_level(self) -> (StyleSource, CascadeLevel) { let level = self.level(); (self.source, level) } }
{ let mut bits = ::std::cmp::min(source_order, SOURCE_ORDER_MAX); bits |= (cascade_level as u8 as u32) << SOURCE_ORDER_BITS; SourceOrderAndCascadeLevel(bits) }
identifier_body
applicable_declarations.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/. */ //! Applicable declarations management. use properties::PropertyDeclarationBlock; use rule_tree::{CascadeLevel, StyleSource}; use servo_arc::Arc; use shared_lock::Locked; use smallvec::SmallVec; use std::fmt::{Debug, self}; use std::mem; /// List of applicable declarations. This is a transient structure that shuttles /// declarations between selector matching and inserting into the rule tree, and /// therefore we want to avoid heap-allocation where possible. /// /// In measurements on wikipedia, we pretty much never have more than 8 applicable /// declarations, so we could consider making this 8 entries instead of 16. /// However, it may depend a lot on workload, and stack space is cheap. pub type ApplicableDeclarationList = SmallVec<[ApplicableDeclarationBlock; 16]>; /// Blink uses 18 bits to store source order, and does not check overflow [1]. /// That's a limit that could be reached in realistic webpages, so we use /// 24 bits and enforce defined behavior in the overflow case. /// /// Note that the value of 24 is also hard-coded into the level() accessor, /// which does a byte-aligned load of the 4th byte. If you change this value /// you'll need to change that as well. /// /// [1] https://cs.chromium.org/chromium/src/third_party/WebKit/Source/core/css/ /// RuleSet.h?l=128&rcl=90140ab80b84d0f889abc253410f44ed54ae04f3 const SOURCE_ORDER_BITS: usize = 24; const SOURCE_ORDER_MASK: u32 = (1 << SOURCE_ORDER_BITS) - 1; const SOURCE_ORDER_MAX: u32 = SOURCE_ORDER_MASK; /// Stores the source order of a block and the cascade level it belongs to. #[cfg_attr(feature = "servo", derive(HeapSizeOf))] #[derive(Clone, Copy, Eq, PartialEq)] struct SourceOrderAndCascadeLevel(u32); impl SourceOrderAndCascadeLevel { fn new(source_order: u32, cascade_level: CascadeLevel) -> SourceOrderAndCascadeLevel { let mut bits = ::std::cmp::min(source_order, SOURCE_ORDER_MAX); bits |= (cascade_level as u8 as u32) << SOURCE_ORDER_BITS; SourceOrderAndCascadeLevel(bits) } fn order(&self) -> u32 { self.0 & SOURCE_ORDER_MASK } fn level(&self) -> CascadeLevel { unsafe { // Transmute rather than shifting so that we're sure the compiler // emits a simple byte-aligned load. let as_bytes: [u8; 4] = mem::transmute(self.0); CascadeLevel::from_byte(as_bytes[3]) } } } impl Debug for SourceOrderAndCascadeLevel { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("SourceOrderAndCascadeLevel") .field("order", &self.order()) .field("level", &self.level()) .finish() } } /// A property declaration together with its precedence among rules of equal /// specificity so that we can sort them. /// /// This represents the declarations in a given declaration block for a given /// importance. #[cfg_attr(feature = "servo", derive(HeapSizeOf))] #[derive(Clone, Debug, PartialEq)] pub struct ApplicableDeclarationBlock { /// The style source, either a style rule, or a property declaration block. #[cfg_attr(feature = "servo", ignore_heap_size_of = "Arc")] pub source: StyleSource, /// The source order of the block, and the cascade level it belongs to. order_and_level: SourceOrderAndCascadeLevel, /// The specificity of the selector this block is represented by. pub specificity: u32, } impl ApplicableDeclarationBlock { /// Constructs an applicable declaration block from a given property /// declaration block and importance. #[inline] pub fn from_declarations(declarations: Arc<Locked<PropertyDeclarationBlock>>, level: CascadeLevel) -> Self { ApplicableDeclarationBlock { source: StyleSource::Declarations(declarations), order_and_level: SourceOrderAndCascadeLevel::new(0, level), specificity: 0, } } /// Constructs an applicable declaration block from the given components #[inline] pub fn new(source: StyleSource, order: u32, level: CascadeLevel, specificity: u32) -> Self { ApplicableDeclarationBlock { source: source, order_and_level: SourceOrderAndCascadeLevel::new(order, level), specificity: specificity, } } /// Returns the source order of the block. #[inline] pub fn
(&self) -> u32 { self.order_and_level.order() } /// Returns the cascade level of the block. #[inline] pub fn level(&self) -> CascadeLevel { self.order_and_level.level() } /// Convenience method to consume self and return the source alongside the /// level. #[inline] pub fn order_and_level(self) -> (StyleSource, CascadeLevel) { let level = self.level(); (self.source, level) } }
source_order
identifier_name
os_str.rs
// // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /// The underlying OsString/OsStr implementation on Unix systems: just /// a `Vec<u8>`/`[u8]`. use borrow::Cow; use fmt; use str; use mem; use rc::Rc; use sync::Arc; use sys_common::{AsInner, IntoInner}; use sys_common::bytestring::debug_fmt_bytestring; use core::str::lossy::Utf8Lossy; #[derive(Clone, Hash)] pub struct Buf { pub inner: Vec<u8> } pub struct Slice { pub inner: [u8] } impl fmt::Debug for Slice { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { debug_fmt_bytestring(&self.inner, formatter) } } impl fmt::Display for Slice { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&Utf8Lossy::from_bytes(&self.inner), formatter) } } impl fmt::Debug for Buf { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(self.as_slice(), formatter) } } impl fmt::Display for Buf { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(self.as_slice(), formatter) } } impl IntoInner<Vec<u8>> for Buf { fn into_inner(self) -> Vec<u8> { self.inner } } impl AsInner<[u8]> for Buf { fn as_inner(&self) -> &[u8] { &self.inner } } impl Buf { pub fn from_string(s: String) -> Buf { Buf { inner: s.into_bytes() } } #[inline] pub fn with_capacity(capacity: usize) -> Buf { Buf { inner: Vec::with_capacity(capacity) } } #[inline] pub fn clear(&mut self) { self.inner.clear() } #[inline] pub fn capacity(&self) -> usize { self.inner.capacity() } #[inline] pub fn reserve(&mut self, additional: usize) { self.inner.reserve(additional) } #[inline] pub fn reserve_exact(&mut self, additional: usize) { self.inner.reserve_exact(additional) } #[inline] pub fn shrink_to_fit(&mut self) { self.inner.shrink_to_fit() } #[inline] pub fn shrink_to(&mut self, min_capacity: usize) { self.inner.shrink_to(min_capacity) } pub fn as_slice(&self) -> &Slice { unsafe { mem::transmute(&*self.inner) } } pub fn into_string(self) -> Result<String, Buf> { String::from_utf8(self.inner).map_err(|p| Buf { inner: p.into_bytes() } ) } pub fn push_slice(&mut self, s: &Slice) { self.inner.extend_from_slice(&s.inner) } #[inline] pub fn into_box(self) -> Box<Slice> { unsafe { mem::transmute(self.inner.into_boxed_slice()) } } #[inline] pub fn from_box(boxed: Box<Slice>) -> Buf { let inner: Box<[u8]> = unsafe { mem::transmute(boxed) }; Buf { inner: inner.into_vec() } } #[inline] pub fn into_arc(&self) -> Arc<Slice> { self.as_slice().into_arc() } #[inline] pub fn into_rc(&self) -> Rc<Slice> { self.as_slice().into_rc() } } impl Slice { fn from_u8_slice(s: &[u8]) -> &Slice { unsafe { mem::transmute(s) } } pub fn from_str(s: &str) -> &Slice { Slice::from_u8_slice(s.as_bytes()) } pub fn to_str(&self) -> Option<&str> { str::from_utf8(&self.inner).ok() } pub fn to_string_lossy(&self) -> Cow<str> { String::from_utf8_lossy(&self.inner) } pub fn to_owned(&self) -> Buf { Buf { inner: self.inner.to_vec() } } #[inline] pub fn into_box(&self) -> Box<Slice> { let boxed: Box<[u8]> = self.inner.into(); unsafe { mem::transmute(boxed) } } pub fn empty_box() -> Box<Slice> { let boxed: Box<[u8]> = Default::default(); unsafe { mem::transmute(boxed) } } #[inline] pub fn into_arc(&self) -> Arc<Slice> { let arc: Arc<[u8]> = Arc::from(&self.inner); unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Slice) } } #[inline] pub fn into_rc(&self) -> Rc<Slice> { let rc: Rc<[u8]> = Rc::from(&self.inner); unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Slice) } } }
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT.
random_line_split
os_str.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /// The underlying OsString/OsStr implementation on Unix systems: just /// a `Vec<u8>`/`[u8]`. use borrow::Cow; use fmt; use str; use mem; use rc::Rc; use sync::Arc; use sys_common::{AsInner, IntoInner}; use sys_common::bytestring::debug_fmt_bytestring; use core::str::lossy::Utf8Lossy; #[derive(Clone, Hash)] pub struct Buf { pub inner: Vec<u8> } pub struct Slice { pub inner: [u8] } impl fmt::Debug for Slice { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { debug_fmt_bytestring(&self.inner, formatter) } } impl fmt::Display for Slice { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&Utf8Lossy::from_bytes(&self.inner), formatter) } } impl fmt::Debug for Buf { fn
(&self, formatter: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(self.as_slice(), formatter) } } impl fmt::Display for Buf { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(self.as_slice(), formatter) } } impl IntoInner<Vec<u8>> for Buf { fn into_inner(self) -> Vec<u8> { self.inner } } impl AsInner<[u8]> for Buf { fn as_inner(&self) -> &[u8] { &self.inner } } impl Buf { pub fn from_string(s: String) -> Buf { Buf { inner: s.into_bytes() } } #[inline] pub fn with_capacity(capacity: usize) -> Buf { Buf { inner: Vec::with_capacity(capacity) } } #[inline] pub fn clear(&mut self) { self.inner.clear() } #[inline] pub fn capacity(&self) -> usize { self.inner.capacity() } #[inline] pub fn reserve(&mut self, additional: usize) { self.inner.reserve(additional) } #[inline] pub fn reserve_exact(&mut self, additional: usize) { self.inner.reserve_exact(additional) } #[inline] pub fn shrink_to_fit(&mut self) { self.inner.shrink_to_fit() } #[inline] pub fn shrink_to(&mut self, min_capacity: usize) { self.inner.shrink_to(min_capacity) } pub fn as_slice(&self) -> &Slice { unsafe { mem::transmute(&*self.inner) } } pub fn into_string(self) -> Result<String, Buf> { String::from_utf8(self.inner).map_err(|p| Buf { inner: p.into_bytes() } ) } pub fn push_slice(&mut self, s: &Slice) { self.inner.extend_from_slice(&s.inner) } #[inline] pub fn into_box(self) -> Box<Slice> { unsafe { mem::transmute(self.inner.into_boxed_slice()) } } #[inline] pub fn from_box(boxed: Box<Slice>) -> Buf { let inner: Box<[u8]> = unsafe { mem::transmute(boxed) }; Buf { inner: inner.into_vec() } } #[inline] pub fn into_arc(&self) -> Arc<Slice> { self.as_slice().into_arc() } #[inline] pub fn into_rc(&self) -> Rc<Slice> { self.as_slice().into_rc() } } impl Slice { fn from_u8_slice(s: &[u8]) -> &Slice { unsafe { mem::transmute(s) } } pub fn from_str(s: &str) -> &Slice { Slice::from_u8_slice(s.as_bytes()) } pub fn to_str(&self) -> Option<&str> { str::from_utf8(&self.inner).ok() } pub fn to_string_lossy(&self) -> Cow<str> { String::from_utf8_lossy(&self.inner) } pub fn to_owned(&self) -> Buf { Buf { inner: self.inner.to_vec() } } #[inline] pub fn into_box(&self) -> Box<Slice> { let boxed: Box<[u8]> = self.inner.into(); unsafe { mem::transmute(boxed) } } pub fn empty_box() -> Box<Slice> { let boxed: Box<[u8]> = Default::default(); unsafe { mem::transmute(boxed) } } #[inline] pub fn into_arc(&self) -> Arc<Slice> { let arc: Arc<[u8]> = Arc::from(&self.inner); unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Slice) } } #[inline] pub fn into_rc(&self) -> Rc<Slice> { let rc: Rc<[u8]> = Rc::from(&self.inner); unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Slice) } } }
fmt
identifier_name
os_str.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /// The underlying OsString/OsStr implementation on Unix systems: just /// a `Vec<u8>`/`[u8]`. use borrow::Cow; use fmt; use str; use mem; use rc::Rc; use sync::Arc; use sys_common::{AsInner, IntoInner}; use sys_common::bytestring::debug_fmt_bytestring; use core::str::lossy::Utf8Lossy; #[derive(Clone, Hash)] pub struct Buf { pub inner: Vec<u8> } pub struct Slice { pub inner: [u8] } impl fmt::Debug for Slice { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { debug_fmt_bytestring(&self.inner, formatter) } } impl fmt::Display for Slice { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&Utf8Lossy::from_bytes(&self.inner), formatter) } } impl fmt::Debug for Buf { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(self.as_slice(), formatter) } } impl fmt::Display for Buf { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(self.as_slice(), formatter) } } impl IntoInner<Vec<u8>> for Buf { fn into_inner(self) -> Vec<u8> { self.inner } } impl AsInner<[u8]> for Buf { fn as_inner(&self) -> &[u8] { &self.inner } } impl Buf { pub fn from_string(s: String) -> Buf { Buf { inner: s.into_bytes() } } #[inline] pub fn with_capacity(capacity: usize) -> Buf { Buf { inner: Vec::with_capacity(capacity) } } #[inline] pub fn clear(&mut self) { self.inner.clear() } #[inline] pub fn capacity(&self) -> usize { self.inner.capacity() } #[inline] pub fn reserve(&mut self, additional: usize) { self.inner.reserve(additional) } #[inline] pub fn reserve_exact(&mut self, additional: usize) { self.inner.reserve_exact(additional) } #[inline] pub fn shrink_to_fit(&mut self) { self.inner.shrink_to_fit() } #[inline] pub fn shrink_to(&mut self, min_capacity: usize) { self.inner.shrink_to(min_capacity) } pub fn as_slice(&self) -> &Slice { unsafe { mem::transmute(&*self.inner) } } pub fn into_string(self) -> Result<String, Buf>
pub fn push_slice(&mut self, s: &Slice) { self.inner.extend_from_slice(&s.inner) } #[inline] pub fn into_box(self) -> Box<Slice> { unsafe { mem::transmute(self.inner.into_boxed_slice()) } } #[inline] pub fn from_box(boxed: Box<Slice>) -> Buf { let inner: Box<[u8]> = unsafe { mem::transmute(boxed) }; Buf { inner: inner.into_vec() } } #[inline] pub fn into_arc(&self) -> Arc<Slice> { self.as_slice().into_arc() } #[inline] pub fn into_rc(&self) -> Rc<Slice> { self.as_slice().into_rc() } } impl Slice { fn from_u8_slice(s: &[u8]) -> &Slice { unsafe { mem::transmute(s) } } pub fn from_str(s: &str) -> &Slice { Slice::from_u8_slice(s.as_bytes()) } pub fn to_str(&self) -> Option<&str> { str::from_utf8(&self.inner).ok() } pub fn to_string_lossy(&self) -> Cow<str> { String::from_utf8_lossy(&self.inner) } pub fn to_owned(&self) -> Buf { Buf { inner: self.inner.to_vec() } } #[inline] pub fn into_box(&self) -> Box<Slice> { let boxed: Box<[u8]> = self.inner.into(); unsafe { mem::transmute(boxed) } } pub fn empty_box() -> Box<Slice> { let boxed: Box<[u8]> = Default::default(); unsafe { mem::transmute(boxed) } } #[inline] pub fn into_arc(&self) -> Arc<Slice> { let arc: Arc<[u8]> = Arc::from(&self.inner); unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Slice) } } #[inline] pub fn into_rc(&self) -> Rc<Slice> { let rc: Rc<[u8]> = Rc::from(&self.inner); unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Slice) } } }
{ String::from_utf8(self.inner).map_err(|p| Buf { inner: p.into_bytes() } ) }
identifier_body
presale.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use ethcore::ethstore::{PresaleWallet, EthStore}; use ethcore::ethstore::dir::RootDiskDirectory;
use ethcore::account_provider::{AccountProvider, AccountProviderSettings}; use helpers::{password_prompt, password_from_file}; use params::SpecType; #[derive(Debug, PartialEq)] pub struct ImportWallet { pub iterations: u32, pub path: String, pub spec: SpecType, pub wallet_path: String, pub password_file: Option<String>, } pub fn execute(cmd: ImportWallet) -> Result<String, String> { let password: String = match cmd.password_file { Some(file) => password_from_file(file)?, None => password_prompt()?, }; let dir = Box::new(RootDiskDirectory::create(cmd.path).unwrap()); let secret_store = Box::new(EthStore::open_with_iterations(dir, cmd.iterations).unwrap()); let acc_provider = AccountProvider::new(secret_store, AccountProviderSettings::default()); let wallet = PresaleWallet::open(cmd.wallet_path).map_err(|_| "Unable to open presale wallet.")?; let kp = wallet.decrypt(&password).map_err(|_| "Invalid password.")?; let address = acc_provider.insert_account(kp.secret().clone(), &password).unwrap(); Ok(format!("{:?}", address)) }
random_line_split
presale.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use ethcore::ethstore::{PresaleWallet, EthStore}; use ethcore::ethstore::dir::RootDiskDirectory; use ethcore::account_provider::{AccountProvider, AccountProviderSettings}; use helpers::{password_prompt, password_from_file}; use params::SpecType; #[derive(Debug, PartialEq)] pub struct
{ pub iterations: u32, pub path: String, pub spec: SpecType, pub wallet_path: String, pub password_file: Option<String>, } pub fn execute(cmd: ImportWallet) -> Result<String, String> { let password: String = match cmd.password_file { Some(file) => password_from_file(file)?, None => password_prompt()?, }; let dir = Box::new(RootDiskDirectory::create(cmd.path).unwrap()); let secret_store = Box::new(EthStore::open_with_iterations(dir, cmd.iterations).unwrap()); let acc_provider = AccountProvider::new(secret_store, AccountProviderSettings::default()); let wallet = PresaleWallet::open(cmd.wallet_path).map_err(|_| "Unable to open presale wallet.")?; let kp = wallet.decrypt(&password).map_err(|_| "Invalid password.")?; let address = acc_provider.insert_account(kp.secret().clone(), &password).unwrap(); Ok(format!("{:?}", address)) }
ImportWallet
identifier_name
presale.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use ethcore::ethstore::{PresaleWallet, EthStore}; use ethcore::ethstore::dir::RootDiskDirectory; use ethcore::account_provider::{AccountProvider, AccountProviderSettings}; use helpers::{password_prompt, password_from_file}; use params::SpecType; #[derive(Debug, PartialEq)] pub struct ImportWallet { pub iterations: u32, pub path: String, pub spec: SpecType, pub wallet_path: String, pub password_file: Option<String>, } pub fn execute(cmd: ImportWallet) -> Result<String, String>
{ let password: String = match cmd.password_file { Some(file) => password_from_file(file)?, None => password_prompt()?, }; let dir = Box::new(RootDiskDirectory::create(cmd.path).unwrap()); let secret_store = Box::new(EthStore::open_with_iterations(dir, cmd.iterations).unwrap()); let acc_provider = AccountProvider::new(secret_store, AccountProviderSettings::default()); let wallet = PresaleWallet::open(cmd.wallet_path).map_err(|_| "Unable to open presale wallet.")?; let kp = wallet.decrypt(&password).map_err(|_| "Invalid password.")?; let address = acc_provider.insert_account(kp.secret().clone(), &password).unwrap(); Ok(format!("{:?}", address)) }
identifier_body
last-use-in-cap-clause.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. // Make sure #1399 stays fixed struct A { a: ~int } fn foo() -> @fn() -> int { let k = ~22; let _u = A {a: k.clone()}; let result: @fn() -> int = || 22; result } pub fn
() { assert_eq!(foo()(), 22); }
main
identifier_name
last-use-in-cap-clause.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. // Make sure #1399 stays fixed struct A { a: ~int } fn foo() -> @fn() -> int
pub fn main() { assert_eq!(foo()(), 22); }
{ let k = ~22; let _u = A {a: k.clone()}; let result: @fn() -> int = || 22; result }
identifier_body
unboxed-closures-blanket-fn.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that you can supply `&F` where `F: Fn()`. #![feature(lang_items, unboxed_closures)] fn a<F:Fn() -> i32>(f: F) -> i32 { f() } fn b(f: &Fn() -> i32) -> i32 { a(f)
} fn c<F:Fn() -> i32>(f: &F) -> i32 { a(f) } fn main() { let z: isize = 7; let x = b(&|| 22); assert_eq!(x, 22); let x = c(&|| 22); assert_eq!(x, 22); }
random_line_split
unboxed-closures-blanket-fn.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that you can supply `&F` where `F: Fn()`. #![feature(lang_items, unboxed_closures)] fn a<F:Fn() -> i32>(f: F) -> i32
fn b(f: &Fn() -> i32) -> i32 { a(f) } fn c<F:Fn() -> i32>(f: &F) -> i32 { a(f) } fn main() { let z: isize = 7; let x = b(&|| 22); assert_eq!(x, 22); let x = c(&|| 22); assert_eq!(x, 22); }
{ f() }
identifier_body
unboxed-closures-blanket-fn.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that you can supply `&F` where `F: Fn()`. #![feature(lang_items, unboxed_closures)] fn a<F:Fn() -> i32>(f: F) -> i32 { f() } fn
(f: &Fn() -> i32) -> i32 { a(f) } fn c<F:Fn() -> i32>(f: &F) -> i32 { a(f) } fn main() { let z: isize = 7; let x = b(&|| 22); assert_eq!(x, 22); let x = c(&|| 22); assert_eq!(x, 22); }
b
identifier_name
TestAcosh.rs
/* * Copyright (C) 2014 The Android Open Source Project * * 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 *
* 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. */ #pragma version(1) #pragma rs java_package_name(android.renderscript.cts) // Don't edit this file! It is auto-generated by frameworks/rs/api/gen_runtime. float __attribute__((kernel)) testAcoshFloatFloat(float in) { return acosh(in); } float2 __attribute__((kernel)) testAcoshFloat2Float2(float2 in) { return acosh(in); } float3 __attribute__((kernel)) testAcoshFloat3Float3(float3 in) { return acosh(in); } float4 __attribute__((kernel)) testAcoshFloat4Float4(float4 in) { return acosh(in); }
* Unless required by applicable law or agreed to in writing, software
random_line_split
lib.rs
pub struct RailFence { rails: usize, } impl RailFence { pub fn new(rails: u32) -> RailFence
pub fn encode(&self, text: &str) -> String { let mut rails = vec![String::new(); self.rails]; let indexes = (0..self.rails).chain((1..self.rails - 1).rev()).cycle(); text.chars() .zip(indexes) .for_each(|(c, i)| rails[i as usize].push(c)); rails.concat() } pub fn decode(&self, cipher: &str) -> String { let array = cipher.chars().collect::<Vec<_>>(); let mut indices: Vec<_> = (0..self.rails - 1) .chain((1..self.rails).rev()) .cycle() .zip(0..cipher.len()) .collect(); indices.sort_unstable(); let mut text: Vec<char> = vec![' '; array.len()]; (0..array.len()).for_each(|i| { let index = indices[i].1; text[index] = array[i]; }); text.iter().collect::<String>() } }
{ RailFence { rails: rails as usize, } }
identifier_body
lib.rs
pub struct RailFence { rails: usize, } impl RailFence { pub fn new(rails: u32) -> RailFence { RailFence { rails: rails as usize, } } pub fn
(&self, text: &str) -> String { let mut rails = vec![String::new(); self.rails]; let indexes = (0..self.rails).chain((1..self.rails - 1).rev()).cycle(); text.chars() .zip(indexes) .for_each(|(c, i)| rails[i as usize].push(c)); rails.concat() } pub fn decode(&self, cipher: &str) -> String { let array = cipher.chars().collect::<Vec<_>>(); let mut indices: Vec<_> = (0..self.rails - 1) .chain((1..self.rails).rev()) .cycle() .zip(0..cipher.len()) .collect(); indices.sort_unstable(); let mut text: Vec<char> = vec![' '; array.len()]; (0..array.len()).for_each(|i| { let index = indices[i].1; text[index] = array[i]; }); text.iter().collect::<String>() } }
encode
identifier_name
lib.rs
pub struct RailFence { rails: usize, } impl RailFence { pub fn new(rails: u32) -> RailFence { RailFence { rails: rails as usize, } } pub fn encode(&self, text: &str) -> String { let mut rails = vec![String::new(); self.rails]; let indexes = (0..self.rails).chain((1..self.rails - 1).rev()).cycle(); text.chars() .zip(indexes) .for_each(|(c, i)| rails[i as usize].push(c)); rails.concat() } pub fn decode(&self, cipher: &str) -> String { let array = cipher.chars().collect::<Vec<_>>(); let mut indices: Vec<_> = (0..self.rails - 1) .chain((1..self.rails).rev()) .cycle() .zip(0..cipher.len()) .collect(); indices.sort_unstable(); let mut text: Vec<char> = vec![' '; array.len()]; (0..array.len()).for_each(|i| { let index = indices[i].1; text[index] = array[i]; });
} }
text.iter().collect::<String>()
random_line_split
main.rs
use std::str::FromStr; use std::io::Read; use std::fs::File; // Input types and decoding // #[derive(Debug, Clone, Copy)] enum Rotation { Left = 1, Forward = 0, Right = -1, } #[derive(Debug)] struct Step { rotation: Rotation, distance: i32, } impl FromStr for Rotation { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err>
} impl FromStr for Step { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { let (dir, dist) = s.split_at(1); Ok(Step { rotation: Rotation::from_str(dir).unwrap(), distance: i32::from_str(dist.trim()).unwrap(), }) } } // Common helpers // #[derive(Debug)] struct Position { direction: i8, x: i32, // Distance in the East - West direction y: i32, // Distance in the South - North direction } impl Position { fn distance(&self) -> i32 { self.x.abs() + self.y.abs() } } fn walk(pos: Position, step: Step) -> Position { let int_dir = (pos.direction + step.rotation as i8 + 4) % 4; let (x, y) = match int_dir { 0 => (pos.x, pos.y + step.distance), 1 => (pos.x - step.distance, pos.y), 2 => (pos.x, pos.y - step.distance), 3 => (pos.x + step.distance, pos.y), _ => panic!("Unknown direction {}", int_dir), }; Position {direction: int_dir, x: x, y: y} } // Puzzle 1 // fn process(input: &String) -> Position { let start = Position {direction: 0, x: 0, y: 0}; input.split(", ") .map(|s| Step::from_str(s).unwrap()) .fold(start, walk) } // Puzzle 2 // fn split_step(step: Step) -> Vec<Step> { let mut v = Vec::new(); v.push(Step {rotation: step.rotation, distance: 1}); for _ in 1..step.distance { v.push(Step {rotation: Rotation::Forward, distance: 1}); } v } fn find_crossing(input: &String) -> Position { let steps = input.split(", ") .map(|s| Step::from_str(s).unwrap()) .flat_map(split_step); let mut pos = Position {direction: 0, x: 0, y:0}; let mut visited : std::collections::HashSet<(i32, i32)> = std::collections::HashSet::new(); visited.insert((0,0)); for s in steps { pos = walk(pos, s); if visited.contains(&(pos.x, pos.y)) { return pos; } visited.insert((pos.x, pos.y)); } panic!("No crossing found after visiting: {:?}", visited); } fn main() { if let Ok(mut f) = File::open("input.txt") { let mut input = String::new(); if let Ok(_) = f.read_to_string(&mut input) { let end = process(&input); println!("Final distance: {:?} at {:?}", end.distance(), end); let crossing = find_crossing(&input); println!("First crossing: {:?} at {:?}", crossing.distance(), crossing); } } }
{ match s.chars().next() { Some('L') => Ok(Rotation::Left), Some('R') => Ok(Rotation::Right), c => Err(format!("Unknown entry: {:?}", c)), } }
identifier_body
main.rs
use std::str::FromStr; use std::io::Read; use std::fs::File; // Input types and decoding // #[derive(Debug, Clone, Copy)] enum Rotation { Left = 1, Forward = 0, Right = -1, } #[derive(Debug)] struct Step { rotation: Rotation, distance: i32, } impl FromStr for Rotation { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { match s.chars().next() { Some('L') => Ok(Rotation::Left), Some('R') => Ok(Rotation::Right), c => Err(format!("Unknown entry: {:?}", c)), } } } impl FromStr for Step { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { let (dir, dist) = s.split_at(1); Ok(Step { rotation: Rotation::from_str(dir).unwrap(), distance: i32::from_str(dist.trim()).unwrap(), }) } } // Common helpers // #[derive(Debug)] struct Position { direction: i8, x: i32, // Distance in the East - West direction y: i32, // Distance in the South - North direction } impl Position { fn distance(&self) -> i32 { self.x.abs() + self.y.abs() }
let (x, y) = match int_dir { 0 => (pos.x, pos.y + step.distance), 1 => (pos.x - step.distance, pos.y), 2 => (pos.x, pos.y - step.distance), 3 => (pos.x + step.distance, pos.y), _ => panic!("Unknown direction {}", int_dir), }; Position {direction: int_dir, x: x, y: y} } // Puzzle 1 // fn process(input: &String) -> Position { let start = Position {direction: 0, x: 0, y: 0}; input.split(", ") .map(|s| Step::from_str(s).unwrap()) .fold(start, walk) } // Puzzle 2 // fn split_step(step: Step) -> Vec<Step> { let mut v = Vec::new(); v.push(Step {rotation: step.rotation, distance: 1}); for _ in 1..step.distance { v.push(Step {rotation: Rotation::Forward, distance: 1}); } v } fn find_crossing(input: &String) -> Position { let steps = input.split(", ") .map(|s| Step::from_str(s).unwrap()) .flat_map(split_step); let mut pos = Position {direction: 0, x: 0, y:0}; let mut visited : std::collections::HashSet<(i32, i32)> = std::collections::HashSet::new(); visited.insert((0,0)); for s in steps { pos = walk(pos, s); if visited.contains(&(pos.x, pos.y)) { return pos; } visited.insert((pos.x, pos.y)); } panic!("No crossing found after visiting: {:?}", visited); } fn main() { if let Ok(mut f) = File::open("input.txt") { let mut input = String::new(); if let Ok(_) = f.read_to_string(&mut input) { let end = process(&input); println!("Final distance: {:?} at {:?}", end.distance(), end); let crossing = find_crossing(&input); println!("First crossing: {:?} at {:?}", crossing.distance(), crossing); } } }
} fn walk(pos: Position, step: Step) -> Position { let int_dir = (pos.direction + step.rotation as i8 + 4) % 4;
random_line_split
main.rs
use std::str::FromStr; use std::io::Read; use std::fs::File; // Input types and decoding // #[derive(Debug, Clone, Copy)] enum Rotation { Left = 1, Forward = 0, Right = -1, } #[derive(Debug)] struct Step { rotation: Rotation, distance: i32, } impl FromStr for Rotation { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { match s.chars().next() { Some('L') => Ok(Rotation::Left), Some('R') => Ok(Rotation::Right), c => Err(format!("Unknown entry: {:?}", c)), } } } impl FromStr for Step { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { let (dir, dist) = s.split_at(1); Ok(Step { rotation: Rotation::from_str(dir).unwrap(), distance: i32::from_str(dist.trim()).unwrap(), }) } } // Common helpers // #[derive(Debug)] struct Position { direction: i8, x: i32, // Distance in the East - West direction y: i32, // Distance in the South - North direction } impl Position { fn
(&self) -> i32 { self.x.abs() + self.y.abs() } } fn walk(pos: Position, step: Step) -> Position { let int_dir = (pos.direction + step.rotation as i8 + 4) % 4; let (x, y) = match int_dir { 0 => (pos.x, pos.y + step.distance), 1 => (pos.x - step.distance, pos.y), 2 => (pos.x, pos.y - step.distance), 3 => (pos.x + step.distance, pos.y), _ => panic!("Unknown direction {}", int_dir), }; Position {direction: int_dir, x: x, y: y} } // Puzzle 1 // fn process(input: &String) -> Position { let start = Position {direction: 0, x: 0, y: 0}; input.split(", ") .map(|s| Step::from_str(s).unwrap()) .fold(start, walk) } // Puzzle 2 // fn split_step(step: Step) -> Vec<Step> { let mut v = Vec::new(); v.push(Step {rotation: step.rotation, distance: 1}); for _ in 1..step.distance { v.push(Step {rotation: Rotation::Forward, distance: 1}); } v } fn find_crossing(input: &String) -> Position { let steps = input.split(", ") .map(|s| Step::from_str(s).unwrap()) .flat_map(split_step); let mut pos = Position {direction: 0, x: 0, y:0}; let mut visited : std::collections::HashSet<(i32, i32)> = std::collections::HashSet::new(); visited.insert((0,0)); for s in steps { pos = walk(pos, s); if visited.contains(&(pos.x, pos.y)) { return pos; } visited.insert((pos.x, pos.y)); } panic!("No crossing found after visiting: {:?}", visited); } fn main() { if let Ok(mut f) = File::open("input.txt") { let mut input = String::new(); if let Ok(_) = f.read_to_string(&mut input) { let end = process(&input); println!("Final distance: {:?} at {:?}", end.distance(), end); let crossing = find_crossing(&input); println!("First crossing: {:?} at {:?}", crossing.distance(), crossing); } } }
distance
identifier_name
seg_queue.rs
//! Unrolled Michael—Scott queues. use std::cell::UnsafeCell; use std::ops::Range; use std::sync::atomic::{self, AtomicBool, AtomicUsize}; use std::{ptr, mem, fmt, cmp}; use epoch::{self, Atomic}; /// The maximal number of entries in a segment. const SEG_SIZE: usize = 32; /// A segment. /// /// Segments are like a slab of items stored all in one node, such that queing and dequing can be /// done faster. struct Segment<T> { /// The used entries in the segment. used: Range<AtomicUsize>, /// The data. data: [UnsafeCell<T>; SEG_SIZE], /// What entries contain valid data? valid: [AtomicBool; SEG_SIZE], /// The next node. next: Atomic<Segment<T>>, } impl<T> Default for Segment<T> { fn default() -> Segment<T> { Segment { used: AtomicUsize::new(0)..AtomicUsize::new(0), data: unsafe { mem::uninitialized() }, // FIXME: This is currently needed due to `AtomicBool` not implementing `Copy`. valid: unsafe { mem::zeroed() }, next: Atomic::null(), } } } impl<T> fmt::Debug for Segment<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Segment {{... }}") } } unsafe impl<T: Send> Sync for Segment<T> {} /// An faster, unrolled Michael-Scott queue. /// /// This queue, usable with any number of producers and consumers, stores so called segments /// (arrays of nodes) in order to be more lightweight. #[derive(Debug)] pub struct SegQueue<T> { /// The head segment. head: Atomic<Segment<T>>, /// The tail segment. tail: Atomic<Segment<T>>, } impl<T> SegQueue<T> { /// Create a new, empty queue. pub fn new() -> SegQueue<T> { // FIXME: This is ugly. // We start setting the two ends to null pointers. let queue = SegQueue { head: Atomic::null(), tail: Atomic::null(), }; // Construct the sentinel node with an empty segment. let sentinel = Box::new(Segment::default()); // Set the two ends to the sentinel node. let guard = epoch::pin(); let sentinel = queue.head.store_and_ref(sentinel, atomic::Ordering::Relaxed, &guard); queue.tail.store_shared(Some(sentinel), atomic::Ordering::Relaxed); queue } /// Push an element to the back of the queue. pub fn queue(&self, elem: T) { // Pin the epoch. let guard = epoch::pin(); loop { // Load the tail of the queue through the epoch. let tail = self.tail.load(atomic::Ordering::Acquire, &guard).unwrap(); // Check if the segment is full. if tail.used.end.load(atomic::Ordering::Relaxed) >= SEG_SIZE { // Segment full. Spin again (the thread exhausting the segment is responsible for // adding a new node). continue; } // Increment the used range to ensure that another thread doesn't write the cell, we'll // use soon. let i = tail.used.end.fetch_add(1, atomic::Ordering::Relaxed); // If and only if the increment range was within the segment size (i.e. that we did // actually get a spare cell), we will write the data. Otherwise, we will spin. if i >= SEG_SIZE { continue; } // Write that data. unsafe { // Obtain the cell. let cell = (*tail).data[i].get(); // Write the data into the cell. ptr::write(&mut *cell, elem); // Now that the cell is initialized, we can set the valid flag. tail.valid[i].store(true, atomic::Ordering::Release); // Handle end-of-segment. if i + 1 == SEG_SIZE { // As we noted before in this function, the thread which exhausts the segment // is responsible for inserting a new node, and that's us. // Append a new segment to the local tail. let tail = tail.next .store_and_ref(Box::new(Segment::default()), atomic::Ordering::Release, &guard); // Store the local tail to the queue. self.tail.store_shared(Some(tail), atomic::Ordering::Release); } // It was queued; break the loop. break; } } } /// Attempt to dequeue from the front. /// /// This returns `None` if the queue is observed to be empty. pub fn dequeue(&self) -> Option<T> { // Pin the epoch. let guard = epoch::pin(); // Spin until the other thread which is currently modfying the queue leaves it in a // dequeue-able state. loop { // Load the head through the guard. let head = self.head.load(atomic::Ordering::Acquire, &guard).unwrap(); // Spin until the ABA condition is solved. loop { // Load the lower bound for the usable entries. let low = head.used.start.load(atomic::Ordering::Relaxed); // Ensure that the usable range is non-empty. if low >= cmp::min(head.used.end.load(atomic::Ordering::Relaxed), SEG_SIZE) { // Since the range is either empty or out-of-segment, we must wait for the // responsible thread to insert a new node. break; } if head.used.start.compare_and_swap(low, low + 1, atomic::Ordering::Relaxed) == low { unsafe { // Read the cell. let ret = ptr::read((*head).data[low].get()); // Spin until the cell's data is valid. while!head.valid[low].load(atomic::Ordering::Acquire) {} // If all the elements in this segment have been dequeued, we must go to // the next segment. if low + 1 == SEG_SIZE { // Spin until the other thread, responsible for adding the new segment, // completes its job. loop { // Check if there is another node. if let Some(next) = head.next.load(atomic::Ordering::Acquire, &guard) { // Another node were found. As the current segment is dead, // update the head node. self.head.store_shared(Some(next), atomic::Ordering::Release); // Unlink the old head node. guard.unlinked(head); // Break to the return statement. break; } } } // Finally return. return Some(ret); } } } // Check if this is the last node and the segment is dead. if head.next.load(atomic::Ordering::Relaxed, &guard).is_none() { // No more nodes. return None; } } } } #[cfg(test)] mod test { const CONC_COUNT: i64 = 1000000; use super::*; use std::thread; use std::sync::Arc; #[test] fn queue_dequeue_1() { let q: SegQueue<i64> = SegQueue::new(); q.queue(37); assert_eq!(q.dequeue(), Some(37)); } #[test] fn queue_dequeue_2() { let q: SegQueue<i64> = SegQueue::new(); q.queue(37); q.queue(48); assert_eq!(q.dequeue(), Some(37)); assert_eq!(q.dequeue(), Some(48)); } #[test] fn queue_dequeue_many_seq() { let q: SegQueue<i64> = SegQueue::new(); for i in 0..200 { q.queue(i) } for i in 0..200 { assert_eq!(q.dequeue(), Some(i)); } } #[test] fn queue_dequeue_many_spsc() { let q: Arc<SegQueue<i64>> = Arc::new(SegQueue::new()); let qr = q.clone(); let join = thread::spawn(move || { let mut next = 0; while next < CONC_COUNT { if let Some(elem) = qr.dequeue() { assert_eq!(elem, next); next += 1; } } }); for i in 0..CONC_COUNT { q.queue(i) } join.join().unwrap(); } #[test] fn queue_dequeue_many_spmc() { fn recv(_t: i32, q: &SegQueue<i64>) { let mut cur = -1; for _i in 0..CONC_COUNT { if let Some(elem) = q.dequeue() { assert!(elem > cur); cur = elem; if cur == CONC_COUNT - 1 { break; } } } } let q: Arc<SegQueue<i64>> = Arc::new(SegQueue::new()); let mut v = Vec::new(); for i in 0..3 { let qr = q.clone(); v.push(thread::spawn(move || recv(i, &qr))); } v.push(thread::spawn(move || for i in 0..CONC_COUNT { q.queue(i); })); for i in v { i.join().unwrap(); } } #[test] fn qu
{ enum LR { Left(i64), Right(i64), } let q: Arc<SegQueue<LR>> = Arc::new(SegQueue::new()); let mut v = Vec::new(); for _t in 0..2 { let qc = q.clone(); v.push(thread::spawn(move || for i in CONC_COUNT - 1..CONC_COUNT { qc.queue(LR::Left(i)) })); let qc = q.clone(); v.push(thread::spawn(move || for i in CONC_COUNT - 1..CONC_COUNT { qc.queue(LR::Right(i)) })); let qc = q.clone(); v.push(thread::spawn(move || { let mut vl = vec![]; let mut vr = vec![]; for _i in 0..CONC_COUNT { match qc.dequeue() { Some(LR::Left(x)) => vl.push(x), Some(LR::Right(x)) => vr.push(x), _ => {} } } let mut vl2 = vl.clone(); let mut vr2 = vr.clone(); vl2.sort(); vr2.sort(); assert_eq!(vl, vl2); assert_eq!(vr, vr2); })); } for i in v { i.join().unwrap(); } } }
eue_dequeue_many_mpmc()
identifier_name
seg_queue.rs
//! Unrolled Michael—Scott queues. use std::cell::UnsafeCell; use std::ops::Range; use std::sync::atomic::{self, AtomicBool, AtomicUsize}; use std::{ptr, mem, fmt, cmp}; use epoch::{self, Atomic}; /// The maximal number of entries in a segment. const SEG_SIZE: usize = 32; /// A segment. /// /// Segments are like a slab of items stored all in one node, such that queing and dequing can be /// done faster. struct Segment<T> { /// The used entries in the segment. used: Range<AtomicUsize>, /// The data. data: [UnsafeCell<T>; SEG_SIZE], /// What entries contain valid data? valid: [AtomicBool; SEG_SIZE], /// The next node. next: Atomic<Segment<T>>, } impl<T> Default for Segment<T> { fn default() -> Segment<T> { Segment { used: AtomicUsize::new(0)..AtomicUsize::new(0), data: unsafe { mem::uninitialized() }, // FIXME: This is currently needed due to `AtomicBool` not implementing `Copy`. valid: unsafe { mem::zeroed() }, next: Atomic::null(), } } } impl<T> fmt::Debug for Segment<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Segment {{... }}") } } unsafe impl<T: Send> Sync for Segment<T> {} /// An faster, unrolled Michael-Scott queue. /// /// This queue, usable with any number of producers and consumers, stores so called segments /// (arrays of nodes) in order to be more lightweight. #[derive(Debug)] pub struct SegQueue<T> { /// The head segment. head: Atomic<Segment<T>>, /// The tail segment. tail: Atomic<Segment<T>>, } impl<T> SegQueue<T> { /// Create a new, empty queue. pub fn new() -> SegQueue<T> { // FIXME: This is ugly. // We start setting the two ends to null pointers. let queue = SegQueue { head: Atomic::null(), tail: Atomic::null(), }; // Construct the sentinel node with an empty segment. let sentinel = Box::new(Segment::default()); // Set the two ends to the sentinel node. let guard = epoch::pin(); let sentinel = queue.head.store_and_ref(sentinel, atomic::Ordering::Relaxed, &guard); queue.tail.store_shared(Some(sentinel), atomic::Ordering::Relaxed); queue } /// Push an element to the back of the queue. pub fn queue(&self, elem: T) { // Pin the epoch. let guard = epoch::pin(); loop { // Load the tail of the queue through the epoch. let tail = self.tail.load(atomic::Ordering::Acquire, &guard).unwrap(); // Check if the segment is full. if tail.used.end.load(atomic::Ordering::Relaxed) >= SEG_SIZE { // Segment full. Spin again (the thread exhausting the segment is responsible for // adding a new node). continue; } // Increment the used range to ensure that another thread doesn't write the cell, we'll // use soon. let i = tail.used.end.fetch_add(1, atomic::Ordering::Relaxed); // If and only if the increment range was within the segment size (i.e. that we did // actually get a spare cell), we will write the data. Otherwise, we will spin. if i >= SEG_SIZE { continue; } // Write that data. unsafe { // Obtain the cell. let cell = (*tail).data[i].get(); // Write the data into the cell. ptr::write(&mut *cell, elem); // Now that the cell is initialized, we can set the valid flag. tail.valid[i].store(true, atomic::Ordering::Release); // Handle end-of-segment. if i + 1 == SEG_SIZE { // As we noted before in this function, the thread which exhausts the segment // is responsible for inserting a new node, and that's us. // Append a new segment to the local tail. let tail = tail.next .store_and_ref(Box::new(Segment::default()), atomic::Ordering::Release, &guard); // Store the local tail to the queue. self.tail.store_shared(Some(tail), atomic::Ordering::Release); } // It was queued; break the loop. break; } } } /// Attempt to dequeue from the front. /// /// This returns `None` if the queue is observed to be empty. pub fn dequeue(&self) -> Option<T> { // Pin the epoch. let guard = epoch::pin(); // Spin until the other thread which is currently modfying the queue leaves it in a // dequeue-able state. loop { // Load the head through the guard. let head = self.head.load(atomic::Ordering::Acquire, &guard).unwrap(); // Spin until the ABA condition is solved. loop { // Load the lower bound for the usable entries. let low = head.used.start.load(atomic::Ordering::Relaxed); // Ensure that the usable range is non-empty. if low >= cmp::min(head.used.end.load(atomic::Ordering::Relaxed), SEG_SIZE) { // Since the range is either empty or out-of-segment, we must wait for the // responsible thread to insert a new node. break; } if head.used.start.compare_and_swap(low, low + 1, atomic::Ordering::Relaxed) == low { unsafe { // Read the cell. let ret = ptr::read((*head).data[low].get()); // Spin until the cell's data is valid. while!head.valid[low].load(atomic::Ordering::Acquire) {} // If all the elements in this segment have been dequeued, we must go to // the next segment. if low + 1 == SEG_SIZE { // Spin until the other thread, responsible for adding the new segment, // completes its job. loop { // Check if there is another node. if let Some(next) = head.next.load(atomic::Ordering::Acquire, &guard) { // Another node were found. As the current segment is dead, // update the head node. self.head.store_shared(Some(next), atomic::Ordering::Release); // Unlink the old head node. guard.unlinked(head); // Break to the return statement. break; } } } // Finally return. return Some(ret); } } } // Check if this is the last node and the segment is dead. if head.next.load(atomic::Ordering::Relaxed, &guard).is_none() { // No more nodes. return None; } } } } #[cfg(test)] mod test { const CONC_COUNT: i64 = 1000000; use super::*; use std::thread; use std::sync::Arc; #[test] fn queue_dequeue_1() { let q: SegQueue<i64> = SegQueue::new(); q.queue(37); assert_eq!(q.dequeue(), Some(37)); } #[test] fn queue_dequeue_2() { let q: SegQueue<i64> = SegQueue::new(); q.queue(37); q.queue(48); assert_eq!(q.dequeue(), Some(37)); assert_eq!(q.dequeue(), Some(48)); } #[test] fn queue_dequeue_many_seq() { let q: SegQueue<i64> = SegQueue::new(); for i in 0..200 { q.queue(i) } for i in 0..200 { assert_eq!(q.dequeue(), Some(i)); } } #[test] fn queue_dequeue_many_spsc() { let q: Arc<SegQueue<i64>> = Arc::new(SegQueue::new()); let qr = q.clone(); let join = thread::spawn(move || { let mut next = 0; while next < CONC_COUNT { if let Some(elem) = qr.dequeue() { assert_eq!(elem, next); next += 1; } } }); for i in 0..CONC_COUNT { q.queue(i) } join.join().unwrap(); } #[test] fn queue_dequeue_many_spmc() { fn recv(_t: i32, q: &SegQueue<i64>) { let mut cur = -1; for _i in 0..CONC_COUNT { if let Some(elem) = q.dequeue() { assert!(elem > cur); cur = elem; if cur == CONC_COUNT - 1 { break; } } } } let q: Arc<SegQueue<i64>> = Arc::new(SegQueue::new()); let mut v = Vec::new(); for i in 0..3 { let qr = q.clone(); v.push(thread::spawn(move || recv(i, &qr))); } v.push(thread::spawn(move || for i in 0..CONC_COUNT { q.queue(i); })); for i in v { i.join().unwrap(); } } #[test] fn queue_dequeue_many_mpmc() { enum LR { Left(i64), Right(i64), } let q: Arc<SegQueue<LR>> = Arc::new(SegQueue::new()); let mut v = Vec::new(); for _t in 0..2 { let qc = q.clone(); v.push(thread::spawn(move || for i in CONC_COUNT - 1..CONC_COUNT { qc.queue(LR::Left(i)) })); let qc = q.clone(); v.push(thread::spawn(move || for i in CONC_COUNT - 1..CONC_COUNT { qc.queue(LR::Right(i)) })); let qc = q.clone(); v.push(thread::spawn(move || { let mut vl = vec![]; let mut vr = vec![];
} } let mut vl2 = vl.clone(); let mut vr2 = vr.clone(); vl2.sort(); vr2.sort(); assert_eq!(vl, vl2); assert_eq!(vr, vr2); })); } for i in v { i.join().unwrap(); } } }
for _i in 0..CONC_COUNT { match qc.dequeue() { Some(LR::Left(x)) => vl.push(x), Some(LR::Right(x)) => vr.push(x), _ => {}
random_line_split
seg_queue.rs
//! Unrolled Michael—Scott queues. use std::cell::UnsafeCell; use std::ops::Range; use std::sync::atomic::{self, AtomicBool, AtomicUsize}; use std::{ptr, mem, fmt, cmp}; use epoch::{self, Atomic}; /// The maximal number of entries in a segment. const SEG_SIZE: usize = 32; /// A segment. /// /// Segments are like a slab of items stored all in one node, such that queing and dequing can be /// done faster. struct Segment<T> { /// The used entries in the segment. used: Range<AtomicUsize>, /// The data. data: [UnsafeCell<T>; SEG_SIZE], /// What entries contain valid data? valid: [AtomicBool; SEG_SIZE], /// The next node. next: Atomic<Segment<T>>, } impl<T> Default for Segment<T> { fn default() -> Segment<T> { Segment { used: AtomicUsize::new(0)..AtomicUsize::new(0), data: unsafe { mem::uninitialized() }, // FIXME: This is currently needed due to `AtomicBool` not implementing `Copy`. valid: unsafe { mem::zeroed() }, next: Atomic::null(), } } } impl<T> fmt::Debug for Segment<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Segment {{... }}") } } unsafe impl<T: Send> Sync for Segment<T> {} /// An faster, unrolled Michael-Scott queue. /// /// This queue, usable with any number of producers and consumers, stores so called segments /// (arrays of nodes) in order to be more lightweight. #[derive(Debug)] pub struct SegQueue<T> { /// The head segment. head: Atomic<Segment<T>>, /// The tail segment. tail: Atomic<Segment<T>>, } impl<T> SegQueue<T> { /// Create a new, empty queue. pub fn new() -> SegQueue<T> { // FIXME: This is ugly. // We start setting the two ends to null pointers. let queue = SegQueue { head: Atomic::null(), tail: Atomic::null(), }; // Construct the sentinel node with an empty segment. let sentinel = Box::new(Segment::default()); // Set the two ends to the sentinel node. let guard = epoch::pin(); let sentinel = queue.head.store_and_ref(sentinel, atomic::Ordering::Relaxed, &guard); queue.tail.store_shared(Some(sentinel), atomic::Ordering::Relaxed); queue } /// Push an element to the back of the queue. pub fn queue(&self, elem: T) { // Pin the epoch. let guard = epoch::pin(); loop { // Load the tail of the queue through the epoch. let tail = self.tail.load(atomic::Ordering::Acquire, &guard).unwrap(); // Check if the segment is full. if tail.used.end.load(atomic::Ordering::Relaxed) >= SEG_SIZE { // Segment full. Spin again (the thread exhausting the segment is responsible for // adding a new node). continue; } // Increment the used range to ensure that another thread doesn't write the cell, we'll // use soon. let i = tail.used.end.fetch_add(1, atomic::Ordering::Relaxed); // If and only if the increment range was within the segment size (i.e. that we did // actually get a spare cell), we will write the data. Otherwise, we will spin. if i >= SEG_SIZE {
// Write that data. unsafe { // Obtain the cell. let cell = (*tail).data[i].get(); // Write the data into the cell. ptr::write(&mut *cell, elem); // Now that the cell is initialized, we can set the valid flag. tail.valid[i].store(true, atomic::Ordering::Release); // Handle end-of-segment. if i + 1 == SEG_SIZE { // As we noted before in this function, the thread which exhausts the segment // is responsible for inserting a new node, and that's us. // Append a new segment to the local tail. let tail = tail.next .store_and_ref(Box::new(Segment::default()), atomic::Ordering::Release, &guard); // Store the local tail to the queue. self.tail.store_shared(Some(tail), atomic::Ordering::Release); } // It was queued; break the loop. break; } } } /// Attempt to dequeue from the front. /// /// This returns `None` if the queue is observed to be empty. pub fn dequeue(&self) -> Option<T> { // Pin the epoch. let guard = epoch::pin(); // Spin until the other thread which is currently modfying the queue leaves it in a // dequeue-able state. loop { // Load the head through the guard. let head = self.head.load(atomic::Ordering::Acquire, &guard).unwrap(); // Spin until the ABA condition is solved. loop { // Load the lower bound for the usable entries. let low = head.used.start.load(atomic::Ordering::Relaxed); // Ensure that the usable range is non-empty. if low >= cmp::min(head.used.end.load(atomic::Ordering::Relaxed), SEG_SIZE) { // Since the range is either empty or out-of-segment, we must wait for the // responsible thread to insert a new node. break; } if head.used.start.compare_and_swap(low, low + 1, atomic::Ordering::Relaxed) == low { unsafe { // Read the cell. let ret = ptr::read((*head).data[low].get()); // Spin until the cell's data is valid. while!head.valid[low].load(atomic::Ordering::Acquire) {} // If all the elements in this segment have been dequeued, we must go to // the next segment. if low + 1 == SEG_SIZE { // Spin until the other thread, responsible for adding the new segment, // completes its job. loop { // Check if there is another node. if let Some(next) = head.next.load(atomic::Ordering::Acquire, &guard) { // Another node were found. As the current segment is dead, // update the head node. self.head.store_shared(Some(next), atomic::Ordering::Release); // Unlink the old head node. guard.unlinked(head); // Break to the return statement. break; } } } // Finally return. return Some(ret); } } } // Check if this is the last node and the segment is dead. if head.next.load(atomic::Ordering::Relaxed, &guard).is_none() { // No more nodes. return None; } } } } #[cfg(test)] mod test { const CONC_COUNT: i64 = 1000000; use super::*; use std::thread; use std::sync::Arc; #[test] fn queue_dequeue_1() { let q: SegQueue<i64> = SegQueue::new(); q.queue(37); assert_eq!(q.dequeue(), Some(37)); } #[test] fn queue_dequeue_2() { let q: SegQueue<i64> = SegQueue::new(); q.queue(37); q.queue(48); assert_eq!(q.dequeue(), Some(37)); assert_eq!(q.dequeue(), Some(48)); } #[test] fn queue_dequeue_many_seq() { let q: SegQueue<i64> = SegQueue::new(); for i in 0..200 { q.queue(i) } for i in 0..200 { assert_eq!(q.dequeue(), Some(i)); } } #[test] fn queue_dequeue_many_spsc() { let q: Arc<SegQueue<i64>> = Arc::new(SegQueue::new()); let qr = q.clone(); let join = thread::spawn(move || { let mut next = 0; while next < CONC_COUNT { if let Some(elem) = qr.dequeue() { assert_eq!(elem, next); next += 1; } } }); for i in 0..CONC_COUNT { q.queue(i) } join.join().unwrap(); } #[test] fn queue_dequeue_many_spmc() { fn recv(_t: i32, q: &SegQueue<i64>) { let mut cur = -1; for _i in 0..CONC_COUNT { if let Some(elem) = q.dequeue() { assert!(elem > cur); cur = elem; if cur == CONC_COUNT - 1 { break; } } } } let q: Arc<SegQueue<i64>> = Arc::new(SegQueue::new()); let mut v = Vec::new(); for i in 0..3 { let qr = q.clone(); v.push(thread::spawn(move || recv(i, &qr))); } v.push(thread::spawn(move || for i in 0..CONC_COUNT { q.queue(i); })); for i in v { i.join().unwrap(); } } #[test] fn queue_dequeue_many_mpmc() { enum LR { Left(i64), Right(i64), } let q: Arc<SegQueue<LR>> = Arc::new(SegQueue::new()); let mut v = Vec::new(); for _t in 0..2 { let qc = q.clone(); v.push(thread::spawn(move || for i in CONC_COUNT - 1..CONC_COUNT { qc.queue(LR::Left(i)) })); let qc = q.clone(); v.push(thread::spawn(move || for i in CONC_COUNT - 1..CONC_COUNT { qc.queue(LR::Right(i)) })); let qc = q.clone(); v.push(thread::spawn(move || { let mut vl = vec![]; let mut vr = vec![]; for _i in 0..CONC_COUNT { match qc.dequeue() { Some(LR::Left(x)) => vl.push(x), Some(LR::Right(x)) => vr.push(x), _ => {} } } let mut vl2 = vl.clone(); let mut vr2 = vr.clone(); vl2.sort(); vr2.sort(); assert_eq!(vl, vl2); assert_eq!(vr, vr2); })); } for i in v { i.join().unwrap(); } } }
continue; }
conditional_block
term.rs
pub static GREEN: Color = 2u16; pub static YELLOW: Color = 3u16; pub static BLUE: Color = 4u16; pub static MAGENTA: Color = 5u16; pub static CYAN: Color = 6u16; pub static WHITE: Color = 7u16; pub static BRIGHT_BLACK: Color = 8u16; pub static BRIGHT_RED: Color = 9u16; pub static BRIGHT_GREEN: Color = 10u16; pub static BRIGHT_YELLOW: Color = 11u16; pub static BRIGHT_BLUE: Color = 12u16; pub static BRIGHT_MAGENTA: Color = 13u16; pub static BRIGHT_CYAN: Color = 14u16; pub static BRIGHT_WHITE: Color = 15u16; }
pub mod color { pub type Color = u16; pub static BLACK: Color = 0u16; pub static RED: Color = 1u16;
random_line_split
error.rs
pub use crate::api::naming::error as naming; pub use crate::rosxmlrpc::error as rosxmlrpc; pub use crate::rosxmlrpc::ResponseError; pub use crate::tcpros::error as tcpros; error_chain::error_chain! { foreign_links { Io(::std::io::Error); FromUTF8(::std::string::FromUtf8Error); Response(ResponseError); SigintOverride(::ctrlc::Error); } links { XmlRpc(rosxmlrpc::Error, rosxmlrpc::ErrorKind); Tcpros(tcpros::Error, tcpros::ErrorKind); Naming(naming::Error, naming::ErrorKind); } errors { Duplicate(t: String) { description("Could not add duplicate") display("Could not add duplicate {}", t) } MismatchedType(topic: String, actual_type: String, attempted_type:String) { description("Attempted to connect to topic with wrong message type") display("Attempted to connect to {} topic '{}' with message type {}", actual_type, topic, attempted_type) } MultipleInitialization { description("Cannot initialize multiple nodes") display("Cannot initialize multiple nodes") } TimeoutError BadYamlData(details: String) { description("Bad YAML data provided") display("Bad YAML data provided: {}", details) } CannotResolveName(name: String) { description("Failed to resolve name") display("Failed to resolve name: {}", name) } CommunicationIssue(details: String) { description("Failure in communication with ROS API") display("Failure in communication with ROS API: {}", details) } } }
error_chain::error_chain! { errors { SystemFail(message: String) { description("Failure to handle API call") display("Failure to handle API call: {}", message) } BadData(message: String) { description("Bad parameters provided in API call") display("Bad parameters provided in API call: {}", message) } } } }
pub mod api {
random_line_split
rest_api.rs
use db; use hyper::header::Authorization; use iron; use iron::prelude::*; use iron::status; use iron::status::Status; use router::Router; use serde_json; use std::error::Error; use std::fmt; use std::io::Read; use utils::json_response; pub fn rest_router() -> Router { let mut router = Router::new(); router.get( "/dashboard/:dashboard_name/tile/:tile_id", tile_get, "tile_get", ); router.post( "/dashboard/:dashboard_name/tile/:tile_id", tile_post, "tile_post", ); router } pub struct AuthToken; #[derive(Debug)] struct StringError(String); impl fmt::Display for StringError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(self, f) } } impl Error for StringError { fn description(&self) -> &str { &*self.0 } } /// Returns token stored in authorization header fn get_request_token(request: &Request) -> Result<String, IronError> { let token = request .headers .get::<Authorization<String>>() .ok_or_else(|| { IronError::new(StringError("Token missing".to_string()), status::Forbidden) })? .to_owned() .0; Ok(token) } impl iron::BeforeMiddleware for AuthToken { fn before(&self, request: &mut Request) -> IronResult<()> { match request.headers.get::<Authorization<String>>() { None => { Err(IronError::new( StringError("Token missing".to_string()), status::Forbidden, )) } Some(_) => Ok(()), } } } pub fn tile_get(req: &mut Request) -> IronResult<Response>
fn _tile_post(req: &mut Request) -> Result<(Status, String), Box<Error>> { let (dashboard_name, tile_id) = { let router = req.extensions.get::<Router>().unwrap(); ( router.find("dashboard_name").unwrap(), router.find("tile_id").unwrap(), ) }; let request_token = get_request_token(req)?; let db = db::Db::new()?; let dashboard = match db.get_dashboard(dashboard_name)? { None => return Ok((Status::NotFound, "Dashboard doesn't exist".to_string())), Some(v) => v, }; let dashboard_api_token = match dashboard.get_api_token() { None => { return Ok(( Status::InternalServerError, "Dashboard doens't have API Token, contact webpage administrators".to_string(), )) } Some(v) => v, }; if &request_token!= dashboard_api_token { return Ok((Status::Forbidden, "Tokens unmatched".to_string())); } let mut json = String::new(); if let Err(e) = req.body.read_to_string(&mut json) { return Ok(( Status::InternalServerError, format!("Reading payload FAILED ({})", e), )); } // TODO: delegate this check to modeule db, this needs better error // propagation. Now it relays on Box which is hard to inspect. Replace it // with own custom error like DbError or something if let Err(e) = serde_json::from_str::<serde_json::Value>(&json) { return Ok(( Status::BadRequest, format!("Unable to unjson payload: ({})", e), )); } db.upsert_tile(dashboard_name, tile_id, &json)?; Ok((Status::Created, "".to_string())) } pub fn tile_post(req: &mut Request) -> IronResult<Response> { let (status, msg) = match _tile_post(req) { Err(_) => return json_response(Status::InternalServerError, "We're working on fix"), Ok(v) => v, }; json_response(status, &msg) }
{ let (dashboard_name, tile_id) = { let router = req.extensions.get::<Router>().unwrap(); ( router.find("dashboard_name").unwrap(), router.find("tile_id").unwrap(), ) }; let db = match db::Db::new() { Err(e) => return json_response(Status::InternalServerError, &e.to_string()), Ok(v) => v, }; match db.get_tile(dashboard_name, tile_id) { Err(e) => json_response(Status::InternalServerError, &e.to_string()), Ok(None) => json_response(Status::NotFound, ""), Ok(Some(val)) => json_response(Status::Ok, val.as_str()), } }
identifier_body
rest_api.rs
use db; use hyper::header::Authorization; use iron; use iron::prelude::*; use iron::status; use iron::status::Status; use router::Router; use serde_json; use std::error::Error; use std::fmt; use std::io::Read; use utils::json_response; pub fn rest_router() -> Router { let mut router = Router::new(); router.get( "/dashboard/:dashboard_name/tile/:tile_id", tile_get, "tile_get", ); router.post( "/dashboard/:dashboard_name/tile/:tile_id", tile_post, "tile_post", ); router } pub struct AuthToken; #[derive(Debug)] struct StringError(String); impl fmt::Display for StringError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(self, f) } } impl Error for StringError { fn description(&self) -> &str { &*self.0 } } /// Returns token stored in authorization header fn get_request_token(request: &Request) -> Result<String, IronError> { let token = request .headers .get::<Authorization<String>>() .ok_or_else(|| { IronError::new(StringError("Token missing".to_string()), status::Forbidden) })? .to_owned() .0; Ok(token) } impl iron::BeforeMiddleware for AuthToken { fn before(&self, request: &mut Request) -> IronResult<()> { match request.headers.get::<Authorization<String>>() { None => { Err(IronError::new( StringError("Token missing".to_string()), status::Forbidden, )) } Some(_) => Ok(()), } } } pub fn
(req: &mut Request) -> IronResult<Response> { let (dashboard_name, tile_id) = { let router = req.extensions.get::<Router>().unwrap(); ( router.find("dashboard_name").unwrap(), router.find("tile_id").unwrap(), ) }; let db = match db::Db::new() { Err(e) => return json_response(Status::InternalServerError, &e.to_string()), Ok(v) => v, }; match db.get_tile(dashboard_name, tile_id) { Err(e) => json_response(Status::InternalServerError, &e.to_string()), Ok(None) => json_response(Status::NotFound, ""), Ok(Some(val)) => json_response(Status::Ok, val.as_str()), } } fn _tile_post(req: &mut Request) -> Result<(Status, String), Box<Error>> { let (dashboard_name, tile_id) = { let router = req.extensions.get::<Router>().unwrap(); ( router.find("dashboard_name").unwrap(), router.find("tile_id").unwrap(), ) }; let request_token = get_request_token(req)?; let db = db::Db::new()?; let dashboard = match db.get_dashboard(dashboard_name)? { None => return Ok((Status::NotFound, "Dashboard doesn't exist".to_string())), Some(v) => v, }; let dashboard_api_token = match dashboard.get_api_token() { None => { return Ok(( Status::InternalServerError, "Dashboard doens't have API Token, contact webpage administrators".to_string(), )) } Some(v) => v, }; if &request_token!= dashboard_api_token { return Ok((Status::Forbidden, "Tokens unmatched".to_string())); } let mut json = String::new(); if let Err(e) = req.body.read_to_string(&mut json) { return Ok(( Status::InternalServerError, format!("Reading payload FAILED ({})", e), )); } // TODO: delegate this check to modeule db, this needs better error // propagation. Now it relays on Box which is hard to inspect. Replace it // with own custom error like DbError or something if let Err(e) = serde_json::from_str::<serde_json::Value>(&json) { return Ok(( Status::BadRequest, format!("Unable to unjson payload: ({})", e), )); } db.upsert_tile(dashboard_name, tile_id, &json)?; Ok((Status::Created, "".to_string())) } pub fn tile_post(req: &mut Request) -> IronResult<Response> { let (status, msg) = match _tile_post(req) { Err(_) => return json_response(Status::InternalServerError, "We're working on fix"), Ok(v) => v, }; json_response(status, &msg) }
tile_get
identifier_name
rest_api.rs
use db; use hyper::header::Authorization; use iron; use iron::prelude::*; use iron::status; use iron::status::Status; use router::Router; use serde_json; use std::error::Error; use std::fmt; use std::io::Read; use utils::json_response; pub fn rest_router() -> Router { let mut router = Router::new(); router.get( "/dashboard/:dashboard_name/tile/:tile_id", tile_get, "tile_get", ); router.post( "/dashboard/:dashboard_name/tile/:tile_id", tile_post, "tile_post", ); router } pub struct AuthToken; #[derive(Debug)] struct StringError(String); impl fmt::Display for StringError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(self, f) } } impl Error for StringError { fn description(&self) -> &str { &*self.0 } } /// Returns token stored in authorization header fn get_request_token(request: &Request) -> Result<String, IronError> { let token = request .headers .get::<Authorization<String>>() .ok_or_else(|| { IronError::new(StringError("Token missing".to_string()), status::Forbidden) })? .to_owned() .0; Ok(token) } impl iron::BeforeMiddleware for AuthToken { fn before(&self, request: &mut Request) -> IronResult<()> { match request.headers.get::<Authorization<String>>() { None => { Err(IronError::new( StringError("Token missing".to_string()),
} } } pub fn tile_get(req: &mut Request) -> IronResult<Response> { let (dashboard_name, tile_id) = { let router = req.extensions.get::<Router>().unwrap(); ( router.find("dashboard_name").unwrap(), router.find("tile_id").unwrap(), ) }; let db = match db::Db::new() { Err(e) => return json_response(Status::InternalServerError, &e.to_string()), Ok(v) => v, }; match db.get_tile(dashboard_name, tile_id) { Err(e) => json_response(Status::InternalServerError, &e.to_string()), Ok(None) => json_response(Status::NotFound, ""), Ok(Some(val)) => json_response(Status::Ok, val.as_str()), } } fn _tile_post(req: &mut Request) -> Result<(Status, String), Box<Error>> { let (dashboard_name, tile_id) = { let router = req.extensions.get::<Router>().unwrap(); ( router.find("dashboard_name").unwrap(), router.find("tile_id").unwrap(), ) }; let request_token = get_request_token(req)?; let db = db::Db::new()?; let dashboard = match db.get_dashboard(dashboard_name)? { None => return Ok((Status::NotFound, "Dashboard doesn't exist".to_string())), Some(v) => v, }; let dashboard_api_token = match dashboard.get_api_token() { None => { return Ok(( Status::InternalServerError, "Dashboard doens't have API Token, contact webpage administrators".to_string(), )) } Some(v) => v, }; if &request_token!= dashboard_api_token { return Ok((Status::Forbidden, "Tokens unmatched".to_string())); } let mut json = String::new(); if let Err(e) = req.body.read_to_string(&mut json) { return Ok(( Status::InternalServerError, format!("Reading payload FAILED ({})", e), )); } // TODO: delegate this check to modeule db, this needs better error // propagation. Now it relays on Box which is hard to inspect. Replace it // with own custom error like DbError or something if let Err(e) = serde_json::from_str::<serde_json::Value>(&json) { return Ok(( Status::BadRequest, format!("Unable to unjson payload: ({})", e), )); } db.upsert_tile(dashboard_name, tile_id, &json)?; Ok((Status::Created, "".to_string())) } pub fn tile_post(req: &mut Request) -> IronResult<Response> { let (status, msg) = match _tile_post(req) { Err(_) => return json_response(Status::InternalServerError, "We're working on fix"), Ok(v) => v, }; json_response(status, &msg) }
status::Forbidden, )) } Some(_) => Ok(()),
random_line_split
add.rs
use anyhow::Result; use clap::{App, ArgMatches}; use rhq::Workspace; use std::{env, path::PathBuf}; #[derive(Debug)] pub struct AddCommand { paths: Option<Vec<PathBuf>>, verbose: bool, } impl AddCommand { pub fn
<'a, 'b: 'a>(app: App<'a, 'b>) -> App<'a, 'b> { app.about("Add existed repositories into management") .arg_from_usage("[paths]... 'Location of local repositories'") .arg_from_usage("-v, --verbose 'Use verbose output'") } pub fn from_matches(m: &ArgMatches) -> AddCommand { AddCommand { paths: m.values_of("paths").map(|s| s.map(PathBuf::from).collect()), verbose: m.is_present("verbose"), } } pub fn run(self) -> Result<()> { let paths = self .paths .unwrap_or_else(|| vec![env::current_dir().expect("env::current_dir()")]); let mut workspace = Workspace::new()?.verbose_output(self.verbose); for path in paths { workspace.add_repository_if_exists(&path)?; } workspace.save_cache()?; Ok(()) } }
app
identifier_name
add.rs
use anyhow::Result; use clap::{App, ArgMatches}; use rhq::Workspace; use std::{env, path::PathBuf}; #[derive(Debug)] pub struct AddCommand { paths: Option<Vec<PathBuf>>, verbose: bool, } impl AddCommand { pub fn app<'a, 'b: 'a>(app: App<'a, 'b>) -> App<'a, 'b> { app.about("Add existed repositories into management") .arg_from_usage("[paths]... 'Location of local repositories'") .arg_from_usage("-v, --verbose 'Use verbose output'") } pub fn from_matches(m: &ArgMatches) -> AddCommand { AddCommand { paths: m.values_of("paths").map(|s| s.map(PathBuf::from).collect()), verbose: m.is_present("verbose"), } }
let mut workspace = Workspace::new()?.verbose_output(self.verbose); for path in paths { workspace.add_repository_if_exists(&path)?; } workspace.save_cache()?; Ok(()) } }
pub fn run(self) -> Result<()> { let paths = self .paths .unwrap_or_else(|| vec![env::current_dir().expect("env::current_dir()")]);
random_line_split
add.rs
use anyhow::Result; use clap::{App, ArgMatches}; use rhq::Workspace; use std::{env, path::PathBuf}; #[derive(Debug)] pub struct AddCommand { paths: Option<Vec<PathBuf>>, verbose: bool, } impl AddCommand { pub fn app<'a, 'b: 'a>(app: App<'a, 'b>) -> App<'a, 'b> { app.about("Add existed repositories into management") .arg_from_usage("[paths]... 'Location of local repositories'") .arg_from_usage("-v, --verbose 'Use verbose output'") } pub fn from_matches(m: &ArgMatches) -> AddCommand
pub fn run(self) -> Result<()> { let paths = self .paths .unwrap_or_else(|| vec![env::current_dir().expect("env::current_dir()")]); let mut workspace = Workspace::new()?.verbose_output(self.verbose); for path in paths { workspace.add_repository_if_exists(&path)?; } workspace.save_cache()?; Ok(()) } }
{ AddCommand { paths: m.values_of("paths").map(|s| s.map(PathBuf::from).collect()), verbose: m.is_present("verbose"), } }
identifier_body
raytracer_pinhole.rs
#![feature(box_syntax)] use std::io::prelude::*; use std::fs::File; use std::ops::{Add, Sub, Mul}; use std::num::Float; use std::default::Default; #[derive(Debug, Copy, Clone, Default)] struct Vector { x: f64, y: f64, z: f64 } #[derive(Debug, Copy, Clone, Default)] struct Ray { o: Vector, d: Vector } #[derive(Debug, Clone, Default)] struct Sphere { radius: f64, position: Vector, color: Vector, } #[derive(Debug, Default)] struct Camera { eye: Ray, // origin and direction of cam // Field of view: right: Vector, // right vector up: Vector, // up vector } trait Shape { fn intersect(self, r: Ray) -> f64; } trait ShapeRef { fn color(self, r: &Ray, t: f64) -> Vector; } impl Shape for Sphere { fn intersect(self, r: Ray) -> f64 { // Solve t^2*d.d + 2*t*(o-p).d + (o-p).(o-p)-R^2 = 0 let eps = 1e-4; let op = &self.position - &r.o; let b = op.dot(&r.d); let mut det = b * b - op.dot(&op) + self.radius * self.radius; if det < 0.0 { return 0.0; } else
if (b - det) > eps { return b-det; } if (b + det) > eps { return b+det; } return 0.0; } } static LIGHT: Ray = Ray { o: Vector{x: 0.0, y: 0.0, z: 0.0 }, d: Vector{x: 0.0, y: 0.0, z: 1.0 } }; impl<'a> ShapeRef for &'a Sphere { fn color(self, r: &Ray, t: f64) -> Vector { let color: Vector = Vector{x: 0.75, y: 0.75, z: 0.75}; let intersection = r.d.smul(t); let surface_normal = (&(&r.o + &intersection) - &self.position).norm(); let diffuse_factor = surface_normal.dot( &(&LIGHT.o + &LIGHT.d).norm() ) ; color.smul(diffuse_factor) } } impl<'a> Add for &'a Vector { type Output = Vector; fn add(self, other: &'a Vector) -> Vector { Vector {x: self.x + other.x, y: self.y + other.y, z: self.z + other.z} } } impl<'a> Sub for &'a Vector { type Output = Vector; fn sub(self, other: &'a Vector) -> Vector { Vector {x: self.x - other.x, y: self.y - other.y, z: self.z - other.z} } } impl<'a> Mul for &'a Vector { type Output = Vector; fn mul(self, other: &'a Vector) -> Vector { Vector {x: self.x * other.x, y: self.y * other.y, z: self.z * other.z} } } trait VectorOps { fn smul(self, rhs: f64) -> Vector; fn norm(self) -> Vector; fn cross(self, rhs: Vector) -> Vector; fn dot(&self, rhs: &Vector) -> f64; } impl VectorOps for Vector { fn smul(self, other: f64) -> Vector { Vector {x: self.x * other, y: self.y * other, z: self.z * other} } fn norm(self) -> Vector { let normalize = 1.0 / (self.x * self.x + self.y * self.y + self.z * self.z).sqrt() ; self.smul( normalize ) } fn cross(self, b: Vector) -> Vector { Vector{x: self.y * b.z - self.z * b.y, y: self.z * b.x - self.x * b.z, z: self.x * b.y - self.y * b.x} } fn dot(&self, other: &Vector) -> f64 { (*self).x * (*other).x + (*self).y * (*other).y + (*self).z * (*other).z } } fn clamp(x: f64) -> f64 { if x < 0.0 { return 0.0; } if x > 1.0 { return 1.0; } x } fn to_int(x: f64) -> i64 { (clamp(x).powf(1.0 / 2.2) * 255.0 + 0.5) as i64 } fn intersect(r: Ray, t: &mut f64, id: &mut usize) -> bool { let inf = 10e20f64; *t = inf; for (i, sphere) in SPHERES.iter().enumerate() { let d: f64 = sphere.clone().intersect(r.clone()); if d!= 0.0 && d < *t { *t = d; *id = i; } } return *t < inf; } static SPHERES: [Sphere; 1] = [ Sphere{ radius: 1.41, position: Vector{ x:0.0, y: 0.0, z: -1.0}, color: Vector{x: 0.25, y: 0.50, z: 0.75} }, ]; fn get_ray(cam: &Camera, a: usize, b: usize) -> Ray { let w = cam.eye.d.norm().smul(-1.0); let u = cam.up.cross(w).norm(); let v = w.cross(u); let u0 = -1.0; let v0 = -1.0; let u1 = 1.0; let v1 = 1.0; let d = 1.0; let across = u.smul(u1-u0); let up = v.smul(v1-v0); let an = (a as f64) / HEIGHT as f64; let bn = (b as f64) / WIDTH as f64; let corner = &(&(&cam.eye.o + &u.smul(u0)) + &v.smul(v0)) - &w.smul(d); let target = &( &corner + &across.smul(an)) + &up.smul(bn); Ray{o: cam.eye.o, d: (&target-&cam.eye.o).norm()} } const WIDTH: usize = 500; const HEIGHT: usize = 500; fn main() { println!("Raytracing..."); let mut cam: Camera = Default::default(); cam.eye.o = Vector {x: 0.0, y: 0.0, z: 1.0}; cam.eye.d = Vector {x: 0.0, y: 0.0, z: -1.0}; cam.up = Vector{x: 0.0, y: 1.0, z: 0.0}; let mut output = box [[Vector{x: 0.0, y: 0.0, z: 0.0}; WIDTH]; HEIGHT]; for i in 0..HEIGHT { for j in 0..WIDTH { let ray: Ray = get_ray(&cam, i, j); let mut t: f64 = 0.0; let mut id: usize = 0; if intersect(ray, &mut t, &mut id) { output[i][j] = (&SPHERES[id]).color(&ray, t); } else { output[i][j].x = 0.25; output[i][j].y = 0.25; output[i][j].z = 0.25; } } } println!("Writing Image..."); let mut f = File::create("image.ppm").unwrap(); f.write_all( format!("P3\n{} {}\n{}\n", WIDTH, HEIGHT, 255).as_bytes() ).ok(); for i in 0..HEIGHT { for j in 0..WIDTH { f.write_all( format!("{} {} {} ", to_int(output[i][j].x), to_int(output[i][j].y), to_int(output[i][j].z)).as_bytes() ).ok(); } } }
{ det = det.sqrt(); }
conditional_block
raytracer_pinhole.rs
#![feature(box_syntax)] use std::io::prelude::*; use std::fs::File; use std::ops::{Add, Sub, Mul}; use std::num::Float; use std::default::Default; #[derive(Debug, Copy, Clone, Default)] struct Vector { x: f64, y: f64, z: f64 } #[derive(Debug, Copy, Clone, Default)] struct Ray { o: Vector, d: Vector } #[derive(Debug, Clone, Default)] struct Sphere { radius: f64, position: Vector, color: Vector, } #[derive(Debug, Default)] struct Camera { eye: Ray, // origin and direction of cam // Field of view: right: Vector, // right vector up: Vector, // up vector } trait Shape { fn intersect(self, r: Ray) -> f64; } trait ShapeRef { fn color(self, r: &Ray, t: f64) -> Vector; } impl Shape for Sphere { fn intersect(self, r: Ray) -> f64 { // Solve t^2*d.d + 2*t*(o-p).d + (o-p).(o-p)-R^2 = 0 let eps = 1e-4; let op = &self.position - &r.o; let b = op.dot(&r.d); let mut det = b * b - op.dot(&op) + self.radius * self.radius; if det < 0.0 { return 0.0; } else { det = det.sqrt(); } if (b - det) > eps { return b-det; } if (b + det) > eps { return b+det; } return 0.0; } } static LIGHT: Ray = Ray { o: Vector{x: 0.0, y: 0.0, z: 0.0 }, d: Vector{x: 0.0, y: 0.0, z: 1.0 } }; impl<'a> ShapeRef for &'a Sphere { fn color(self, r: &Ray, t: f64) -> Vector { let color: Vector = Vector{x: 0.75, y: 0.75, z: 0.75}; let intersection = r.d.smul(t); let surface_normal = (&(&r.o + &intersection) - &self.position).norm(); let diffuse_factor = surface_normal.dot( &(&LIGHT.o + &LIGHT.d).norm() ) ; color.smul(diffuse_factor) } } impl<'a> Add for &'a Vector { type Output = Vector; fn add(self, other: &'a Vector) -> Vector { Vector {x: self.x + other.x, y: self.y + other.y, z: self.z + other.z} } } impl<'a> Sub for &'a Vector { type Output = Vector; fn sub(self, other: &'a Vector) -> Vector { Vector {x: self.x - other.x, y: self.y - other.y, z: self.z - other.z} } } impl<'a> Mul for &'a Vector { type Output = Vector; fn mul(self, other: &'a Vector) -> Vector { Vector {x: self.x * other.x, y: self.y * other.y, z: self.z * other.z} } } trait VectorOps { fn smul(self, rhs: f64) -> Vector; fn norm(self) -> Vector; fn cross(self, rhs: Vector) -> Vector; fn dot(&self, rhs: &Vector) -> f64; } impl VectorOps for Vector { fn smul(self, other: f64) -> Vector { Vector {x: self.x * other, y: self.y * other, z: self.z * other} } fn norm(self) -> Vector { let normalize = 1.0 / (self.x * self.x + self.y * self.y + self.z * self.z).sqrt() ; self.smul( normalize ) } fn
(self, b: Vector) -> Vector { Vector{x: self.y * b.z - self.z * b.y, y: self.z * b.x - self.x * b.z, z: self.x * b.y - self.y * b.x} } fn dot(&self, other: &Vector) -> f64 { (*self).x * (*other).x + (*self).y * (*other).y + (*self).z * (*other).z } } fn clamp(x: f64) -> f64 { if x < 0.0 { return 0.0; } if x > 1.0 { return 1.0; } x } fn to_int(x: f64) -> i64 { (clamp(x).powf(1.0 / 2.2) * 255.0 + 0.5) as i64 } fn intersect(r: Ray, t: &mut f64, id: &mut usize) -> bool { let inf = 10e20f64; *t = inf; for (i, sphere) in SPHERES.iter().enumerate() { let d: f64 = sphere.clone().intersect(r.clone()); if d!= 0.0 && d < *t { *t = d; *id = i; } } return *t < inf; } static SPHERES: [Sphere; 1] = [ Sphere{ radius: 1.41, position: Vector{ x:0.0, y: 0.0, z: -1.0}, color: Vector{x: 0.25, y: 0.50, z: 0.75} }, ]; fn get_ray(cam: &Camera, a: usize, b: usize) -> Ray { let w = cam.eye.d.norm().smul(-1.0); let u = cam.up.cross(w).norm(); let v = w.cross(u); let u0 = -1.0; let v0 = -1.0; let u1 = 1.0; let v1 = 1.0; let d = 1.0; let across = u.smul(u1-u0); let up = v.smul(v1-v0); let an = (a as f64) / HEIGHT as f64; let bn = (b as f64) / WIDTH as f64; let corner = &(&(&cam.eye.o + &u.smul(u0)) + &v.smul(v0)) - &w.smul(d); let target = &( &corner + &across.smul(an)) + &up.smul(bn); Ray{o: cam.eye.o, d: (&target-&cam.eye.o).norm()} } const WIDTH: usize = 500; const HEIGHT: usize = 500; fn main() { println!("Raytracing..."); let mut cam: Camera = Default::default(); cam.eye.o = Vector {x: 0.0, y: 0.0, z: 1.0}; cam.eye.d = Vector {x: 0.0, y: 0.0, z: -1.0}; cam.up = Vector{x: 0.0, y: 1.0, z: 0.0}; let mut output = box [[Vector{x: 0.0, y: 0.0, z: 0.0}; WIDTH]; HEIGHT]; for i in 0..HEIGHT { for j in 0..WIDTH { let ray: Ray = get_ray(&cam, i, j); let mut t: f64 = 0.0; let mut id: usize = 0; if intersect(ray, &mut t, &mut id) { output[i][j] = (&SPHERES[id]).color(&ray, t); } else { output[i][j].x = 0.25; output[i][j].y = 0.25; output[i][j].z = 0.25; } } } println!("Writing Image..."); let mut f = File::create("image.ppm").unwrap(); f.write_all( format!("P3\n{} {}\n{}\n", WIDTH, HEIGHT, 255).as_bytes() ).ok(); for i in 0..HEIGHT { for j in 0..WIDTH { f.write_all( format!("{} {} {} ", to_int(output[i][j].x), to_int(output[i][j].y), to_int(output[i][j].z)).as_bytes() ).ok(); } } }
cross
identifier_name
raytracer_pinhole.rs
#![feature(box_syntax)] use std::io::prelude::*; use std::fs::File; use std::ops::{Add, Sub, Mul}; use std::num::Float; use std::default::Default; #[derive(Debug, Copy, Clone, Default)] struct Vector { x: f64, y: f64, z: f64 } #[derive(Debug, Copy, Clone, Default)] struct Ray { o: Vector, d: Vector } #[derive(Debug, Clone, Default)] struct Sphere { radius: f64, position: Vector, color: Vector, } #[derive(Debug, Default)] struct Camera { eye: Ray, // origin and direction of cam // Field of view: right: Vector, // right vector up: Vector, // up vector } trait Shape { fn intersect(self, r: Ray) -> f64; } trait ShapeRef { fn color(self, r: &Ray, t: f64) -> Vector; } impl Shape for Sphere { fn intersect(self, r: Ray) -> f64 { // Solve t^2*d.d + 2*t*(o-p).d + (o-p).(o-p)-R^2 = 0 let eps = 1e-4; let op = &self.position - &r.o; let b = op.dot(&r.d); let mut det = b * b - op.dot(&op) + self.radius * self.radius; if det < 0.0 { return 0.0; } else { det = det.sqrt(); } if (b - det) > eps { return b-det; } if (b + det) > eps { return b+det; } return 0.0; } } static LIGHT: Ray = Ray { o: Vector{x: 0.0, y: 0.0, z: 0.0 }, d: Vector{x: 0.0, y: 0.0, z: 1.0 } }; impl<'a> ShapeRef for &'a Sphere { fn color(self, r: &Ray, t: f64) -> Vector { let color: Vector = Vector{x: 0.75, y: 0.75, z: 0.75}; let intersection = r.d.smul(t); let surface_normal = (&(&r.o + &intersection) - &self.position).norm(); let diffuse_factor = surface_normal.dot( &(&LIGHT.o + &LIGHT.d).norm() ) ; color.smul(diffuse_factor) } } impl<'a> Add for &'a Vector { type Output = Vector; fn add(self, other: &'a Vector) -> Vector { Vector {x: self.x + other.x, y: self.y + other.y, z: self.z + other.z} } } impl<'a> Sub for &'a Vector { type Output = Vector; fn sub(self, other: &'a Vector) -> Vector { Vector {x: self.x - other.x, y: self.y - other.y, z: self.z - other.z} } } impl<'a> Mul for &'a Vector { type Output = Vector; fn mul(self, other: &'a Vector) -> Vector { Vector {x: self.x * other.x, y: self.y * other.y, z: self.z * other.z} } } trait VectorOps { fn smul(self, rhs: f64) -> Vector; fn norm(self) -> Vector; fn cross(self, rhs: Vector) -> Vector; fn dot(&self, rhs: &Vector) -> f64; } impl VectorOps for Vector { fn smul(self, other: f64) -> Vector { Vector {x: self.x * other, y: self.y * other, z: self.z * other} } fn norm(self) -> Vector { let normalize = 1.0 / (self.x * self.x + self.y * self.y + self.z * self.z).sqrt() ; self.smul( normalize ) } fn cross(self, b: Vector) -> Vector { Vector{x: self.y * b.z - self.z * b.y, y: self.z * b.x - self.x * b.z, z: self.x * b.y - self.y * b.x} } fn dot(&self, other: &Vector) -> f64 { (*self).x * (*other).x + (*self).y * (*other).y + (*self).z * (*other).z } } fn clamp(x: f64) -> f64 { if x < 0.0 { return 0.0; } if x > 1.0 { return 1.0; } x } fn to_int(x: f64) -> i64 { (clamp(x).powf(1.0 / 2.2) * 255.0 + 0.5) as i64 } fn intersect(r: Ray, t: &mut f64, id: &mut usize) -> bool { let inf = 10e20f64; *t = inf; for (i, sphere) in SPHERES.iter().enumerate() { let d: f64 = sphere.clone().intersect(r.clone()); if d!= 0.0 && d < *t { *t = d; *id = i; } } return *t < inf; } static SPHERES: [Sphere; 1] = [ Sphere{ radius: 1.41, position: Vector{ x:0.0, y: 0.0, z: -1.0}, color: Vector{x: 0.25, y: 0.50, z: 0.75} }, ]; fn get_ray(cam: &Camera, a: usize, b: usize) -> Ray { let w = cam.eye.d.norm().smul(-1.0); let u = cam.up.cross(w).norm(); let v = w.cross(u); let u0 = -1.0; let v0 = -1.0; let u1 = 1.0; let v1 = 1.0; let d = 1.0; let across = u.smul(u1-u0); let up = v.smul(v1-v0); let an = (a as f64) / HEIGHT as f64; let bn = (b as f64) / WIDTH as f64; let corner = &(&(&cam.eye.o + &u.smul(u0)) + &v.smul(v0)) - &w.smul(d); let target = &( &corner + &across.smul(an)) + &up.smul(bn); Ray{o: cam.eye.o, d: (&target-&cam.eye.o).norm()} } const WIDTH: usize = 500;
let mut cam: Camera = Default::default(); cam.eye.o = Vector {x: 0.0, y: 0.0, z: 1.0}; cam.eye.d = Vector {x: 0.0, y: 0.0, z: -1.0}; cam.up = Vector{x: 0.0, y: 1.0, z: 0.0}; let mut output = box [[Vector{x: 0.0, y: 0.0, z: 0.0}; WIDTH]; HEIGHT]; for i in 0..HEIGHT { for j in 0..WIDTH { let ray: Ray = get_ray(&cam, i, j); let mut t: f64 = 0.0; let mut id: usize = 0; if intersect(ray, &mut t, &mut id) { output[i][j] = (&SPHERES[id]).color(&ray, t); } else { output[i][j].x = 0.25; output[i][j].y = 0.25; output[i][j].z = 0.25; } } } println!("Writing Image..."); let mut f = File::create("image.ppm").unwrap(); f.write_all( format!("P3\n{} {}\n{}\n", WIDTH, HEIGHT, 255).as_bytes() ).ok(); for i in 0..HEIGHT { for j in 0..WIDTH { f.write_all( format!("{} {} {} ", to_int(output[i][j].x), to_int(output[i][j].y), to_int(output[i][j].z)).as_bytes() ).ok(); } } }
const HEIGHT: usize = 500; fn main() { println!("Raytracing...");
random_line_split
editfns.rs
//! Lisp functions pertaining to editing. use libc::{c_uchar, ptrdiff_t}; use remacs_macros::lisp_fn; use remacs_sys::{EmacsInt, Fadd_text_properties, Fcons, Fcopy_sequence, Finsert_char, Qinteger_or_marker_p, Qmark_inactive, Qnil}; use remacs_sys::{buf_charpos_to_bytepos, globals, set_point_both}; use buffers::get_buffer; use lisp::LispObject; use lisp::defsubr; use marker::{marker_position, set_point_from_marker}; use multibyte::raw_byte_codepoint; use threads::ThreadState; use util::clip_to_bounds; /// Return value of point, as an integer. /// Beginning of buffer is position (point-min). #[lisp_fn] pub fn point() -> LispObject { let buffer_ref = ThreadState::current_buffer(); LispObject::from_natnum(buffer_ref.pt as EmacsInt) } /// Return the number of characters in the current buffer. /// If BUFFER is not nil, return the number of characters in that buffer /// instead. /// /// This does not take narrowing into account; to count the number of /// characters in the accessible portion of the current buffer, use /// `(- (point-max) (point-min))', and to count the number of characters /// in some other BUFFER, use /// `(with-current-buffer BUFFER (- (point-max) (point-min)))'. #[lisp_fn(min = "0")] pub fn buffer_size(buffer: LispObject) -> LispObject { let buffer_ref = if buffer.is_not_nil() { get_buffer(buffer).as_buffer_or_error() } else { ThreadState::current_buffer() }; LispObject::from_natnum((buffer_ref.z() - buffer_ref.beg()) as EmacsInt) } /// Return t if point is at the end of the buffer. /// If the buffer is narrowed, this means the end of the narrowed part. #[lisp_fn] pub fn eobp() -> LispObject { let buffer_ref = ThreadState::current_buffer(); LispObject::from_bool(buffer_ref.zv() == buffer_ref.pt) } /// Return t if point is at the beginning of the buffer. If the /// buffer is narrowed, this means the beginning of the narrowed part. #[lisp_fn] pub fn bobp() -> LispObject { let buffer_ref = ThreadState::current_buffer(); LispObject::from_bool(buffer_ref.pt == buffer_ref.begv) } /// Return t if point is at the beginning of a line. #[lisp_fn] pub fn bolp() -> LispObject { let buffer_ref = ThreadState::current_buffer(); LispObject::from_bool( buffer_ref.pt == buffer_ref.begv || buffer_ref.fetch_byte(buffer_ref.pt_byte - 1) == b'\n', ) } /// Return t if point is at the end of a line. /// `End of a line' includes point being at the end of the buffer. #[lisp_fn] pub fn eolp() -> LispObject { let buffer_ref = ThreadState::current_buffer(); LispObject::from_bool( buffer_ref.pt == buffer_ref.zv() || buffer_ref.fetch_byte(buffer_ref.pt_byte) == b'\n', ) } /// Return the start or end position of the region. /// BEGINNINGP means return the start. /// If there is no region active, signal an error. fn region_limit(beginningp: bool) -> LispObject { let current_buf = ThreadState::current_buffer(); if LispObject::from(unsafe { globals.f_Vtransient_mark_mode }).is_not_nil() && LispObject::from(unsafe { globals.f_Vmark_even_if_inactive }).is_nil() && current_buf.mark_active().is_nil() { xsignal!(Qmark_inactive); } let m = marker_position(current_buf.mark()); if m.is_nil() { error!("The mark is not set now, so there is no region"); } let num = m.as_fixnum_or_error(); // Clip to the current narrowing (bug#11770) if ((current_buf.pt as EmacsInt) < num) == beginningp { LispObject::from_fixnum(current_buf.pt as EmacsInt) } else { LispObject::from_fixnum(clip_to_bounds(current_buf.begv, num, current_buf.zv) as EmacsInt) } } /// Return the integer value of point or mark, whichever is smaller. #[lisp_fn] fn region_beginning() -> LispObject
/// Return the integer value of point or mark, whichever is larger. #[lisp_fn] fn region_end() -> LispObject { region_limit(false) } /// Return this buffer's mark, as a marker object. /// Watch out! Moving this marker changes the mark position. /// If you set the marker not to point anywhere, the buffer will have no mark. #[lisp_fn] fn mark_marker() -> LispObject { ThreadState::current_buffer().mark() } /// Return the minimum permissible value of point in the current /// buffer. This is 1, unless narrowing (a buffer restriction) is in /// effect. #[lisp_fn] pub fn point_min() -> LispObject { LispObject::from_natnum(ThreadState::current_buffer().begv as EmacsInt) } /// Return the maximum permissible value of point in the current /// buffer. This is (1+ (buffer-size)), unless narrowing (a buffer /// restriction) is in effect, in which case it is less. #[lisp_fn] pub fn point_max() -> LispObject { LispObject::from_natnum(ThreadState::current_buffer().zv() as EmacsInt) } /// Set point to POSITION, a number or marker. /// Beginning of buffer is position (point-min), end is (point-max). /// /// The return value is POSITION. #[lisp_fn(intspec = "NGoto char: ")] pub fn goto_char(position: LispObject) -> LispObject { if let Some(marker) = position.as_marker() { set_point_from_marker(marker); } else if let Some(num) = position.as_fixnum() { let cur_buf = ThreadState::current_buffer(); let pos = clip_to_bounds(cur_buf.begv, num, cur_buf.zv); let bytepos = unsafe { buf_charpos_to_bytepos(cur_buf.as_ptr(), pos) }; unsafe { set_point_both(pos, bytepos) }; } else { wrong_type!(Qinteger_or_marker_p, position) }; position } /// Return the byte position for character position POSITION. /// If POSITION is out of range, the value is nil. #[lisp_fn] pub fn position_bytes(position: LispObject) -> LispObject { let pos = position.as_fixnum_coerce_marker_or_error() as ptrdiff_t; let cur_buf = ThreadState::current_buffer(); if pos >= cur_buf.begv && pos <= cur_buf.zv { let bytepos = unsafe { buf_charpos_to_bytepos(cur_buf.as_ptr(), pos) }; LispObject::from_natnum(bytepos as EmacsInt) } else { LispObject::constant_nil() } } /// TODO: Write better docstring /// Insert COUNT (second arg) copies of BYTE (first arg). /// Both arguments are required. /// BYTE is a number of the range 0..255. /// /// If BYTE is 128..255 and the current buffer is multibyte, the /// corresponding eight-bit character is inserted. /// /// Point, and before-insertion markers, are relocated as in the function `insert'. /// The optional third arg INHERIT, if non-nil, says to inherit text properties /// from adjoining text, if those properties are sticky. #[lisp_fn(min = "2")] pub fn insert_byte(mut byte: LispObject, count: LispObject, inherit: LispObject) -> LispObject { let b = byte.as_fixnum_or_error(); if b < 0 || b > 255 { args_out_of_range!( byte, LispObject::from_fixnum(0), LispObject::from_fixnum(255) ) } let buf = ThreadState::current_buffer(); if b >= 128 && LispObject::from(buf.enable_multibyte_characters).is_not_nil() { byte = LispObject::from_natnum(raw_byte_codepoint(b as c_uchar) as EmacsInt); } unsafe { LispObject::from(Finsert_char( byte.to_raw(), count.to_raw(), inherit.to_raw(), )) } } /// Return the character following point, as a number. At the end of /// the buffer or accessible region, return 0. #[lisp_fn] pub fn following_char() -> LispObject { let buffer_ref = ThreadState::current_buffer(); if buffer_ref.pt >= buffer_ref.zv { LispObject::from_natnum(0) } else { LispObject::from_natnum(buffer_ref.fetch_char(buffer_ref.pt_byte) as EmacsInt) } } /// Return character in current buffer at position POS. /// POS is an integer or a marker and defaults to point. /// If POS is out of range, the value is nil. #[lisp_fn(min = "0")] pub fn char_after(mut pos: LispObject) -> LispObject { let buffer_ref = ThreadState::current_buffer(); if pos.is_nil() { pos = point(); } if pos.is_marker() { let pos_byte = pos.as_marker().unwrap().bytepos_or_error(); // Note that this considers the position in the current buffer, // even if the marker is from another buffer. if pos_byte < buffer_ref.begv_byte || pos_byte >= buffer_ref.zv_byte { LispObject::constant_nil() } else { LispObject::from_natnum(buffer_ref.fetch_char(pos_byte) as EmacsInt) } } else { let p = pos.as_fixnum_coerce_marker_or_error() as ptrdiff_t; if p < buffer_ref.begv || p >= buffer_ref.zv() { LispObject::constant_nil() } else { let pos_byte = unsafe { buf_charpos_to_bytepos(buffer_ref.as_ptr(), p) }; LispObject::from_natnum(buffer_ref.fetch_char(pos_byte) as EmacsInt) } } } /// Return a copy of STRING with text properties added. /// First argument is the string to copy. /// Remaining arguments form a sequence of PROPERTY VALUE pairs for text /// properties to add to the result. /// usage: (propertize STRING &rest PROPERTIES) #[lisp_fn(min = "1")] pub fn propertize(args: &mut [LispObject]) -> LispObject { /* Number of args must be odd. */ if args.len() & 1 == 0 { error!("Wrong number of arguments"); } let mut it = args.iter(); // the unwrap call is safe, the number of args has already been checked let first = it.next().unwrap(); let orig_string = first.as_string_or_error(); let copy = LispObject::from(unsafe { Fcopy_sequence(first.to_raw()) }); // this is a C style Lisp_Object because that is what Fcons expects and returns. // Once Fcons is ported to Rust this can be migrated to a LispObject. let mut properties = Qnil; while let Some(a) = it.next() { let b = it.next().unwrap(); // safe due to the odd check at the beginning properties = unsafe { Fcons(a.to_raw(), Fcons(b.to_raw(), properties)) }; } unsafe { Fadd_text_properties( LispObject::from_natnum(0).to_raw(), LispObject::from_natnum(orig_string.len_chars() as EmacsInt).to_raw(), properties, copy.to_raw(), ); }; copy } include!(concat!(env!("OUT_DIR"), "/editfns_exports.rs"));
{ region_limit(true) }
identifier_body
editfns.rs
//! Lisp functions pertaining to editing. use libc::{c_uchar, ptrdiff_t}; use remacs_macros::lisp_fn; use remacs_sys::{EmacsInt, Fadd_text_properties, Fcons, Fcopy_sequence, Finsert_char, Qinteger_or_marker_p, Qmark_inactive, Qnil}; use remacs_sys::{buf_charpos_to_bytepos, globals, set_point_both}; use buffers::get_buffer; use lisp::LispObject; use lisp::defsubr; use marker::{marker_position, set_point_from_marker}; use multibyte::raw_byte_codepoint; use threads::ThreadState; use util::clip_to_bounds; /// Return value of point, as an integer. /// Beginning of buffer is position (point-min). #[lisp_fn] pub fn point() -> LispObject { let buffer_ref = ThreadState::current_buffer(); LispObject::from_natnum(buffer_ref.pt as EmacsInt) } /// Return the number of characters in the current buffer. /// If BUFFER is not nil, return the number of characters in that buffer /// instead. /// /// This does not take narrowing into account; to count the number of /// characters in the accessible portion of the current buffer, use /// `(- (point-max) (point-min))', and to count the number of characters /// in some other BUFFER, use /// `(with-current-buffer BUFFER (- (point-max) (point-min)))'. #[lisp_fn(min = "0")] pub fn buffer_size(buffer: LispObject) -> LispObject { let buffer_ref = if buffer.is_not_nil() { get_buffer(buffer).as_buffer_or_error() } else { ThreadState::current_buffer() }; LispObject::from_natnum((buffer_ref.z() - buffer_ref.beg()) as EmacsInt) } /// Return t if point is at the end of the buffer. /// If the buffer is narrowed, this means the end of the narrowed part. #[lisp_fn] pub fn eobp() -> LispObject { let buffer_ref = ThreadState::current_buffer(); LispObject::from_bool(buffer_ref.zv() == buffer_ref.pt) } /// Return t if point is at the beginning of the buffer. If the /// buffer is narrowed, this means the beginning of the narrowed part. #[lisp_fn] pub fn bobp() -> LispObject { let buffer_ref = ThreadState::current_buffer(); LispObject::from_bool(buffer_ref.pt == buffer_ref.begv) } /// Return t if point is at the beginning of a line. #[lisp_fn] pub fn bolp() -> LispObject { let buffer_ref = ThreadState::current_buffer(); LispObject::from_bool( buffer_ref.pt == buffer_ref.begv || buffer_ref.fetch_byte(buffer_ref.pt_byte - 1) == b'\n', ) } /// Return t if point is at the end of a line. /// `End of a line' includes point being at the end of the buffer. #[lisp_fn] pub fn eolp() -> LispObject { let buffer_ref = ThreadState::current_buffer(); LispObject::from_bool( buffer_ref.pt == buffer_ref.zv() || buffer_ref.fetch_byte(buffer_ref.pt_byte) == b'\n', ) } /// Return the start or end position of the region. /// BEGINNINGP means return the start. /// If there is no region active, signal an error. fn region_limit(beginningp: bool) -> LispObject { let current_buf = ThreadState::current_buffer(); if LispObject::from(unsafe { globals.f_Vtransient_mark_mode }).is_not_nil() && LispObject::from(unsafe { globals.f_Vmark_even_if_inactive }).is_nil() && current_buf.mark_active().is_nil() { xsignal!(Qmark_inactive); } let m = marker_position(current_buf.mark()); if m.is_nil() { error!("The mark is not set now, so there is no region"); } let num = m.as_fixnum_or_error(); // Clip to the current narrowing (bug#11770) if ((current_buf.pt as EmacsInt) < num) == beginningp { LispObject::from_fixnum(current_buf.pt as EmacsInt) } else { LispObject::from_fixnum(clip_to_bounds(current_buf.begv, num, current_buf.zv) as EmacsInt) } } /// Return the integer value of point or mark, whichever is smaller. #[lisp_fn] fn region_beginning() -> LispObject { region_limit(true) } /// Return the integer value of point or mark, whichever is larger. #[lisp_fn] fn region_end() -> LispObject { region_limit(false) } /// Return this buffer's mark, as a marker object. /// Watch out! Moving this marker changes the mark position. /// If you set the marker not to point anywhere, the buffer will have no mark. #[lisp_fn] fn mark_marker() -> LispObject { ThreadState::current_buffer().mark() } /// Return the minimum permissible value of point in the current /// buffer. This is 1, unless narrowing (a buffer restriction) is in /// effect. #[lisp_fn] pub fn point_min() -> LispObject { LispObject::from_natnum(ThreadState::current_buffer().begv as EmacsInt) } /// Return the maximum permissible value of point in the current /// buffer. This is (1+ (buffer-size)), unless narrowing (a buffer /// restriction) is in effect, in which case it is less. #[lisp_fn] pub fn point_max() -> LispObject { LispObject::from_natnum(ThreadState::current_buffer().zv() as EmacsInt) } /// Set point to POSITION, a number or marker. /// Beginning of buffer is position (point-min), end is (point-max). /// /// The return value is POSITION. #[lisp_fn(intspec = "NGoto char: ")] pub fn goto_char(position: LispObject) -> LispObject { if let Some(marker) = position.as_marker() { set_point_from_marker(marker); } else if let Some(num) = position.as_fixnum() { let cur_buf = ThreadState::current_buffer(); let pos = clip_to_bounds(cur_buf.begv, num, cur_buf.zv); let bytepos = unsafe { buf_charpos_to_bytepos(cur_buf.as_ptr(), pos) }; unsafe { set_point_both(pos, bytepos) }; } else {
} /// Return the byte position for character position POSITION. /// If POSITION is out of range, the value is nil. #[lisp_fn] pub fn position_bytes(position: LispObject) -> LispObject { let pos = position.as_fixnum_coerce_marker_or_error() as ptrdiff_t; let cur_buf = ThreadState::current_buffer(); if pos >= cur_buf.begv && pos <= cur_buf.zv { let bytepos = unsafe { buf_charpos_to_bytepos(cur_buf.as_ptr(), pos) }; LispObject::from_natnum(bytepos as EmacsInt) } else { LispObject::constant_nil() } } /// TODO: Write better docstring /// Insert COUNT (second arg) copies of BYTE (first arg). /// Both arguments are required. /// BYTE is a number of the range 0..255. /// /// If BYTE is 128..255 and the current buffer is multibyte, the /// corresponding eight-bit character is inserted. /// /// Point, and before-insertion markers, are relocated as in the function `insert'. /// The optional third arg INHERIT, if non-nil, says to inherit text properties /// from adjoining text, if those properties are sticky. #[lisp_fn(min = "2")] pub fn insert_byte(mut byte: LispObject, count: LispObject, inherit: LispObject) -> LispObject { let b = byte.as_fixnum_or_error(); if b < 0 || b > 255 { args_out_of_range!( byte, LispObject::from_fixnum(0), LispObject::from_fixnum(255) ) } let buf = ThreadState::current_buffer(); if b >= 128 && LispObject::from(buf.enable_multibyte_characters).is_not_nil() { byte = LispObject::from_natnum(raw_byte_codepoint(b as c_uchar) as EmacsInt); } unsafe { LispObject::from(Finsert_char( byte.to_raw(), count.to_raw(), inherit.to_raw(), )) } } /// Return the character following point, as a number. At the end of /// the buffer or accessible region, return 0. #[lisp_fn] pub fn following_char() -> LispObject { let buffer_ref = ThreadState::current_buffer(); if buffer_ref.pt >= buffer_ref.zv { LispObject::from_natnum(0) } else { LispObject::from_natnum(buffer_ref.fetch_char(buffer_ref.pt_byte) as EmacsInt) } } /// Return character in current buffer at position POS. /// POS is an integer or a marker and defaults to point. /// If POS is out of range, the value is nil. #[lisp_fn(min = "0")] pub fn char_after(mut pos: LispObject) -> LispObject { let buffer_ref = ThreadState::current_buffer(); if pos.is_nil() { pos = point(); } if pos.is_marker() { let pos_byte = pos.as_marker().unwrap().bytepos_or_error(); // Note that this considers the position in the current buffer, // even if the marker is from another buffer. if pos_byte < buffer_ref.begv_byte || pos_byte >= buffer_ref.zv_byte { LispObject::constant_nil() } else { LispObject::from_natnum(buffer_ref.fetch_char(pos_byte) as EmacsInt) } } else { let p = pos.as_fixnum_coerce_marker_or_error() as ptrdiff_t; if p < buffer_ref.begv || p >= buffer_ref.zv() { LispObject::constant_nil() } else { let pos_byte = unsafe { buf_charpos_to_bytepos(buffer_ref.as_ptr(), p) }; LispObject::from_natnum(buffer_ref.fetch_char(pos_byte) as EmacsInt) } } } /// Return a copy of STRING with text properties added. /// First argument is the string to copy. /// Remaining arguments form a sequence of PROPERTY VALUE pairs for text /// properties to add to the result. /// usage: (propertize STRING &rest PROPERTIES) #[lisp_fn(min = "1")] pub fn propertize(args: &mut [LispObject]) -> LispObject { /* Number of args must be odd. */ if args.len() & 1 == 0 { error!("Wrong number of arguments"); } let mut it = args.iter(); // the unwrap call is safe, the number of args has already been checked let first = it.next().unwrap(); let orig_string = first.as_string_or_error(); let copy = LispObject::from(unsafe { Fcopy_sequence(first.to_raw()) }); // this is a C style Lisp_Object because that is what Fcons expects and returns. // Once Fcons is ported to Rust this can be migrated to a LispObject. let mut properties = Qnil; while let Some(a) = it.next() { let b = it.next().unwrap(); // safe due to the odd check at the beginning properties = unsafe { Fcons(a.to_raw(), Fcons(b.to_raw(), properties)) }; } unsafe { Fadd_text_properties( LispObject::from_natnum(0).to_raw(), LispObject::from_natnum(orig_string.len_chars() as EmacsInt).to_raw(), properties, copy.to_raw(), ); }; copy } include!(concat!(env!("OUT_DIR"), "/editfns_exports.rs"));
wrong_type!(Qinteger_or_marker_p, position) }; position
random_line_split
editfns.rs
//! Lisp functions pertaining to editing. use libc::{c_uchar, ptrdiff_t}; use remacs_macros::lisp_fn; use remacs_sys::{EmacsInt, Fadd_text_properties, Fcons, Fcopy_sequence, Finsert_char, Qinteger_or_marker_p, Qmark_inactive, Qnil}; use remacs_sys::{buf_charpos_to_bytepos, globals, set_point_both}; use buffers::get_buffer; use lisp::LispObject; use lisp::defsubr; use marker::{marker_position, set_point_from_marker}; use multibyte::raw_byte_codepoint; use threads::ThreadState; use util::clip_to_bounds; /// Return value of point, as an integer. /// Beginning of buffer is position (point-min). #[lisp_fn] pub fn point() -> LispObject { let buffer_ref = ThreadState::current_buffer(); LispObject::from_natnum(buffer_ref.pt as EmacsInt) } /// Return the number of characters in the current buffer. /// If BUFFER is not nil, return the number of characters in that buffer /// instead. /// /// This does not take narrowing into account; to count the number of /// characters in the accessible portion of the current buffer, use /// `(- (point-max) (point-min))', and to count the number of characters /// in some other BUFFER, use /// `(with-current-buffer BUFFER (- (point-max) (point-min)))'. #[lisp_fn(min = "0")] pub fn buffer_size(buffer: LispObject) -> LispObject { let buffer_ref = if buffer.is_not_nil() { get_buffer(buffer).as_buffer_or_error() } else { ThreadState::current_buffer() }; LispObject::from_natnum((buffer_ref.z() - buffer_ref.beg()) as EmacsInt) } /// Return t if point is at the end of the buffer. /// If the buffer is narrowed, this means the end of the narrowed part. #[lisp_fn] pub fn eobp() -> LispObject { let buffer_ref = ThreadState::current_buffer(); LispObject::from_bool(buffer_ref.zv() == buffer_ref.pt) } /// Return t if point is at the beginning of the buffer. If the /// buffer is narrowed, this means the beginning of the narrowed part. #[lisp_fn] pub fn bobp() -> LispObject { let buffer_ref = ThreadState::current_buffer(); LispObject::from_bool(buffer_ref.pt == buffer_ref.begv) } /// Return t if point is at the beginning of a line. #[lisp_fn] pub fn bolp() -> LispObject { let buffer_ref = ThreadState::current_buffer(); LispObject::from_bool( buffer_ref.pt == buffer_ref.begv || buffer_ref.fetch_byte(buffer_ref.pt_byte - 1) == b'\n', ) } /// Return t if point is at the end of a line. /// `End of a line' includes point being at the end of the buffer. #[lisp_fn] pub fn eolp() -> LispObject { let buffer_ref = ThreadState::current_buffer(); LispObject::from_bool( buffer_ref.pt == buffer_ref.zv() || buffer_ref.fetch_byte(buffer_ref.pt_byte) == b'\n', ) } /// Return the start or end position of the region. /// BEGINNINGP means return the start. /// If there is no region active, signal an error. fn region_limit(beginningp: bool) -> LispObject { let current_buf = ThreadState::current_buffer(); if LispObject::from(unsafe { globals.f_Vtransient_mark_mode }).is_not_nil() && LispObject::from(unsafe { globals.f_Vmark_even_if_inactive }).is_nil() && current_buf.mark_active().is_nil() { xsignal!(Qmark_inactive); } let m = marker_position(current_buf.mark()); if m.is_nil() { error!("The mark is not set now, so there is no region"); } let num = m.as_fixnum_or_error(); // Clip to the current narrowing (bug#11770) if ((current_buf.pt as EmacsInt) < num) == beginningp { LispObject::from_fixnum(current_buf.pt as EmacsInt) } else { LispObject::from_fixnum(clip_to_bounds(current_buf.begv, num, current_buf.zv) as EmacsInt) } } /// Return the integer value of point or mark, whichever is smaller. #[lisp_fn] fn region_beginning() -> LispObject { region_limit(true) } /// Return the integer value of point or mark, whichever is larger. #[lisp_fn] fn
() -> LispObject { region_limit(false) } /// Return this buffer's mark, as a marker object. /// Watch out! Moving this marker changes the mark position. /// If you set the marker not to point anywhere, the buffer will have no mark. #[lisp_fn] fn mark_marker() -> LispObject { ThreadState::current_buffer().mark() } /// Return the minimum permissible value of point in the current /// buffer. This is 1, unless narrowing (a buffer restriction) is in /// effect. #[lisp_fn] pub fn point_min() -> LispObject { LispObject::from_natnum(ThreadState::current_buffer().begv as EmacsInt) } /// Return the maximum permissible value of point in the current /// buffer. This is (1+ (buffer-size)), unless narrowing (a buffer /// restriction) is in effect, in which case it is less. #[lisp_fn] pub fn point_max() -> LispObject { LispObject::from_natnum(ThreadState::current_buffer().zv() as EmacsInt) } /// Set point to POSITION, a number or marker. /// Beginning of buffer is position (point-min), end is (point-max). /// /// The return value is POSITION. #[lisp_fn(intspec = "NGoto char: ")] pub fn goto_char(position: LispObject) -> LispObject { if let Some(marker) = position.as_marker() { set_point_from_marker(marker); } else if let Some(num) = position.as_fixnum() { let cur_buf = ThreadState::current_buffer(); let pos = clip_to_bounds(cur_buf.begv, num, cur_buf.zv); let bytepos = unsafe { buf_charpos_to_bytepos(cur_buf.as_ptr(), pos) }; unsafe { set_point_both(pos, bytepos) }; } else { wrong_type!(Qinteger_or_marker_p, position) }; position } /// Return the byte position for character position POSITION. /// If POSITION is out of range, the value is nil. #[lisp_fn] pub fn position_bytes(position: LispObject) -> LispObject { let pos = position.as_fixnum_coerce_marker_or_error() as ptrdiff_t; let cur_buf = ThreadState::current_buffer(); if pos >= cur_buf.begv && pos <= cur_buf.zv { let bytepos = unsafe { buf_charpos_to_bytepos(cur_buf.as_ptr(), pos) }; LispObject::from_natnum(bytepos as EmacsInt) } else { LispObject::constant_nil() } } /// TODO: Write better docstring /// Insert COUNT (second arg) copies of BYTE (first arg). /// Both arguments are required. /// BYTE is a number of the range 0..255. /// /// If BYTE is 128..255 and the current buffer is multibyte, the /// corresponding eight-bit character is inserted. /// /// Point, and before-insertion markers, are relocated as in the function `insert'. /// The optional third arg INHERIT, if non-nil, says to inherit text properties /// from adjoining text, if those properties are sticky. #[lisp_fn(min = "2")] pub fn insert_byte(mut byte: LispObject, count: LispObject, inherit: LispObject) -> LispObject { let b = byte.as_fixnum_or_error(); if b < 0 || b > 255 { args_out_of_range!( byte, LispObject::from_fixnum(0), LispObject::from_fixnum(255) ) } let buf = ThreadState::current_buffer(); if b >= 128 && LispObject::from(buf.enable_multibyte_characters).is_not_nil() { byte = LispObject::from_natnum(raw_byte_codepoint(b as c_uchar) as EmacsInt); } unsafe { LispObject::from(Finsert_char( byte.to_raw(), count.to_raw(), inherit.to_raw(), )) } } /// Return the character following point, as a number. At the end of /// the buffer or accessible region, return 0. #[lisp_fn] pub fn following_char() -> LispObject { let buffer_ref = ThreadState::current_buffer(); if buffer_ref.pt >= buffer_ref.zv { LispObject::from_natnum(0) } else { LispObject::from_natnum(buffer_ref.fetch_char(buffer_ref.pt_byte) as EmacsInt) } } /// Return character in current buffer at position POS. /// POS is an integer or a marker and defaults to point. /// If POS is out of range, the value is nil. #[lisp_fn(min = "0")] pub fn char_after(mut pos: LispObject) -> LispObject { let buffer_ref = ThreadState::current_buffer(); if pos.is_nil() { pos = point(); } if pos.is_marker() { let pos_byte = pos.as_marker().unwrap().bytepos_or_error(); // Note that this considers the position in the current buffer, // even if the marker is from another buffer. if pos_byte < buffer_ref.begv_byte || pos_byte >= buffer_ref.zv_byte { LispObject::constant_nil() } else { LispObject::from_natnum(buffer_ref.fetch_char(pos_byte) as EmacsInt) } } else { let p = pos.as_fixnum_coerce_marker_or_error() as ptrdiff_t; if p < buffer_ref.begv || p >= buffer_ref.zv() { LispObject::constant_nil() } else { let pos_byte = unsafe { buf_charpos_to_bytepos(buffer_ref.as_ptr(), p) }; LispObject::from_natnum(buffer_ref.fetch_char(pos_byte) as EmacsInt) } } } /// Return a copy of STRING with text properties added. /// First argument is the string to copy. /// Remaining arguments form a sequence of PROPERTY VALUE pairs for text /// properties to add to the result. /// usage: (propertize STRING &rest PROPERTIES) #[lisp_fn(min = "1")] pub fn propertize(args: &mut [LispObject]) -> LispObject { /* Number of args must be odd. */ if args.len() & 1 == 0 { error!("Wrong number of arguments"); } let mut it = args.iter(); // the unwrap call is safe, the number of args has already been checked let first = it.next().unwrap(); let orig_string = first.as_string_or_error(); let copy = LispObject::from(unsafe { Fcopy_sequence(first.to_raw()) }); // this is a C style Lisp_Object because that is what Fcons expects and returns. // Once Fcons is ported to Rust this can be migrated to a LispObject. let mut properties = Qnil; while let Some(a) = it.next() { let b = it.next().unwrap(); // safe due to the odd check at the beginning properties = unsafe { Fcons(a.to_raw(), Fcons(b.to_raw(), properties)) }; } unsafe { Fadd_text_properties( LispObject::from_natnum(0).to_raw(), LispObject::from_natnum(orig_string.len_chars() as EmacsInt).to_raw(), properties, copy.to_raw(), ); }; copy } include!(concat!(env!("OUT_DIR"), "/editfns_exports.rs"));
region_end
identifier_name
editfns.rs
//! Lisp functions pertaining to editing. use libc::{c_uchar, ptrdiff_t}; use remacs_macros::lisp_fn; use remacs_sys::{EmacsInt, Fadd_text_properties, Fcons, Fcopy_sequence, Finsert_char, Qinteger_or_marker_p, Qmark_inactive, Qnil}; use remacs_sys::{buf_charpos_to_bytepos, globals, set_point_both}; use buffers::get_buffer; use lisp::LispObject; use lisp::defsubr; use marker::{marker_position, set_point_from_marker}; use multibyte::raw_byte_codepoint; use threads::ThreadState; use util::clip_to_bounds; /// Return value of point, as an integer. /// Beginning of buffer is position (point-min). #[lisp_fn] pub fn point() -> LispObject { let buffer_ref = ThreadState::current_buffer(); LispObject::from_natnum(buffer_ref.pt as EmacsInt) } /// Return the number of characters in the current buffer. /// If BUFFER is not nil, return the number of characters in that buffer /// instead. /// /// This does not take narrowing into account; to count the number of /// characters in the accessible portion of the current buffer, use /// `(- (point-max) (point-min))', and to count the number of characters /// in some other BUFFER, use /// `(with-current-buffer BUFFER (- (point-max) (point-min)))'. #[lisp_fn(min = "0")] pub fn buffer_size(buffer: LispObject) -> LispObject { let buffer_ref = if buffer.is_not_nil() { get_buffer(buffer).as_buffer_or_error() } else { ThreadState::current_buffer() }; LispObject::from_natnum((buffer_ref.z() - buffer_ref.beg()) as EmacsInt) } /// Return t if point is at the end of the buffer. /// If the buffer is narrowed, this means the end of the narrowed part. #[lisp_fn] pub fn eobp() -> LispObject { let buffer_ref = ThreadState::current_buffer(); LispObject::from_bool(buffer_ref.zv() == buffer_ref.pt) } /// Return t if point is at the beginning of the buffer. If the /// buffer is narrowed, this means the beginning of the narrowed part. #[lisp_fn] pub fn bobp() -> LispObject { let buffer_ref = ThreadState::current_buffer(); LispObject::from_bool(buffer_ref.pt == buffer_ref.begv) } /// Return t if point is at the beginning of a line. #[lisp_fn] pub fn bolp() -> LispObject { let buffer_ref = ThreadState::current_buffer(); LispObject::from_bool( buffer_ref.pt == buffer_ref.begv || buffer_ref.fetch_byte(buffer_ref.pt_byte - 1) == b'\n', ) } /// Return t if point is at the end of a line. /// `End of a line' includes point being at the end of the buffer. #[lisp_fn] pub fn eolp() -> LispObject { let buffer_ref = ThreadState::current_buffer(); LispObject::from_bool( buffer_ref.pt == buffer_ref.zv() || buffer_ref.fetch_byte(buffer_ref.pt_byte) == b'\n', ) } /// Return the start or end position of the region. /// BEGINNINGP means return the start. /// If there is no region active, signal an error. fn region_limit(beginningp: bool) -> LispObject { let current_buf = ThreadState::current_buffer(); if LispObject::from(unsafe { globals.f_Vtransient_mark_mode }).is_not_nil() && LispObject::from(unsafe { globals.f_Vmark_even_if_inactive }).is_nil() && current_buf.mark_active().is_nil() { xsignal!(Qmark_inactive); } let m = marker_position(current_buf.mark()); if m.is_nil() { error!("The mark is not set now, so there is no region"); } let num = m.as_fixnum_or_error(); // Clip to the current narrowing (bug#11770) if ((current_buf.pt as EmacsInt) < num) == beginningp { LispObject::from_fixnum(current_buf.pt as EmacsInt) } else { LispObject::from_fixnum(clip_to_bounds(current_buf.begv, num, current_buf.zv) as EmacsInt) } } /// Return the integer value of point or mark, whichever is smaller. #[lisp_fn] fn region_beginning() -> LispObject { region_limit(true) } /// Return the integer value of point or mark, whichever is larger. #[lisp_fn] fn region_end() -> LispObject { region_limit(false) } /// Return this buffer's mark, as a marker object. /// Watch out! Moving this marker changes the mark position. /// If you set the marker not to point anywhere, the buffer will have no mark. #[lisp_fn] fn mark_marker() -> LispObject { ThreadState::current_buffer().mark() } /// Return the minimum permissible value of point in the current /// buffer. This is 1, unless narrowing (a buffer restriction) is in /// effect. #[lisp_fn] pub fn point_min() -> LispObject { LispObject::from_natnum(ThreadState::current_buffer().begv as EmacsInt) } /// Return the maximum permissible value of point in the current /// buffer. This is (1+ (buffer-size)), unless narrowing (a buffer /// restriction) is in effect, in which case it is less. #[lisp_fn] pub fn point_max() -> LispObject { LispObject::from_natnum(ThreadState::current_buffer().zv() as EmacsInt) } /// Set point to POSITION, a number or marker. /// Beginning of buffer is position (point-min), end is (point-max). /// /// The return value is POSITION. #[lisp_fn(intspec = "NGoto char: ")] pub fn goto_char(position: LispObject) -> LispObject { if let Some(marker) = position.as_marker() { set_point_from_marker(marker); } else if let Some(num) = position.as_fixnum() { let cur_buf = ThreadState::current_buffer(); let pos = clip_to_bounds(cur_buf.begv, num, cur_buf.zv); let bytepos = unsafe { buf_charpos_to_bytepos(cur_buf.as_ptr(), pos) }; unsafe { set_point_both(pos, bytepos) }; } else { wrong_type!(Qinteger_or_marker_p, position) }; position } /// Return the byte position for character position POSITION. /// If POSITION is out of range, the value is nil. #[lisp_fn] pub fn position_bytes(position: LispObject) -> LispObject { let pos = position.as_fixnum_coerce_marker_or_error() as ptrdiff_t; let cur_buf = ThreadState::current_buffer(); if pos >= cur_buf.begv && pos <= cur_buf.zv { let bytepos = unsafe { buf_charpos_to_bytepos(cur_buf.as_ptr(), pos) }; LispObject::from_natnum(bytepos as EmacsInt) } else { LispObject::constant_nil() } } /// TODO: Write better docstring /// Insert COUNT (second arg) copies of BYTE (first arg). /// Both arguments are required. /// BYTE is a number of the range 0..255. /// /// If BYTE is 128..255 and the current buffer is multibyte, the /// corresponding eight-bit character is inserted. /// /// Point, and before-insertion markers, are relocated as in the function `insert'. /// The optional third arg INHERIT, if non-nil, says to inherit text properties /// from adjoining text, if those properties are sticky. #[lisp_fn(min = "2")] pub fn insert_byte(mut byte: LispObject, count: LispObject, inherit: LispObject) -> LispObject { let b = byte.as_fixnum_or_error(); if b < 0 || b > 255 { args_out_of_range!( byte, LispObject::from_fixnum(0), LispObject::from_fixnum(255) ) } let buf = ThreadState::current_buffer(); if b >= 128 && LispObject::from(buf.enable_multibyte_characters).is_not_nil() { byte = LispObject::from_natnum(raw_byte_codepoint(b as c_uchar) as EmacsInt); } unsafe { LispObject::from(Finsert_char( byte.to_raw(), count.to_raw(), inherit.to_raw(), )) } } /// Return the character following point, as a number. At the end of /// the buffer or accessible region, return 0. #[lisp_fn] pub fn following_char() -> LispObject { let buffer_ref = ThreadState::current_buffer(); if buffer_ref.pt >= buffer_ref.zv { LispObject::from_natnum(0) } else { LispObject::from_natnum(buffer_ref.fetch_char(buffer_ref.pt_byte) as EmacsInt) } } /// Return character in current buffer at position POS. /// POS is an integer or a marker and defaults to point. /// If POS is out of range, the value is nil. #[lisp_fn(min = "0")] pub fn char_after(mut pos: LispObject) -> LispObject { let buffer_ref = ThreadState::current_buffer(); if pos.is_nil() { pos = point(); } if pos.is_marker() { let pos_byte = pos.as_marker().unwrap().bytepos_or_error(); // Note that this considers the position in the current buffer, // even if the marker is from another buffer. if pos_byte < buffer_ref.begv_byte || pos_byte >= buffer_ref.zv_byte { LispObject::constant_nil() } else
} else { let p = pos.as_fixnum_coerce_marker_or_error() as ptrdiff_t; if p < buffer_ref.begv || p >= buffer_ref.zv() { LispObject::constant_nil() } else { let pos_byte = unsafe { buf_charpos_to_bytepos(buffer_ref.as_ptr(), p) }; LispObject::from_natnum(buffer_ref.fetch_char(pos_byte) as EmacsInt) } } } /// Return a copy of STRING with text properties added. /// First argument is the string to copy. /// Remaining arguments form a sequence of PROPERTY VALUE pairs for text /// properties to add to the result. /// usage: (propertize STRING &rest PROPERTIES) #[lisp_fn(min = "1")] pub fn propertize(args: &mut [LispObject]) -> LispObject { /* Number of args must be odd. */ if args.len() & 1 == 0 { error!("Wrong number of arguments"); } let mut it = args.iter(); // the unwrap call is safe, the number of args has already been checked let first = it.next().unwrap(); let orig_string = first.as_string_or_error(); let copy = LispObject::from(unsafe { Fcopy_sequence(first.to_raw()) }); // this is a C style Lisp_Object because that is what Fcons expects and returns. // Once Fcons is ported to Rust this can be migrated to a LispObject. let mut properties = Qnil; while let Some(a) = it.next() { let b = it.next().unwrap(); // safe due to the odd check at the beginning properties = unsafe { Fcons(a.to_raw(), Fcons(b.to_raw(), properties)) }; } unsafe { Fadd_text_properties( LispObject::from_natnum(0).to_raw(), LispObject::from_natnum(orig_string.len_chars() as EmacsInt).to_raw(), properties, copy.to_raw(), ); }; copy } include!(concat!(env!("OUT_DIR"), "/editfns_exports.rs"));
{ LispObject::from_natnum(buffer_ref.fetch_char(pos_byte) as EmacsInt) }
conditional_block
ast.rs
use std::fmt::{Debug, Error, Formatter}; pub enum Expr { Number(i32), Op(Box<Expr>, Opcode, Box<Expr>), Error, } #[derive(Copy, Clone)]
Div, Add, Sub, } impl Debug for Expr { fn fmt(&self, fmt: &mut Formatter) -> Result<(), Error> { use self::Expr::*; match *self { Number(n) => write!(fmt, "{:?}", n), Op(ref l, op, ref r) => write!(fmt, "({:?} {:?} {:?})", l, op, r), Error => write!(fmt, "error"), } } } impl Debug for Opcode { fn fmt(&self, fmt: &mut Formatter) -> Result<(), Error> { use self::Opcode::*; match *self { Mul => write!(fmt, "*"), Div => write!(fmt, "/"), Add => write!(fmt, "+"), Sub => write!(fmt, "-"), } } }
pub enum Opcode { Mul,
random_line_split
ast.rs
use std::fmt::{Debug, Error, Formatter}; pub enum Expr { Number(i32), Op(Box<Expr>, Opcode, Box<Expr>), Error, } #[derive(Copy, Clone)] pub enum Opcode { Mul, Div, Add, Sub, } impl Debug for Expr { fn fmt(&self, fmt: &mut Formatter) -> Result<(), Error> { use self::Expr::*; match *self { Number(n) => write!(fmt, "{:?}", n), Op(ref l, op, ref r) => write!(fmt, "({:?} {:?} {:?})", l, op, r), Error => write!(fmt, "error"), } } } impl Debug for Opcode { fn fmt(&self, fmt: &mut Formatter) -> Result<(), Error>
}
{ use self::Opcode::*; match *self { Mul => write!(fmt, "*"), Div => write!(fmt, "/"), Add => write!(fmt, "+"), Sub => write!(fmt, "-"), } }
identifier_body
ast.rs
use std::fmt::{Debug, Error, Formatter}; pub enum Expr { Number(i32), Op(Box<Expr>, Opcode, Box<Expr>), Error, } #[derive(Copy, Clone)] pub enum Opcode { Mul, Div, Add, Sub, } impl Debug for Expr { fn
(&self, fmt: &mut Formatter) -> Result<(), Error> { use self::Expr::*; match *self { Number(n) => write!(fmt, "{:?}", n), Op(ref l, op, ref r) => write!(fmt, "({:?} {:?} {:?})", l, op, r), Error => write!(fmt, "error"), } } } impl Debug for Opcode { fn fmt(&self, fmt: &mut Formatter) -> Result<(), Error> { use self::Opcode::*; match *self { Mul => write!(fmt, "*"), Div => write!(fmt, "/"), Add => write!(fmt, "+"), Sub => write!(fmt, "-"), } } }
fmt
identifier_name
command.rs
// Copyright 2017 Google Inc. // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use shell_command::ShellCommand; use nom::IResult; use std::process::Command; use std::env; use std::env::VarError; fn token_char(ch: char) -> bool { if ch.len_utf8() > 1 { return false; } match ch { '\x00'... '\x20' => false, '\x7f' | '"' | '\'' | '>' | '<' | '|' | ';' | '{' | '}' | '$' => false, _ => true, } } fn var_char(ch: char) -> bool { match ch { 'a'... 'z' => true, 'A'... 'Z' => true, '0'... '9' => true, '_' => true, _ => false, } } enum TokenPart { Bare(String), Placeholder, EnvVariable(String), } struct Token(Vec<TokenPart>); impl Token { fn into_string(self, args: &mut Iterator<Item = &str>) -> Result<String, VarError> { let mut token = String::from(""); for part in self.0 { match part { TokenPart::Bare(s) => token += &s, TokenPart::Placeholder => token += args.next().expect("Too many placeholders"), TokenPart::EnvVariable(name) => { debug!("Environment variable {}", name); token += &env::var(name)? } } } Ok(token) } } named!(bare_token<&str, TokenPart>, map!(take_while1_s!(token_char), |s| TokenPart::Bare(String::from(s)))); named!(quoted_token<&str, TokenPart>, map!(delimited!(tag_s!("\""), take_until_s!("\""), tag_s!("\"")), |s| TokenPart::Bare(String::from(s)))); named!(place_holder<&str, TokenPart>, map!(tag_s!("{}"), |_| TokenPart::Placeholder)); named!(env_var<&str, TokenPart>, map!(preceded!(tag!("$"), take_while1_s!(var_char)), |name| TokenPart::EnvVariable(String::from(name)))); named!(command_token<&str, Token>, map!(many1!(alt!(bare_token | quoted_token | place_holder | env_var)), |vec| Token(vec))); named!(command< &str, Vec<Token> >, terminated!(ws!(many1!(command_token)), eof!())); /// Creates a new commadn from `format` and `args` /// # Examples #[macro_export] macro_rules! cmd { ($format:expr) => ($crate::new_command($format, &[]).unwrap()); ($format:expr, $($arg:expr),+) => ($crate::new_command($format, &[$($arg),+]).unwrap()); } fn parse_cmd<'a>(format: &'a str, args: &'a [&str]) -> Result<Vec<String>, VarError> { let tokens = match command(format) { IResult::Done(_, result) => result, IResult::Error(error) => panic!("Error {:?}", error), IResult::Incomplete(needed) => panic!("Needed {:?}", needed) }; let args = args.iter().map(|a| *a).collect::<Vec<_>>(); let mut args = args.into_iter(); tokens.into_iter().map(|token| token.into_string(&mut args)) .collect::<Result<Vec<_>, _>>() } /// Creates a new command from `format` and `args`. /// The function is invoked from `cmd!` macro internally. pub fn new_command(format: &str, args: &[&str]) -> Result<ShellCommand, VarError> { let vec = parse_cmd(format, args)?; let mut command = Command::new(&vec[0]); if vec.len() > 1 { command.args(&vec[1..]); } let line = vec.join(" "); Ok(ShellCommand::new(line, command)) } #[test] fn
() { let tokens = parse_cmd(r#"cmd 1 2 3 " 4" {}"#, &["5"]).unwrap(); assert_eq!("cmd", tokens[0]); assert_eq!("1", tokens[1]); assert_eq!("2", tokens[2]); assert_eq!("3", tokens[3]); assert_eq!("\n 4", tokens[4]); assert_eq!("5", tokens[5]); } #[test] fn test_parse_cmd_env() { use env_logger; env_logger::init().unwrap(); env::set_var("MY_VAR", "VALUE"); let tokens = parse_cmd("echo $MY_VAR/dir", &[]).unwrap(); assert_eq!("VALUE/dir", tokens[1]); }
test_parse_cmd
identifier_name
command.rs
// Copyright 2017 Google Inc. // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use shell_command::ShellCommand; use nom::IResult; use std::process::Command; use std::env; use std::env::VarError; fn token_char(ch: char) -> bool { if ch.len_utf8() > 1 { return false; } match ch { '\x00'... '\x20' => false, '\x7f' | '"' | '\'' | '>' | '<' | '|' | ';' | '{' | '}' | '$' => false, _ => true, } } fn var_char(ch: char) -> bool { match ch { 'a'... 'z' => true, 'A'... 'Z' => true, '0'... '9' => true, '_' => true, _ => false, } } enum TokenPart { Bare(String), Placeholder,
impl Token { fn into_string(self, args: &mut Iterator<Item = &str>) -> Result<String, VarError> { let mut token = String::from(""); for part in self.0 { match part { TokenPart::Bare(s) => token += &s, TokenPart::Placeholder => token += args.next().expect("Too many placeholders"), TokenPart::EnvVariable(name) => { debug!("Environment variable {}", name); token += &env::var(name)? } } } Ok(token) } } named!(bare_token<&str, TokenPart>, map!(take_while1_s!(token_char), |s| TokenPart::Bare(String::from(s)))); named!(quoted_token<&str, TokenPart>, map!(delimited!(tag_s!("\""), take_until_s!("\""), tag_s!("\"")), |s| TokenPart::Bare(String::from(s)))); named!(place_holder<&str, TokenPart>, map!(tag_s!("{}"), |_| TokenPart::Placeholder)); named!(env_var<&str, TokenPart>, map!(preceded!(tag!("$"), take_while1_s!(var_char)), |name| TokenPart::EnvVariable(String::from(name)))); named!(command_token<&str, Token>, map!(many1!(alt!(bare_token | quoted_token | place_holder | env_var)), |vec| Token(vec))); named!(command< &str, Vec<Token> >, terminated!(ws!(many1!(command_token)), eof!())); /// Creates a new commadn from `format` and `args` /// # Examples #[macro_export] macro_rules! cmd { ($format:expr) => ($crate::new_command($format, &[]).unwrap()); ($format:expr, $($arg:expr),+) => ($crate::new_command($format, &[$($arg),+]).unwrap()); } fn parse_cmd<'a>(format: &'a str, args: &'a [&str]) -> Result<Vec<String>, VarError> { let tokens = match command(format) { IResult::Done(_, result) => result, IResult::Error(error) => panic!("Error {:?}", error), IResult::Incomplete(needed) => panic!("Needed {:?}", needed) }; let args = args.iter().map(|a| *a).collect::<Vec<_>>(); let mut args = args.into_iter(); tokens.into_iter().map(|token| token.into_string(&mut args)) .collect::<Result<Vec<_>, _>>() } /// Creates a new command from `format` and `args`. /// The function is invoked from `cmd!` macro internally. pub fn new_command(format: &str, args: &[&str]) -> Result<ShellCommand, VarError> { let vec = parse_cmd(format, args)?; let mut command = Command::new(&vec[0]); if vec.len() > 1 { command.args(&vec[1..]); } let line = vec.join(" "); Ok(ShellCommand::new(line, command)) } #[test] fn test_parse_cmd() { let tokens = parse_cmd(r#"cmd 1 2 3 " 4" {}"#, &["5"]).unwrap(); assert_eq!("cmd", tokens[0]); assert_eq!("1", tokens[1]); assert_eq!("2", tokens[2]); assert_eq!("3", tokens[3]); assert_eq!("\n 4", tokens[4]); assert_eq!("5", tokens[5]); } #[test] fn test_parse_cmd_env() { use env_logger; env_logger::init().unwrap(); env::set_var("MY_VAR", "VALUE"); let tokens = parse_cmd("echo $MY_VAR/dir", &[]).unwrap(); assert_eq!("VALUE/dir", tokens[1]); }
EnvVariable(String), } struct Token(Vec<TokenPart>);
random_line_split
command.rs
// Copyright 2017 Google Inc. // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use shell_command::ShellCommand; use nom::IResult; use std::process::Command; use std::env; use std::env::VarError; fn token_char(ch: char) -> bool { if ch.len_utf8() > 1 { return false; } match ch { '\x00'... '\x20' => false, '\x7f' | '"' | '\'' | '>' | '<' | '|' | ';' | '{' | '}' | '$' => false, _ => true, } } fn var_char(ch: char) -> bool { match ch { 'a'... 'z' => true, 'A'... 'Z' => true, '0'... '9' => true, '_' => true, _ => false, } } enum TokenPart { Bare(String), Placeholder, EnvVariable(String), } struct Token(Vec<TokenPart>); impl Token { fn into_string(self, args: &mut Iterator<Item = &str>) -> Result<String, VarError> { let mut token = String::from(""); for part in self.0 { match part { TokenPart::Bare(s) => token += &s, TokenPart::Placeholder => token += args.next().expect("Too many placeholders"), TokenPart::EnvVariable(name) => { debug!("Environment variable {}", name); token += &env::var(name)? } } } Ok(token) } } named!(bare_token<&str, TokenPart>, map!(take_while1_s!(token_char), |s| TokenPart::Bare(String::from(s)))); named!(quoted_token<&str, TokenPart>, map!(delimited!(tag_s!("\""), take_until_s!("\""), tag_s!("\"")), |s| TokenPart::Bare(String::from(s)))); named!(place_holder<&str, TokenPart>, map!(tag_s!("{}"), |_| TokenPart::Placeholder)); named!(env_var<&str, TokenPart>, map!(preceded!(tag!("$"), take_while1_s!(var_char)), |name| TokenPart::EnvVariable(String::from(name)))); named!(command_token<&str, Token>, map!(many1!(alt!(bare_token | quoted_token | place_holder | env_var)), |vec| Token(vec))); named!(command< &str, Vec<Token> >, terminated!(ws!(many1!(command_token)), eof!())); /// Creates a new commadn from `format` and `args` /// # Examples #[macro_export] macro_rules! cmd { ($format:expr) => ($crate::new_command($format, &[]).unwrap()); ($format:expr, $($arg:expr),+) => ($crate::new_command($format, &[$($arg),+]).unwrap()); } fn parse_cmd<'a>(format: &'a str, args: &'a [&str]) -> Result<Vec<String>, VarError>
/// Creates a new command from `format` and `args`. /// The function is invoked from `cmd!` macro internally. pub fn new_command(format: &str, args: &[&str]) -> Result<ShellCommand, VarError> { let vec = parse_cmd(format, args)?; let mut command = Command::new(&vec[0]); if vec.len() > 1 { command.args(&vec[1..]); } let line = vec.join(" "); Ok(ShellCommand::new(line, command)) } #[test] fn test_parse_cmd() { let tokens = parse_cmd(r#"cmd 1 2 3 " 4" {}"#, &["5"]).unwrap(); assert_eq!("cmd", tokens[0]); assert_eq!("1", tokens[1]); assert_eq!("2", tokens[2]); assert_eq!("3", tokens[3]); assert_eq!("\n 4", tokens[4]); assert_eq!("5", tokens[5]); } #[test] fn test_parse_cmd_env() { use env_logger; env_logger::init().unwrap(); env::set_var("MY_VAR", "VALUE"); let tokens = parse_cmd("echo $MY_VAR/dir", &[]).unwrap(); assert_eq!("VALUE/dir", tokens[1]); }
{ let tokens = match command(format) { IResult::Done(_, result) => result, IResult::Error(error) => panic!("Error {:?}", error), IResult::Incomplete(needed) => panic!("Needed {:?}", needed) }; let args = args.iter().map(|a| *a).collect::<Vec<_>>(); let mut args = args.into_iter(); tokens.into_iter().map(|token| token.into_string(&mut args)) .collect::<Result<Vec<_>, _>>() }
identifier_body
document_rule.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/. */ //! [@document rules](https://www.w3.org/TR/2012/WD-css3-conditional-20120911/#at-document) //! initially in CSS Conditional Rules Module Level 3, @document has been postponed to the level 4. //! We implement the prefixed `@-moz-document`. use cssparser::{Parser, Token, SourceLocation, BasicParseError}; use media_queries::Device; use parser::{Parse, ParserContext}; use shared_lock::{DeepCloneWithLock, Locked, SharedRwLock, SharedRwLockReadGuard, ToCssWithGuard}; use std::fmt; use style_traits::{ToCss, ParseError, StyleParseError}; use stylearc::Arc; use stylesheets::CssRules; use values::specified::url::SpecifiedUrl; #[derive(Debug)] /// A @-moz-document rule pub struct DocumentRule { /// The parsed condition pub condition: DocumentCondition, /// Child rules pub rules: Arc<Locked<CssRules>>, /// The line and column of the rule's source code. pub source_location: SourceLocation, } impl ToCssWithGuard for DocumentRule { fn to_css<W>(&self, guard: &SharedRwLockReadGuard, dest: &mut W) -> fmt::Result where W: fmt::Write { try!(dest.write_str("@-moz-document ")); try!(self.condition.to_css(dest)); try!(dest.write_str(" {")); for rule in self.rules.read_with(guard).0.iter() { try!(dest.write_str(" ")); try!(rule.to_css(guard, dest)); } dest.write_str(" }") } } impl DeepCloneWithLock for DocumentRule { /// Deep clones this DocumentRule. fn deep_clone_with_lock( &self, lock: &SharedRwLock, guard: &SharedRwLockReadGuard, ) -> Self { let rules = self.rules.read_with(guard); DocumentRule { condition: self.condition.clone(), rules: Arc::new(lock.wrap(rules.deep_clone_with_lock(lock, guard))), source_location: self.source_location.clone(), } } } /// A URL matching function for a `@document` rule's condition. #[derive(Clone, Debug)] pub enum UrlMatchingFunction { /// Exact URL matching function. It evaluates to true whenever the /// URL of the document being styled is exactly the URL given. Url(SpecifiedUrl), /// URL prefix matching function. It evaluates to true whenever the /// URL of the document being styled has the argument to the /// function as an initial substring (which is true when the two /// strings are equal). When the argument is the empty string, /// it evaluates to true for all documents. UrlPrefix(String), /// Domain matching function. It evaluates to true whenever the URL /// of the document being styled has a host subcomponent and that
/// function or a final substring of the host component is a /// period (U+002E) immediately followed by the argument to the /// ‘domain()’ function. Domain(String), /// Regular expression matching function. It evaluates to true /// whenever the regular expression matches the entirety of the URL /// of the document being styled. RegExp(String), } macro_rules! parse_quoted_or_unquoted_string { ($input:ident, $url_matching_function:expr) => { $input.parse_nested_block(|input| { let start = input.position(); input.parse_entirely(|input| { match input.next() { Ok(Token::QuotedString(value)) => Ok($url_matching_function(value.into_owned())), Ok(t) => Err(BasicParseError::UnexpectedToken(t).into()), Err(e) => Err(e.into()), } }).or_else(|_: ParseError| { while let Ok(_) = input.next() {} Ok($url_matching_function(input.slice_from(start).to_string())) }) }) } } impl UrlMatchingFunction { /// Parse a URL matching function for a`@document` rule's condition. pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<UrlMatchingFunction, ParseError<'i>> { if input.try(|input| input.expect_function_matching("url-prefix")).is_ok() { parse_quoted_or_unquoted_string!(input, UrlMatchingFunction::UrlPrefix) } else if input.try(|input| input.expect_function_matching("domain")).is_ok() { parse_quoted_or_unquoted_string!(input, UrlMatchingFunction::Domain) } else if input.try(|input| input.expect_function_matching("regexp")).is_ok() { input.parse_nested_block(|input| { Ok(UrlMatchingFunction::RegExp(input.expect_string()?.into_owned())) }) } else if let Ok(url) = input.try(|input| SpecifiedUrl::parse(context, input)) { Ok(UrlMatchingFunction::Url(url)) } else { Err(StyleParseError::UnspecifiedError.into()) } } #[cfg(feature = "gecko")] /// Evaluate a URL matching function. pub fn evaluate(&self, device: &Device) -> bool { use gecko_bindings::bindings::Gecko_DocumentRule_UseForPresentation; use gecko_bindings::structs::URLMatchingFunction as GeckoUrlMatchingFunction; use nsstring::nsCString; let func = match *self { UrlMatchingFunction::Url(_) => GeckoUrlMatchingFunction::eURL, UrlMatchingFunction::UrlPrefix(_) => GeckoUrlMatchingFunction::eURLPrefix, UrlMatchingFunction::Domain(_) => GeckoUrlMatchingFunction::eDomain, UrlMatchingFunction::RegExp(_) => GeckoUrlMatchingFunction::eRegExp, }; let pattern = nsCString::from(match *self { UrlMatchingFunction::Url(ref url) => url.as_str(), UrlMatchingFunction::UrlPrefix(ref pat) | UrlMatchingFunction::Domain(ref pat) | UrlMatchingFunction::RegExp(ref pat) => pat, }); unsafe { Gecko_DocumentRule_UseForPresentation(&*device.pres_context, &*pattern, func) } } #[cfg(not(feature = "gecko"))] /// Evaluate a URL matching function. pub fn evaluate(&self, _: &Device) -> bool { false } } impl ToCss for UrlMatchingFunction { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { UrlMatchingFunction::Url(ref url) => { url.to_css(dest) }, UrlMatchingFunction::UrlPrefix(ref url_prefix) => { dest.write_str("url-prefix(")?; url_prefix.to_css(dest)?; dest.write_str(")") }, UrlMatchingFunction::Domain(ref domain) => { dest.write_str("domain(")?; domain.to_css(dest)?; dest.write_str(")") }, UrlMatchingFunction::RegExp(ref regex) => { dest.write_str("regexp(")?; regex.to_css(dest)?; dest.write_str(")") }, } } } /// A `@document` rule's condition. /// /// https://www.w3.org/TR/2012/WD-css3-conditional-20120911/#at-document /// /// The `@document` rule's condition is written as a comma-separated list of /// URL matching functions, and the condition evaluates to true whenever any /// one of those functions evaluates to true. #[derive(Clone, Debug)] pub struct DocumentCondition(Vec<UrlMatchingFunction>); impl DocumentCondition { /// Parse a document condition. pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> { input.parse_comma_separated(|input| UrlMatchingFunction::parse(context, input)) .map(DocumentCondition) } /// Evaluate a document condition. pub fn evaluate(&self, device: &Device) -> bool { self.0.iter().any(|ref url_matching_function| url_matching_function.evaluate(device) ) } } impl ToCss for DocumentCondition { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { let mut iter = self.0.iter(); let first = iter.next() .expect("Empty DocumentCondition, should contain at least one URL matching function"); first.to_css(dest)?; for url_matching_function in iter { dest.write_str(", ")?; url_matching_function.to_css(dest)?; } Ok(()) } }
/// host subcomponent is exactly the argument to the ‘domain()’
random_line_split
document_rule.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/. */ //! [@document rules](https://www.w3.org/TR/2012/WD-css3-conditional-20120911/#at-document) //! initially in CSS Conditional Rules Module Level 3, @document has been postponed to the level 4. //! We implement the prefixed `@-moz-document`. use cssparser::{Parser, Token, SourceLocation, BasicParseError}; use media_queries::Device; use parser::{Parse, ParserContext}; use shared_lock::{DeepCloneWithLock, Locked, SharedRwLock, SharedRwLockReadGuard, ToCssWithGuard}; use std::fmt; use style_traits::{ToCss, ParseError, StyleParseError}; use stylearc::Arc; use stylesheets::CssRules; use values::specified::url::SpecifiedUrl; #[derive(Debug)] /// A @-moz-document rule pub struct DocumentRule { /// The parsed condition pub condition: DocumentCondition, /// Child rules pub rules: Arc<Locked<CssRules>>, /// The line and column of the rule's source code. pub source_location: SourceLocation, } impl ToCssWithGuard for DocumentRule { fn to_css<W>(&self, guard: &SharedRwLockReadGuard, dest: &mut W) -> fmt::Result where W: fmt::Write { try!(dest.write_str("@-moz-document ")); try!(self.condition.to_css(dest)); try!(dest.write_str(" {")); for rule in self.rules.read_with(guard).0.iter() { try!(dest.write_str(" ")); try!(rule.to_css(guard, dest)); } dest.write_str(" }") } } impl DeepCloneWithLock for DocumentRule { /// Deep clones this DocumentRule. fn deep_clone_with_lock( &self, lock: &SharedRwLock, guard: &SharedRwLockReadGuard, ) -> Self { let rules = self.rules.read_with(guard); DocumentRule { condition: self.condition.clone(), rules: Arc::new(lock.wrap(rules.deep_clone_with_lock(lock, guard))), source_location: self.source_location.clone(), } } } /// A URL matching function for a `@document` rule's condition. #[derive(Clone, Debug)] pub enum UrlMatchingFunction { /// Exact URL matching function. It evaluates to true whenever the /// URL of the document being styled is exactly the URL given. Url(SpecifiedUrl), /// URL prefix matching function. It evaluates to true whenever the /// URL of the document being styled has the argument to the /// function as an initial substring (which is true when the two /// strings are equal). When the argument is the empty string, /// it evaluates to true for all documents. UrlPrefix(String), /// Domain matching function. It evaluates to true whenever the URL /// of the document being styled has a host subcomponent and that /// host subcomponent is exactly the argument to the ‘domain()’ /// function or a final substring of the host component is a /// period (U+002E) immediately followed by the argument to the /// ‘domain()’ function. Domain(String), /// Regular expression matching function. It evaluates to true /// whenever the regular expression matches the entirety of the URL /// of the document being styled. RegExp(String), } macro_rules! parse_quoted_or_unquoted_string { ($input:ident, $url_matching_function:expr) => { $input.parse_nested_block(|input| { let start = input.position(); input.parse_entirely(|input| { match input.next() { Ok(Token::QuotedString(value)) => Ok($url_matching_function(value.into_owned())), Ok(t) => Err(BasicParseError::UnexpectedToken(t).into()), Err(e) => Err(e.into()), } }).or_else(|_: ParseError| { while let Ok(_) = input.next() {} Ok($url_matching_function(input.slice_from(start).to_string())) }) }) } } impl UrlMatchingFunction { /// Parse a URL matching function for a`@document` rule's condition. pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<UrlMatchingFunction, ParseError<'i>> { if input.try(|input| input.expect_function_matching("url-prefix")).is_ok() { parse_quoted_or_unquoted_string!(input, UrlMatchingFunction::UrlPrefix) } else if input.try(|input| input.expect_function_matching("domain")).is_ok() {
input.try(|input| input.expect_function_matching("regexp")).is_ok() { input.parse_nested_block(|input| { Ok(UrlMatchingFunction::RegExp(input.expect_string()?.into_owned())) }) } else if let Ok(url) = input.try(|input| SpecifiedUrl::parse(context, input)) { Ok(UrlMatchingFunction::Url(url)) } else { Err(StyleParseError::UnspecifiedError.into()) } } #[cfg(feature = "gecko")] /// Evaluate a URL matching function. pub fn evaluate(&self, device: &Device) -> bool { use gecko_bindings::bindings::Gecko_DocumentRule_UseForPresentation; use gecko_bindings::structs::URLMatchingFunction as GeckoUrlMatchingFunction; use nsstring::nsCString; let func = match *self { UrlMatchingFunction::Url(_) => GeckoUrlMatchingFunction::eURL, UrlMatchingFunction::UrlPrefix(_) => GeckoUrlMatchingFunction::eURLPrefix, UrlMatchingFunction::Domain(_) => GeckoUrlMatchingFunction::eDomain, UrlMatchingFunction::RegExp(_) => GeckoUrlMatchingFunction::eRegExp, }; let pattern = nsCString::from(match *self { UrlMatchingFunction::Url(ref url) => url.as_str(), UrlMatchingFunction::UrlPrefix(ref pat) | UrlMatchingFunction::Domain(ref pat) | UrlMatchingFunction::RegExp(ref pat) => pat, }); unsafe { Gecko_DocumentRule_UseForPresentation(&*device.pres_context, &*pattern, func) } } #[cfg(not(feature = "gecko"))] /// Evaluate a URL matching function. pub fn evaluate(&self, _: &Device) -> bool { false } } impl ToCss for UrlMatchingFunction { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { UrlMatchingFunction::Url(ref url) => { url.to_css(dest) }, UrlMatchingFunction::UrlPrefix(ref url_prefix) => { dest.write_str("url-prefix(")?; url_prefix.to_css(dest)?; dest.write_str(")") }, UrlMatchingFunction::Domain(ref domain) => { dest.write_str("domain(")?; domain.to_css(dest)?; dest.write_str(")") }, UrlMatchingFunction::RegExp(ref regex) => { dest.write_str("regexp(")?; regex.to_css(dest)?; dest.write_str(")") }, } } } /// A `@document` rule's condition. /// /// https://www.w3.org/TR/2012/WD-css3-conditional-20120911/#at-document /// /// The `@document` rule's condition is written as a comma-separated list of /// URL matching functions, and the condition evaluates to true whenever any /// one of those functions evaluates to true. #[derive(Clone, Debug)] pub struct DocumentCondition(Vec<UrlMatchingFunction>); impl DocumentCondition { /// Parse a document condition. pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> { input.parse_comma_separated(|input| UrlMatchingFunction::parse(context, input)) .map(DocumentCondition) } /// Evaluate a document condition. pub fn evaluate(&self, device: &Device) -> bool { self.0.iter().any(|ref url_matching_function| url_matching_function.evaluate(device) ) } } impl ToCss for DocumentCondition { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { let mut iter = self.0.iter(); let first = iter.next() .expect("Empty DocumentCondition, should contain at least one URL matching function"); first.to_css(dest)?; for url_matching_function in iter { dest.write_str(", ")?; url_matching_function.to_css(dest)?; } Ok(()) } }
parse_quoted_or_unquoted_string!(input, UrlMatchingFunction::Domain) } else if
conditional_block
document_rule.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/. */ //! [@document rules](https://www.w3.org/TR/2012/WD-css3-conditional-20120911/#at-document) //! initially in CSS Conditional Rules Module Level 3, @document has been postponed to the level 4. //! We implement the prefixed `@-moz-document`. use cssparser::{Parser, Token, SourceLocation, BasicParseError}; use media_queries::Device; use parser::{Parse, ParserContext}; use shared_lock::{DeepCloneWithLock, Locked, SharedRwLock, SharedRwLockReadGuard, ToCssWithGuard}; use std::fmt; use style_traits::{ToCss, ParseError, StyleParseError}; use stylearc::Arc; use stylesheets::CssRules; use values::specified::url::SpecifiedUrl; #[derive(Debug)] /// A @-moz-document rule pub struct DocumentRule { /// The parsed condition pub condition: DocumentCondition, /// Child rules pub rules: Arc<Locked<CssRules>>, /// The line and column of the rule's source code. pub source_location: SourceLocation, } impl ToCssWithGuard for DocumentRule { fn to_css<W>(&self, guard: &SharedRwLockReadGuard, dest: &mut W) -> fmt::Result where W: fmt::Write
} impl DeepCloneWithLock for DocumentRule { /// Deep clones this DocumentRule. fn deep_clone_with_lock( &self, lock: &SharedRwLock, guard: &SharedRwLockReadGuard, ) -> Self { let rules = self.rules.read_with(guard); DocumentRule { condition: self.condition.clone(), rules: Arc::new(lock.wrap(rules.deep_clone_with_lock(lock, guard))), source_location: self.source_location.clone(), } } } /// A URL matching function for a `@document` rule's condition. #[derive(Clone, Debug)] pub enum UrlMatchingFunction { /// Exact URL matching function. It evaluates to true whenever the /// URL of the document being styled is exactly the URL given. Url(SpecifiedUrl), /// URL prefix matching function. It evaluates to true whenever the /// URL of the document being styled has the argument to the /// function as an initial substring (which is true when the two /// strings are equal). When the argument is the empty string, /// it evaluates to true for all documents. UrlPrefix(String), /// Domain matching function. It evaluates to true whenever the URL /// of the document being styled has a host subcomponent and that /// host subcomponent is exactly the argument to the ‘domain()’ /// function or a final substring of the host component is a /// period (U+002E) immediately followed by the argument to the /// ‘domain()’ function. Domain(String), /// Regular expression matching function. It evaluates to true /// whenever the regular expression matches the entirety of the URL /// of the document being styled. RegExp(String), } macro_rules! parse_quoted_or_unquoted_string { ($input:ident, $url_matching_function:expr) => { $input.parse_nested_block(|input| { let start = input.position(); input.parse_entirely(|input| { match input.next() { Ok(Token::QuotedString(value)) => Ok($url_matching_function(value.into_owned())), Ok(t) => Err(BasicParseError::UnexpectedToken(t).into()), Err(e) => Err(e.into()), } }).or_else(|_: ParseError| { while let Ok(_) = input.next() {} Ok($url_matching_function(input.slice_from(start).to_string())) }) }) } } impl UrlMatchingFunction { /// Parse a URL matching function for a`@document` rule's condition. pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<UrlMatchingFunction, ParseError<'i>> { if input.try(|input| input.expect_function_matching("url-prefix")).is_ok() { parse_quoted_or_unquoted_string!(input, UrlMatchingFunction::UrlPrefix) } else if input.try(|input| input.expect_function_matching("domain")).is_ok() { parse_quoted_or_unquoted_string!(input, UrlMatchingFunction::Domain) } else if input.try(|input| input.expect_function_matching("regexp")).is_ok() { input.parse_nested_block(|input| { Ok(UrlMatchingFunction::RegExp(input.expect_string()?.into_owned())) }) } else if let Ok(url) = input.try(|input| SpecifiedUrl::parse(context, input)) { Ok(UrlMatchingFunction::Url(url)) } else { Err(StyleParseError::UnspecifiedError.into()) } } #[cfg(feature = "gecko")] /// Evaluate a URL matching function. pub fn evaluate(&self, device: &Device) -> bool { use gecko_bindings::bindings::Gecko_DocumentRule_UseForPresentation; use gecko_bindings::structs::URLMatchingFunction as GeckoUrlMatchingFunction; use nsstring::nsCString; let func = match *self { UrlMatchingFunction::Url(_) => GeckoUrlMatchingFunction::eURL, UrlMatchingFunction::UrlPrefix(_) => GeckoUrlMatchingFunction::eURLPrefix, UrlMatchingFunction::Domain(_) => GeckoUrlMatchingFunction::eDomain, UrlMatchingFunction::RegExp(_) => GeckoUrlMatchingFunction::eRegExp, }; let pattern = nsCString::from(match *self { UrlMatchingFunction::Url(ref url) => url.as_str(), UrlMatchingFunction::UrlPrefix(ref pat) | UrlMatchingFunction::Domain(ref pat) | UrlMatchingFunction::RegExp(ref pat) => pat, }); unsafe { Gecko_DocumentRule_UseForPresentation(&*device.pres_context, &*pattern, func) } } #[cfg(not(feature = "gecko"))] /// Evaluate a URL matching function. pub fn evaluate(&self, _: &Device) -> bool { false } } impl ToCss for UrlMatchingFunction { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { UrlMatchingFunction::Url(ref url) => { url.to_css(dest) }, UrlMatchingFunction::UrlPrefix(ref url_prefix) => { dest.write_str("url-prefix(")?; url_prefix.to_css(dest)?; dest.write_str(")") }, UrlMatchingFunction::Domain(ref domain) => { dest.write_str("domain(")?; domain.to_css(dest)?; dest.write_str(")") }, UrlMatchingFunction::RegExp(ref regex) => { dest.write_str("regexp(")?; regex.to_css(dest)?; dest.write_str(")") }, } } } /// A `@document` rule's condition. /// /// https://www.w3.org/TR/2012/WD-css3-conditional-20120911/#at-document /// /// The `@document` rule's condition is written as a comma-separated list of /// URL matching functions, and the condition evaluates to true whenever any /// one of those functions evaluates to true. #[derive(Clone, Debug)] pub struct DocumentCondition(Vec<UrlMatchingFunction>); impl DocumentCondition { /// Parse a document condition. pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> { input.parse_comma_separated(|input| UrlMatchingFunction::parse(context, input)) .map(DocumentCondition) } /// Evaluate a document condition. pub fn evaluate(&self, device: &Device) -> bool { self.0.iter().any(|ref url_matching_function| url_matching_function.evaluate(device) ) } } impl ToCss for DocumentCondition { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { let mut iter = self.0.iter(); let first = iter.next() .expect("Empty DocumentCondition, should contain at least one URL matching function"); first.to_css(dest)?; for url_matching_function in iter { dest.write_str(", ")?; url_matching_function.to_css(dest)?; } Ok(()) } }
{ try!(dest.write_str("@-moz-document ")); try!(self.condition.to_css(dest)); try!(dest.write_str(" {")); for rule in self.rules.read_with(guard).0.iter() { try!(dest.write_str(" ")); try!(rule.to_css(guard, dest)); } dest.write_str(" }") }
identifier_body
document_rule.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/. */ //! [@document rules](https://www.w3.org/TR/2012/WD-css3-conditional-20120911/#at-document) //! initially in CSS Conditional Rules Module Level 3, @document has been postponed to the level 4. //! We implement the prefixed `@-moz-document`. use cssparser::{Parser, Token, SourceLocation, BasicParseError}; use media_queries::Device; use parser::{Parse, ParserContext}; use shared_lock::{DeepCloneWithLock, Locked, SharedRwLock, SharedRwLockReadGuard, ToCssWithGuard}; use std::fmt; use style_traits::{ToCss, ParseError, StyleParseError}; use stylearc::Arc; use stylesheets::CssRules; use values::specified::url::SpecifiedUrl; #[derive(Debug)] /// A @-moz-document rule pub struct
{ /// The parsed condition pub condition: DocumentCondition, /// Child rules pub rules: Arc<Locked<CssRules>>, /// The line and column of the rule's source code. pub source_location: SourceLocation, } impl ToCssWithGuard for DocumentRule { fn to_css<W>(&self, guard: &SharedRwLockReadGuard, dest: &mut W) -> fmt::Result where W: fmt::Write { try!(dest.write_str("@-moz-document ")); try!(self.condition.to_css(dest)); try!(dest.write_str(" {")); for rule in self.rules.read_with(guard).0.iter() { try!(dest.write_str(" ")); try!(rule.to_css(guard, dest)); } dest.write_str(" }") } } impl DeepCloneWithLock for DocumentRule { /// Deep clones this DocumentRule. fn deep_clone_with_lock( &self, lock: &SharedRwLock, guard: &SharedRwLockReadGuard, ) -> Self { let rules = self.rules.read_with(guard); DocumentRule { condition: self.condition.clone(), rules: Arc::new(lock.wrap(rules.deep_clone_with_lock(lock, guard))), source_location: self.source_location.clone(), } } } /// A URL matching function for a `@document` rule's condition. #[derive(Clone, Debug)] pub enum UrlMatchingFunction { /// Exact URL matching function. It evaluates to true whenever the /// URL of the document being styled is exactly the URL given. Url(SpecifiedUrl), /// URL prefix matching function. It evaluates to true whenever the /// URL of the document being styled has the argument to the /// function as an initial substring (which is true when the two /// strings are equal). When the argument is the empty string, /// it evaluates to true for all documents. UrlPrefix(String), /// Domain matching function. It evaluates to true whenever the URL /// of the document being styled has a host subcomponent and that /// host subcomponent is exactly the argument to the ‘domain()’ /// function or a final substring of the host component is a /// period (U+002E) immediately followed by the argument to the /// ‘domain()’ function. Domain(String), /// Regular expression matching function. It evaluates to true /// whenever the regular expression matches the entirety of the URL /// of the document being styled. RegExp(String), } macro_rules! parse_quoted_or_unquoted_string { ($input:ident, $url_matching_function:expr) => { $input.parse_nested_block(|input| { let start = input.position(); input.parse_entirely(|input| { match input.next() { Ok(Token::QuotedString(value)) => Ok($url_matching_function(value.into_owned())), Ok(t) => Err(BasicParseError::UnexpectedToken(t).into()), Err(e) => Err(e.into()), } }).or_else(|_: ParseError| { while let Ok(_) = input.next() {} Ok($url_matching_function(input.slice_from(start).to_string())) }) }) } } impl UrlMatchingFunction { /// Parse a URL matching function for a`@document` rule's condition. pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<UrlMatchingFunction, ParseError<'i>> { if input.try(|input| input.expect_function_matching("url-prefix")).is_ok() { parse_quoted_or_unquoted_string!(input, UrlMatchingFunction::UrlPrefix) } else if input.try(|input| input.expect_function_matching("domain")).is_ok() { parse_quoted_or_unquoted_string!(input, UrlMatchingFunction::Domain) } else if input.try(|input| input.expect_function_matching("regexp")).is_ok() { input.parse_nested_block(|input| { Ok(UrlMatchingFunction::RegExp(input.expect_string()?.into_owned())) }) } else if let Ok(url) = input.try(|input| SpecifiedUrl::parse(context, input)) { Ok(UrlMatchingFunction::Url(url)) } else { Err(StyleParseError::UnspecifiedError.into()) } } #[cfg(feature = "gecko")] /// Evaluate a URL matching function. pub fn evaluate(&self, device: &Device) -> bool { use gecko_bindings::bindings::Gecko_DocumentRule_UseForPresentation; use gecko_bindings::structs::URLMatchingFunction as GeckoUrlMatchingFunction; use nsstring::nsCString; let func = match *self { UrlMatchingFunction::Url(_) => GeckoUrlMatchingFunction::eURL, UrlMatchingFunction::UrlPrefix(_) => GeckoUrlMatchingFunction::eURLPrefix, UrlMatchingFunction::Domain(_) => GeckoUrlMatchingFunction::eDomain, UrlMatchingFunction::RegExp(_) => GeckoUrlMatchingFunction::eRegExp, }; let pattern = nsCString::from(match *self { UrlMatchingFunction::Url(ref url) => url.as_str(), UrlMatchingFunction::UrlPrefix(ref pat) | UrlMatchingFunction::Domain(ref pat) | UrlMatchingFunction::RegExp(ref pat) => pat, }); unsafe { Gecko_DocumentRule_UseForPresentation(&*device.pres_context, &*pattern, func) } } #[cfg(not(feature = "gecko"))] /// Evaluate a URL matching function. pub fn evaluate(&self, _: &Device) -> bool { false } } impl ToCss for UrlMatchingFunction { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { UrlMatchingFunction::Url(ref url) => { url.to_css(dest) }, UrlMatchingFunction::UrlPrefix(ref url_prefix) => { dest.write_str("url-prefix(")?; url_prefix.to_css(dest)?; dest.write_str(")") }, UrlMatchingFunction::Domain(ref domain) => { dest.write_str("domain(")?; domain.to_css(dest)?; dest.write_str(")") }, UrlMatchingFunction::RegExp(ref regex) => { dest.write_str("regexp(")?; regex.to_css(dest)?; dest.write_str(")") }, } } } /// A `@document` rule's condition. /// /// https://www.w3.org/TR/2012/WD-css3-conditional-20120911/#at-document /// /// The `@document` rule's condition is written as a comma-separated list of /// URL matching functions, and the condition evaluates to true whenever any /// one of those functions evaluates to true. #[derive(Clone, Debug)] pub struct DocumentCondition(Vec<UrlMatchingFunction>); impl DocumentCondition { /// Parse a document condition. pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> { input.parse_comma_separated(|input| UrlMatchingFunction::parse(context, input)) .map(DocumentCondition) } /// Evaluate a document condition. pub fn evaluate(&self, device: &Device) -> bool { self.0.iter().any(|ref url_matching_function| url_matching_function.evaluate(device) ) } } impl ToCss for DocumentCondition { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { let mut iter = self.0.iter(); let first = iter.next() .expect("Empty DocumentCondition, should contain at least one URL matching function"); first.to_css(dest)?; for url_matching_function in iter { dest.write_str(", ")?; url_matching_function.to_css(dest)?; } Ok(()) } }
DocumentRule
identifier_name
issue-4264.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. // pretty-compare-only // pretty-mode:typed // pp-exact:issue-4264.pp // #4264 fixed-length vector types pub fn foo(_: [int,..3]) {} pub fn bar() { const FOO: uint = 5u - 4u; let _: [(),..FOO] = [()]; let _ : [(),..1u] = [()]; let _ = &([1i,2,3]) as *const _ as *const [int,..3u]; format!("test"); }
pub type Foo = [int,..3u]; pub struct Bar { pub x: [int,..3u] } pub struct TupleBar([int,..4u]); pub enum Baz { BazVariant([int,..5u]) } pub fn id<T>(x: T) -> T { x } pub fn use_id() { let _ = id::<[int,..3u]>([1,2,3]); } fn main() {}
random_line_split
issue-4264.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. // pretty-compare-only // pretty-mode:typed // pp-exact:issue-4264.pp // #4264 fixed-length vector types pub fn foo(_: [int,..3]) {} pub fn bar() { const FOO: uint = 5u - 4u; let _: [(),..FOO] = [()]; let _ : [(),..1u] = [()]; let _ = &([1i,2,3]) as *const _ as *const [int,..3u]; format!("test"); } pub type Foo = [int,..3u]; pub struct Bar { pub x: [int,..3u] } pub struct TupleBar([int,..4u]); pub enum Baz { BazVariant([int,..5u]) } pub fn id<T>(x: T) -> T
pub fn use_id() { let _ = id::<[int,..3u]>([1,2,3]); } fn main() {}
{ x }
identifier_body
issue-4264.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. // pretty-compare-only // pretty-mode:typed // pp-exact:issue-4264.pp // #4264 fixed-length vector types pub fn foo(_: [int,..3]) {} pub fn bar() { const FOO: uint = 5u - 4u; let _: [(),..FOO] = [()]; let _ : [(),..1u] = [()]; let _ = &([1i,2,3]) as *const _ as *const [int,..3u]; format!("test"); } pub type Foo = [int,..3u]; pub struct Bar { pub x: [int,..3u] } pub struct
([int,..4u]); pub enum Baz { BazVariant([int,..5u]) } pub fn id<T>(x: T) -> T { x } pub fn use_id() { let _ = id::<[int,..3u]>([1,2,3]); } fn main() {}
TupleBar
identifier_name
mod.rs
/* convert module * === * */ use std::fmt; use std::fmt::{Display, Formatter}; use std::rc::Rc; use ::runtime::units::{Unit, UnitDatabase}; use ::runtime::parse::ConvPrimitive; use ::utils::{NO_PREFIX, prefix_as_num}; #[derive(Debug)] pub enum ConversionError { OutOfRange(bool), // input or output value not a valid f64, false: input UnitNotFound(bool), // the unit was not found, false: input TypeMismatch, // the units' types disagree, ie volume into length } const INPUT: bool = false; const OUTPUT: bool = true; #[derive(Debug, Copy, Clone)] pub enum
{ Short, Desc, Long, } impl Display for ConversionFmt { fn fmt(&self, f: &mut Formatter) -> fmt::Result { match *self { ConversionFmt::Short => write!(f, "s: short / value only"), ConversionFmt::Desc => write!(f, "d: descriptive / value and output unit"), ConversionFmt::Long => write!(f, "l: long / input and output values and units"), } } } #[derive(Debug)] pub struct Conversion { from_prefix: char, to_prefix: char, pub from_alias: String, pub to_alias: String, pub from_tag: Option<String>, pub to_tag: Option<String>, pub from: Option<Rc<Unit>>, pub to: Option<Rc<Unit>>, pub input: f64, pub result: Result<f64, ConversionError>, pub format: ConversionFmt, } impl Conversion { fn new(input_prefix: char, input_alias: String, input_tag: Option<String>, output_prefix: char, output_alias: String, output_tag: Option<String>, input_val: f64) -> Conversion { Conversion { from_prefix: input_prefix, to_prefix: output_prefix, from_alias: input_alias, to_alias: output_alias, from_tag: input_tag, to_tag: output_tag, from: None, to: None, input: input_val, result: Ok(1.0), format: ConversionFmt::Desc, } } } impl Display for Conversion { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.result { Ok(ref output) => { match self.format { ConversionFmt::Short => write!(f, "{}", output), ConversionFmt::Desc => { let mut prefix = String::with_capacity(1); if self.to_prefix!= NO_PREFIX { prefix.push(self.to_prefix); } write!(f, "{} {}{}", output, prefix, self.to_alias) }, ConversionFmt::Long => { let mut to_prefix = String::with_capacity(1); let mut from_prefix = String::with_capacity(1); if self.to_prefix!= NO_PREFIX { to_prefix.push(self.to_prefix); } if self.from_prefix!= NO_PREFIX { from_prefix.push(self.from_prefix); } write!(f, "{} {}{} = {} {}{}", self.input, from_prefix, self.from_alias, output, to_prefix, self.to_alias) }, } }, Err(ref err) => { match err { &ConversionError::OutOfRange(in_or_out) => { write!(f, "Conversion error: {} value is out of range", if in_or_out == OUTPUT { "output" } else { "input" }) }, &ConversionError::UnitNotFound(in_or_out) => { // TODO output tag write!(f, "Conversion error: no unit called \'{}\' was found", if in_or_out == OUTPUT { &self.to_alias } else { &self.from_alias }) }, &ConversionError::TypeMismatch => write!(f, "Conversion error: input and output types differ.\ \'{}\' is a {} and \'{}\' is a {}", self.from_alias, self.from.as_ref().unwrap().unit_type, self.to_alias, self.to.as_ref().unwrap().unit_type), } }, } } } /* Performs a unit conversion given as an input value, input unit and prefix, * and an output unit and prefix. Fetches the units from the given units database * A struct conversion is returned allowing the caller to do with it as they * please. Note that struct Conversion implements the Display trait and tracks * its own validity / error state. This function returns as soon as an error is * encountered. * * Parameters: * - input: the value to be converted * - from_prefix: the single character metric prefix of the input unit * - from: name / alias of the unit to that will be converted * - to_prefix: the single character metric prefix of the output unit * - to: name / alias of the unit to convert to * - units: reference to the database that holds all of the units * * Stages of Conversion: * 1. scale input using prefix and dimensions * 2. invert result if necessary * 3. change result to base units * 4. adjust result to output scale * 5. change result to output units * 6. invert result if necessary * 7. scale result using prefix and dimensions */ pub fn convert(input: f64, from_prefix: char, from: String, from_tag: Option<String>, to_prefix: char, to: String, to_tag: Option<String>, units: &UnitDatabase) -> Conversion { //println!("from_tag: {:?} to_tag: {:?}", from_tag, to_tag); let mut conversion = Conversion::new(from_prefix,from, from_tag, to_prefix,to, to_tag, input); // if the input value is NaN, INF, or too small // Exactly 0 is acceptable however which is_normal() does not account for if (!conversion.input.is_normal()) && (conversion.input!= 0.0) { conversion.result = Err(ConversionError::OutOfRange(INPUT)); return conversion; } conversion.from = units.query(&conversion.from_alias, conversion.from_tag.as_ref()); conversion.to = units.query(&conversion.to_alias, conversion.to_tag.as_ref()); if conversion.from.is_none() { conversion.result = Err(ConversionError::UnitNotFound(INPUT)); } if conversion.to.is_none() { conversion.result = Err(ConversionError::UnitNotFound(OUTPUT)); } if conversion.result.is_err() { return conversion; } if conversion.to.as_ref().unwrap().unit_type!= conversion.from.as_ref().unwrap().unit_type { conversion.result = Err(ConversionError::TypeMismatch); return conversion; } // do not initialize yet. we will fetch these values from conversion let from_conv_factor: f64; let from_zero_point: f64; let from_dims: i32; let from_is_inverse: bool; let to_conv_factor: f64; let to_zero_point: f64; let to_dims: i32; let to_is_inverse: bool; { // borrow scope for retrieving the unit properties // avoids massive method chains on struct Conversion let unit_from = conversion.from.as_ref().unwrap(); from_conv_factor = unit_from.conv_factor; from_zero_point = unit_from.zero_point; from_dims = unit_from.dimensions as i32; from_is_inverse = unit_from.inverse; let unit_to = conversion.to.as_ref().unwrap(); to_conv_factor = unit_to.conv_factor; to_zero_point = unit_to.zero_point; to_dims = unit_to.dimensions as i32; to_is_inverse = unit_to.inverse; } // end borrow scope // S1 let mut output_val = conversion.input * prefix_as_num( conversion.from_prefix) .unwrap().powi(from_dims); // S2 if from_is_inverse { output_val = 1.0 / output_val; } output_val *= from_conv_factor; // S3 output_val += from_zero_point - to_zero_point; // S4 output_val /= to_conv_factor; // S5 // S6 if to_is_inverse { output_val = 1.0 / output_val; } // S7 output_val /= prefix_as_num(conversion.to_prefix).unwrap().powi(to_dims); // if the output value is NaN, INF, or too small to properly represent // Exactly 0 is acceptable however which is_normal() does not account for if (!output_val.is_normal()) && (output_val!= 0.0) { conversion.result = Err(ConversionError::OutOfRange(OUTPUT)); return conversion; } conversion.result = Ok(output_val); conversion } pub fn convert_all(conv_primitive: ConvPrimitive, units: &UnitDatabase) -> Vec<Conversion> { let mut all_conversions = Vec::with_capacity(1); for value_expr in conv_primitive.input_vals { for output_unit in conv_primitive.output_units.iter() { //println!("{:?}", output_unit); all_conversions.push( convert(value_expr.value, conv_primitive.input_unit.prefix, conv_primitive.input_unit.alias.clone().unwrap(), conv_primitive.input_unit.tag.clone(), output_unit.clone().prefix, output_unit.clone().alias.unwrap(), output_unit.tag.clone(), units) ); } } all_conversions }
ConversionFmt
identifier_name
mod.rs
/* convert module * === * */ use std::fmt; use std::fmt::{Display, Formatter}; use std::rc::Rc; use ::runtime::units::{Unit, UnitDatabase}; use ::runtime::parse::ConvPrimitive; use ::utils::{NO_PREFIX, prefix_as_num}; #[derive(Debug)] pub enum ConversionError { OutOfRange(bool), // input or output value not a valid f64, false: input UnitNotFound(bool), // the unit was not found, false: input TypeMismatch, // the units' types disagree, ie volume into length } const INPUT: bool = false; const OUTPUT: bool = true; #[derive(Debug, Copy, Clone)] pub enum ConversionFmt { Short, Desc, Long, } impl Display for ConversionFmt { fn fmt(&self, f: &mut Formatter) -> fmt::Result { match *self { ConversionFmt::Short => write!(f, "s: short / value only"), ConversionFmt::Desc => write!(f, "d: descriptive / value and output unit"), ConversionFmt::Long => write!(f, "l: long / input and output values and units"), } } } #[derive(Debug)] pub struct Conversion { from_prefix: char, to_prefix: char, pub from_alias: String, pub to_alias: String, pub from_tag: Option<String>, pub to_tag: Option<String>, pub from: Option<Rc<Unit>>, pub to: Option<Rc<Unit>>, pub input: f64, pub result: Result<f64, ConversionError>, pub format: ConversionFmt, } impl Conversion { fn new(input_prefix: char, input_alias: String, input_tag: Option<String>, output_prefix: char, output_alias: String, output_tag: Option<String>, input_val: f64) -> Conversion { Conversion { from_prefix: input_prefix, to_prefix: output_prefix, from_alias: input_alias, to_alias: output_alias, from_tag: input_tag, to_tag: output_tag, from: None, to: None, input: input_val, result: Ok(1.0), format: ConversionFmt::Desc, } } } impl Display for Conversion { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.result { Ok(ref output) => { match self.format { ConversionFmt::Short => write!(f, "{}", output), ConversionFmt::Desc => { let mut prefix = String::with_capacity(1); if self.to_prefix!= NO_PREFIX { prefix.push(self.to_prefix); } write!(f, "{} {}{}", output, prefix, self.to_alias) }, ConversionFmt::Long => { let mut to_prefix = String::with_capacity(1); let mut from_prefix = String::with_capacity(1); if self.to_prefix!= NO_PREFIX { to_prefix.push(self.to_prefix); } if self.from_prefix!= NO_PREFIX { from_prefix.push(self.from_prefix); } write!(f, "{} {}{} = {} {}{}", self.input, from_prefix, self.from_alias, output, to_prefix, self.to_alias) }, } }, Err(ref err) => { match err { &ConversionError::OutOfRange(in_or_out) => { write!(f, "Conversion error: {} value is out of range", if in_or_out == OUTPUT { "output" } else { "input" }) }, &ConversionError::UnitNotFound(in_or_out) => { // TODO output tag write!(f, "Conversion error: no unit called \'{}\' was found", if in_or_out == OUTPUT { &self.to_alias } else { &self.from_alias }) }, &ConversionError::TypeMismatch => write!(f, "Conversion error: input and output types differ.\ \'{}\' is a {} and \'{}\' is a {}", self.from_alias, self.from.as_ref().unwrap().unit_type, self.to_alias, self.to.as_ref().unwrap().unit_type), } }, } } } /* Performs a unit conversion given as an input value, input unit and prefix, * and an output unit and prefix. Fetches the units from the given units database * A struct conversion is returned allowing the caller to do with it as they * please. Note that struct Conversion implements the Display trait and tracks * its own validity / error state. This function returns as soon as an error is * encountered. * * Parameters: * - input: the value to be converted * - from_prefix: the single character metric prefix of the input unit * - from: name / alias of the unit to that will be converted * - to_prefix: the single character metric prefix of the output unit * - to: name / alias of the unit to convert to * - units: reference to the database that holds all of the units * * Stages of Conversion: * 1. scale input using prefix and dimensions * 2. invert result if necessary * 3. change result to base units * 4. adjust result to output scale * 5. change result to output units * 6. invert result if necessary * 7. scale result using prefix and dimensions */ pub fn convert(input: f64, from_prefix: char, from: String, from_tag: Option<String>, to_prefix: char, to: String, to_tag: Option<String>, units: &UnitDatabase) -> Conversion { //println!("from_tag: {:?} to_tag: {:?}", from_tag, to_tag); let mut conversion = Conversion::new(from_prefix,from, from_tag, to_prefix,to, to_tag, input); // if the input value is NaN, INF, or too small // Exactly 0 is acceptable however which is_normal() does not account for if (!conversion.input.is_normal()) && (conversion.input!= 0.0) { conversion.result = Err(ConversionError::OutOfRange(INPUT)); return conversion; } conversion.from = units.query(&conversion.from_alias, conversion.from_tag.as_ref()); conversion.to = units.query(&conversion.to_alias, conversion.to_tag.as_ref()); if conversion.from.is_none() { conversion.result = Err(ConversionError::UnitNotFound(INPUT)); } if conversion.to.is_none() { conversion.result = Err(ConversionError::UnitNotFound(OUTPUT)); } if conversion.result.is_err() { return conversion; } if conversion.to.as_ref().unwrap().unit_type!= conversion.from.as_ref().unwrap().unit_type { conversion.result = Err(ConversionError::TypeMismatch); return conversion; } // do not initialize yet. we will fetch these values from conversion let from_conv_factor: f64; let from_zero_point: f64; let from_dims: i32; let from_is_inverse: bool; let to_conv_factor: f64; let to_zero_point: f64; let to_dims: i32; let to_is_inverse: bool; { // borrow scope for retrieving the unit properties // avoids massive method chains on struct Conversion let unit_from = conversion.from.as_ref().unwrap(); from_conv_factor = unit_from.conv_factor; from_zero_point = unit_from.zero_point; from_dims = unit_from.dimensions as i32; from_is_inverse = unit_from.inverse; let unit_to = conversion.to.as_ref().unwrap(); to_conv_factor = unit_to.conv_factor; to_zero_point = unit_to.zero_point; to_dims = unit_to.dimensions as i32; to_is_inverse = unit_to.inverse; } // end borrow scope
// S1 let mut output_val = conversion.input * prefix_as_num( conversion.from_prefix) .unwrap().powi(from_dims); // S2 if from_is_inverse { output_val = 1.0 / output_val; } output_val *= from_conv_factor; // S3 output_val += from_zero_point - to_zero_point; // S4 output_val /= to_conv_factor; // S5 // S6 if to_is_inverse { output_val = 1.0 / output_val; } // S7 output_val /= prefix_as_num(conversion.to_prefix).unwrap().powi(to_dims); // if the output value is NaN, INF, or too small to properly represent // Exactly 0 is acceptable however which is_normal() does not account for if (!output_val.is_normal()) && (output_val!= 0.0) { conversion.result = Err(ConversionError::OutOfRange(OUTPUT)); return conversion; } conversion.result = Ok(output_val); conversion } pub fn convert_all(conv_primitive: ConvPrimitive, units: &UnitDatabase) -> Vec<Conversion> { let mut all_conversions = Vec::with_capacity(1); for value_expr in conv_primitive.input_vals { for output_unit in conv_primitive.output_units.iter() { //println!("{:?}", output_unit); all_conversions.push( convert(value_expr.value, conv_primitive.input_unit.prefix, conv_primitive.input_unit.alias.clone().unwrap(), conv_primitive.input_unit.tag.clone(), output_unit.clone().prefix, output_unit.clone().alias.unwrap(), output_unit.tag.clone(), units) ); } } all_conversions }
random_line_split
static-relocation-model.rs
// revisions: x64 A64 ppc64le // assembly-output: emit-asm // [x64] compile-flags: --target x86_64-unknown-linux-gnu -Crelocation-model=static // [x64] needs-llvm-components: x86 // [A64] compile-flags: --target aarch64-unknown-linux-gnu -Crelocation-model=static // [A64] needs-llvm-components: aarch64 // [ppc64le] compile-flags: --target powerpc64le-unknown-linux-gnu -Crelocation-model=static // [ppc64le] needs-llvm-components: powerpc #![feature(no_core, lang_items)] #![no_core] #![crate_type="rlib"] #[lang="sized"] trait Sized {} #[lang="copy"] trait Copy {} #[lang="sync"] trait Sync {} #[lang = "drop_in_place"] fn drop_in_place<T>(_: *mut T) {} impl Copy for u8 {} impl Sync for u8 {} #[no_mangle]
fn chaenomeles(); } // CHECK-LABEL: banana: // x64: movb chaenomeles{{(\(%[a-z0-9]+\))?}}, %{{[a-z0-9]+}} // A64: adrp [[REG:[a-z0-9]+]], chaenomeles // A64-NEXT: ldrb {{[a-z0-9]+}}, {{\[}}[[REG]], :lo12:chaenomeles] #[no_mangle] pub fn banana() -> u8 { unsafe { *(chaenomeles as *mut u8) } } // CHECK-LABEL: peach: // x64: movb banana{{(\(%[a-z0-9]+\))?}}, %{{[a-z0-9]+}} // A64: adrp [[REG2:[a-z0-9]+]], banana // A64-NEXT: ldrb {{[a-z0-9]+}}, {{\[}}[[REG2]], :lo12:banana] #[no_mangle] pub fn peach() -> u8 { unsafe { *(banana as *mut u8) } } // CHECK-LABEL: mango: // x64: movq EXOCHORDA{{(\(%[a-z0-9]+\))?}}, %[[REG:[a-z0-9]+]] // x64-NEXT: movb (%[[REG]]), %{{[a-z0-9]+}} // A64: adrp [[REG2:[a-z0-9]+]], EXOCHORDA // A64-NEXT: ldr {{[a-z0-9]+}}, {{\[}}[[REG2]], :lo12:EXOCHORDA] #[no_mangle] pub fn mango() -> u8 { unsafe { *EXOCHORDA } } // CHECK-LABEL: orange: // x64: mov{{l|absq}} $PIERIS, %{{[a-z0-9]+}} // A64: adrp [[REG2:[a-z0-9]+]], PIERIS // A64-NEXT: add {{[a-z0-9]+}}, [[REG2]], :lo12:PIERIS #[no_mangle] pub fn orange() -> &'static u8 { &PIERIS } // For ppc64 we need to make sure to generate TOC entries even with the static relocation model // ppc64le:.tc chaenomeles[TC],chaenomeles // ppc64le:.tc banana[TC],banana // ppc64le:.tc EXOCHORDA[TC],EXOCHORDA // ppc64le:.tc PIERIS[TC],PIERIS
pub static PIERIS: u8 = 42; extern "C" { static EXOCHORDA: *mut u8;
random_line_split
static-relocation-model.rs
// revisions: x64 A64 ppc64le // assembly-output: emit-asm // [x64] compile-flags: --target x86_64-unknown-linux-gnu -Crelocation-model=static // [x64] needs-llvm-components: x86 // [A64] compile-flags: --target aarch64-unknown-linux-gnu -Crelocation-model=static // [A64] needs-llvm-components: aarch64 // [ppc64le] compile-flags: --target powerpc64le-unknown-linux-gnu -Crelocation-model=static // [ppc64le] needs-llvm-components: powerpc #![feature(no_core, lang_items)] #![no_core] #![crate_type="rlib"] #[lang="sized"] trait Sized {} #[lang="copy"] trait Copy {} #[lang="sync"] trait Sync {} #[lang = "drop_in_place"] fn drop_in_place<T>(_: *mut T) {} impl Copy for u8 {} impl Sync for u8 {} #[no_mangle] pub static PIERIS: u8 = 42; extern "C" { static EXOCHORDA: *mut u8; fn chaenomeles(); } // CHECK-LABEL: banana: // x64: movb chaenomeles{{(\(%[a-z0-9]+\))?}}, %{{[a-z0-9]+}} // A64: adrp [[REG:[a-z0-9]+]], chaenomeles // A64-NEXT: ldrb {{[a-z0-9]+}}, {{\[}}[[REG]], :lo12:chaenomeles] #[no_mangle] pub fn banana() -> u8 { unsafe { *(chaenomeles as *mut u8) } } // CHECK-LABEL: peach: // x64: movb banana{{(\(%[a-z0-9]+\))?}}, %{{[a-z0-9]+}} // A64: adrp [[REG2:[a-z0-9]+]], banana // A64-NEXT: ldrb {{[a-z0-9]+}}, {{\[}}[[REG2]], :lo12:banana] #[no_mangle] pub fn peach() -> u8 { unsafe { *(banana as *mut u8) } } // CHECK-LABEL: mango: // x64: movq EXOCHORDA{{(\(%[a-z0-9]+\))?}}, %[[REG:[a-z0-9]+]] // x64-NEXT: movb (%[[REG]]), %{{[a-z0-9]+}} // A64: adrp [[REG2:[a-z0-9]+]], EXOCHORDA // A64-NEXT: ldr {{[a-z0-9]+}}, {{\[}}[[REG2]], :lo12:EXOCHORDA] #[no_mangle] pub fn mango() -> u8 { unsafe { *EXOCHORDA } } // CHECK-LABEL: orange: // x64: mov{{l|absq}} $PIERIS, %{{[a-z0-9]+}} // A64: adrp [[REG2:[a-z0-9]+]], PIERIS // A64-NEXT: add {{[a-z0-9]+}}, [[REG2]], :lo12:PIERIS #[no_mangle] pub fn
() -> &'static u8 { &PIERIS } // For ppc64 we need to make sure to generate TOC entries even with the static relocation model // ppc64le:.tc chaenomeles[TC],chaenomeles // ppc64le:.tc banana[TC],banana // ppc64le:.tc EXOCHORDA[TC],EXOCHORDA // ppc64le:.tc PIERIS[TC],PIERIS
orange
identifier_name
static-relocation-model.rs
// revisions: x64 A64 ppc64le // assembly-output: emit-asm // [x64] compile-flags: --target x86_64-unknown-linux-gnu -Crelocation-model=static // [x64] needs-llvm-components: x86 // [A64] compile-flags: --target aarch64-unknown-linux-gnu -Crelocation-model=static // [A64] needs-llvm-components: aarch64 // [ppc64le] compile-flags: --target powerpc64le-unknown-linux-gnu -Crelocation-model=static // [ppc64le] needs-llvm-components: powerpc #![feature(no_core, lang_items)] #![no_core] #![crate_type="rlib"] #[lang="sized"] trait Sized {} #[lang="copy"] trait Copy {} #[lang="sync"] trait Sync {} #[lang = "drop_in_place"] fn drop_in_place<T>(_: *mut T) {} impl Copy for u8 {} impl Sync for u8 {} #[no_mangle] pub static PIERIS: u8 = 42; extern "C" { static EXOCHORDA: *mut u8; fn chaenomeles(); } // CHECK-LABEL: banana: // x64: movb chaenomeles{{(\(%[a-z0-9]+\))?}}, %{{[a-z0-9]+}} // A64: adrp [[REG:[a-z0-9]+]], chaenomeles // A64-NEXT: ldrb {{[a-z0-9]+}}, {{\[}}[[REG]], :lo12:chaenomeles] #[no_mangle] pub fn banana() -> u8 { unsafe { *(chaenomeles as *mut u8) } } // CHECK-LABEL: peach: // x64: movb banana{{(\(%[a-z0-9]+\))?}}, %{{[a-z0-9]+}} // A64: adrp [[REG2:[a-z0-9]+]], banana // A64-NEXT: ldrb {{[a-z0-9]+}}, {{\[}}[[REG2]], :lo12:banana] #[no_mangle] pub fn peach() -> u8 { unsafe { *(banana as *mut u8) } } // CHECK-LABEL: mango: // x64: movq EXOCHORDA{{(\(%[a-z0-9]+\))?}}, %[[REG:[a-z0-9]+]] // x64-NEXT: movb (%[[REG]]), %{{[a-z0-9]+}} // A64: adrp [[REG2:[a-z0-9]+]], EXOCHORDA // A64-NEXT: ldr {{[a-z0-9]+}}, {{\[}}[[REG2]], :lo12:EXOCHORDA] #[no_mangle] pub fn mango() -> u8 { unsafe { *EXOCHORDA } } // CHECK-LABEL: orange: // x64: mov{{l|absq}} $PIERIS, %{{[a-z0-9]+}} // A64: adrp [[REG2:[a-z0-9]+]], PIERIS // A64-NEXT: add {{[a-z0-9]+}}, [[REG2]], :lo12:PIERIS #[no_mangle] pub fn orange() -> &'static u8
// For ppc64 we need to make sure to generate TOC entries even with the static relocation model // ppc64le:.tc chaenomeles[TC],chaenomeles // ppc64le:.tc banana[TC],banana // ppc64le:.tc EXOCHORDA[TC],EXOCHORDA // ppc64le:.tc PIERIS[TC],PIERIS
{ &PIERIS }
identifier_body
unsized.rs
// compile-flags:-g // === GDB TESTS =================================================================================== // gdb-command:run // gdb-command:print *a
// gdb-command:print *b // gdbg-check:$2 = {value = {value = [...] "abc"}} // gdbr-check:$2 = unsized::Foo<unsized::Foo<[u8]>> {value: unsized::Foo<[u8]> {value: [...]}} #![feature(omit_gdb_pretty_printer_section)] #![omit_gdb_pretty_printer_section] struct Foo<T:?Sized> { value: T } fn main() { let foo: Foo<Foo<[u8; 4]>> = Foo { value: Foo { value: *b"abc\0" } }; let a: &Foo<[u8]> = &foo.value; let b: &Foo<Foo<[u8]>> = &foo; zzz(); // #break } fn zzz() { () }
// gdbg-check:$1 = {value = [...] "abc"} // gdbr-check:$1 = unsized::Foo<[u8]> {value: [...]}
random_line_split
unsized.rs
// compile-flags:-g // === GDB TESTS =================================================================================== // gdb-command:run // gdb-command:print *a // gdbg-check:$1 = {value = [...] "abc"} // gdbr-check:$1 = unsized::Foo<[u8]> {value: [...]} // gdb-command:print *b // gdbg-check:$2 = {value = {value = [...] "abc"}} // gdbr-check:$2 = unsized::Foo<unsized::Foo<[u8]>> {value: unsized::Foo<[u8]> {value: [...]}} #![feature(omit_gdb_pretty_printer_section)] #![omit_gdb_pretty_printer_section] struct
<T:?Sized> { value: T } fn main() { let foo: Foo<Foo<[u8; 4]>> = Foo { value: Foo { value: *b"abc\0" } }; let a: &Foo<[u8]> = &foo.value; let b: &Foo<Foo<[u8]>> = &foo; zzz(); // #break } fn zzz() { () }
Foo
identifier_name
feature-gate-unboxed-closures-manual-impls.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. #![allow(dead_code)] struct Foo; impl Fn<(), ()> for Foo { //~ ERROR manual implementations of `Fn` are experimental extern "rust-call" fn call(&self, args: ()) -> () {} } struct Bar; impl FnMut<(), ()> for Bar { //~ ERROR manual implementations of `FnMut` are experimental extern "rust-call" fn call_mut(&self, args: ()) -> () {} }
} fn main() {}
struct Baz; impl FnOnce<(), ()> for Baz { //~ ERROR manual implementations of `FnOnce` are experimental extern "rust-call" fn call_once(&self, args: ()) -> () {}
random_line_split
feature-gate-unboxed-closures-manual-impls.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. #![allow(dead_code)] struct Foo; impl Fn<(), ()> for Foo { //~ ERROR manual implementations of `Fn` are experimental extern "rust-call" fn call(&self, args: ()) -> () {} } struct Bar; impl FnMut<(), ()> for Bar { //~ ERROR manual implementations of `FnMut` are experimental extern "rust-call" fn call_mut(&self, args: ()) -> ()
} struct Baz; impl FnOnce<(), ()> for Baz { //~ ERROR manual implementations of `FnOnce` are experimental extern "rust-call" fn call_once(&self, args: ()) -> () {} } fn main() {}
{}
identifier_body
feature-gate-unboxed-closures-manual-impls.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. #![allow(dead_code)] struct Foo; impl Fn<(), ()> for Foo { //~ ERROR manual implementations of `Fn` are experimental extern "rust-call" fn call(&self, args: ()) -> () {} } struct Bar; impl FnMut<(), ()> for Bar { //~ ERROR manual implementations of `FnMut` are experimental extern "rust-call" fn
(&self, args: ()) -> () {} } struct Baz; impl FnOnce<(), ()> for Baz { //~ ERROR manual implementations of `FnOnce` are experimental extern "rust-call" fn call_once(&self, args: ()) -> () {} } fn main() {}
call_mut
identifier_name
main.rs
extern crate tera; use std::alloc::System; use tera::{Context, Tera}; #[global_allocator] static GLOBAL: System = System; static BIG_TABLE_TEMPLATE: &'static str = "<table> {% for row in table %} <tr>{% for col in row %}<td>{{ col }}</td>{% endfor %}</tr> {% endfor %} </table>"; fn main() { let size = 100; let mut table = Vec::with_capacity(size); for _ in 0..size { let mut inner = Vec::with_capacity(size); for i in 0..size {
table.push(inner); } let mut tera = Tera::default(); tera.add_raw_templates(vec![("big-table.html", BIG_TABLE_TEMPLATE)]).unwrap(); let mut ctx = Context::new(); ctx.insert("table", &table); let _ = tera.render("big-table.html", &ctx).unwrap(); println!("Done!"); }
inner.push(i); }
random_line_split
main.rs
extern crate tera; use std::alloc::System; use tera::{Context, Tera}; #[global_allocator] static GLOBAL: System = System; static BIG_TABLE_TEMPLATE: &'static str = "<table> {% for row in table %} <tr>{% for col in row %}<td>{{ col }}</td>{% endfor %}</tr> {% endfor %} </table>"; fn
() { let size = 100; let mut table = Vec::with_capacity(size); for _ in 0..size { let mut inner = Vec::with_capacity(size); for i in 0..size { inner.push(i); } table.push(inner); } let mut tera = Tera::default(); tera.add_raw_templates(vec![("big-table.html", BIG_TABLE_TEMPLATE)]).unwrap(); let mut ctx = Context::new(); ctx.insert("table", &table); let _ = tera.render("big-table.html", &ctx).unwrap(); println!("Done!"); }
main
identifier_name
main.rs
extern crate tera; use std::alloc::System; use tera::{Context, Tera}; #[global_allocator] static GLOBAL: System = System; static BIG_TABLE_TEMPLATE: &'static str = "<table> {% for row in table %} <tr>{% for col in row %}<td>{{ col }}</td>{% endfor %}</tr> {% endfor %} </table>"; fn main()
{ let size = 100; let mut table = Vec::with_capacity(size); for _ in 0..size { let mut inner = Vec::with_capacity(size); for i in 0..size { inner.push(i); } table.push(inner); } let mut tera = Tera::default(); tera.add_raw_templates(vec![("big-table.html", BIG_TABLE_TEMPLATE)]).unwrap(); let mut ctx = Context::new(); ctx.insert("table", &table); let _ = tera.render("big-table.html", &ctx).unwrap(); println!("Done!"); }
identifier_body
zhttpto.rs
// // zhttpto.rs // // Starting code for PS1 // Running on Rust 0.9 // // Note that this code has serious security risks! You should not run it // on any system with access to sensitive files. // // University of Virginia - cs4414 Spring 2014 // Weilin Xu and David Evans // Version 0.3 #[feature(globs)]; use std::io::*; use std::io::net::ip::{SocketAddr}; use std::{str,os}; use std::str; use std::io::File; static IP: &'static str = "127.0.0.1"; static PORT: int = 4414; static mut COUNT: int =0; fn
() { let addr = from_str::<SocketAddr>(format!("{:s}:{:d}", IP, PORT)).unwrap(); let mut acceptor = net::tcp::TcpListener::bind(addr).listen(); println(format!("Listening on [{:s}]...", addr.to_str())); for stream in acceptor.incoming() { // Spawn a task to handle the connection do spawn { let mut stream = stream; match stream { Some(ref mut s) => { match s.peer_name() { Some(pn) => {println(format!("Received connection from: [{:s}]", pn.to_str()));}, None => () } }, None => () } let mut buf = [0,..500]; stream.read(buf); let request_str = str::from_utf8(buf).to_owned(); if(request_str.contains("GET")){ let tempstr: ~[&str]= request_str.split(' ').collect(); if(tempstr[1].len() >2){ let file = Path::new(tempstr[1].slice_from(1)); println!("{}",tempstr[1].slice_from(1)); if tempstr[1].ends_with(".html") { match result(|| File::open(&file)) { Ok(mut f) => { println!("FILE OK"); let response: ~[u8] = f.read_to_end(); stream.write(response); }, Err(e) => { if e.kind == PermissionDenied { stream.write("404".as_bytes()); } else if e.kind == FileNotFound { stream.write("404".as_bytes()); } else { stream.write("io error".as_bytes()); } } } } } } println(format!("Received request :\n{:s}", request_str)); unsafe{ COUNT +=1; let response: ~str = ~"HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n <doctype!html><html><head><title>Hello, Rust!</title> <style>body { background-color: #111; color: #FFEEAA } h1 { font-size:2cm; text-align: center; color: black; text-shadow: 0 0 4mm red} h2 { font-size:2cm; text-align: center; color: black; text-shadow: 0 0 4mm green} </style></head> <body> <h1>Greetings, Krusty!</h1> <h2> Visitors:" + COUNT.to_str() + "</h2></body></html>\r\n"; stream.write(response.as_bytes()); println!("Connection terminates."); } } } } //fn loadFile(path: &str)-> &str{ //}
main
identifier_name
zhttpto.rs
// // zhttpto.rs // // Starting code for PS1 // Running on Rust 0.9 // // Note that this code has serious security risks! You should not run it // on any system with access to sensitive files. // // University of Virginia - cs4414 Spring 2014 // Weilin Xu and David Evans // Version 0.3 #[feature(globs)]; use std::io::*; use std::io::net::ip::{SocketAddr}; use std::{str,os}; use std::str; use std::io::File; static IP: &'static str = "127.0.0.1"; static PORT: int = 4414; static mut COUNT: int =0; fn main() { let addr = from_str::<SocketAddr>(format!("{:s}:{:d}", IP, PORT)).unwrap(); let mut acceptor = net::tcp::TcpListener::bind(addr).listen(); println(format!("Listening on [{:s}]...", addr.to_str())); for stream in acceptor.incoming() { // Spawn a task to handle the connection do spawn { let mut stream = stream; match stream { Some(ref mut s) => { match s.peer_name() { Some(pn) => {println(format!("Received connection from: [{:s}]", pn.to_str()));}, None => () }
stream.read(buf); let request_str = str::from_utf8(buf).to_owned(); if(request_str.contains("GET")){ let tempstr: ~[&str]= request_str.split(' ').collect(); if(tempstr[1].len() >2){ let file = Path::new(tempstr[1].slice_from(1)); println!("{}",tempstr[1].slice_from(1)); if tempstr[1].ends_with(".html") { match result(|| File::open(&file)) { Ok(mut f) => { println!("FILE OK"); let response: ~[u8] = f.read_to_end(); stream.write(response); }, Err(e) => { if e.kind == PermissionDenied { stream.write("404".as_bytes()); } else if e.kind == FileNotFound { stream.write("404".as_bytes()); } else { stream.write("io error".as_bytes()); } } } } } } println(format!("Received request :\n{:s}", request_str)); unsafe{ COUNT +=1; let response: ~str = ~"HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n <doctype!html><html><head><title>Hello, Rust!</title> <style>body { background-color: #111; color: #FFEEAA } h1 { font-size:2cm; text-align: center; color: black; text-shadow: 0 0 4mm red} h2 { font-size:2cm; text-align: center; color: black; text-shadow: 0 0 4mm green} </style></head> <body> <h1>Greetings, Krusty!</h1> <h2> Visitors:" + COUNT.to_str() + "</h2></body></html>\r\n"; stream.write(response.as_bytes()); println!("Connection terminates."); } } } } //fn loadFile(path: &str)-> &str{ //}
}, None => () } let mut buf = [0, ..500];
random_line_split
zhttpto.rs
// // zhttpto.rs // // Starting code for PS1 // Running on Rust 0.9 // // Note that this code has serious security risks! You should not run it // on any system with access to sensitive files. // // University of Virginia - cs4414 Spring 2014 // Weilin Xu and David Evans // Version 0.3 #[feature(globs)]; use std::io::*; use std::io::net::ip::{SocketAddr}; use std::{str,os}; use std::str; use std::io::File; static IP: &'static str = "127.0.0.1"; static PORT: int = 4414; static mut COUNT: int =0; fn main()
let mut buf = [0,..500]; stream.read(buf); let request_str = str::from_utf8(buf).to_owned(); if(request_str.contains("GET")){ let tempstr: ~[&str]= request_str.split(' ').collect(); if(tempstr[1].len() >2){ let file = Path::new(tempstr[1].slice_from(1)); println!("{}",tempstr[1].slice_from(1)); if tempstr[1].ends_with(".html") { match result(|| File::open(&file)) { Ok(mut f) => { println!("FILE OK"); let response: ~[u8] = f.read_to_end(); stream.write(response); }, Err(e) => { if e.kind == PermissionDenied { stream.write("404".as_bytes()); } else if e.kind == FileNotFound { stream.write("404".as_bytes()); } else { stream.write("io error".as_bytes()); } } } } } } println(format!("Received request :\n{:s}", request_str)); unsafe{ COUNT +=1; let response: ~str = ~"HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n <doctype!html><html><head><title>Hello, Rust!</title> <style>body { background-color: #111; color: #FFEEAA } h1 { font-size:2cm; text-align: center; color: black; text-shadow: 0 0 4mm red} h2 { font-size:2cm; text-align: center; color: black; text-shadow: 0 0 4mm green} </style></head> <body> <h1>Greetings, Krusty!</h1> <h2> Visitors:" + COUNT.to_str() + "</h2></body></html>\r\n"; stream.write(response.as_bytes()); println!("Connection terminates."); } } } } //fn loadFile(path: &str)-> &str{ //}
{ let addr = from_str::<SocketAddr>(format!("{:s}:{:d}", IP, PORT)).unwrap(); let mut acceptor = net::tcp::TcpListener::bind(addr).listen(); println(format!("Listening on [{:s}] ...", addr.to_str())); for stream in acceptor.incoming() { // Spawn a task to handle the connection do spawn { let mut stream = stream; match stream { Some(ref mut s) => { match s.peer_name() { Some(pn) => {println(format!("Received connection from: [{:s}]", pn.to_str()));}, None => () } }, None => () }
identifier_body
domstringmap.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::DOMStringMapBinding; use dom::bindings::codegen::Bindings::DOMStringMapBinding::DOMStringMapMethods; use dom::bindings::error::ErrorResult; use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, Root}; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::htmlelement::HTMLElement; use dom::node::window_from_node; use util::str::DOMString; #[dom_struct] pub struct DOMStringMap { reflector_: Reflector, element: JS<HTMLElement>, } impl DOMStringMap { fn new_inherited(element: &HTMLElement) -> DOMStringMap { DOMStringMap { reflector_: Reflector::new(), element: JS::from_ref(element), }
GlobalRef::Window(window.r()), DOMStringMapBinding::Wrap) } } // https://html.spec.whatwg.org/multipage/#domstringmap impl DOMStringMapMethods for DOMStringMap { // https://html.spec.whatwg.org/multipage/#dom-domstringmap-removeitem fn NamedDeleter(&self, name: DOMString) { self.element.delete_custom_attr(name) } // https://html.spec.whatwg.org/multipage/#dom-domstringmap-setitem fn NamedSetter(&self, name: DOMString, value: DOMString) -> ErrorResult { self.element.set_custom_attr(name, value) } // https://html.spec.whatwg.org/multipage/#dom-domstringmap-nameditem fn NamedGetter(&self, name: DOMString, found: &mut bool) -> DOMString { match self.element.get_custom_attr(name) { Some(value) => { *found = true; value.clone() }, None => { *found = false; DOMString::new() } } } // https://html.spec.whatwg.org/multipage/#the-domstringmap-interface:supported-property-names fn SupportedPropertyNames(&self) -> Vec<DOMString> { self.element.supported_prop_names_custom_attr().iter().cloned().collect() } }
} pub fn new(element: &HTMLElement) -> Root<DOMStringMap> { let window = window_from_node(element); reflect_dom_object(box DOMStringMap::new_inherited(element),
random_line_split
domstringmap.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::DOMStringMapBinding; use dom::bindings::codegen::Bindings::DOMStringMapBinding::DOMStringMapMethods; use dom::bindings::error::ErrorResult; use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, Root}; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::htmlelement::HTMLElement; use dom::node::window_from_node; use util::str::DOMString; #[dom_struct] pub struct DOMStringMap { reflector_: Reflector, element: JS<HTMLElement>, } impl DOMStringMap { fn new_inherited(element: &HTMLElement) -> DOMStringMap { DOMStringMap { reflector_: Reflector::new(), element: JS::from_ref(element), } } pub fn new(element: &HTMLElement) -> Root<DOMStringMap>
} // https://html.spec.whatwg.org/multipage/#domstringmap impl DOMStringMapMethods for DOMStringMap { // https://html.spec.whatwg.org/multipage/#dom-domstringmap-removeitem fn NamedDeleter(&self, name: DOMString) { self.element.delete_custom_attr(name) } // https://html.spec.whatwg.org/multipage/#dom-domstringmap-setitem fn NamedSetter(&self, name: DOMString, value: DOMString) -> ErrorResult { self.element.set_custom_attr(name, value) } // https://html.spec.whatwg.org/multipage/#dom-domstringmap-nameditem fn NamedGetter(&self, name: DOMString, found: &mut bool) -> DOMString { match self.element.get_custom_attr(name) { Some(value) => { *found = true; value.clone() }, None => { *found = false; DOMString::new() } } } // https://html.spec.whatwg.org/multipage/#the-domstringmap-interface:supported-property-names fn SupportedPropertyNames(&self) -> Vec<DOMString> { self.element.supported_prop_names_custom_attr().iter().cloned().collect() } }
{ let window = window_from_node(element); reflect_dom_object(box DOMStringMap::new_inherited(element), GlobalRef::Window(window.r()), DOMStringMapBinding::Wrap) }
identifier_body
domstringmap.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::DOMStringMapBinding; use dom::bindings::codegen::Bindings::DOMStringMapBinding::DOMStringMapMethods; use dom::bindings::error::ErrorResult; use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, Root}; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::htmlelement::HTMLElement; use dom::node::window_from_node; use util::str::DOMString; #[dom_struct] pub struct DOMStringMap { reflector_: Reflector, element: JS<HTMLElement>, } impl DOMStringMap { fn new_inherited(element: &HTMLElement) -> DOMStringMap { DOMStringMap { reflector_: Reflector::new(), element: JS::from_ref(element), } } pub fn new(element: &HTMLElement) -> Root<DOMStringMap> { let window = window_from_node(element); reflect_dom_object(box DOMStringMap::new_inherited(element), GlobalRef::Window(window.r()), DOMStringMapBinding::Wrap) } } // https://html.spec.whatwg.org/multipage/#domstringmap impl DOMStringMapMethods for DOMStringMap { // https://html.spec.whatwg.org/multipage/#dom-domstringmap-removeitem fn NamedDeleter(&self, name: DOMString) { self.element.delete_custom_attr(name) } // https://html.spec.whatwg.org/multipage/#dom-domstringmap-setitem fn NamedSetter(&self, name: DOMString, value: DOMString) -> ErrorResult { self.element.set_custom_attr(name, value) } // https://html.spec.whatwg.org/multipage/#dom-domstringmap-nameditem fn NamedGetter(&self, name: DOMString, found: &mut bool) -> DOMString { match self.element.get_custom_attr(name) { Some(value) => { *found = true; value.clone() }, None => { *found = false; DOMString::new() } } } // https://html.spec.whatwg.org/multipage/#the-domstringmap-interface:supported-property-names fn
(&self) -> Vec<DOMString> { self.element.supported_prop_names_custom_attr().iter().cloned().collect() } }
SupportedPropertyNames
identifier_name
video.rs
use ffmpeg::frame; use glium::texture::{SrgbTexture2d}; use glium::{Program, Display, VertexBuffer, Surface}; use glium::buffer::BufferView; use glium::buffer::BufferMode::Persistent; use glium::buffer::BufferType::PixelUnpackBuffer; use glium::index::PrimitiveType::TriangleStrip; use glium::index::NoIndices; use glium::texture::SrgbFormat::U8U8U8U8; use glium::texture::MipmapsOption::NoMipmap; use renderer::{Support}; #[derive(Copy, Clone, Debug)] struct Vertex { position: [f32; 2], texture: [f32; 2], } implement_vertex!(Vertex, position, texture); pub struct
<'a> { display: &'a Display, program: Program, vertices: VertexBuffer<Vertex>, timestamp: i64, buffer: Option<BufferView<[(u8, u8, u8, u8)]>>, texture: Option<SrgbTexture2d>, } impl<'a> Video<'a> { pub fn new<'b>(display: &'b Display) -> Video<'b> { Video { display: display, program: program!(display, 100 => { vertex: " #version 100 precision lowp float; attribute vec2 position; attribute vec2 texture; varying vec2 v_texture; void main() { gl_Position = vec4(position, 0.0, 1.0); v_texture = texture; } ", fragment: " #version 100 precision lowp float; uniform sampler2D tex; uniform float alpha; varying vec2 v_texture; void main() { gl_FragColor = texture2D(tex, v_texture); gl_FragColor.a = alpha; } ", }, ).unwrap(), vertices: VertexBuffer::new(display, &[ Vertex { position: [-1.0, 1.0], texture: [0.0, 0.0] }, Vertex { position: [ 1.0, 1.0], texture: [1.0, 0.0] }, Vertex { position: [-1.0, -1.0], texture: [0.0, 1.0] }, Vertex { position: [ 1.0, -1.0], texture: [1.0, 1.0] }, ]).unwrap(), timestamp: -1, buffer: None, texture: None, } } pub fn render<T: Surface>(&mut self, target: &mut T, support: &Support, frame: &frame::Video) { if self.timestamp < frame.timestamp().unwrap() { self.timestamp = frame.timestamp().unwrap(); if self.buffer.is_none() { self.buffer = Some(BufferView::empty_array(self.display, PixelUnpackBuffer, (frame.width() * frame.height()) as usize, Persistent).unwrap()); self.texture = Some(SrgbTexture2d::empty_with_format(self.display, U8U8U8U8, NoMipmap, frame.width(), frame.height()).unwrap()); } // write to the buffer self.buffer.as_mut().unwrap().write(frame.plane(0)); // write the buffer to the texture self.texture.as_mut().unwrap().main_level() .raw_upload_from_pixel_buffer_inverted(self.buffer.as_ref().unwrap().as_slice(), 0.. frame.width(), 0.. frame.height(), 0.. 1); } let uniforms = uniform! { alpha: 0.8, tex: support.settings().texture().filtering().background().sampled(self.texture.as_ref().unwrap()), }; target.clear_color(1.0, 1.0, 1.0, 1.0); target.draw(&self.vertices, &NoIndices(TriangleStrip), &self.program, &uniforms, &Default::default()).unwrap(); } }
Video
identifier_name
video.rs
use ffmpeg::frame; use glium::texture::{SrgbTexture2d}; use glium::{Program, Display, VertexBuffer, Surface}; use glium::buffer::BufferView; use glium::buffer::BufferMode::Persistent; use glium::buffer::BufferType::PixelUnpackBuffer; use glium::index::PrimitiveType::TriangleStrip; use glium::index::NoIndices; use glium::texture::SrgbFormat::U8U8U8U8; use glium::texture::MipmapsOption::NoMipmap; use renderer::{Support}; #[derive(Copy, Clone, Debug)] struct Vertex { position: [f32; 2], texture: [f32; 2], } implement_vertex!(Vertex, position, texture); pub struct Video<'a> { display: &'a Display, program: Program, vertices: VertexBuffer<Vertex>, timestamp: i64, buffer: Option<BufferView<[(u8, u8, u8, u8)]>>, texture: Option<SrgbTexture2d>, } impl<'a> Video<'a> { pub fn new<'b>(display: &'b Display) -> Video<'b> { Video { display: display, program: program!(display, 100 => { vertex: " #version 100 precision lowp float; attribute vec2 position; attribute vec2 texture; varying vec2 v_texture; void main() { gl_Position = vec4(position, 0.0, 1.0); v_texture = texture; } ", fragment: " #version 100 precision lowp float; uniform sampler2D tex; uniform float alpha; varying vec2 v_texture; void main() { gl_FragColor = texture2D(tex, v_texture); gl_FragColor.a = alpha; } ", }, ).unwrap(), vertices: VertexBuffer::new(display, &[ Vertex { position: [-1.0, 1.0], texture: [0.0, 0.0] }, Vertex { position: [ 1.0, 1.0], texture: [1.0, 0.0] }, Vertex { position: [-1.0, -1.0], texture: [0.0, 1.0] }, Vertex { position: [ 1.0, -1.0], texture: [1.0, 1.0] }, ]).unwrap(), timestamp: -1, buffer: None, texture: None, } } pub fn render<T: Surface>(&mut self, target: &mut T, support: &Support, frame: &frame::Video) { if self.timestamp < frame.timestamp().unwrap() { self.timestamp = frame.timestamp().unwrap(); if self.buffer.is_none()
// write to the buffer self.buffer.as_mut().unwrap().write(frame.plane(0)); // write the buffer to the texture self.texture.as_mut().unwrap().main_level() .raw_upload_from_pixel_buffer_inverted(self.buffer.as_ref().unwrap().as_slice(), 0.. frame.width(), 0.. frame.height(), 0.. 1); } let uniforms = uniform! { alpha: 0.8, tex: support.settings().texture().filtering().background().sampled(self.texture.as_ref().unwrap()), }; target.clear_color(1.0, 1.0, 1.0, 1.0); target.draw(&self.vertices, &NoIndices(TriangleStrip), &self.program, &uniforms, &Default::default()).unwrap(); } }
{ self.buffer = Some(BufferView::empty_array(self.display, PixelUnpackBuffer, (frame.width() * frame.height()) as usize, Persistent).unwrap()); self.texture = Some(SrgbTexture2d::empty_with_format(self.display, U8U8U8U8, NoMipmap, frame.width(), frame.height()).unwrap()); }
conditional_block
video.rs
use ffmpeg::frame; use glium::texture::{SrgbTexture2d}; use glium::{Program, Display, VertexBuffer, Surface}; use glium::buffer::BufferView; use glium::buffer::BufferMode::Persistent; use glium::buffer::BufferType::PixelUnpackBuffer; use glium::index::PrimitiveType::TriangleStrip; use glium::index::NoIndices; use glium::texture::SrgbFormat::U8U8U8U8; use glium::texture::MipmapsOption::NoMipmap; use renderer::{Support}; #[derive(Copy, Clone, Debug)] struct Vertex { position: [f32; 2], texture: [f32; 2], } implement_vertex!(Vertex, position, texture); pub struct Video<'a> { display: &'a Display, program: Program, vertices: VertexBuffer<Vertex>, timestamp: i64, buffer: Option<BufferView<[(u8, u8, u8, u8)]>>, texture: Option<SrgbTexture2d>, } impl<'a> Video<'a> { pub fn new<'b>(display: &'b Display) -> Video<'b> { Video { display: display, program: program!(display, 100 => { vertex: " #version 100 precision lowp float; attribute vec2 position; attribute vec2 texture; varying vec2 v_texture; void main() { gl_Position = vec4(position, 0.0, 1.0); v_texture = texture; } ", fragment: " #version 100 precision lowp float; uniform sampler2D tex; uniform float alpha; varying vec2 v_texture; void main() { gl_FragColor = texture2D(tex, v_texture); gl_FragColor.a = alpha; } ", }, ).unwrap(), vertices: VertexBuffer::new(display, &[ Vertex { position: [-1.0, 1.0], texture: [0.0, 0.0] }, Vertex { position: [ 1.0, 1.0], texture: [1.0, 0.0] }, Vertex { position: [-1.0, -1.0], texture: [0.0, 1.0] }, Vertex { position: [ 1.0, -1.0], texture: [1.0, 1.0] }, ]).unwrap(), timestamp: -1, buffer: None, texture: None, } } pub fn render<T: Surface>(&mut self, target: &mut T, support: &Support, frame: &frame::Video) { if self.timestamp < frame.timestamp().unwrap() { self.timestamp = frame.timestamp().unwrap(); if self.buffer.is_none() { self.buffer = Some(BufferView::empty_array(self.display, PixelUnpackBuffer, (frame.width() * frame.height()) as usize, Persistent).unwrap());
self.texture = Some(SrgbTexture2d::empty_with_format(self.display, U8U8U8U8, NoMipmap, frame.width(), frame.height()).unwrap()); } // write to the buffer self.buffer.as_mut().unwrap().write(frame.plane(0)); // write the buffer to the texture self.texture.as_mut().unwrap().main_level() .raw_upload_from_pixel_buffer_inverted(self.buffer.as_ref().unwrap().as_slice(), 0.. frame.width(), 0.. frame.height(), 0.. 1); } let uniforms = uniform! { alpha: 0.8, tex: support.settings().texture().filtering().background().sampled(self.texture.as_ref().unwrap()), }; target.clear_color(1.0, 1.0, 1.0, 1.0); target.draw(&self.vertices, &NoIndices(TriangleStrip), &self.program, &uniforms, &Default::default()).unwrap(); } }
random_line_split
type_channel.rs
//! Type channel. //! //! A type channel is a number that represents the number of channel a type is associated with. For //! instance, most people people might already be used to RGB and RGBA colors. They can for instance //! be encoded as 4D-floating numbers. Type channels encode such information. use std::fmt; use serde::de::{self, Deserialize, Deserializer, Visitor, Unexpected}; use serde::ser::{Serialize, Serializer}; /// Output type channels. Can be 1, 2, 3 or 4 channels. #[derive(Clone, Copy, Debug, Hash, Eq, PartialEq)] pub enum TypeChan { One, Two, Three, Four } impl Serialize for TypeChan { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer { match *self { TypeChan::One => serializer.serialize_u8(1), TypeChan::Two => serializer.serialize_u8(2), TypeChan::Three => serializer.serialize_u8(3), TypeChan::Four => serializer.serialize_u8(4), } } } impl<'de> Deserialize<'de> for TypeChan { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de> { struct V; impl<'de> Visitor<'de> for V { type Value = TypeChan; fn expecting(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error>
fn visit_u64<E>(self, x: u64) -> Result<Self::Value, E> where E: de::Error { match x { 1 => Ok(TypeChan::One), 2 => Ok(TypeChan::Two), 3 => Ok(TypeChan::Three), 4 => Ok(TypeChan::Four), x => Err(E::invalid_value(Unexpected::Unsigned(x as u64), &"1, 2, 3 or 4")) } } } deserializer.deserialize_u64(V) } } #[cfg(test)] mod tests { use super::*; #[test] fn serialize_type_chan() { use serde_json::to_string; assert_eq!(to_string(&TypeChan::One).unwrap(), "1"); assert_eq!(to_string(&TypeChan::Two).unwrap(), "2"); assert_eq!(to_string(&TypeChan::Three).unwrap(),"3"); assert_eq!(to_string(&TypeChan::Four).unwrap(), "4"); } #[test] fn deserialize_type_chan() { use serde_json::from_str; assert_eq!(from_str::<TypeChan>("1").unwrap(), TypeChan::One); assert_eq!(from_str::<TypeChan>("2").unwrap(), TypeChan::Two); assert_eq!(from_str::<TypeChan>("3").unwrap(), TypeChan::Three); assert_eq!(from_str::<TypeChan>("4").unwrap(), TypeChan::Four); assert!(from_str::<TypeChan>("5").is_err()); } }
{ f.write_str("a valid type channel") }
identifier_body
type_channel.rs
//! Type channel. //! //! A type channel is a number that represents the number of channel a type is associated with. For //! instance, most people people might already be used to RGB and RGBA colors. They can for instance //! be encoded as 4D-floating numbers. Type channels encode such information. use std::fmt; use serde::de::{self, Deserialize, Deserializer, Visitor, Unexpected}; use serde::ser::{Serialize, Serializer}; /// Output type channels. Can be 1, 2, 3 or 4 channels. #[derive(Clone, Copy, Debug, Hash, Eq, PartialEq)] pub enum TypeChan { One, Two, Three, Four } impl Serialize for TypeChan { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer { match *self { TypeChan::One => serializer.serialize_u8(1), TypeChan::Two => serializer.serialize_u8(2), TypeChan::Three => serializer.serialize_u8(3), TypeChan::Four => serializer.serialize_u8(4), } } } impl<'de> Deserialize<'de> for TypeChan { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de> { struct V; impl<'de> Visitor<'de> for V { type Value = TypeChan; fn
(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { f.write_str("a valid type channel") } fn visit_u64<E>(self, x: u64) -> Result<Self::Value, E> where E: de::Error { match x { 1 => Ok(TypeChan::One), 2 => Ok(TypeChan::Two), 3 => Ok(TypeChan::Three), 4 => Ok(TypeChan::Four), x => Err(E::invalid_value(Unexpected::Unsigned(x as u64), &"1, 2, 3 or 4")) } } } deserializer.deserialize_u64(V) } } #[cfg(test)] mod tests { use super::*; #[test] fn serialize_type_chan() { use serde_json::to_string; assert_eq!(to_string(&TypeChan::One).unwrap(), "1"); assert_eq!(to_string(&TypeChan::Two).unwrap(), "2"); assert_eq!(to_string(&TypeChan::Three).unwrap(),"3"); assert_eq!(to_string(&TypeChan::Four).unwrap(), "4"); } #[test] fn deserialize_type_chan() { use serde_json::from_str; assert_eq!(from_str::<TypeChan>("1").unwrap(), TypeChan::One); assert_eq!(from_str::<TypeChan>("2").unwrap(), TypeChan::Two); assert_eq!(from_str::<TypeChan>("3").unwrap(), TypeChan::Three); assert_eq!(from_str::<TypeChan>("4").unwrap(), TypeChan::Four); assert!(from_str::<TypeChan>("5").is_err()); } }
expecting
identifier_name
type_channel.rs
//! Type channel. //! //! A type channel is a number that represents the number of channel a type is associated with. For //! instance, most people people might already be used to RGB and RGBA colors. They can for instance //! be encoded as 4D-floating numbers. Type channels encode such information. use std::fmt; use serde::de::{self, Deserialize, Deserializer, Visitor, Unexpected}; use serde::ser::{Serialize, Serializer}; /// Output type channels. Can be 1, 2, 3 or 4 channels. #[derive(Clone, Copy, Debug, Hash, Eq, PartialEq)] pub enum TypeChan { One, Two, Three, Four } impl Serialize for TypeChan { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer { match *self {
} } } impl<'de> Deserialize<'de> for TypeChan { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de> { struct V; impl<'de> Visitor<'de> for V { type Value = TypeChan; fn expecting(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { f.write_str("a valid type channel") } fn visit_u64<E>(self, x: u64) -> Result<Self::Value, E> where E: de::Error { match x { 1 => Ok(TypeChan::One), 2 => Ok(TypeChan::Two), 3 => Ok(TypeChan::Three), 4 => Ok(TypeChan::Four), x => Err(E::invalid_value(Unexpected::Unsigned(x as u64), &"1, 2, 3 or 4")) } } } deserializer.deserialize_u64(V) } } #[cfg(test)] mod tests { use super::*; #[test] fn serialize_type_chan() { use serde_json::to_string; assert_eq!(to_string(&TypeChan::One).unwrap(), "1"); assert_eq!(to_string(&TypeChan::Two).unwrap(), "2"); assert_eq!(to_string(&TypeChan::Three).unwrap(),"3"); assert_eq!(to_string(&TypeChan::Four).unwrap(), "4"); } #[test] fn deserialize_type_chan() { use serde_json::from_str; assert_eq!(from_str::<TypeChan>("1").unwrap(), TypeChan::One); assert_eq!(from_str::<TypeChan>("2").unwrap(), TypeChan::Two); assert_eq!(from_str::<TypeChan>("3").unwrap(), TypeChan::Three); assert_eq!(from_str::<TypeChan>("4").unwrap(), TypeChan::Four); assert!(from_str::<TypeChan>("5").is_err()); } }
TypeChan::One => serializer.serialize_u8(1), TypeChan::Two => serializer.serialize_u8(2), TypeChan::Three => serializer.serialize_u8(3), TypeChan::Four => serializer.serialize_u8(4),
random_line_split
mod.rs
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ use std::io; use std::net::{TcpListener, TcpStream}; use super::Transport; impl Transport for TcpStream {} pub trait TransportServer { type Transport: Transport; fn accept(&self) -> io::Result<Self::Transport>; } impl TransportServer for TcpListener { type Transport = TcpStream; fn
(&self) -> io::Result<TcpStream> { self.accept().map(|res| res.0) } } impl<F, T> TransportServer for F where F: Fn() -> io::Result<T>, T: Transport { type Transport = T; fn accept(&self) -> io::Result<T> { self() } }
accept
identifier_name
mod.rs
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ use std::io; use std::net::{TcpListener, TcpStream}; use super::Transport; impl Transport for TcpStream {} pub trait TransportServer { type Transport: Transport; fn accept(&self) -> io::Result<Self::Transport>; } impl TransportServer for TcpListener {
type Transport = TcpStream; fn accept(&self) -> io::Result<TcpStream> { self.accept().map(|res| res.0) } } impl<F, T> TransportServer for F where F: Fn() -> io::Result<T>, T: Transport { type Transport = T; fn accept(&self) -> io::Result<T> { self() } }
random_line_split
mod.rs
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ use std::io; use std::net::{TcpListener, TcpStream}; use super::Transport; impl Transport for TcpStream {} pub trait TransportServer { type Transport: Transport; fn accept(&self) -> io::Result<Self::Transport>; } impl TransportServer for TcpListener { type Transport = TcpStream; fn accept(&self) -> io::Result<TcpStream> { self.accept().map(|res| res.0) } } impl<F, T> TransportServer for F where F: Fn() -> io::Result<T>, T: Transport { type Transport = T; fn accept(&self) -> io::Result<T>
}
{ self() }
identifier_body
location.rs
//! Fractal Global Location module //! //! This module holds the Fractal Global Address, and Geological location data type objects. #[cfg(feature = "json-types")] use rustc_serialize::json; /// The particulars of the place where an organization or person resides #[derive(PartialEq, Debug, Clone, RustcEncodable, RustcDecodable)] pub struct Address { /// First Address address1: String, /// Second Address address2: Option<String>, /// The City city: String, /// The State state: String, /// The Zip Code zip: String, /// The Country country: String, } impl Address { /// Creates a new `Address` pub fn new<S: AsRef<str>>(address1: S, address2: Option<S>, city: S, state: S, zip: S, country: S) -> Address { Address { address1: address1.as_ref().to_owned(), address2: match address2 { Some(s) => Some(s.as_ref().to_owned()), None => None, }, city: city.as_ref().to_owned(), state: state.as_ref().to_owned(), zip: zip.as_ref().to_owned(), country: country.as_ref().to_owned(), } } /// Returns address line 1 pub fn get_address1(&self) -> &str { &self.address1 } /// Returns address line 2 pub fn get_address2(&self) -> Option<&str>
/// Returns the city pub fn get_city(&self) -> &str { &self.city } /// Returns the state pub fn get_state(&self) -> &str { &self.state } /// Returns the zip code pub fn get_zip(&self) -> &str { &self.zip } /// Returns the country pub fn get_country(&self) -> &str { &self.country } } #[cfg(feature = "json-types")] impl json::ToJson for Address { fn to_json(&self) -> json::Json { let mut object = json::Object::new(); let _ = object.insert(String::from("address1"), self.address1.to_json()); let _ = object.insert(String::from("address2"), self.address2.to_json()); let _ = object.insert(String::from("city"), self.city.to_json()); let _ = object.insert(String::from("state"), self.state.to_json()); let _ = object.insert(String::from("zip"), self.zip.to_json()); let _ = object.insert(String::from("country"), self.country.to_json()); json::Json::Object(object) } }
{ match self.address2 { Some(ref addr2) => Some(addr2), None => None, } }
identifier_body
location.rs
//! Fractal Global Location module //! //! This module holds the Fractal Global Address, and Geological location data type objects. #[cfg(feature = "json-types")] use rustc_serialize::json; /// The particulars of the place where an organization or person resides #[derive(PartialEq, Debug, Clone, RustcEncodable, RustcDecodable)] pub struct Address { /// First Address address1: String, /// Second Address address2: Option<String>, /// The City city: String, /// The State state: String, /// The Zip Code zip: String, /// The Country country: String, } impl Address { /// Creates a new `Address` pub fn new<S: AsRef<str>>(address1: S, address2: Option<S>, city: S, state: S, zip: S, country: S) -> Address { Address { address1: address1.as_ref().to_owned(), address2: match address2 { Some(s) => Some(s.as_ref().to_owned()), None => None, }, city: city.as_ref().to_owned(), state: state.as_ref().to_owned(), zip: zip.as_ref().to_owned(), country: country.as_ref().to_owned(),
pub fn get_address1(&self) -> &str { &self.address1 } /// Returns address line 2 pub fn get_address2(&self) -> Option<&str> { match self.address2 { Some(ref addr2) => Some(addr2), None => None, } } /// Returns the city pub fn get_city(&self) -> &str { &self.city } /// Returns the state pub fn get_state(&self) -> &str { &self.state } /// Returns the zip code pub fn get_zip(&self) -> &str { &self.zip } /// Returns the country pub fn get_country(&self) -> &str { &self.country } } #[cfg(feature = "json-types")] impl json::ToJson for Address { fn to_json(&self) -> json::Json { let mut object = json::Object::new(); let _ = object.insert(String::from("address1"), self.address1.to_json()); let _ = object.insert(String::from("address2"), self.address2.to_json()); let _ = object.insert(String::from("city"), self.city.to_json()); let _ = object.insert(String::from("state"), self.state.to_json()); let _ = object.insert(String::from("zip"), self.zip.to_json()); let _ = object.insert(String::from("country"), self.country.to_json()); json::Json::Object(object) } }
} } /// Returns address line 1
random_line_split
location.rs
//! Fractal Global Location module //! //! This module holds the Fractal Global Address, and Geological location data type objects. #[cfg(feature = "json-types")] use rustc_serialize::json; /// The particulars of the place where an organization or person resides #[derive(PartialEq, Debug, Clone, RustcEncodable, RustcDecodable)] pub struct Address { /// First Address address1: String, /// Second Address address2: Option<String>, /// The City city: String, /// The State state: String, /// The Zip Code zip: String, /// The Country country: String, } impl Address { /// Creates a new `Address` pub fn new<S: AsRef<str>>(address1: S, address2: Option<S>, city: S, state: S, zip: S, country: S) -> Address { Address { address1: address1.as_ref().to_owned(), address2: match address2 { Some(s) => Some(s.as_ref().to_owned()), None => None, }, city: city.as_ref().to_owned(), state: state.as_ref().to_owned(), zip: zip.as_ref().to_owned(), country: country.as_ref().to_owned(), } } /// Returns address line 1 pub fn
(&self) -> &str { &self.address1 } /// Returns address line 2 pub fn get_address2(&self) -> Option<&str> { match self.address2 { Some(ref addr2) => Some(addr2), None => None, } } /// Returns the city pub fn get_city(&self) -> &str { &self.city } /// Returns the state pub fn get_state(&self) -> &str { &self.state } /// Returns the zip code pub fn get_zip(&self) -> &str { &self.zip } /// Returns the country pub fn get_country(&self) -> &str { &self.country } } #[cfg(feature = "json-types")] impl json::ToJson for Address { fn to_json(&self) -> json::Json { let mut object = json::Object::new(); let _ = object.insert(String::from("address1"), self.address1.to_json()); let _ = object.insert(String::from("address2"), self.address2.to_json()); let _ = object.insert(String::from("city"), self.city.to_json()); let _ = object.insert(String::from("state"), self.state.to_json()); let _ = object.insert(String::from("zip"), self.zip.to_json()); let _ = object.insert(String::from("country"), self.country.to_json()); json::Json::Object(object) } }
get_address1
identifier_name
rustc.rs
use std::path::Path; use util::{self, CargoResult, internal, ChainError}; pub struct Rustc { pub verbose_version: String, pub host: String, pub cap_lints: bool, } impl Rustc { /// Run the compiler at `path` to learn varioues pieces of information about /// it. /// /// If successful this function returns a description of the compiler along /// with a list of its capabilities. pub fn new<P: AsRef<Path>>(path: P) -> CargoResult<Rustc> { let mut cmd = util::process(path.as_ref()); cmd.arg("-vV"); let mut ret = Rustc::blank(); let mut first = cmd.clone(); first.arg("--cap-lints").arg("allow"); let output = match first.exec_with_output() { Ok(output) => { ret.cap_lints = true; output } Err(..) => try!(cmd.exec_with_output()), }; ret.verbose_version = try!(String::from_utf8(output.stdout).map_err(|_| { internal("rustc -v didn't return utf8 output") })); ret.host = { let triple = ret.verbose_version.lines().filter(|l| { l.starts_with("host: ") }).map(|l| &l[6..]).next(); let triple = try!(triple.chain_error(|| { internal("rustc -v didn't have a line for `host:`") })); triple.to_string() }; Ok(ret) } pub fn
() -> Rustc { Rustc { verbose_version: String::new(), host: String::new(), cap_lints: false, } } }
blank
identifier_name
rustc.rs
use std::path::Path; use util::{self, CargoResult, internal, ChainError}; pub struct Rustc { pub verbose_version: String, pub host: String, pub cap_lints: bool, } impl Rustc { /// Run the compiler at `path` to learn varioues pieces of information about /// it. /// /// If successful this function returns a description of the compiler along /// with a list of its capabilities. pub fn new<P: AsRef<Path>>(path: P) -> CargoResult<Rustc> { let mut cmd = util::process(path.as_ref());
cmd.arg("-vV"); let mut ret = Rustc::blank(); let mut first = cmd.clone(); first.arg("--cap-lints").arg("allow"); let output = match first.exec_with_output() { Ok(output) => { ret.cap_lints = true; output } Err(..) => try!(cmd.exec_with_output()), }; ret.verbose_version = try!(String::from_utf8(output.stdout).map_err(|_| { internal("rustc -v didn't return utf8 output") })); ret.host = { let triple = ret.verbose_version.lines().filter(|l| { l.starts_with("host: ") }).map(|l| &l[6..]).next(); let triple = try!(triple.chain_error(|| { internal("rustc -v didn't have a line for `host:`") })); triple.to_string() }; Ok(ret) } pub fn blank() -> Rustc { Rustc { verbose_version: String::new(), host: String::new(), cap_lints: false, } } }
random_line_split
cell.rs
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. //! Shareable mutable containers. //! //! Values of the `Cell<T>` and `RefCell<T>` types may be mutated through shared references (i.e. //! the common `&T` type), whereas most Rust types can only be mutated through unique (`&mut T`) //! references. We say that `Cell<T>` and `RefCell<T>` provide 'interior mutability', in contrast //! with typical Rust types that exhibit 'inherited mutability'. //! //! Cell types come in two flavors: `Cell<T>` and `RefCell<T>`. `Cell<T>` provides `get` and `set` //! methods that change the interior value with a single method call. `Cell<T>` though is only //! compatible with types that implement `Copy`. For other types, one must use the `RefCell<T>` //! type, acquiring a write lock before mutating. //! //! `RefCell<T>` uses Rust's lifetimes to implement 'dynamic borrowing', a process whereby one can //! claim temporary, exclusive, mutable access to the inner value. Borrows for `RefCell<T>`s are //! tracked 'at runtime', unlike Rust's native reference types which are entirely tracked //! statically, at compile time. Because `RefCell<T>` borrows are dynamic it is possible to attempt //! to borrow a value that is already mutably borrowed; when this happens it results in task panic. //! //! # When to choose interior mutability //! //! The more common inherited mutability, where one must have unique access to mutate a value, is //! one of the key language elements that enables Rust to reason strongly about pointer aliasing, //! statically preventing crash bugs. Because of that, inherited mutability is preferred, and //! interior mutability is something of a last resort. Since cell types enable mutation where it //! would otherwise be disallowed though, there are occasions when interior mutability might be //! appropriate, or even *must* be used, e.g. //! //! * Introducing inherited mutability roots to shared types. //! * Implementation details of logically-immutable methods. //! * Mutating implementations of `clone`. //! //! ## Introducing inherited mutability roots to shared types //! //! Shared smart pointer types, including `Rc<T>` and `Arc<T>`, provide containers that can be //! cloned and shared between multiple parties. Because the contained values may be //! multiply-aliased, they can only be borrowed as shared references, not mutable references. //! Without cells it would be impossible to mutate data inside of shared boxes at all! //! //! It's very common then to put a `RefCell<T>` inside shared pointer types to reintroduce //! mutability: //! //! ``` //! use std::collections::HashMap; //! use std::cell::RefCell; //! use std::rc::Rc; //! //! fn main() { //! let shared_map: Rc<RefCell<_>> = Rc::new(RefCell::new(HashMap::new())); //! shared_map.borrow_mut().insert("africa", 92388); //! shared_map.borrow_mut().insert("kyoto", 11837); //! shared_map.borrow_mut().insert("piccadilly", 11826); //! shared_map.borrow_mut().insert("marbles", 38); //! } //! ``` //! //! Note that this example uses `Rc<T>` and not `Arc<T>`. `RefCell<T>`s are for single-threaded //! scenarios. Consider using `Mutex<T>` if you need shared mutability in a multi-threaded //! situation. //! //! ## Implementation details of logically-immutable methods //! //! Occasionally it may be desirable not to expose in an API that there is mutation happening //! "under the hood". This may be because logically the operation is immutable, but e.g. caching //! forces the implementation to perform mutation; or because you must employ mutation to implement //! a trait method that was originally defined to take `&self`. //! //! ``` //! use std::cell::RefCell; //! //! struct Graph { //! edges: Vec<(uint, uint)>, //! span_tree_cache: RefCell<Option<Vec<(uint, uint)>>> //! } //! //! impl Graph { //! fn minimum_spanning_tree(&self) -> Vec<(uint, uint)> { //! // Create a new scope to contain the lifetime of the //! // dynamic borrow //! { //! // Take a reference to the inside of cache cell //! let mut cache = self.span_tree_cache.borrow_mut(); //! if cache.is_some() { //! return cache.as_ref().unwrap().clone(); //! } //! //! let span_tree = self.calc_span_tree(); //! *cache = Some(span_tree); //! } //! //! // Recursive call to return the just-cached value. //! // Note that if we had not let the previous borrow //! // of the cache fall out of scope then the subsequent //! // recursive borrow would cause a dynamic task panic. //! // This is the major hazard of using `RefCell`. //! self.minimum_spanning_tree() //! } //! # fn calc_span_tree(&self) -> Vec<(uint, uint)> { vec![] } //! } //! ``` //! //! ## Mutating implementations of `clone` //! //! This is simply a special - but common - case of the previous: hiding mutability for operations //! that appear to be immutable. The `clone` method is expected to not change the source value, and //! is declared to take `&self`, not `&mut self`. Therefore any mutation that happens in the //! `clone` method must use cell types. For example, `Rc<T>` maintains its reference counts within a //! `Cell<T>`. //! //! ``` //! use std::cell::Cell; //! //! struct Rc<T> { //! ptr: *mut RcBox<T> //! } //! //! struct RcBox<T> { //! value: T, //! refcount: Cell<uint> //! } //! //! impl<T> Clone for Rc<T> { //! fn clone(&self) -> Rc<T> { //! unsafe { //! (*self.ptr).refcount.set((*self.ptr).refcount.get() + 1); //! Rc { ptr: self.ptr } //! } //! } //! } //! ``` //! #![stable(feature = "rust1", since = "1.0.0")] use clone::Clone; use cmp::PartialEq; use default::Default; use marker::{Copy, Send}; use ops::{Deref, DerefMut, Drop}; use option::Option; use option::Option::{None, Some}; /// A mutable memory location that admits only `Copy` data. /// /// See the [module-level documentation](index.html) for more. #[stable(feature = "rust1", since = "1.0.0")] pub struct Cell<T> { value: UnsafeCell<T>, } impl<T:Copy> Cell<T> { /// Creates a new `Cell` containing the given value. /// /// # Examples /// /// ``` /// use std::cell::Cell; /// /// let c = Cell::new(5); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn new(value: T) -> Cell<T> { Cell { value: UnsafeCell::new(value), } } /// Returns a copy of the contained value. /// /// # Examples /// /// ``` /// use std::cell::Cell; /// /// let c = Cell::new(5); /// /// let five = c.get(); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn get(&self) -> T { unsafe{ *self.value.get() } } /// Sets the contained value. /// /// # Examples /// /// ``` /// use std::cell::Cell; /// /// let c = Cell::new(5); /// /// c.set(10); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn set(&self, value: T) { unsafe { *self.value.get() = value; } } /// Get a reference to the underlying `UnsafeCell`. /// /// # Unsafety /// /// This function is `unsafe` because `UnsafeCell`'s field is public. /// /// # Examples /// /// ``` /// use std::cell::Cell; /// /// let c = Cell::new(5); /// /// let uc = unsafe { c.as_unsafe_cell() }; /// ``` #[inline] #[unstable(feature = "core")] pub unsafe fn as_unsafe_cell<'a>(&'a self) -> &'a UnsafeCell<T> { &self.value } } #[stable(feature = "rust1", since = "1.0.0")] unsafe impl<T> Send for Cell<T> where T: Send {} #[stable(feature = "rust1", since = "1.0.0")] impl<T:Copy> Clone for Cell<T> { fn clone(&self) -> Cell<T> { Cell::new(self.get()) } } #[stable(feature = "rust1", since = "1.0.0")] impl<T:Default + Copy> Default for Cell<T> { #[stable(feature = "rust1", since = "1.0.0")] fn default() -> Cell<T> { Cell::new(Default::default()) } } #[stable(feature = "rust1", since = "1.0.0")] impl<T:PartialEq + Copy> PartialEq for Cell<T> { fn eq(&self, other: &Cell<T>) -> bool { self.get() == other.get() } } /// A mutable memory location with dynamically checked borrow rules /// /// See the [module-level documentation](index.html) for more. #[stable(feature = "rust1", since = "1.0.0")] pub struct RefCell<T> { value: UnsafeCell<T>, borrow: Cell<BorrowFlag>, } /// An enumeration of values returned from the `state` method on a `RefCell<T>`. #[derive(Copy, Clone, PartialEq, Debug)] #[unstable(feature = "std_misc")] pub enum BorrowState { /// The cell is currently being read, there is at least one active `borrow`. Reading, /// The cell is currently being written to, there is an active `borrow_mut`. Writing, /// There are no outstanding borrows on this cell. Unused, } // Values [1, MAX-1] represent the number of `Ref` active // (will not outgrow its range since `uint` is the size of the address space) type BorrowFlag = uint; const UNUSED: BorrowFlag = 0; const WRITING: BorrowFlag = -1; impl<T> RefCell<T> { /// Creates a new `RefCell` containing `value`. /// /// # Examples /// /// ``` /// use std::cell::RefCell; /// /// let c = RefCell::new(5); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn new(value: T) -> RefCell<T> { RefCell { value: UnsafeCell::new(value), borrow: Cell::new(UNUSED), } } /// Consumes the `RefCell`, returning the wrapped value. /// /// # Examples /// /// ``` /// use std::cell::RefCell; /// /// let c = RefCell::new(5); /// /// let five = c.into_inner(); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn into_inner(self) -> T { // Since this function takes `self` (the `RefCell`) by value, the // compiler statically verifies that it is not currently borrowed. // Therefore the following assertion is just a `debug_assert!`. debug_assert!(self.borrow.get() == UNUSED); unsafe { self.value.into_inner() } } /// Query the current state of this `RefCell` /// /// The returned value can be dispatched on to determine if a call to /// `borrow` or `borrow_mut` would succeed. #[unstable(feature = "std_misc")] pub fn borrow_state(&self) -> BorrowState { match self.borrow.get() { WRITING => BorrowState::Writing, UNUSED => BorrowState::Unused, _ => BorrowState::Reading, } } /// Attempts to immutably borrow the wrapped value. /// /// The borrow lasts until the returned `Ref` exits scope. Multiple /// immutable borrows can be taken out at the same time. /// /// Returns `None` if the value is currently mutably borrowed. #[unstable(feature = "core", reason = "may be renamed or removed")] #[deprecated(since = "1.0.0", reason = "dispatch on `cell.borrow_state()` instead")] pub fn try_borrow<'a>(&'a self) -> Option<Ref<'a, T>> { match BorrowRef::new(&self.borrow) { Some(b) => Some(Ref { _value: unsafe { &*self.value.get() }, _borrow: b }), None => None, } } /// Immutably borrows the wrapped value. /// /// The borrow lasts until the returned `Ref` exits scope. Multiple /// immutable borrows can be taken out at the same time. /// /// # Panics
/// Panics if the value is currently mutably borrowed. /// /// # Examples /// /// ``` /// use std::cell::RefCell; /// /// let c = RefCell::new(5); /// /// let borrowed_five = c.borrow(); /// let borrowed_five2 = c.borrow(); /// ``` /// /// An example of panic: /// /// ``` /// use std::cell::RefCell; /// use std::thread::Thread; /// /// let result = Thread::scoped(move || { /// let c = RefCell::new(5); /// let m = c.borrow_mut(); /// /// let b = c.borrow(); // this causes a panic /// }).join(); /// /// assert!(result.is_err()); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn borrow<'a>(&'a self) -> Ref<'a, T> { match BorrowRef::new(&self.borrow) { Some(b) => Ref { _value: unsafe { &*self.value.get() }, _borrow: b, }, None => panic!("RefCell<T> already mutably borrowed"), } } /// Mutably borrows the wrapped value. /// /// The borrow lasts until the returned `RefMut` exits scope. The value /// cannot be borrowed while this borrow is active. /// /// Returns `None` if the value is currently borrowed. #[unstable(feature = "core", reason = "may be renamed or removed")] #[deprecated(since = "1.0.0", reason = "dispatch on `cell.borrow_state()` instead")] pub fn try_borrow_mut<'a>(&'a self) -> Option<RefMut<'a, T>> { match BorrowRefMut::new(&self.borrow) { Some(b) => Some(RefMut { _value: unsafe { &mut *self.value.get() }, _borrow: b }), None => None, } } /// Mutably borrows the wrapped value. /// /// The borrow lasts until the returned `RefMut` exits scope. The value /// cannot be borrowed while this borrow is active. /// /// # Panics /// /// Panics if the value is currently borrowed. /// /// # Examples /// /// ``` /// use std::cell::RefCell; /// /// let c = RefCell::new(5); /// /// let borrowed_five = c.borrow_mut(); /// ``` /// /// An example of panic: /// /// ``` /// use std::cell::RefCell; /// use std::thread::Thread; /// /// let result = Thread::scoped(move || { /// let c = RefCell::new(5); /// let m = c.borrow_mut(); /// /// let b = c.borrow_mut(); // this causes a panic /// }).join(); /// /// assert!(result.is_err()); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn borrow_mut<'a>(&'a self) -> RefMut<'a, T> { match BorrowRefMut::new(&self.borrow) { Some(b) => RefMut { _value: unsafe { &mut *self.value.get() }, _borrow: b, }, None => panic!("RefCell<T> already borrowed"), } } /// Get a reference to the underlying `UnsafeCell`. /// /// This can be used to circumvent `RefCell`'s safety checks. /// /// This function is `unsafe` because `UnsafeCell`'s field is public. #[inline] #[unstable(feature = "core")] pub unsafe fn as_unsafe_cell<'a>(&'a self) -> &'a UnsafeCell<T> { &self.value } } #[stable(feature = "rust1", since = "1.0.0")] unsafe impl<T> Send for RefCell<T> where T: Send {} #[stable(feature = "rust1", since = "1.0.0")] impl<T: Clone> Clone for RefCell<T> { fn clone(&self) -> RefCell<T> { RefCell::new(self.borrow().clone()) } } #[stable(feature = "rust1", since = "1.0.0")] impl<T:Default> Default for RefCell<T> { #[stable(feature = "rust1", since = "1.0.0")] fn default() -> RefCell<T> { RefCell::new(Default::default()) } } #[stable(feature = "rust1", since = "1.0.0")] impl<T: PartialEq> PartialEq for RefCell<T> { fn eq(&self, other: &RefCell<T>) -> bool { *self.borrow() == *other.borrow() } } struct BorrowRef<'b> { _borrow: &'b Cell<BorrowFlag>, } impl<'b> BorrowRef<'b> { fn new(borrow: &'b Cell<BorrowFlag>) -> Option<BorrowRef<'b>> { match borrow.get() { WRITING => None, b => { borrow.set(b + 1); Some(BorrowRef { _borrow: borrow }) }, } } } #[unsafe_destructor] impl<'b> Drop for BorrowRef<'b> { fn drop(&mut self) { let borrow = self._borrow.get(); debug_assert!(borrow!= WRITING && borrow!= UNUSED); self._borrow.set(borrow - 1); } } impl<'b> Clone for BorrowRef<'b> { fn clone(&self) -> BorrowRef<'b> { // Since this Ref exists, we know the borrow flag // is not set to WRITING. let borrow = self._borrow.get(); debug_assert!(borrow!= WRITING && borrow!= UNUSED); self._borrow.set(borrow + 1); BorrowRef { _borrow: self._borrow } } } /// Wraps a borrowed reference to a value in a `RefCell` box. /// A wrapper type for an immutably borrowed value from a `RefCell<T>`. /// /// See the [module-level documentation](index.html) for more. #[stable(feature = "rust1", since = "1.0.0")] pub struct Ref<'b, T:'b> { // FIXME #12808: strange name to try to avoid interfering with // field accesses of the contained type via Deref _value: &'b T, _borrow: BorrowRef<'b>, } #[stable(feature = "rust1", since = "1.0.0")] impl<'b, T> Deref for Ref<'b, T> { type Target = T; #[inline] fn deref<'a>(&'a self) -> &'a T { self._value } } /// Copy a `Ref`. /// /// The `RefCell` is already immutably borrowed, so this cannot fail. /// /// A `Clone` implementation would interfere with the widespread /// use of `r.borrow().clone()` to clone the contents of a `RefCell`. #[unstable(feature = "core", reason = "likely to be moved to a method, pending language changes")] pub fn clone_ref<'b, T:Clone>(orig: &Ref<'b, T>) -> Ref<'b, T> { Ref { _value: orig._value, _borrow: orig._borrow.clone(), } } struct BorrowRefMut<'b> { _borrow: &'b Cell<BorrowFlag>, } #[unsafe_destructor] impl<'b> Drop for BorrowRefMut<'b> { fn drop(&mut self) { let borrow = self._borrow.get(); debug_assert!(borrow == WRITING); self._borrow.set(UNUSED); } } impl<'b> BorrowRefMut<'b> { fn new(borrow: &'b Cell<BorrowFlag>) -> Option<BorrowRefMut<'b>> { match borrow.get() { UNUSED => { borrow.set(WRITING); Some(BorrowRefMut { _borrow: borrow }) }, _ => None, } } } /// A wrapper type for a mutably borrowed value from a `RefCell<T>`. /// /// See the [module-level documentation](index.html) for more. #[stable(feature = "rust1", since = "1.0.0")] pub struct RefMut<'b, T:'b> { // FIXME #12808: strange name to try to avoid interfering with // field accesses of the contained type via Deref _value: &'b mut T, _borrow: BorrowRefMut<'b>, } #[stable(feature = "rust1", since = "1.0.0")] impl<'b, T> Deref for RefMut<'b, T> { type Target = T; #[inline] fn deref<'a>(&'a self) -> &'a T { self._value } } #[stable(feature = "rust1", since = "1.0.0")] impl<'b, T> DerefMut for RefMut<'b, T> { #[inline] fn deref_mut<'a>(&'a mut self) -> &'a mut T { self._value } } /// The core primitive for interior mutability in Rust. /// /// `UnsafeCell<T>` is a type that wraps some `T` and indicates unsafe interior operations on the /// wrapped type. Types with an `UnsafeCell<T>` field are considered to have an 'unsafe interior'. /// The `UnsafeCell<T>` type is the only legal way to obtain aliasable data that is considered /// mutable. In general, transmuting an `&T` type into an `&mut T` is considered undefined behavior. /// /// Types like `Cell<T>` and `RefCell<T>` use this type to wrap their internal data. /// /// `UnsafeCell<T>` doesn't opt-out from any marker traits, instead, types with an `UnsafeCell<T>` /// interior are expected to opt-out from those traits themselves. /// /// # Examples /// /// ``` /// use std::cell::UnsafeCell; /// use std::marker::Sync; /// /// struct NotThreadSafe<T> { /// value: UnsafeCell<T>, /// } /// /// unsafe impl<T> Sync for NotThreadSafe<T> {} /// ``` /// /// **NOTE:** `UnsafeCell<T>`'s fields are public to allow static initializers. It is not /// recommended to access its fields directly, `get` should be used instead. #[lang="unsafe"] #[stable(feature = "rust1", since = "1.0.0")] pub struct UnsafeCell<T> { /// Wrapped value /// /// This field should not be accessed directly, it is made public for static /// initializers. #[unstable(feature = "core")] pub value: T, } impl<T> UnsafeCell<T> { /// Construct a new instance of `UnsafeCell` which will wrap the specified /// value. /// /// All access to the inner value through methods is `unsafe`, and it is highly discouraged to /// access the fields directly. /// /// # Examples /// /// ``` /// use std::cell::UnsafeCell; /// /// let uc = UnsafeCell::new(5); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn new(value: T) -> UnsafeCell<T> { UnsafeCell { value: value } } /// Gets a mutable pointer to the wrapped value. /// /// # Examples /// /// ``` /// use std::cell::UnsafeCell; /// /// let uc = UnsafeCell::new(5); /// /// let five = uc.get(); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn get(&self) -> *mut T { &self.value as *const T as *mut T } /// Unwraps the value /// /// # Unsafety /// /// This function is unsafe because there is no guarantee that this or other threads are /// currently inspecting the inner value. /// /// # Examples /// /// ``` /// use std::cell::UnsafeCell; /// /// let uc = UnsafeCell::new(5); /// /// let five = unsafe { uc.into_inner() }; /// ```
///
random_line_split
cell.rs
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. //! Shareable mutable containers. //! //! Values of the `Cell<T>` and `RefCell<T>` types may be mutated through shared references (i.e. //! the common `&T` type), whereas most Rust types can only be mutated through unique (`&mut T`) //! references. We say that `Cell<T>` and `RefCell<T>` provide 'interior mutability', in contrast //! with typical Rust types that exhibit 'inherited mutability'. //! //! Cell types come in two flavors: `Cell<T>` and `RefCell<T>`. `Cell<T>` provides `get` and `set` //! methods that change the interior value with a single method call. `Cell<T>` though is only //! compatible with types that implement `Copy`. For other types, one must use the `RefCell<T>` //! type, acquiring a write lock before mutating. //! //! `RefCell<T>` uses Rust's lifetimes to implement 'dynamic borrowing', a process whereby one can //! claim temporary, exclusive, mutable access to the inner value. Borrows for `RefCell<T>`s are //! tracked 'at runtime', unlike Rust's native reference types which are entirely tracked //! statically, at compile time. Because `RefCell<T>` borrows are dynamic it is possible to attempt //! to borrow a value that is already mutably borrowed; when this happens it results in task panic. //! //! # When to choose interior mutability //! //! The more common inherited mutability, where one must have unique access to mutate a value, is //! one of the key language elements that enables Rust to reason strongly about pointer aliasing, //! statically preventing crash bugs. Because of that, inherited mutability is preferred, and //! interior mutability is something of a last resort. Since cell types enable mutation where it //! would otherwise be disallowed though, there are occasions when interior mutability might be //! appropriate, or even *must* be used, e.g. //! //! * Introducing inherited mutability roots to shared types. //! * Implementation details of logically-immutable methods. //! * Mutating implementations of `clone`. //! //! ## Introducing inherited mutability roots to shared types //! //! Shared smart pointer types, including `Rc<T>` and `Arc<T>`, provide containers that can be //! cloned and shared between multiple parties. Because the contained values may be //! multiply-aliased, they can only be borrowed as shared references, not mutable references. //! Without cells it would be impossible to mutate data inside of shared boxes at all! //! //! It's very common then to put a `RefCell<T>` inside shared pointer types to reintroduce //! mutability: //! //! ``` //! use std::collections::HashMap; //! use std::cell::RefCell; //! use std::rc::Rc; //! //! fn main() { //! let shared_map: Rc<RefCell<_>> = Rc::new(RefCell::new(HashMap::new())); //! shared_map.borrow_mut().insert("africa", 92388); //! shared_map.borrow_mut().insert("kyoto", 11837); //! shared_map.borrow_mut().insert("piccadilly", 11826); //! shared_map.borrow_mut().insert("marbles", 38); //! } //! ``` //! //! Note that this example uses `Rc<T>` and not `Arc<T>`. `RefCell<T>`s are for single-threaded //! scenarios. Consider using `Mutex<T>` if you need shared mutability in a multi-threaded //! situation. //! //! ## Implementation details of logically-immutable methods //! //! Occasionally it may be desirable not to expose in an API that there is mutation happening //! "under the hood". This may be because logically the operation is immutable, but e.g. caching //! forces the implementation to perform mutation; or because you must employ mutation to implement //! a trait method that was originally defined to take `&self`. //! //! ``` //! use std::cell::RefCell; //! //! struct Graph { //! edges: Vec<(uint, uint)>, //! span_tree_cache: RefCell<Option<Vec<(uint, uint)>>> //! } //! //! impl Graph { //! fn minimum_spanning_tree(&self) -> Vec<(uint, uint)> { //! // Create a new scope to contain the lifetime of the //! // dynamic borrow //! { //! // Take a reference to the inside of cache cell //! let mut cache = self.span_tree_cache.borrow_mut(); //! if cache.is_some() { //! return cache.as_ref().unwrap().clone(); //! } //! //! let span_tree = self.calc_span_tree(); //! *cache = Some(span_tree); //! } //! //! // Recursive call to return the just-cached value. //! // Note that if we had not let the previous borrow //! // of the cache fall out of scope then the subsequent //! // recursive borrow would cause a dynamic task panic. //! // This is the major hazard of using `RefCell`. //! self.minimum_spanning_tree() //! } //! # fn calc_span_tree(&self) -> Vec<(uint, uint)> { vec![] } //! } //! ``` //! //! ## Mutating implementations of `clone` //! //! This is simply a special - but common - case of the previous: hiding mutability for operations //! that appear to be immutable. The `clone` method is expected to not change the source value, and //! is declared to take `&self`, not `&mut self`. Therefore any mutation that happens in the //! `clone` method must use cell types. For example, `Rc<T>` maintains its reference counts within a //! `Cell<T>`. //! //! ``` //! use std::cell::Cell; //! //! struct Rc<T> { //! ptr: *mut RcBox<T> //! } //! //! struct RcBox<T> { //! value: T, //! refcount: Cell<uint> //! } //! //! impl<T> Clone for Rc<T> { //! fn clone(&self) -> Rc<T> { //! unsafe { //! (*self.ptr).refcount.set((*self.ptr).refcount.get() + 1); //! Rc { ptr: self.ptr } //! } //! } //! } //! ``` //! #![stable(feature = "rust1", since = "1.0.0")] use clone::Clone; use cmp::PartialEq; use default::Default; use marker::{Copy, Send}; use ops::{Deref, DerefMut, Drop}; use option::Option; use option::Option::{None, Some}; /// A mutable memory location that admits only `Copy` data. /// /// See the [module-level documentation](index.html) for more. #[stable(feature = "rust1", since = "1.0.0")] pub struct Cell<T> { value: UnsafeCell<T>, } impl<T:Copy> Cell<T> { /// Creates a new `Cell` containing the given value. /// /// # Examples /// /// ``` /// use std::cell::Cell; /// /// let c = Cell::new(5); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn new(value: T) -> Cell<T> { Cell { value: UnsafeCell::new(value), } } /// Returns a copy of the contained value. /// /// # Examples /// /// ``` /// use std::cell::Cell; /// /// let c = Cell::new(5); /// /// let five = c.get(); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn get(&self) -> T { unsafe{ *self.value.get() } } /// Sets the contained value. /// /// # Examples /// /// ``` /// use std::cell::Cell; /// /// let c = Cell::new(5); /// /// c.set(10); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn set(&self, value: T) { unsafe { *self.value.get() = value; } } /// Get a reference to the underlying `UnsafeCell`. /// /// # Unsafety /// /// This function is `unsafe` because `UnsafeCell`'s field is public. /// /// # Examples /// /// ``` /// use std::cell::Cell; /// /// let c = Cell::new(5); /// /// let uc = unsafe { c.as_unsafe_cell() }; /// ``` #[inline] #[unstable(feature = "core")] pub unsafe fn as_unsafe_cell<'a>(&'a self) -> &'a UnsafeCell<T> { &self.value } } #[stable(feature = "rust1", since = "1.0.0")] unsafe impl<T> Send for Cell<T> where T: Send {} #[stable(feature = "rust1", since = "1.0.0")] impl<T:Copy> Clone for Cell<T> { fn clone(&self) -> Cell<T> { Cell::new(self.get()) } } #[stable(feature = "rust1", since = "1.0.0")] impl<T:Default + Copy> Default for Cell<T> { #[stable(feature = "rust1", since = "1.0.0")] fn default() -> Cell<T> { Cell::new(Default::default()) } } #[stable(feature = "rust1", since = "1.0.0")] impl<T:PartialEq + Copy> PartialEq for Cell<T> { fn eq(&self, other: &Cell<T>) -> bool { self.get() == other.get() } } /// A mutable memory location with dynamically checked borrow rules /// /// See the [module-level documentation](index.html) for more. #[stable(feature = "rust1", since = "1.0.0")] pub struct RefCell<T> { value: UnsafeCell<T>, borrow: Cell<BorrowFlag>, } /// An enumeration of values returned from the `state` method on a `RefCell<T>`. #[derive(Copy, Clone, PartialEq, Debug)] #[unstable(feature = "std_misc")] pub enum BorrowState { /// The cell is currently being read, there is at least one active `borrow`. Reading, /// The cell is currently being written to, there is an active `borrow_mut`. Writing, /// There are no outstanding borrows on this cell. Unused, } // Values [1, MAX-1] represent the number of `Ref` active // (will not outgrow its range since `uint` is the size of the address space) type BorrowFlag = uint; const UNUSED: BorrowFlag = 0; const WRITING: BorrowFlag = -1; impl<T> RefCell<T> { /// Creates a new `RefCell` containing `value`. /// /// # Examples /// /// ``` /// use std::cell::RefCell; /// /// let c = RefCell::new(5); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn new(value: T) -> RefCell<T> { RefCell { value: UnsafeCell::new(value), borrow: Cell::new(UNUSED), } } /// Consumes the `RefCell`, returning the wrapped value. /// /// # Examples /// /// ``` /// use std::cell::RefCell; /// /// let c = RefCell::new(5); /// /// let five = c.into_inner(); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn into_inner(self) -> T { // Since this function takes `self` (the `RefCell`) by value, the // compiler statically verifies that it is not currently borrowed. // Therefore the following assertion is just a `debug_assert!`. debug_assert!(self.borrow.get() == UNUSED); unsafe { self.value.into_inner() } } /// Query the current state of this `RefCell` /// /// The returned value can be dispatched on to determine if a call to /// `borrow` or `borrow_mut` would succeed. #[unstable(feature = "std_misc")] pub fn borrow_state(&self) -> BorrowState { match self.borrow.get() { WRITING => BorrowState::Writing, UNUSED => BorrowState::Unused, _ => BorrowState::Reading, } } /// Attempts to immutably borrow the wrapped value. /// /// The borrow lasts until the returned `Ref` exits scope. Multiple /// immutable borrows can be taken out at the same time. /// /// Returns `None` if the value is currently mutably borrowed. #[unstable(feature = "core", reason = "may be renamed or removed")] #[deprecated(since = "1.0.0", reason = "dispatch on `cell.borrow_state()` instead")] pub fn try_borrow<'a>(&'a self) -> Option<Ref<'a, T>> { match BorrowRef::new(&self.borrow) { Some(b) => Some(Ref { _value: unsafe { &*self.value.get() }, _borrow: b }), None => None, } } /// Immutably borrows the wrapped value. /// /// The borrow lasts until the returned `Ref` exits scope. Multiple /// immutable borrows can be taken out at the same time. /// /// # Panics /// /// Panics if the value is currently mutably borrowed. /// /// # Examples /// /// ``` /// use std::cell::RefCell; /// /// let c = RefCell::new(5); /// /// let borrowed_five = c.borrow(); /// let borrowed_five2 = c.borrow(); /// ``` /// /// An example of panic: /// /// ``` /// use std::cell::RefCell; /// use std::thread::Thread; /// /// let result = Thread::scoped(move || { /// let c = RefCell::new(5); /// let m = c.borrow_mut(); /// /// let b = c.borrow(); // this causes a panic /// }).join(); /// /// assert!(result.is_err()); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn borrow<'a>(&'a self) -> Ref<'a, T> { match BorrowRef::new(&self.borrow) { Some(b) => Ref { _value: unsafe { &*self.value.get() }, _borrow: b, }, None => panic!("RefCell<T> already mutably borrowed"), } } /// Mutably borrows the wrapped value. /// /// The borrow lasts until the returned `RefMut` exits scope. The value /// cannot be borrowed while this borrow is active. /// /// Returns `None` if the value is currently borrowed. #[unstable(feature = "core", reason = "may be renamed or removed")] #[deprecated(since = "1.0.0", reason = "dispatch on `cell.borrow_state()` instead")] pub fn try_borrow_mut<'a>(&'a self) -> Option<RefMut<'a, T>> { match BorrowRefMut::new(&self.borrow) { Some(b) => Some(RefMut { _value: unsafe { &mut *self.value.get() }, _borrow: b }), None => None, } } /// Mutably borrows the wrapped value. /// /// The borrow lasts until the returned `RefMut` exits scope. The value /// cannot be borrowed while this borrow is active. /// /// # Panics /// /// Panics if the value is currently borrowed. /// /// # Examples /// /// ``` /// use std::cell::RefCell; /// /// let c = RefCell::new(5); /// /// let borrowed_five = c.borrow_mut(); /// ``` /// /// An example of panic: /// /// ``` /// use std::cell::RefCell; /// use std::thread::Thread; /// /// let result = Thread::scoped(move || { /// let c = RefCell::new(5); /// let m = c.borrow_mut(); /// /// let b = c.borrow_mut(); // this causes a panic /// }).join(); /// /// assert!(result.is_err()); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn borrow_mut<'a>(&'a self) -> RefMut<'a, T> { match BorrowRefMut::new(&self.borrow) { Some(b) => RefMut { _value: unsafe { &mut *self.value.get() }, _borrow: b, }, None => panic!("RefCell<T> already borrowed"), } } /// Get a reference to the underlying `UnsafeCell`. /// /// This can be used to circumvent `RefCell`'s safety checks. /// /// This function is `unsafe` because `UnsafeCell`'s field is public. #[inline] #[unstable(feature = "core")] pub unsafe fn as_unsafe_cell<'a>(&'a self) -> &'a UnsafeCell<T> { &self.value } } #[stable(feature = "rust1", since = "1.0.0")] unsafe impl<T> Send for RefCell<T> where T: Send {} #[stable(feature = "rust1", since = "1.0.0")] impl<T: Clone> Clone for RefCell<T> { fn clone(&self) -> RefCell<T> { RefCell::new(self.borrow().clone()) } } #[stable(feature = "rust1", since = "1.0.0")] impl<T:Default> Default for RefCell<T> { #[stable(feature = "rust1", since = "1.0.0")] fn default() -> RefCell<T> { RefCell::new(Default::default()) } } #[stable(feature = "rust1", since = "1.0.0")] impl<T: PartialEq> PartialEq for RefCell<T> { fn eq(&self, other: &RefCell<T>) -> bool { *self.borrow() == *other.borrow() } } struct BorrowRef<'b> { _borrow: &'b Cell<BorrowFlag>, } impl<'b> BorrowRef<'b> { fn new(borrow: &'b Cell<BorrowFlag>) -> Option<BorrowRef<'b>> { match borrow.get() { WRITING => None, b => { borrow.set(b + 1); Some(BorrowRef { _borrow: borrow }) }, } } } #[unsafe_destructor] impl<'b> Drop for BorrowRef<'b> { fn drop(&mut self) { let borrow = self._borrow.get(); debug_assert!(borrow!= WRITING && borrow!= UNUSED); self._borrow.set(borrow - 1); } } impl<'b> Clone for BorrowRef<'b> { fn clone(&self) -> BorrowRef<'b> { // Since this Ref exists, we know the borrow flag // is not set to WRITING. let borrow = self._borrow.get(); debug_assert!(borrow!= WRITING && borrow!= UNUSED); self._borrow.set(borrow + 1); BorrowRef { _borrow: self._borrow } } } /// Wraps a borrowed reference to a value in a `RefCell` box. /// A wrapper type for an immutably borrowed value from a `RefCell<T>`. /// /// See the [module-level documentation](index.html) for more. #[stable(feature = "rust1", since = "1.0.0")] pub struct Ref<'b, T:'b> { // FIXME #12808: strange name to try to avoid interfering with // field accesses of the contained type via Deref _value: &'b T, _borrow: BorrowRef<'b>, } #[stable(feature = "rust1", since = "1.0.0")] impl<'b, T> Deref for Ref<'b, T> { type Target = T; #[inline] fn deref<'a>(&'a self) -> &'a T { self._value } } /// Copy a `Ref`. /// /// The `RefCell` is already immutably borrowed, so this cannot fail. /// /// A `Clone` implementation would interfere with the widespread /// use of `r.borrow().clone()` to clone the contents of a `RefCell`. #[unstable(feature = "core", reason = "likely to be moved to a method, pending language changes")] pub fn clone_ref<'b, T:Clone>(orig: &Ref<'b, T>) -> Ref<'b, T> { Ref { _value: orig._value, _borrow: orig._borrow.clone(), } } struct BorrowRefMut<'b> { _borrow: &'b Cell<BorrowFlag>, } #[unsafe_destructor] impl<'b> Drop for BorrowRefMut<'b> { fn drop(&mut self) { let borrow = self._borrow.get(); debug_assert!(borrow == WRITING); self._borrow.set(UNUSED); } } impl<'b> BorrowRefMut<'b> { fn new(borrow: &'b Cell<BorrowFlag>) -> Option<BorrowRefMut<'b>> { match borrow.get() { UNUSED => { borrow.set(WRITING); Some(BorrowRefMut { _borrow: borrow }) }, _ => None, } } } /// A wrapper type for a mutably borrowed value from a `RefCell<T>`. /// /// See the [module-level documentation](index.html) for more. #[stable(feature = "rust1", since = "1.0.0")] pub struct RefMut<'b, T:'b> { // FIXME #12808: strange name to try to avoid interfering with // field accesses of the contained type via Deref _value: &'b mut T, _borrow: BorrowRefMut<'b>, } #[stable(feature = "rust1", since = "1.0.0")] impl<'b, T> Deref for RefMut<'b, T> { type Target = T; #[inline] fn deref<'a>(&'a self) -> &'a T { self._value } } #[stable(feature = "rust1", since = "1.0.0")] impl<'b, T> DerefMut for RefMut<'b, T> { #[inline] fn deref_mut<'a>(&'a mut self) -> &'a mut T { self._value } } /// The core primitive for interior mutability in Rust. /// /// `UnsafeCell<T>` is a type that wraps some `T` and indicates unsafe interior operations on the /// wrapped type. Types with an `UnsafeCell<T>` field are considered to have an 'unsafe interior'. /// The `UnsafeCell<T>` type is the only legal way to obtain aliasable data that is considered /// mutable. In general, transmuting an `&T` type into an `&mut T` is considered undefined behavior. /// /// Types like `Cell<T>` and `RefCell<T>` use this type to wrap their internal data. /// /// `UnsafeCell<T>` doesn't opt-out from any marker traits, instead, types with an `UnsafeCell<T>` /// interior are expected to opt-out from those traits themselves. /// /// # Examples /// /// ``` /// use std::cell::UnsafeCell; /// use std::marker::Sync; /// /// struct NotThreadSafe<T> { /// value: UnsafeCell<T>, /// } /// /// unsafe impl<T> Sync for NotThreadSafe<T> {} /// ``` /// /// **NOTE:** `UnsafeCell<T>`'s fields are public to allow static initializers. It is not /// recommended to access its fields directly, `get` should be used instead. #[lang="unsafe"] #[stable(feature = "rust1", since = "1.0.0")] pub struct UnsafeCell<T> { /// Wrapped value /// /// This field should not be accessed directly, it is made public for static /// initializers. #[unstable(feature = "core")] pub value: T, } impl<T> UnsafeCell<T> { /// Construct a new instance of `UnsafeCell` which will wrap the specified /// value. /// /// All access to the inner value through methods is `unsafe`, and it is highly discouraged to /// access the fields directly. /// /// # Examples /// /// ``` /// use std::cell::UnsafeCell; /// /// let uc = UnsafeCell::new(5); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn new(value: T) -> UnsafeCell<T> { UnsafeCell { value: value } } /// Gets a mutable pointer to the wrapped value. /// /// # Examples /// /// ``` /// use std::cell::UnsafeCell; /// /// let uc = UnsafeCell::new(5); /// /// let five = uc.get(); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn
(&self) -> *mut T { &self.value as *const T as *mut T } /// Unwraps the value /// /// # Unsafety /// /// This function is unsafe because there is no guarantee that this or other threads are /// currently inspecting the inner value. /// /// # Examples /// /// ``` /// use std::cell::UnsafeCell; /// /// let uc = UnsafeCell::new(5); /// /// let five = unsafe { uc.into_inner() }; ///
get
identifier_name
cell.rs
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. //! Shareable mutable containers. //! //! Values of the `Cell<T>` and `RefCell<T>` types may be mutated through shared references (i.e. //! the common `&T` type), whereas most Rust types can only be mutated through unique (`&mut T`) //! references. We say that `Cell<T>` and `RefCell<T>` provide 'interior mutability', in contrast //! with typical Rust types that exhibit 'inherited mutability'. //! //! Cell types come in two flavors: `Cell<T>` and `RefCell<T>`. `Cell<T>` provides `get` and `set` //! methods that change the interior value with a single method call. `Cell<T>` though is only //! compatible with types that implement `Copy`. For other types, one must use the `RefCell<T>` //! type, acquiring a write lock before mutating. //! //! `RefCell<T>` uses Rust's lifetimes to implement 'dynamic borrowing', a process whereby one can //! claim temporary, exclusive, mutable access to the inner value. Borrows for `RefCell<T>`s are //! tracked 'at runtime', unlike Rust's native reference types which are entirely tracked //! statically, at compile time. Because `RefCell<T>` borrows are dynamic it is possible to attempt //! to borrow a value that is already mutably borrowed; when this happens it results in task panic. //! //! # When to choose interior mutability //! //! The more common inherited mutability, where one must have unique access to mutate a value, is //! one of the key language elements that enables Rust to reason strongly about pointer aliasing, //! statically preventing crash bugs. Because of that, inherited mutability is preferred, and //! interior mutability is something of a last resort. Since cell types enable mutation where it //! would otherwise be disallowed though, there are occasions when interior mutability might be //! appropriate, or even *must* be used, e.g. //! //! * Introducing inherited mutability roots to shared types. //! * Implementation details of logically-immutable methods. //! * Mutating implementations of `clone`. //! //! ## Introducing inherited mutability roots to shared types //! //! Shared smart pointer types, including `Rc<T>` and `Arc<T>`, provide containers that can be //! cloned and shared between multiple parties. Because the contained values may be //! multiply-aliased, they can only be borrowed as shared references, not mutable references. //! Without cells it would be impossible to mutate data inside of shared boxes at all! //! //! It's very common then to put a `RefCell<T>` inside shared pointer types to reintroduce //! mutability: //! //! ``` //! use std::collections::HashMap; //! use std::cell::RefCell; //! use std::rc::Rc; //! //! fn main() { //! let shared_map: Rc<RefCell<_>> = Rc::new(RefCell::new(HashMap::new())); //! shared_map.borrow_mut().insert("africa", 92388); //! shared_map.borrow_mut().insert("kyoto", 11837); //! shared_map.borrow_mut().insert("piccadilly", 11826); //! shared_map.borrow_mut().insert("marbles", 38); //! } //! ``` //! //! Note that this example uses `Rc<T>` and not `Arc<T>`. `RefCell<T>`s are for single-threaded //! scenarios. Consider using `Mutex<T>` if you need shared mutability in a multi-threaded //! situation. //! //! ## Implementation details of logically-immutable methods //! //! Occasionally it may be desirable not to expose in an API that there is mutation happening //! "under the hood". This may be because logically the operation is immutable, but e.g. caching //! forces the implementation to perform mutation; or because you must employ mutation to implement //! a trait method that was originally defined to take `&self`. //! //! ``` //! use std::cell::RefCell; //! //! struct Graph { //! edges: Vec<(uint, uint)>, //! span_tree_cache: RefCell<Option<Vec<(uint, uint)>>> //! } //! //! impl Graph { //! fn minimum_spanning_tree(&self) -> Vec<(uint, uint)> { //! // Create a new scope to contain the lifetime of the //! // dynamic borrow //! { //! // Take a reference to the inside of cache cell //! let mut cache = self.span_tree_cache.borrow_mut(); //! if cache.is_some() { //! return cache.as_ref().unwrap().clone(); //! } //! //! let span_tree = self.calc_span_tree(); //! *cache = Some(span_tree); //! } //! //! // Recursive call to return the just-cached value. //! // Note that if we had not let the previous borrow //! // of the cache fall out of scope then the subsequent //! // recursive borrow would cause a dynamic task panic. //! // This is the major hazard of using `RefCell`. //! self.minimum_spanning_tree() //! } //! # fn calc_span_tree(&self) -> Vec<(uint, uint)> { vec![] } //! } //! ``` //! //! ## Mutating implementations of `clone` //! //! This is simply a special - but common - case of the previous: hiding mutability for operations //! that appear to be immutable. The `clone` method is expected to not change the source value, and //! is declared to take `&self`, not `&mut self`. Therefore any mutation that happens in the //! `clone` method must use cell types. For example, `Rc<T>` maintains its reference counts within a //! `Cell<T>`. //! //! ``` //! use std::cell::Cell; //! //! struct Rc<T> { //! ptr: *mut RcBox<T> //! } //! //! struct RcBox<T> { //! value: T, //! refcount: Cell<uint> //! } //! //! impl<T> Clone for Rc<T> { //! fn clone(&self) -> Rc<T> { //! unsafe { //! (*self.ptr).refcount.set((*self.ptr).refcount.get() + 1); //! Rc { ptr: self.ptr } //! } //! } //! } //! ``` //! #![stable(feature = "rust1", since = "1.0.0")] use clone::Clone; use cmp::PartialEq; use default::Default; use marker::{Copy, Send}; use ops::{Deref, DerefMut, Drop}; use option::Option; use option::Option::{None, Some}; /// A mutable memory location that admits only `Copy` data. /// /// See the [module-level documentation](index.html) for more. #[stable(feature = "rust1", since = "1.0.0")] pub struct Cell<T> { value: UnsafeCell<T>, } impl<T:Copy> Cell<T> { /// Creates a new `Cell` containing the given value. /// /// # Examples /// /// ``` /// use std::cell::Cell; /// /// let c = Cell::new(5); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn new(value: T) -> Cell<T> { Cell { value: UnsafeCell::new(value), } } /// Returns a copy of the contained value. /// /// # Examples /// /// ``` /// use std::cell::Cell; /// /// let c = Cell::new(5); /// /// let five = c.get(); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn get(&self) -> T { unsafe{ *self.value.get() } } /// Sets the contained value. /// /// # Examples /// /// ``` /// use std::cell::Cell; /// /// let c = Cell::new(5); /// /// c.set(10); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn set(&self, value: T) { unsafe { *self.value.get() = value; } } /// Get a reference to the underlying `UnsafeCell`. /// /// # Unsafety /// /// This function is `unsafe` because `UnsafeCell`'s field is public. /// /// # Examples /// /// ``` /// use std::cell::Cell; /// /// let c = Cell::new(5); /// /// let uc = unsafe { c.as_unsafe_cell() }; /// ``` #[inline] #[unstable(feature = "core")] pub unsafe fn as_unsafe_cell<'a>(&'a self) -> &'a UnsafeCell<T> { &self.value } } #[stable(feature = "rust1", since = "1.0.0")] unsafe impl<T> Send for Cell<T> where T: Send {} #[stable(feature = "rust1", since = "1.0.0")] impl<T:Copy> Clone for Cell<T> { fn clone(&self) -> Cell<T> { Cell::new(self.get()) } } #[stable(feature = "rust1", since = "1.0.0")] impl<T:Default + Copy> Default for Cell<T> { #[stable(feature = "rust1", since = "1.0.0")] fn default() -> Cell<T> { Cell::new(Default::default()) } } #[stable(feature = "rust1", since = "1.0.0")] impl<T:PartialEq + Copy> PartialEq for Cell<T> { fn eq(&self, other: &Cell<T>) -> bool { self.get() == other.get() } } /// A mutable memory location with dynamically checked borrow rules /// /// See the [module-level documentation](index.html) for more. #[stable(feature = "rust1", since = "1.0.0")] pub struct RefCell<T> { value: UnsafeCell<T>, borrow: Cell<BorrowFlag>, } /// An enumeration of values returned from the `state` method on a `RefCell<T>`. #[derive(Copy, Clone, PartialEq, Debug)] #[unstable(feature = "std_misc")] pub enum BorrowState { /// The cell is currently being read, there is at least one active `borrow`. Reading, /// The cell is currently being written to, there is an active `borrow_mut`. Writing, /// There are no outstanding borrows on this cell. Unused, } // Values [1, MAX-1] represent the number of `Ref` active // (will not outgrow its range since `uint` is the size of the address space) type BorrowFlag = uint; const UNUSED: BorrowFlag = 0; const WRITING: BorrowFlag = -1; impl<T> RefCell<T> { /// Creates a new `RefCell` containing `value`. /// /// # Examples /// /// ``` /// use std::cell::RefCell; /// /// let c = RefCell::new(5); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn new(value: T) -> RefCell<T> { RefCell { value: UnsafeCell::new(value), borrow: Cell::new(UNUSED), } } /// Consumes the `RefCell`, returning the wrapped value. /// /// # Examples /// /// ``` /// use std::cell::RefCell; /// /// let c = RefCell::new(5); /// /// let five = c.into_inner(); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn into_inner(self) -> T { // Since this function takes `self` (the `RefCell`) by value, the // compiler statically verifies that it is not currently borrowed. // Therefore the following assertion is just a `debug_assert!`. debug_assert!(self.borrow.get() == UNUSED); unsafe { self.value.into_inner() } } /// Query the current state of this `RefCell` /// /// The returned value can be dispatched on to determine if a call to /// `borrow` or `borrow_mut` would succeed. #[unstable(feature = "std_misc")] pub fn borrow_state(&self) -> BorrowState { match self.borrow.get() { WRITING => BorrowState::Writing, UNUSED => BorrowState::Unused, _ => BorrowState::Reading, } } /// Attempts to immutably borrow the wrapped value. /// /// The borrow lasts until the returned `Ref` exits scope. Multiple /// immutable borrows can be taken out at the same time. /// /// Returns `None` if the value is currently mutably borrowed. #[unstable(feature = "core", reason = "may be renamed or removed")] #[deprecated(since = "1.0.0", reason = "dispatch on `cell.borrow_state()` instead")] pub fn try_borrow<'a>(&'a self) -> Option<Ref<'a, T>> { match BorrowRef::new(&self.borrow) { Some(b) => Some(Ref { _value: unsafe { &*self.value.get() }, _borrow: b }), None => None, } } /// Immutably borrows the wrapped value. /// /// The borrow lasts until the returned `Ref` exits scope. Multiple /// immutable borrows can be taken out at the same time. /// /// # Panics /// /// Panics if the value is currently mutably borrowed. /// /// # Examples /// /// ``` /// use std::cell::RefCell; /// /// let c = RefCell::new(5); /// /// let borrowed_five = c.borrow(); /// let borrowed_five2 = c.borrow(); /// ``` /// /// An example of panic: /// /// ``` /// use std::cell::RefCell; /// use std::thread::Thread; /// /// let result = Thread::scoped(move || { /// let c = RefCell::new(5); /// let m = c.borrow_mut(); /// /// let b = c.borrow(); // this causes a panic /// }).join(); /// /// assert!(result.is_err()); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn borrow<'a>(&'a self) -> Ref<'a, T> { match BorrowRef::new(&self.borrow) { Some(b) => Ref { _value: unsafe { &*self.value.get() }, _borrow: b, }, None => panic!("RefCell<T> already mutably borrowed"), } } /// Mutably borrows the wrapped value. /// /// The borrow lasts until the returned `RefMut` exits scope. The value /// cannot be borrowed while this borrow is active. /// /// Returns `None` if the value is currently borrowed. #[unstable(feature = "core", reason = "may be renamed or removed")] #[deprecated(since = "1.0.0", reason = "dispatch on `cell.borrow_state()` instead")] pub fn try_borrow_mut<'a>(&'a self) -> Option<RefMut<'a, T>> { match BorrowRefMut::new(&self.borrow) { Some(b) => Some(RefMut { _value: unsafe { &mut *self.value.get() }, _borrow: b }), None => None, } } /// Mutably borrows the wrapped value. /// /// The borrow lasts until the returned `RefMut` exits scope. The value /// cannot be borrowed while this borrow is active. /// /// # Panics /// /// Panics if the value is currently borrowed. /// /// # Examples /// /// ``` /// use std::cell::RefCell; /// /// let c = RefCell::new(5); /// /// let borrowed_five = c.borrow_mut(); /// ``` /// /// An example of panic: /// /// ``` /// use std::cell::RefCell; /// use std::thread::Thread; /// /// let result = Thread::scoped(move || { /// let c = RefCell::new(5); /// let m = c.borrow_mut(); /// /// let b = c.borrow_mut(); // this causes a panic /// }).join(); /// /// assert!(result.is_err()); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn borrow_mut<'a>(&'a self) -> RefMut<'a, T> { match BorrowRefMut::new(&self.borrow) { Some(b) => RefMut { _value: unsafe { &mut *self.value.get() }, _borrow: b, }, None => panic!("RefCell<T> already borrowed"), } } /// Get a reference to the underlying `UnsafeCell`. /// /// This can be used to circumvent `RefCell`'s safety checks. /// /// This function is `unsafe` because `UnsafeCell`'s field is public. #[inline] #[unstable(feature = "core")] pub unsafe fn as_unsafe_cell<'a>(&'a self) -> &'a UnsafeCell<T>
} #[stable(feature = "rust1", since = "1.0.0")] unsafe impl<T> Send for RefCell<T> where T: Send {} #[stable(feature = "rust1", since = "1.0.0")] impl<T: Clone> Clone for RefCell<T> { fn clone(&self) -> RefCell<T> { RefCell::new(self.borrow().clone()) } } #[stable(feature = "rust1", since = "1.0.0")] impl<T:Default> Default for RefCell<T> { #[stable(feature = "rust1", since = "1.0.0")] fn default() -> RefCell<T> { RefCell::new(Default::default()) } } #[stable(feature = "rust1", since = "1.0.0")] impl<T: PartialEq> PartialEq for RefCell<T> { fn eq(&self, other: &RefCell<T>) -> bool { *self.borrow() == *other.borrow() } } struct BorrowRef<'b> { _borrow: &'b Cell<BorrowFlag>, } impl<'b> BorrowRef<'b> { fn new(borrow: &'b Cell<BorrowFlag>) -> Option<BorrowRef<'b>> { match borrow.get() { WRITING => None, b => { borrow.set(b + 1); Some(BorrowRef { _borrow: borrow }) }, } } } #[unsafe_destructor] impl<'b> Drop for BorrowRef<'b> { fn drop(&mut self) { let borrow = self._borrow.get(); debug_assert!(borrow!= WRITING && borrow!= UNUSED); self._borrow.set(borrow - 1); } } impl<'b> Clone for BorrowRef<'b> { fn clone(&self) -> BorrowRef<'b> { // Since this Ref exists, we know the borrow flag // is not set to WRITING. let borrow = self._borrow.get(); debug_assert!(borrow!= WRITING && borrow!= UNUSED); self._borrow.set(borrow + 1); BorrowRef { _borrow: self._borrow } } } /// Wraps a borrowed reference to a value in a `RefCell` box. /// A wrapper type for an immutably borrowed value from a `RefCell<T>`. /// /// See the [module-level documentation](index.html) for more. #[stable(feature = "rust1", since = "1.0.0")] pub struct Ref<'b, T:'b> { // FIXME #12808: strange name to try to avoid interfering with // field accesses of the contained type via Deref _value: &'b T, _borrow: BorrowRef<'b>, } #[stable(feature = "rust1", since = "1.0.0")] impl<'b, T> Deref for Ref<'b, T> { type Target = T; #[inline] fn deref<'a>(&'a self) -> &'a T { self._value } } /// Copy a `Ref`. /// /// The `RefCell` is already immutably borrowed, so this cannot fail. /// /// A `Clone` implementation would interfere with the widespread /// use of `r.borrow().clone()` to clone the contents of a `RefCell`. #[unstable(feature = "core", reason = "likely to be moved to a method, pending language changes")] pub fn clone_ref<'b, T:Clone>(orig: &Ref<'b, T>) -> Ref<'b, T> { Ref { _value: orig._value, _borrow: orig._borrow.clone(), } } struct BorrowRefMut<'b> { _borrow: &'b Cell<BorrowFlag>, } #[unsafe_destructor] impl<'b> Drop for BorrowRefMut<'b> { fn drop(&mut self) { let borrow = self._borrow.get(); debug_assert!(borrow == WRITING); self._borrow.set(UNUSED); } } impl<'b> BorrowRefMut<'b> { fn new(borrow: &'b Cell<BorrowFlag>) -> Option<BorrowRefMut<'b>> { match borrow.get() { UNUSED => { borrow.set(WRITING); Some(BorrowRefMut { _borrow: borrow }) }, _ => None, } } } /// A wrapper type for a mutably borrowed value from a `RefCell<T>`. /// /// See the [module-level documentation](index.html) for more. #[stable(feature = "rust1", since = "1.0.0")] pub struct RefMut<'b, T:'b> { // FIXME #12808: strange name to try to avoid interfering with // field accesses of the contained type via Deref _value: &'b mut T, _borrow: BorrowRefMut<'b>, } #[stable(feature = "rust1", since = "1.0.0")] impl<'b, T> Deref for RefMut<'b, T> { type Target = T; #[inline] fn deref<'a>(&'a self) -> &'a T { self._value } } #[stable(feature = "rust1", since = "1.0.0")] impl<'b, T> DerefMut for RefMut<'b, T> { #[inline] fn deref_mut<'a>(&'a mut self) -> &'a mut T { self._value } } /// The core primitive for interior mutability in Rust. /// /// `UnsafeCell<T>` is a type that wraps some `T` and indicates unsafe interior operations on the /// wrapped type. Types with an `UnsafeCell<T>` field are considered to have an 'unsafe interior'. /// The `UnsafeCell<T>` type is the only legal way to obtain aliasable data that is considered /// mutable. In general, transmuting an `&T` type into an `&mut T` is considered undefined behavior. /// /// Types like `Cell<T>` and `RefCell<T>` use this type to wrap their internal data. /// /// `UnsafeCell<T>` doesn't opt-out from any marker traits, instead, types with an `UnsafeCell<T>` /// interior are expected to opt-out from those traits themselves. /// /// # Examples /// /// ``` /// use std::cell::UnsafeCell; /// use std::marker::Sync; /// /// struct NotThreadSafe<T> { /// value: UnsafeCell<T>, /// } /// /// unsafe impl<T> Sync for NotThreadSafe<T> {} /// ``` /// /// **NOTE:** `UnsafeCell<T>`'s fields are public to allow static initializers. It is not /// recommended to access its fields directly, `get` should be used instead. #[lang="unsafe"] #[stable(feature = "rust1", since = "1.0.0")] pub struct UnsafeCell<T> { /// Wrapped value /// /// This field should not be accessed directly, it is made public for static /// initializers. #[unstable(feature = "core")] pub value: T, } impl<T> UnsafeCell<T> { /// Construct a new instance of `UnsafeCell` which will wrap the specified /// value. /// /// All access to the inner value through methods is `unsafe`, and it is highly discouraged to /// access the fields directly. /// /// # Examples /// /// ``` /// use std::cell::UnsafeCell; /// /// let uc = UnsafeCell::new(5); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn new(value: T) -> UnsafeCell<T> { UnsafeCell { value: value } } /// Gets a mutable pointer to the wrapped value. /// /// # Examples /// /// ``` /// use std::cell::UnsafeCell; /// /// let uc = UnsafeCell::new(5); /// /// let five = uc.get(); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn get(&self) -> *mut T { &self.value as *const T as *mut T } /// Unwraps the value /// /// # Unsafety /// /// This function is unsafe because there is no guarantee that this or other threads are /// currently inspecting the inner value. /// /// # Examples /// /// ``` /// use std::cell::UnsafeCell; /// /// let uc = UnsafeCell::new(5); /// /// let five = unsafe { uc.into_inner() }; ///
{ &self.value }
identifier_body
config.rs
//! Defines configuration file format. use anyhow::{anyhow, Result}; use glob::Pattern; use lazy_static::lazy_static; use serde::Deserialize; use std::{ fs, io::Read, ops::{Deref, DerefMut}, path::{Path, PathBuf}, }; lazy_static! { static ref CONFIG_PATH: PathBuf = dirs::config_dir() .map(|config_path| config_path.join("rhq/config.toml")) .expect("failed to determine the configuration path"); } /// configuration load from config files #[derive(Deserialize)] struct RawConfigData { root: Option<String>, default_host: Option<String>, includes: Option<Vec<String>>, excludes: Option<Vec<String>>, } #[derive(Debug)] pub struct ConfigData { pub root_dir: PathBuf, pub host: String, pub include_dirs: Vec<PathBuf>, pub exclude_patterns: Vec<Pattern>, } impl ConfigData { fn
(raw: RawConfigData) -> Result<Self> { let root_dir = raw.root.as_deref().unwrap_or("~/rhq"); let root_dir = crate::util::make_path_buf(root_dir)?; let include_dirs = raw .includes .as_deref() .unwrap_or(&[]) .iter() .filter_map(|root| crate::util::make_path_buf(&root).ok()) .collect(); let exclude_patterns = raw .excludes .as_deref() .unwrap_or(&[]) .iter() .filter_map(|ex| { ::shellexpand::full(&ex) .ok() .map(|ex| ex.replace(r"\", "/")) .and_then(|ex| ::glob::Pattern::new(&ex).ok()) }) .collect(); let host = raw.default_host.unwrap_or_else(|| "github.com".to_owned()); Ok(Self { root_dir, host, include_dirs, exclude_patterns, }) } } #[derive(Debug)] pub struct Config { path: PathBuf, data: ConfigData, } impl Config { pub fn new(config_path: Option<&Path>) -> Result<Self> { let config_path: &Path = config_path.unwrap_or_else(|| &*CONFIG_PATH); if!config_path.is_file() { return Err(anyhow!( "Failed to load configuration file (config_path = {})", config_path.display() )); } let mut content = String::new(); fs::File::open(config_path)?.read_to_string(&mut content)?; let data = ::toml::from_str(&content)?; Ok(Config { path: config_path.into(), data: ConfigData::from_raw(data)?, }) } pub fn cache_dir(&self) -> PathBuf { self.root_dir.join(".cache.json") } } impl Deref for Config { type Target = ConfigData; #[inline] fn deref(&self) -> &Self::Target { &self.data } } impl DerefMut for Config { #[inline] fn deref_mut(&mut self) -> &mut Self::Target { &mut self.data } }
from_raw
identifier_name
config.rs
//! Defines configuration file format. use anyhow::{anyhow, Result}; use glob::Pattern; use lazy_static::lazy_static; use serde::Deserialize; use std::{ fs, io::Read, ops::{Deref, DerefMut},
}; lazy_static! { static ref CONFIG_PATH: PathBuf = dirs::config_dir() .map(|config_path| config_path.join("rhq/config.toml")) .expect("failed to determine the configuration path"); } /// configuration load from config files #[derive(Deserialize)] struct RawConfigData { root: Option<String>, default_host: Option<String>, includes: Option<Vec<String>>, excludes: Option<Vec<String>>, } #[derive(Debug)] pub struct ConfigData { pub root_dir: PathBuf, pub host: String, pub include_dirs: Vec<PathBuf>, pub exclude_patterns: Vec<Pattern>, } impl ConfigData { fn from_raw(raw: RawConfigData) -> Result<Self> { let root_dir = raw.root.as_deref().unwrap_or("~/rhq"); let root_dir = crate::util::make_path_buf(root_dir)?; let include_dirs = raw .includes .as_deref() .unwrap_or(&[]) .iter() .filter_map(|root| crate::util::make_path_buf(&root).ok()) .collect(); let exclude_patterns = raw .excludes .as_deref() .unwrap_or(&[]) .iter() .filter_map(|ex| { ::shellexpand::full(&ex) .ok() .map(|ex| ex.replace(r"\", "/")) .and_then(|ex| ::glob::Pattern::new(&ex).ok()) }) .collect(); let host = raw.default_host.unwrap_or_else(|| "github.com".to_owned()); Ok(Self { root_dir, host, include_dirs, exclude_patterns, }) } } #[derive(Debug)] pub struct Config { path: PathBuf, data: ConfigData, } impl Config { pub fn new(config_path: Option<&Path>) -> Result<Self> { let config_path: &Path = config_path.unwrap_or_else(|| &*CONFIG_PATH); if!config_path.is_file() { return Err(anyhow!( "Failed to load configuration file (config_path = {})", config_path.display() )); } let mut content = String::new(); fs::File::open(config_path)?.read_to_string(&mut content)?; let data = ::toml::from_str(&content)?; Ok(Config { path: config_path.into(), data: ConfigData::from_raw(data)?, }) } pub fn cache_dir(&self) -> PathBuf { self.root_dir.join(".cache.json") } } impl Deref for Config { type Target = ConfigData; #[inline] fn deref(&self) -> &Self::Target { &self.data } } impl DerefMut for Config { #[inline] fn deref_mut(&mut self) -> &mut Self::Target { &mut self.data } }
path::{Path, PathBuf},
random_line_split
config.rs
//! Defines configuration file format. use anyhow::{anyhow, Result}; use glob::Pattern; use lazy_static::lazy_static; use serde::Deserialize; use std::{ fs, io::Read, ops::{Deref, DerefMut}, path::{Path, PathBuf}, }; lazy_static! { static ref CONFIG_PATH: PathBuf = dirs::config_dir() .map(|config_path| config_path.join("rhq/config.toml")) .expect("failed to determine the configuration path"); } /// configuration load from config files #[derive(Deserialize)] struct RawConfigData { root: Option<String>, default_host: Option<String>, includes: Option<Vec<String>>, excludes: Option<Vec<String>>, } #[derive(Debug)] pub struct ConfigData { pub root_dir: PathBuf, pub host: String, pub include_dirs: Vec<PathBuf>, pub exclude_patterns: Vec<Pattern>, } impl ConfigData { fn from_raw(raw: RawConfigData) -> Result<Self> { let root_dir = raw.root.as_deref().unwrap_or("~/rhq"); let root_dir = crate::util::make_path_buf(root_dir)?; let include_dirs = raw .includes .as_deref() .unwrap_or(&[]) .iter() .filter_map(|root| crate::util::make_path_buf(&root).ok()) .collect(); let exclude_patterns = raw .excludes .as_deref() .unwrap_or(&[]) .iter() .filter_map(|ex| { ::shellexpand::full(&ex) .ok() .map(|ex| ex.replace(r"\", "/")) .and_then(|ex| ::glob::Pattern::new(&ex).ok()) }) .collect(); let host = raw.default_host.unwrap_or_else(|| "github.com".to_owned()); Ok(Self { root_dir, host, include_dirs, exclude_patterns, }) } } #[derive(Debug)] pub struct Config { path: PathBuf, data: ConfigData, } impl Config { pub fn new(config_path: Option<&Path>) -> Result<Self> { let config_path: &Path = config_path.unwrap_or_else(|| &*CONFIG_PATH); if!config_path.is_file() { return Err(anyhow!( "Failed to load configuration file (config_path = {})", config_path.display() )); } let mut content = String::new(); fs::File::open(config_path)?.read_to_string(&mut content)?; let data = ::toml::from_str(&content)?; Ok(Config { path: config_path.into(), data: ConfigData::from_raw(data)?, }) } pub fn cache_dir(&self) -> PathBuf { self.root_dir.join(".cache.json") } } impl Deref for Config { type Target = ConfigData; #[inline] fn deref(&self) -> &Self::Target { &self.data } } impl DerefMut for Config { #[inline] fn deref_mut(&mut self) -> &mut Self::Target
}
{ &mut self.data }
identifier_body
config.rs
//! Defines configuration file format. use anyhow::{anyhow, Result}; use glob::Pattern; use lazy_static::lazy_static; use serde::Deserialize; use std::{ fs, io::Read, ops::{Deref, DerefMut}, path::{Path, PathBuf}, }; lazy_static! { static ref CONFIG_PATH: PathBuf = dirs::config_dir() .map(|config_path| config_path.join("rhq/config.toml")) .expect("failed to determine the configuration path"); } /// configuration load from config files #[derive(Deserialize)] struct RawConfigData { root: Option<String>, default_host: Option<String>, includes: Option<Vec<String>>, excludes: Option<Vec<String>>, } #[derive(Debug)] pub struct ConfigData { pub root_dir: PathBuf, pub host: String, pub include_dirs: Vec<PathBuf>, pub exclude_patterns: Vec<Pattern>, } impl ConfigData { fn from_raw(raw: RawConfigData) -> Result<Self> { let root_dir = raw.root.as_deref().unwrap_or("~/rhq"); let root_dir = crate::util::make_path_buf(root_dir)?; let include_dirs = raw .includes .as_deref() .unwrap_or(&[]) .iter() .filter_map(|root| crate::util::make_path_buf(&root).ok()) .collect(); let exclude_patterns = raw .excludes .as_deref() .unwrap_or(&[]) .iter() .filter_map(|ex| { ::shellexpand::full(&ex) .ok() .map(|ex| ex.replace(r"\", "/")) .and_then(|ex| ::glob::Pattern::new(&ex).ok()) }) .collect(); let host = raw.default_host.unwrap_or_else(|| "github.com".to_owned()); Ok(Self { root_dir, host, include_dirs, exclude_patterns, }) } } #[derive(Debug)] pub struct Config { path: PathBuf, data: ConfigData, } impl Config { pub fn new(config_path: Option<&Path>) -> Result<Self> { let config_path: &Path = config_path.unwrap_or_else(|| &*CONFIG_PATH); if!config_path.is_file()
let mut content = String::new(); fs::File::open(config_path)?.read_to_string(&mut content)?; let data = ::toml::from_str(&content)?; Ok(Config { path: config_path.into(), data: ConfigData::from_raw(data)?, }) } pub fn cache_dir(&self) -> PathBuf { self.root_dir.join(".cache.json") } } impl Deref for Config { type Target = ConfigData; #[inline] fn deref(&self) -> &Self::Target { &self.data } } impl DerefMut for Config { #[inline] fn deref_mut(&mut self) -> &mut Self::Target { &mut self.data } }
{ return Err(anyhow!( "Failed to load configuration file (config_path = {})", config_path.display() )); }
conditional_block
opcode.rs
enum_from_primitive! { #[derive(Debug)] pub enum Opcode { Special = 0b000000, RegImm = 0b000001, Addi = 0b001000, Addiu = 0b001001, Andi = 0b001100, Ori = 0b001101, Lui = 0b001111, Mtc0 = 0b010000, Beq = 0b000100, Bne = 0b000101, Beql = 0b010100, Bnel = 0b010101, Lw = 0b100011, Sw = 0b101011, } }
enum_from_primitive! { #[derive(Debug)] pub enum SpecialOpcode { Sll = 0b000000, Srl = 0b000010, Sllv = 0b000100, Srlv = 0b000110, Jr = 0b001000, Multu = 0b011001, Mfhi = 0b010000, Mflo = 0b010010, Addu = 0b100001, Subu = 0b100011, And = 0b100100, Or = 0b100101, Xor = 0b100110, Sltu = 0b101011, } } enum_from_primitive! { #[derive(Debug)] pub enum RegImmOpcode { Bgezal = 0b10001, } }
random_line_split
sync.rs
#![crate_name = "sync"] /* * This file is part of the uutils coreutils package. * * (c) Alexander Fomin <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* Last synced with: sync (GNU coreutils) 8.13 */ extern crate getopts; extern crate libc; #[path = "../common/util.rs"] #[macro_use] mod util; static NAME: &'static str = "sync"; static VERSION: &'static str = "1.0.0"; #[cfg(unix)] mod platform { use super::libc; extern { fn sync() -> libc::c_void; } pub unsafe fn do_sync() -> isize { sync(); 0 } } #[cfg(windows)] mod platform { pub use super::libc; use std::{mem, string}; use std::ptr::null; extern "system" { fn CreateFileA(lpFileName: *const libc::c_char, dwDesiredAccess: libc::uint32_t, dwShareMode: libc::uint32_t, lpSecurityAttributes: *const libc::c_void, // *LPSECURITY_ATTRIBUTES dwCreationDisposition: libc::uint32_t, dwFlagsAndAttributes: libc::uint32_t, hTemplateFile: *const libc::c_void) -> *const libc::c_void; fn GetDriveTypeA(lpRootPathName: *const libc::c_char) -> libc::c_uint; fn GetLastError() -> libc::uint32_t; fn FindFirstVolumeA(lpszVolumeName: *mut libc::c_char, cchBufferLength: libc::uint32_t) -> *const libc::c_void; fn FindNextVolumeA(hFindVolume: *const libc::c_void, lpszVolumeName: *mut libc::c_char, cchBufferLength: libc::uint32_t) -> libc::c_int; fn FindVolumeClose(hFindVolume: *const libc::c_void) -> libc::c_int; fn FlushFileBuffers(hFile: *const libc::c_void) -> libc::c_int; } #[allow(unused_unsafe)] unsafe fn
(name: &str) { let name_buffer = name.to_c_str().as_ptr(); if 0x00000003 == GetDriveTypeA(name_buffer) { // DRIVE_FIXED let sliced_name = &name[..name.len() - 1]; // eliminate trailing backslash let sliced_name_buffer = sliced_name.to_c_str().as_ptr(); match CreateFileA(sliced_name_buffer, 0xC0000000, // GENERIC_WRITE 0x00000003, // FILE_SHARE_WRITE, null(), 0x00000003, // OPEN_EXISTING 0, null()) { -1 => { // INVALID_HANDLE_VALUE crash!(GetLastError(), "failed to create volume handle"); } handle => { if FlushFileBuffers(handle) == 0 { crash!(GetLastError(), "failed to flush file buffer"); } } } } } #[allow(unused_unsafe)] unsafe fn find_first_volume() -> (String, *const libc::c_void) { let mut name: [libc::c_char; 260] = mem::uninitialized(); // MAX_PATH match FindFirstVolumeA(name.as_mut_ptr(), name.len() as libc::uint32_t) { -1 => { // INVALID_HANDLE_VALUE crash!(GetLastError(), "failed to find first volume"); } handle => { (string::raw::from_buf(name.as_ptr() as *const u8), handle) } } } #[allow(unused_unsafe)] unsafe fn find_all_volumes() -> Vec<String> { match find_first_volume() { (first_volume, next_volume_handle) => { let mut volumes = vec![first_volume]; loop { let mut name: [libc::c_char; 260] = mem::uninitialized(); // MAX_PATH match FindNextVolumeA(next_volume_handle, name.as_mut_ptr(), name.len() as libc::uint32_t) { 0 => { match GetLastError() { 0x12 => { // ERROR_NO_MORE_FILES FindVolumeClose(next_volume_handle); // ignore FindVolumeClose() failures break; } err => { crash!(err, "failed to find next volume"); } } } _ => { volumes.push(string::raw::from_buf(name.as_ptr() as *const u8)); } } } volumes } } } pub unsafe fn do_sync() -> int { let volumes = find_all_volumes(); for vol in volumes.iter() { flush_volume(&vol); } 0 } } pub fn uumain(args: Vec<String>) -> i32 { let mut opts = getopts::Options::new(); opts.optflag("h", "help", "display this help and exit"); opts.optflag("V", "version", "output version information and exit"); let matches = match opts.parse(&args[1..]) { Ok(m) => { m } _ => { help(&opts); return 1 } }; if matches.opt_present("h") { help(&opts); return 0 } if matches.opt_present("V") { version(); return 0 } sync(); 0 } fn version() { println!("{} (uutils) {}", NAME, VERSION); println!("The MIT License"); println!(""); println!("Author -- Alexander Fomin."); } fn help(opts: &getopts::Options) { let msg = format!("{0} {1} Usage: {0} [OPTION] Force changed blocks to disk, update the super block.", NAME, VERSION); print!("{}", opts.usage(&msg)); } fn sync() -> isize { unsafe { platform::do_sync() } }
flush_volume
identifier_name
sync.rs
#![crate_name = "sync"] /* * This file is part of the uutils coreutils package. * * (c) Alexander Fomin <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* Last synced with: sync (GNU coreutils) 8.13 */ extern crate getopts; extern crate libc; #[path = "../common/util.rs"] #[macro_use] mod util; static NAME: &'static str = "sync"; static VERSION: &'static str = "1.0.0"; #[cfg(unix)] mod platform { use super::libc; extern { fn sync() -> libc::c_void; } pub unsafe fn do_sync() -> isize { sync(); 0 } } #[cfg(windows)] mod platform { pub use super::libc; use std::{mem, string}; use std::ptr::null; extern "system" { fn CreateFileA(lpFileName: *const libc::c_char, dwDesiredAccess: libc::uint32_t, dwShareMode: libc::uint32_t, lpSecurityAttributes: *const libc::c_void, // *LPSECURITY_ATTRIBUTES dwCreationDisposition: libc::uint32_t, dwFlagsAndAttributes: libc::uint32_t, hTemplateFile: *const libc::c_void) -> *const libc::c_void; fn GetDriveTypeA(lpRootPathName: *const libc::c_char) -> libc::c_uint; fn GetLastError() -> libc::uint32_t; fn FindFirstVolumeA(lpszVolumeName: *mut libc::c_char, cchBufferLength: libc::uint32_t) -> *const libc::c_void; fn FindNextVolumeA(hFindVolume: *const libc::c_void, lpszVolumeName: *mut libc::c_char, cchBufferLength: libc::uint32_t) -> libc::c_int; fn FindVolumeClose(hFindVolume: *const libc::c_void) -> libc::c_int; fn FlushFileBuffers(hFile: *const libc::c_void) -> libc::c_int; } #[allow(unused_unsafe)] unsafe fn flush_volume(name: &str) { let name_buffer = name.to_c_str().as_ptr(); if 0x00000003 == GetDriveTypeA(name_buffer) { // DRIVE_FIXED let sliced_name = &name[..name.len() - 1]; // eliminate trailing backslash let sliced_name_buffer = sliced_name.to_c_str().as_ptr(); match CreateFileA(sliced_name_buffer, 0xC0000000, // GENERIC_WRITE 0x00000003, // FILE_SHARE_WRITE, null(), 0x00000003, // OPEN_EXISTING 0, null()) { -1 => { // INVALID_HANDLE_VALUE crash!(GetLastError(), "failed to create volume handle"); } handle => { if FlushFileBuffers(handle) == 0 { crash!(GetLastError(), "failed to flush file buffer"); } } } } } #[allow(unused_unsafe)] unsafe fn find_first_volume() -> (String, *const libc::c_void) { let mut name: [libc::c_char; 260] = mem::uninitialized(); // MAX_PATH match FindFirstVolumeA(name.as_mut_ptr(), name.len() as libc::uint32_t) { -1 => { // INVALID_HANDLE_VALUE crash!(GetLastError(), "failed to find first volume"); } handle =>
} } #[allow(unused_unsafe)] unsafe fn find_all_volumes() -> Vec<String> { match find_first_volume() { (first_volume, next_volume_handle) => { let mut volumes = vec![first_volume]; loop { let mut name: [libc::c_char; 260] = mem::uninitialized(); // MAX_PATH match FindNextVolumeA(next_volume_handle, name.as_mut_ptr(), name.len() as libc::uint32_t) { 0 => { match GetLastError() { 0x12 => { // ERROR_NO_MORE_FILES FindVolumeClose(next_volume_handle); // ignore FindVolumeClose() failures break; } err => { crash!(err, "failed to find next volume"); } } } _ => { volumes.push(string::raw::from_buf(name.as_ptr() as *const u8)); } } } volumes } } } pub unsafe fn do_sync() -> int { let volumes = find_all_volumes(); for vol in volumes.iter() { flush_volume(&vol); } 0 } } pub fn uumain(args: Vec<String>) -> i32 { let mut opts = getopts::Options::new(); opts.optflag("h", "help", "display this help and exit"); opts.optflag("V", "version", "output version information and exit"); let matches = match opts.parse(&args[1..]) { Ok(m) => { m } _ => { help(&opts); return 1 } }; if matches.opt_present("h") { help(&opts); return 0 } if matches.opt_present("V") { version(); return 0 } sync(); 0 } fn version() { println!("{} (uutils) {}", NAME, VERSION); println!("The MIT License"); println!(""); println!("Author -- Alexander Fomin."); } fn help(opts: &getopts::Options) { let msg = format!("{0} {1} Usage: {0} [OPTION] Force changed blocks to disk, update the super block.", NAME, VERSION); print!("{}", opts.usage(&msg)); } fn sync() -> isize { unsafe { platform::do_sync() } }
{ (string::raw::from_buf(name.as_ptr() as *const u8), handle) }
conditional_block