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
iterable.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(generic_associated_types)] //~^ WARNING the feature `generic_associated_types` is incomplete use std::ops::Deref; // FIXME(#44265): "lifetime parameters are not allowed on this type" errors will be addressed in a // follow-up PR. trait Iterable { type Item<'a>; type Iter<'a>: Iterator<Item = Self::Item<'a>>; //~^ ERROR lifetime parameters are not allowed on this type [E0110] fn iter<'a>(&'a self) -> Self::Iter<'a>; //~^ ERROR lifetime parameters are not allowed on this type [E0110] } // Impl for struct type impl<T> Iterable for Vec<T> { type Item<'a> = &'a T; type Iter<'a> = std::slice::Iter<'a, T>; fn iter<'a>(&'a self) -> Self::Iter<'a> { //~^ ERROR lifetime parameters are not allowed on this type [E0110] self.iter() } } // Impl for a primitive type impl<T> Iterable for [T] { type Item<'a> = &'a T; type Iter<'a> = std::slice::Iter<'a, T>; fn iter<'a>(&'a self) -> Self::Iter<'a> { //~^ ERROR lifetime parameters are not allowed on this type [E0110] self.iter() } } fn make_iter<'a, I: Iterable>(it: &'a I) -> I::Iter<'a> { //~^ ERROR lifetime parameters are not allowed on this type [E0110] it.iter() } fn get_first<'a, I: Iterable>(it: &'a I) -> Option<I::Item<'a>>
fn main() {}
{ //~^ ERROR lifetime parameters are not allowed on this type [E0110] it.iter().next() }
identifier_body
iterable.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(generic_associated_types)] //~^ WARNING the feature `generic_associated_types` is incomplete use std::ops::Deref; // FIXME(#44265): "lifetime parameters are not allowed on this type" errors will be addressed in a
//~^ ERROR lifetime parameters are not allowed on this type [E0110] fn iter<'a>(&'a self) -> Self::Iter<'a>; //~^ ERROR lifetime parameters are not allowed on this type [E0110] } // Impl for struct type impl<T> Iterable for Vec<T> { type Item<'a> = &'a T; type Iter<'a> = std::slice::Iter<'a, T>; fn iter<'a>(&'a self) -> Self::Iter<'a> { //~^ ERROR lifetime parameters are not allowed on this type [E0110] self.iter() } } // Impl for a primitive type impl<T> Iterable for [T] { type Item<'a> = &'a T; type Iter<'a> = std::slice::Iter<'a, T>; fn iter<'a>(&'a self) -> Self::Iter<'a> { //~^ ERROR lifetime parameters are not allowed on this type [E0110] self.iter() } } fn make_iter<'a, I: Iterable>(it: &'a I) -> I::Iter<'a> { //~^ ERROR lifetime parameters are not allowed on this type [E0110] it.iter() } fn get_first<'a, I: Iterable>(it: &'a I) -> Option<I::Item<'a>> { //~^ ERROR lifetime parameters are not allowed on this type [E0110] it.iter().next() } fn main() {}
// follow-up PR. trait Iterable { type Item<'a>; type Iter<'a>: Iterator<Item = Self::Item<'a>>;
random_line_split
iterable.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(generic_associated_types)] //~^ WARNING the feature `generic_associated_types` is incomplete use std::ops::Deref; // FIXME(#44265): "lifetime parameters are not allowed on this type" errors will be addressed in a // follow-up PR. trait Iterable { type Item<'a>; type Iter<'a>: Iterator<Item = Self::Item<'a>>; //~^ ERROR lifetime parameters are not allowed on this type [E0110] fn iter<'a>(&'a self) -> Self::Iter<'a>; //~^ ERROR lifetime parameters are not allowed on this type [E0110] } // Impl for struct type impl<T> Iterable for Vec<T> { type Item<'a> = &'a T; type Iter<'a> = std::slice::Iter<'a, T>; fn iter<'a>(&'a self) -> Self::Iter<'a> { //~^ ERROR lifetime parameters are not allowed on this type [E0110] self.iter() } } // Impl for a primitive type impl<T> Iterable for [T] { type Item<'a> = &'a T; type Iter<'a> = std::slice::Iter<'a, T>; fn iter<'a>(&'a self) -> Self::Iter<'a> { //~^ ERROR lifetime parameters are not allowed on this type [E0110] self.iter() } } fn make_iter<'a, I: Iterable>(it: &'a I) -> I::Iter<'a> { //~^ ERROR lifetime parameters are not allowed on this type [E0110] it.iter() } fn
<'a, I: Iterable>(it: &'a I) -> Option<I::Item<'a>> { //~^ ERROR lifetime parameters are not allowed on this type [E0110] it.iter().next() } fn main() {}
get_first
identifier_name
xor-joiner.rs
// Exercise 2.3 use std::os; use std::io::File; fn xor(a: &[u8], b: &[u8]) -> ~[u8] { let mut ret = ~[]; for i in range(0, a.len()) {
} fn main() { let args: ~[~str] = os::args(); if args.len()!= 3 { println!("Usage: {:s} <inputfile1> <inputfile2>", args[0]); } else { let fname1 = &args[1]; let fname2 = &args[2]; let path1 = Path::new(fname1.clone()); let path2 = Path::new(fname2.clone()); let share_file1 = File::open(&path1); let share_file2 = File::open(&path2); match (share_file1, share_file2) { (Some(mut share1), Some(mut share2)) => { let share1bytes: ~[u8] = share1.read_to_end(); let share2bytes: ~[u8] = share2.read_to_end(); print!("{:s}", std::str::from_utf8_owned( xor(share1bytes, share2bytes))); }, (_, _) => fail!("Error opening input files!") } } }
ret.push(a[i] ^ b[i]); } ret
random_line_split
xor-joiner.rs
// Exercise 2.3 use std::os; use std::io::File; fn xor(a: &[u8], b: &[u8]) -> ~[u8] { let mut ret = ~[]; for i in range(0, a.len()) { ret.push(a[i] ^ b[i]); } ret } fn main() { let args: ~[~str] = os::args(); if args.len()!= 3 { println!("Usage: {:s} <inputfile1> <inputfile2>", args[0]); } else { let fname1 = &args[1]; let fname2 = &args[2]; let path1 = Path::new(fname1.clone()); let path2 = Path::new(fname2.clone()); let share_file1 = File::open(&path1); let share_file2 = File::open(&path2); match (share_file1, share_file2) { (Some(mut share1), Some(mut share2)) =>
, (_, _) => fail!("Error opening input files!") } } }
{ let share1bytes: ~[u8] = share1.read_to_end(); let share2bytes: ~[u8] = share2.read_to_end(); print!("{:s}", std::str::from_utf8_owned( xor(share1bytes, share2bytes))); }
conditional_block
xor-joiner.rs
// Exercise 2.3 use std::os; use std::io::File; fn xor(a: &[u8], b: &[u8]) -> ~[u8] { let mut ret = ~[]; for i in range(0, a.len()) { ret.push(a[i] ^ b[i]); } ret } fn
() { let args: ~[~str] = os::args(); if args.len()!= 3 { println!("Usage: {:s} <inputfile1> <inputfile2>", args[0]); } else { let fname1 = &args[1]; let fname2 = &args[2]; let path1 = Path::new(fname1.clone()); let path2 = Path::new(fname2.clone()); let share_file1 = File::open(&path1); let share_file2 = File::open(&path2); match (share_file1, share_file2) { (Some(mut share1), Some(mut share2)) => { let share1bytes: ~[u8] = share1.read_to_end(); let share2bytes: ~[u8] = share2.read_to_end(); print!("{:s}", std::str::from_utf8_owned( xor(share1bytes, share2bytes))); }, (_, _) => fail!("Error opening input files!") } } }
main
identifier_name
xor-joiner.rs
// Exercise 2.3 use std::os; use std::io::File; fn xor(a: &[u8], b: &[u8]) -> ~[u8] { let mut ret = ~[]; for i in range(0, a.len()) { ret.push(a[i] ^ b[i]); } ret } fn main()
} } }
{ let args: ~[~str] = os::args(); if args.len() != 3 { println!("Usage: {:s} <inputfile1> <inputfile2>", args[0]); } else { let fname1 = &args[1]; let fname2 = &args[2]; let path1 = Path::new(fname1.clone()); let path2 = Path::new(fname2.clone()); let share_file1 = File::open(&path1); let share_file2 = File::open(&path2); match (share_file1, share_file2) { (Some(mut share1), Some(mut share2)) => { let share1bytes: ~[u8] = share1.read_to_end(); let share2bytes: ~[u8] = share2.read_to_end(); print!("{:s}", std::str::from_utf8_owned( xor(share1bytes, share2bytes))); } , (_, _) => fail!("Error opening input files!")
identifier_body
upsert_resolution.rs
// Copyright 2016 Mozilla // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. #![allow(dead_code)] //! This module implements the upsert resolution algorithm described at //! https://github.com/mozilla/mentat/wiki/Transacting:-upsert-resolution-algorithm. use std::collections::{ BTreeMap, BTreeSet, }; use indexmap; use petgraph::unionfind; use errors::{ DbErrorKind, Result, }; use types::{ AVPair, }; use internal_types::{ Population, TempIdHandle, TempIdMap, Term, TermWithoutTempIds, TermWithTempIds, TypedValueOr, }; use mentat_core::util::Either::*; use mentat_core::{ attribute, Attribute, Entid, Schema, TypedValue, }; use edn::entities::OpType; use schema::SchemaBuilding; /// A "Simple upsert" that looks like [:db/add TEMPID a v], where a is :db.unique/identity. #[derive(Clone,Debug,Eq,Hash,Ord,PartialOrd,PartialEq)] struct UpsertE(TempIdHandle, Entid, TypedValue); /// A "Complex upsert" that looks like [:db/add TEMPID a OTHERID], where a is :db.unique/identity #[derive(Clone,Debug,Eq,Hash,Ord,PartialOrd,PartialEq)] struct UpsertEV(TempIdHandle, Entid, TempIdHandle); /// A generation collects entities into populations at a single evolutionary step in the upsert /// resolution evolution process. /// /// The upsert resolution process is only concerned with [:db/add...] entities until the final /// entid allocations. That's why we separate into special simple and complex upsert types /// immediately, and then collect the more general term types for final resolution. #[derive(Clone,Debug,Default,Eq,Hash,Ord,PartialOrd,PartialEq)] pub(crate) struct Generation { /// "Simple upserts" that look like [:db/add TEMPID a v], where a is :db.unique/identity. upserts_e: Vec<UpsertE>, /// "Complex upserts" that look like [:db/add TEMPID a OTHERID], where a is :db.unique/identity upserts_ev: Vec<UpsertEV>, /// Entities that look like: /// - [:db/add TEMPID b OTHERID]. b may be :db.unique/identity if it has failed to upsert. /// - [:db/add TEMPID b v]. b may be :db.unique/identity if it has failed to upsert. /// - [:db/add e b OTHERID]. allocations: Vec<TermWithTempIds>, /// Entities that upserted and no longer reference tempids. These assertions are guaranteed to /// be in the store. upserted: Vec<TermWithoutTempIds>, /// Entities that resolved due to other upserts and no longer reference tempids. These /// assertions may or may not be in the store. resolved: Vec<TermWithoutTempIds>, } #[derive(Clone,Debug,Default,Eq,Hash,Ord,PartialOrd,PartialEq)] pub(crate) struct FinalPopulations { /// Upserts that upserted. pub upserted: Vec<TermWithoutTempIds>, /// Allocations that resolved due to other upserts. pub resolved: Vec<TermWithoutTempIds>, /// Allocations that required new entid allocations. pub allocated: Vec<TermWithoutTempIds>, } impl Generation { /// Split entities into a generation of populations that need to evolve to have their tempids /// resolved or allocated, and a population of inert entities that do not reference tempids. pub(crate) fn from<I>(terms: I, schema: &Schema) -> Result<(Generation, Population)> where I: IntoIterator<Item=TermWithTempIds> { let mut generation = Generation::default(); let mut inert = vec![]; let is_unique = |a: Entid| -> Result<bool> { let attribute: &Attribute = schema.require_attribute_for_entid(a)?; Ok(attribute.unique == Some(attribute::Unique::Identity)) }; for term in terms.into_iter() { match term { Term::AddOrRetract(op, Right(e), a, Right(v)) => { if op == OpType::Add && is_unique(a)? { generation.upserts_ev.push(UpsertEV(e, a, v)); } else { generation.allocations.push(Term::AddOrRetract(op, Right(e), a, Right(v))); } }, Term::AddOrRetract(op, Right(e), a, Left(v)) => { if op == OpType::Add && is_unique(a)? { generation.upserts_e.push(UpsertE(e, a, v)); } else { generation.allocations.push(Term::AddOrRetract(op, Right(e), a, Left(v))); } }, Term::AddOrRetract(op, Left(e), a, Right(v)) => { generation.allocations.push(Term::AddOrRetract(op, Left(e), a, Right(v))); }, Term::AddOrRetract(op, Left(e), a, Left(v)) => { inert.push(Term::AddOrRetract(op, Left(e), a, Left(v))); }, } } Ok((generation, inert)) } /// Return true if it's possible to evolve this generation further. /// /// Note that there can be complex upserts but no simple upserts to help resolve them, and in /// this case, we cannot evolve further. pub(crate) fn can_evolve(&self) -> bool { !self.upserts_e.is_empty() } /// Evolve this generation one step further by rewriting the existing :db/add entities using the /// given temporary IDs. /// /// TODO: Considering doing this in place; the function already consumes `self`. pub(crate) fn evolve_one_step(self, temp_id_map: &TempIdMap) -> Generation { let mut next = Generation::default(); // We'll iterate our own allocations to resolve more things, but terms that have already // resolved stay resolved. next.resolved = self.resolved; for UpsertE(t, a, v) in self.upserts_e { match temp_id_map.get(&*t) { Some(&n) => next.upserted.push(Term::AddOrRetract(OpType::Add, n, a, v)), None => next.allocations.push(Term::AddOrRetract(OpType::Add, Right(t), a, Left(v))), } } for UpsertEV(t1, a, t2) in self.upserts_ev { match (temp_id_map.get(&*t1), temp_id_map.get(&*t2)) { (Some(_), Some(&n2)) => { // Even though we can resolve entirely, it's possible that the remaining upsert // could conflict. Moving straight to resolved doesn't give us a chance to // search the store for the conflict. next.upserts_e.push(UpsertE(t1, a, TypedValue::Ref(n2.0))) }, (None, Some(&n2)) => next.upserts_e.push(UpsertE(t1, a, TypedValue::Ref(n2.0))), (Some(&n1), None) => next.allocations.push(Term::AddOrRetract(OpType::Add, Left(n1), a, Right(t2))), (None, None) => next.upserts_ev.push(UpsertEV(t1, a, t2)) } } // There's no particular need to separate resolved from allocations right here and right // now, although it is convenient. for term in self.allocations { // TODO: find an expression that destructures less? I still expect this to be efficient // but it's a little verbose. match term { Term::AddOrRetract(op, Right(t1), a, Right(t2)) => { match (temp_id_map.get(&*t1), temp_id_map.get(&*t2)) { (Some(&n1), Some(&n2)) => next.resolved.push(Term::AddOrRetract(op, n1, a, TypedValue::Ref(n2.0))), (None, Some(&n2)) => next.allocations.push(Term::AddOrRetract(op, Right(t1), a, Left(TypedValue::Ref(n2.0)))), (Some(&n1), None) => next.allocations.push(Term::AddOrRetract(op, Left(n1), a, Right(t2))), (None, None) => next.allocations.push(Term::AddOrRetract(op, Right(t1), a, Right(t2))), } }, Term::AddOrRetract(op, Right(t), a, Left(v)) => { match temp_id_map.get(&*t) { Some(&n) => next.resolved.push(Term::AddOrRetract(op, n, a, v)), None => next.allocations.push(Term::AddOrRetract(op, Right(t), a, Left(v))), } }, Term::AddOrRetract(op, Left(e), a, Right(t)) => { match temp_id_map.get(&*t) { Some(&n) => next.resolved.push(Term::AddOrRetract(op, e, a, TypedValue::Ref(n.0))), None => next.allocations.push(Term::AddOrRetract(op, Left(e), a, Right(t))), } }, Term::AddOrRetract(_, Left(_), _, Left(_)) => unreachable!(), } } next } // Collect id->[a v] pairs that might upsert at this evolutionary step. pub(crate) fn temp_id_avs<'a>(&'a self) -> Vec<(TempIdHandle, AVPair)> { let mut temp_id_avs: Vec<(TempIdHandle, AVPair)> = vec![]; // TODO: map/collect. for &UpsertE(ref t, ref a, ref v) in &self.upserts_e { // TODO: figure out how to make this less expensive, i.e., don't require // clone() of an arbitrary value. temp_id_avs.push((t.clone(), (*a, v.clone()))); } temp_id_avs } /// Evolve potential upserts that haven't resolved into allocations. pub(crate) fn allocate_unresolved_upserts(&mut self) -> Result<()> { let mut upserts_ev = vec![]; ::std::mem::swap(&mut self.upserts_ev, &mut upserts_ev); self.allocations.extend(upserts_ev.into_iter().map(|UpsertEV(t1, a, t2)| Term::AddOrRetract(OpType::Add, Right(t1), a, Right(t2)))); Ok(()) } /// After evolution is complete, yield the set of tempids that require entid allocation. /// /// Some of the tempids may be identified, so we also provide a map from tempid to a dense set /// of contiguous integer labels. pub(crate) fn temp_ids_in_allocations(&self, schema: &Schema) -> Result<BTreeMap<TempIdHandle, usize>> { assert!(self.upserts_e.is_empty(), "All upserts should have been upserted, resolved, or moved to the allocated population!"); assert!(self.upserts_ev.is_empty(), "All upserts should have been upserted, resolved, or moved to the allocated population!"); let mut temp_ids: BTreeSet<TempIdHandle> = BTreeSet::default(); let mut tempid_avs: BTreeMap<(Entid, TypedValueOr<TempIdHandle>), Vec<TempIdHandle>> = BTreeMap::default(); for term in self.allocations.iter() { match term { &Term::AddOrRetract(OpType::Add, Right(ref t1), a, Right(ref t2)) => { temp_ids.insert(t1.clone()); temp_ids.insert(t2.clone()); let attribute: &Attribute = schema.require_attribute_for_entid(a)?; if attribute.unique == Some(attribute::Unique::Identity)
}, &Term::AddOrRetract(OpType::Add, Right(ref t), a, ref x @ Left(_)) => { temp_ids.insert(t.clone()); let attribute: &Attribute = schema.require_attribute_for_entid(a)?; if attribute.unique == Some(attribute::Unique::Identity) { tempid_avs.entry((a, x.clone())).or_insert(vec![]).push(t.clone()); } }, &Term::AddOrRetract(OpType::Add, Left(_), _, Right(ref t)) => { temp_ids.insert(t.clone()); }, &Term::AddOrRetract(OpType::Add, Left(_), _, Left(_)) => unreachable!(), &Term::AddOrRetract(OpType::Retract, _, _, _) => { // [:db/retract...] entities never allocate entids; they have to resolve due to // other upserts (or they fail the transaction). }, } } // Now we union-find all the known tempids. Two tempids are unioned if they both appear as // the entity of an `[a v]` upsert, including when the value column `v` is itself a tempid. let mut uf = unionfind::UnionFind::new(temp_ids.len()); // The union-find implementation from petgraph operates on contiguous indices, so we need to // maintain the map from our tempids to indices ourselves. let temp_ids: BTreeMap<TempIdHandle, usize> = temp_ids.into_iter().enumerate().map(|(i, tempid)| (tempid, i)).collect(); debug!("need to label tempids aggregated using tempid_avs {:?}", tempid_avs); for vs in tempid_avs.values() { vs.first().and_then(|first| temp_ids.get(first)).map(|&first_index| { for tempid in vs { temp_ids.get(tempid).map(|&i| uf.union(first_index, i)); } }); } debug!("union-find aggregation {:?}", uf.clone().into_labeling()); // Now that we have aggregated tempids, we need to label them using the smallest number of // contiguous labels possible. let mut tempid_map: BTreeMap<TempIdHandle, usize> = BTreeMap::default(); let mut dense_labels: indexmap::IndexSet<usize> = indexmap::IndexSet::default(); // We want to produce results that are as deterministic as possible, so we allocate labels // for tempids in sorted order. This has the effect of making "a" allocate before "b", // which is pleasant for testing. for (tempid, tempid_index) in temp_ids { let rep = uf.find_mut(tempid_index); dense_labels.insert(rep); dense_labels.get_full(&rep).map(|(dense_index, _)| tempid_map.insert(tempid.clone(), dense_index)); } debug!("labeled tempids using {} labels: {:?}", dense_labels.len(), tempid_map); Ok(tempid_map) } /// After evolution is complete, use the provided allocated entids to segment `self` into /// populations, each with no references to tempids. pub(crate) fn into_final_populations(self, temp_id_map: &TempIdMap) -> Result<FinalPopulations> { assert!(self.upserts_e.is_empty()); assert!(self.upserts_ev.is_empty()); let mut populations = FinalPopulations::default(); populations.upserted = self.upserted; populations.resolved = self.resolved; for term in self.allocations { let allocated = match term { // TODO: consider require implementing require on temp_id_map. Term::AddOrRetract(op, Right(t1), a, Right(t2)) => { match (op, temp_id_map.get(&*t1), temp_id_map.get(&*t2)) { (op, Some(&n1), Some(&n2)) => Term::AddOrRetract(op, n1, a, TypedValue::Ref(n2.0)), (OpType::Add, _, _) => unreachable!(), // This is a coding error -- every tempid in a :db/add entity should resolve or be allocated. (OpType::Retract, _, _) => bail!(DbErrorKind::NotYetImplemented(format!("[:db/retract...] entity referenced tempid that did not upsert: one of {}, {}", t1, t2))), } }, Term::AddOrRetract(op, Right(t), a, Left(v)) => { match (op, temp_id_map.get(&*t)) { (op, Some(&n)) => Term::AddOrRetract(op, n, a, v), (OpType::Add, _) => unreachable!(), // This is a coding error. (OpType::Retract, _) => bail!(DbErrorKind::NotYetImplemented(format!("[:db/retract...] entity referenced tempid that did not upsert: {}", t))), } }, Term::AddOrRetract(op, Left(e), a, Right(t)) => { match (op, temp_id_map.get(&*t)) { (op, Some(&n)) => Term::AddOrRetract(op, e, a, TypedValue::Ref(n.0)), (OpType::Add, _) => unreachable!(), // This is a coding error. (OpType::Retract, _) => bail!(DbErrorKind::NotYetImplemented(format!("[:db/retract...] entity referenced tempid that did not upsert: {}", t))), } }, Term::AddOrRetract(_, Left(_), _, Left(_)) => unreachable!(), // This is a coding error -- these should not be in allocations. }; populations.allocated.push(allocated); } Ok(populations) } }
{ tempid_avs.entry((a, Right(t2.clone()))).or_insert(vec![]).push(t1.clone()); }
conditional_block
upsert_resolution.rs
// Copyright 2016 Mozilla // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. #![allow(dead_code)] //! This module implements the upsert resolution algorithm described at //! https://github.com/mozilla/mentat/wiki/Transacting:-upsert-resolution-algorithm. use std::collections::{ BTreeMap, BTreeSet, }; use indexmap; use petgraph::unionfind; use errors::{ DbErrorKind, Result, }; use types::{ AVPair, }; use internal_types::{ Population, TempIdHandle, TempIdMap, Term, TermWithoutTempIds, TermWithTempIds, TypedValueOr, }; use mentat_core::util::Either::*; use mentat_core::{ attribute, Attribute, Entid, Schema, TypedValue, }; use edn::entities::OpType; use schema::SchemaBuilding; /// A "Simple upsert" that looks like [:db/add TEMPID a v], where a is :db.unique/identity. #[derive(Clone,Debug,Eq,Hash,Ord,PartialOrd,PartialEq)] struct UpsertE(TempIdHandle, Entid, TypedValue); /// A "Complex upsert" that looks like [:db/add TEMPID a OTHERID], where a is :db.unique/identity #[derive(Clone,Debug,Eq,Hash,Ord,PartialOrd,PartialEq)] struct UpsertEV(TempIdHandle, Entid, TempIdHandle); /// A generation collects entities into populations at a single evolutionary step in the upsert /// resolution evolution process. /// /// The upsert resolution process is only concerned with [:db/add...] entities until the final /// entid allocations. That's why we separate into special simple and complex upsert types /// immediately, and then collect the more general term types for final resolution. #[derive(Clone,Debug,Default,Eq,Hash,Ord,PartialOrd,PartialEq)] pub(crate) struct Generation { /// "Simple upserts" that look like [:db/add TEMPID a v], where a is :db.unique/identity. upserts_e: Vec<UpsertE>, /// "Complex upserts" that look like [:db/add TEMPID a OTHERID], where a is :db.unique/identity upserts_ev: Vec<UpsertEV>, /// Entities that look like: /// - [:db/add TEMPID b OTHERID]. b may be :db.unique/identity if it has failed to upsert. /// - [:db/add TEMPID b v]. b may be :db.unique/identity if it has failed to upsert. /// - [:db/add e b OTHERID]. allocations: Vec<TermWithTempIds>, /// Entities that upserted and no longer reference tempids. These assertions are guaranteed to /// be in the store. upserted: Vec<TermWithoutTempIds>, /// Entities that resolved due to other upserts and no longer reference tempids. These /// assertions may or may not be in the store. resolved: Vec<TermWithoutTempIds>, } #[derive(Clone,Debug,Default,Eq,Hash,Ord,PartialOrd,PartialEq)] pub(crate) struct FinalPopulations { /// Upserts that upserted. pub upserted: Vec<TermWithoutTempIds>, /// Allocations that resolved due to other upserts. pub resolved: Vec<TermWithoutTempIds>, /// Allocations that required new entid allocations. pub allocated: Vec<TermWithoutTempIds>, } impl Generation { /// Split entities into a generation of populations that need to evolve to have their tempids /// resolved or allocated, and a population of inert entities that do not reference tempids. pub(crate) fn from<I>(terms: I, schema: &Schema) -> Result<(Generation, Population)> where I: IntoIterator<Item=TermWithTempIds> { let mut generation = Generation::default(); let mut inert = vec![]; let is_unique = |a: Entid| -> Result<bool> { let attribute: &Attribute = schema.require_attribute_for_entid(a)?; Ok(attribute.unique == Some(attribute::Unique::Identity)) }; for term in terms.into_iter() { match term { Term::AddOrRetract(op, Right(e), a, Right(v)) => { if op == OpType::Add && is_unique(a)? { generation.upserts_ev.push(UpsertEV(e, a, v)); } else { generation.allocations.push(Term::AddOrRetract(op, Right(e), a, Right(v))); } }, Term::AddOrRetract(op, Right(e), a, Left(v)) => { if op == OpType::Add && is_unique(a)? { generation.upserts_e.push(UpsertE(e, a, v)); } else { generation.allocations.push(Term::AddOrRetract(op, Right(e), a, Left(v))); } }, Term::AddOrRetract(op, Left(e), a, Right(v)) => { generation.allocations.push(Term::AddOrRetract(op, Left(e), a, Right(v))); }, Term::AddOrRetract(op, Left(e), a, Left(v)) => { inert.push(Term::AddOrRetract(op, Left(e), a, Left(v))); }, } } Ok((generation, inert)) } /// Return true if it's possible to evolve this generation further. /// /// Note that there can be complex upserts but no simple upserts to help resolve them, and in /// this case, we cannot evolve further. pub(crate) fn can_evolve(&self) -> bool { !self.upserts_e.is_empty() } /// Evolve this generation one step further by rewriting the existing :db/add entities using the /// given temporary IDs. /// /// TODO: Considering doing this in place; the function already consumes `self`. pub(crate) fn evolve_one_step(self, temp_id_map: &TempIdMap) -> Generation { let mut next = Generation::default(); // We'll iterate our own allocations to resolve more things, but terms that have already // resolved stay resolved. next.resolved = self.resolved; for UpsertE(t, a, v) in self.upserts_e { match temp_id_map.get(&*t) { Some(&n) => next.upserted.push(Term::AddOrRetract(OpType::Add, n, a, v)), None => next.allocations.push(Term::AddOrRetract(OpType::Add, Right(t), a, Left(v))), } } for UpsertEV(t1, a, t2) in self.upserts_ev { match (temp_id_map.get(&*t1), temp_id_map.get(&*t2)) { (Some(_), Some(&n2)) => { // Even though we can resolve entirely, it's possible that the remaining upsert // could conflict. Moving straight to resolved doesn't give us a chance to // search the store for the conflict. next.upserts_e.push(UpsertE(t1, a, TypedValue::Ref(n2.0))) }, (None, Some(&n2)) => next.upserts_e.push(UpsertE(t1, a, TypedValue::Ref(n2.0))), (Some(&n1), None) => next.allocations.push(Term::AddOrRetract(OpType::Add, Left(n1), a, Right(t2))), (None, None) => next.upserts_ev.push(UpsertEV(t1, a, t2)) } } // There's no particular need to separate resolved from allocations right here and right // now, although it is convenient. for term in self.allocations { // TODO: find an expression that destructures less? I still expect this to be efficient // but it's a little verbose. match term { Term::AddOrRetract(op, Right(t1), a, Right(t2)) => { match (temp_id_map.get(&*t1), temp_id_map.get(&*t2)) { (Some(&n1), Some(&n2)) => next.resolved.push(Term::AddOrRetract(op, n1, a, TypedValue::Ref(n2.0))), (None, Some(&n2)) => next.allocations.push(Term::AddOrRetract(op, Right(t1), a, Left(TypedValue::Ref(n2.0)))), (Some(&n1), None) => next.allocations.push(Term::AddOrRetract(op, Left(n1), a, Right(t2))), (None, None) => next.allocations.push(Term::AddOrRetract(op, Right(t1), a, Right(t2))), } }, Term::AddOrRetract(op, Right(t), a, Left(v)) => { match temp_id_map.get(&*t) { Some(&n) => next.resolved.push(Term::AddOrRetract(op, n, a, v)), None => next.allocations.push(Term::AddOrRetract(op, Right(t), a, Left(v))), } }, Term::AddOrRetract(op, Left(e), a, Right(t)) => { match temp_id_map.get(&*t) { Some(&n) => next.resolved.push(Term::AddOrRetract(op, e, a, TypedValue::Ref(n.0))), None => next.allocations.push(Term::AddOrRetract(op, Left(e), a, Right(t))), } }, Term::AddOrRetract(_, Left(_), _, Left(_)) => unreachable!(), } } next } // Collect id->[a v] pairs that might upsert at this evolutionary step. pub(crate) fn temp_id_avs<'a>(&'a self) -> Vec<(TempIdHandle, AVPair)>
/// Evolve potential upserts that haven't resolved into allocations. pub(crate) fn allocate_unresolved_upserts(&mut self) -> Result<()> { let mut upserts_ev = vec![]; ::std::mem::swap(&mut self.upserts_ev, &mut upserts_ev); self.allocations.extend(upserts_ev.into_iter().map(|UpsertEV(t1, a, t2)| Term::AddOrRetract(OpType::Add, Right(t1), a, Right(t2)))); Ok(()) } /// After evolution is complete, yield the set of tempids that require entid allocation. /// /// Some of the tempids may be identified, so we also provide a map from tempid to a dense set /// of contiguous integer labels. pub(crate) fn temp_ids_in_allocations(&self, schema: &Schema) -> Result<BTreeMap<TempIdHandle, usize>> { assert!(self.upserts_e.is_empty(), "All upserts should have been upserted, resolved, or moved to the allocated population!"); assert!(self.upserts_ev.is_empty(), "All upserts should have been upserted, resolved, or moved to the allocated population!"); let mut temp_ids: BTreeSet<TempIdHandle> = BTreeSet::default(); let mut tempid_avs: BTreeMap<(Entid, TypedValueOr<TempIdHandle>), Vec<TempIdHandle>> = BTreeMap::default(); for term in self.allocations.iter() { match term { &Term::AddOrRetract(OpType::Add, Right(ref t1), a, Right(ref t2)) => { temp_ids.insert(t1.clone()); temp_ids.insert(t2.clone()); let attribute: &Attribute = schema.require_attribute_for_entid(a)?; if attribute.unique == Some(attribute::Unique::Identity) { tempid_avs.entry((a, Right(t2.clone()))).or_insert(vec![]).push(t1.clone()); } }, &Term::AddOrRetract(OpType::Add, Right(ref t), a, ref x @ Left(_)) => { temp_ids.insert(t.clone()); let attribute: &Attribute = schema.require_attribute_for_entid(a)?; if attribute.unique == Some(attribute::Unique::Identity) { tempid_avs.entry((a, x.clone())).or_insert(vec![]).push(t.clone()); } }, &Term::AddOrRetract(OpType::Add, Left(_), _, Right(ref t)) => { temp_ids.insert(t.clone()); }, &Term::AddOrRetract(OpType::Add, Left(_), _, Left(_)) => unreachable!(), &Term::AddOrRetract(OpType::Retract, _, _, _) => { // [:db/retract...] entities never allocate entids; they have to resolve due to // other upserts (or they fail the transaction). }, } } // Now we union-find all the known tempids. Two tempids are unioned if they both appear as // the entity of an `[a v]` upsert, including when the value column `v` is itself a tempid. let mut uf = unionfind::UnionFind::new(temp_ids.len()); // The union-find implementation from petgraph operates on contiguous indices, so we need to // maintain the map from our tempids to indices ourselves. let temp_ids: BTreeMap<TempIdHandle, usize> = temp_ids.into_iter().enumerate().map(|(i, tempid)| (tempid, i)).collect(); debug!("need to label tempids aggregated using tempid_avs {:?}", tempid_avs); for vs in tempid_avs.values() { vs.first().and_then(|first| temp_ids.get(first)).map(|&first_index| { for tempid in vs { temp_ids.get(tempid).map(|&i| uf.union(first_index, i)); } }); } debug!("union-find aggregation {:?}", uf.clone().into_labeling()); // Now that we have aggregated tempids, we need to label them using the smallest number of // contiguous labels possible. let mut tempid_map: BTreeMap<TempIdHandle, usize> = BTreeMap::default(); let mut dense_labels: indexmap::IndexSet<usize> = indexmap::IndexSet::default(); // We want to produce results that are as deterministic as possible, so we allocate labels // for tempids in sorted order. This has the effect of making "a" allocate before "b", // which is pleasant for testing. for (tempid, tempid_index) in temp_ids { let rep = uf.find_mut(tempid_index); dense_labels.insert(rep); dense_labels.get_full(&rep).map(|(dense_index, _)| tempid_map.insert(tempid.clone(), dense_index)); } debug!("labeled tempids using {} labels: {:?}", dense_labels.len(), tempid_map); Ok(tempid_map) } /// After evolution is complete, use the provided allocated entids to segment `self` into /// populations, each with no references to tempids. pub(crate) fn into_final_populations(self, temp_id_map: &TempIdMap) -> Result<FinalPopulations> { assert!(self.upserts_e.is_empty()); assert!(self.upserts_ev.is_empty()); let mut populations = FinalPopulations::default(); populations.upserted = self.upserted; populations.resolved = self.resolved; for term in self.allocations { let allocated = match term { // TODO: consider require implementing require on temp_id_map. Term::AddOrRetract(op, Right(t1), a, Right(t2)) => { match (op, temp_id_map.get(&*t1), temp_id_map.get(&*t2)) { (op, Some(&n1), Some(&n2)) => Term::AddOrRetract(op, n1, a, TypedValue::Ref(n2.0)), (OpType::Add, _, _) => unreachable!(), // This is a coding error -- every tempid in a :db/add entity should resolve or be allocated. (OpType::Retract, _, _) => bail!(DbErrorKind::NotYetImplemented(format!("[:db/retract...] entity referenced tempid that did not upsert: one of {}, {}", t1, t2))), } }, Term::AddOrRetract(op, Right(t), a, Left(v)) => { match (op, temp_id_map.get(&*t)) { (op, Some(&n)) => Term::AddOrRetract(op, n, a, v), (OpType::Add, _) => unreachable!(), // This is a coding error. (OpType::Retract, _) => bail!(DbErrorKind::NotYetImplemented(format!("[:db/retract...] entity referenced tempid that did not upsert: {}", t))), } }, Term::AddOrRetract(op, Left(e), a, Right(t)) => { match (op, temp_id_map.get(&*t)) { (op, Some(&n)) => Term::AddOrRetract(op, e, a, TypedValue::Ref(n.0)), (OpType::Add, _) => unreachable!(), // This is a coding error. (OpType::Retract, _) => bail!(DbErrorKind::NotYetImplemented(format!("[:db/retract...] entity referenced tempid that did not upsert: {}", t))), } }, Term::AddOrRetract(_, Left(_), _, Left(_)) => unreachable!(), // This is a coding error -- these should not be in allocations. }; populations.allocated.push(allocated); } Ok(populations) } }
{ let mut temp_id_avs: Vec<(TempIdHandle, AVPair)> = vec![]; // TODO: map/collect. for &UpsertE(ref t, ref a, ref v) in &self.upserts_e { // TODO: figure out how to make this less expensive, i.e., don't require // clone() of an arbitrary value. temp_id_avs.push((t.clone(), (*a, v.clone()))); } temp_id_avs }
identifier_body
upsert_resolution.rs
// Copyright 2016 Mozilla // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. #![allow(dead_code)] //! This module implements the upsert resolution algorithm described at //! https://github.com/mozilla/mentat/wiki/Transacting:-upsert-resolution-algorithm. use std::collections::{ BTreeMap, BTreeSet, }; use indexmap; use petgraph::unionfind; use errors::{ DbErrorKind, Result, }; use types::{ AVPair, }; use internal_types::{ Population, TempIdHandle, TempIdMap, Term, TermWithoutTempIds, TermWithTempIds, TypedValueOr, }; use mentat_core::util::Either::*; use mentat_core::{ attribute, Attribute, Entid, Schema, TypedValue, }; use edn::entities::OpType; use schema::SchemaBuilding; /// A "Simple upsert" that looks like [:db/add TEMPID a v], where a is :db.unique/identity. #[derive(Clone,Debug,Eq,Hash,Ord,PartialOrd,PartialEq)] struct UpsertE(TempIdHandle, Entid, TypedValue); /// A "Complex upsert" that looks like [:db/add TEMPID a OTHERID], where a is :db.unique/identity #[derive(Clone,Debug,Eq,Hash,Ord,PartialOrd,PartialEq)] struct UpsertEV(TempIdHandle, Entid, TempIdHandle); /// A generation collects entities into populations at a single evolutionary step in the upsert /// resolution evolution process. /// /// The upsert resolution process is only concerned with [:db/add...] entities until the final /// entid allocations. That's why we separate into special simple and complex upsert types /// immediately, and then collect the more general term types for final resolution. #[derive(Clone,Debug,Default,Eq,Hash,Ord,PartialOrd,PartialEq)] pub(crate) struct Generation { /// "Simple upserts" that look like [:db/add TEMPID a v], where a is :db.unique/identity. upserts_e: Vec<UpsertE>, /// "Complex upserts" that look like [:db/add TEMPID a OTHERID], where a is :db.unique/identity upserts_ev: Vec<UpsertEV>, /// Entities that look like: /// - [:db/add TEMPID b OTHERID]. b may be :db.unique/identity if it has failed to upsert. /// - [:db/add TEMPID b v]. b may be :db.unique/identity if it has failed to upsert. /// - [:db/add e b OTHERID]. allocations: Vec<TermWithTempIds>, /// Entities that upserted and no longer reference tempids. These assertions are guaranteed to /// be in the store. upserted: Vec<TermWithoutTempIds>, /// Entities that resolved due to other upserts and no longer reference tempids. These /// assertions may or may not be in the store. resolved: Vec<TermWithoutTempIds>, } #[derive(Clone,Debug,Default,Eq,Hash,Ord,PartialOrd,PartialEq)] pub(crate) struct FinalPopulations { /// Upserts that upserted. pub upserted: Vec<TermWithoutTempIds>, /// Allocations that resolved due to other upserts. pub resolved: Vec<TermWithoutTempIds>, /// Allocations that required new entid allocations. pub allocated: Vec<TermWithoutTempIds>, } impl Generation { /// Split entities into a generation of populations that need to evolve to have their tempids /// resolved or allocated, and a population of inert entities that do not reference tempids. pub(crate) fn from<I>(terms: I, schema: &Schema) -> Result<(Generation, Population)> where I: IntoIterator<Item=TermWithTempIds> { let mut generation = Generation::default(); let mut inert = vec![]; let is_unique = |a: Entid| -> Result<bool> { let attribute: &Attribute = schema.require_attribute_for_entid(a)?; Ok(attribute.unique == Some(attribute::Unique::Identity)) }; for term in terms.into_iter() { match term { Term::AddOrRetract(op, Right(e), a, Right(v)) => { if op == OpType::Add && is_unique(a)? { generation.upserts_ev.push(UpsertEV(e, a, v)); } else { generation.allocations.push(Term::AddOrRetract(op, Right(e), a, Right(v))); } }, Term::AddOrRetract(op, Right(e), a, Left(v)) => { if op == OpType::Add && is_unique(a)? { generation.upserts_e.push(UpsertE(e, a, v)); } else { generation.allocations.push(Term::AddOrRetract(op, Right(e), a, Left(v))); } }, Term::AddOrRetract(op, Left(e), a, Right(v)) => { generation.allocations.push(Term::AddOrRetract(op, Left(e), a, Right(v))); }, Term::AddOrRetract(op, Left(e), a, Left(v)) => { inert.push(Term::AddOrRetract(op, Left(e), a, Left(v))); }, } } Ok((generation, inert)) } /// Return true if it's possible to evolve this generation further. /// /// Note that there can be complex upserts but no simple upserts to help resolve them, and in /// this case, we cannot evolve further. pub(crate) fn can_evolve(&self) -> bool { !self.upserts_e.is_empty() } /// Evolve this generation one step further by rewriting the existing :db/add entities using the /// given temporary IDs. /// /// TODO: Considering doing this in place; the function already consumes `self`. pub(crate) fn evolve_one_step(self, temp_id_map: &TempIdMap) -> Generation { let mut next = Generation::default(); // We'll iterate our own allocations to resolve more things, but terms that have already // resolved stay resolved. next.resolved = self.resolved; for UpsertE(t, a, v) in self.upserts_e { match temp_id_map.get(&*t) { Some(&n) => next.upserted.push(Term::AddOrRetract(OpType::Add, n, a, v)), None => next.allocations.push(Term::AddOrRetract(OpType::Add, Right(t), a, Left(v))), } } for UpsertEV(t1, a, t2) in self.upserts_ev { match (temp_id_map.get(&*t1), temp_id_map.get(&*t2)) { (Some(_), Some(&n2)) => { // Even though we can resolve entirely, it's possible that the remaining upsert // could conflict. Moving straight to resolved doesn't give us a chance to // search the store for the conflict. next.upserts_e.push(UpsertE(t1, a, TypedValue::Ref(n2.0))) }, (None, Some(&n2)) => next.upserts_e.push(UpsertE(t1, a, TypedValue::Ref(n2.0))), (Some(&n1), None) => next.allocations.push(Term::AddOrRetract(OpType::Add, Left(n1), a, Right(t2))), (None, None) => next.upserts_ev.push(UpsertEV(t1, a, t2)) } } // There's no particular need to separate resolved from allocations right here and right // now, although it is convenient. for term in self.allocations { // TODO: find an expression that destructures less? I still expect this to be efficient // but it's a little verbose. match term { Term::AddOrRetract(op, Right(t1), a, Right(t2)) => { match (temp_id_map.get(&*t1), temp_id_map.get(&*t2)) { (Some(&n1), Some(&n2)) => next.resolved.push(Term::AddOrRetract(op, n1, a, TypedValue::Ref(n2.0))), (None, Some(&n2)) => next.allocations.push(Term::AddOrRetract(op, Right(t1), a, Left(TypedValue::Ref(n2.0)))), (Some(&n1), None) => next.allocations.push(Term::AddOrRetract(op, Left(n1), a, Right(t2))), (None, None) => next.allocations.push(Term::AddOrRetract(op, Right(t1), a, Right(t2))), } }, Term::AddOrRetract(op, Right(t), a, Left(v)) => { match temp_id_map.get(&*t) { Some(&n) => next.resolved.push(Term::AddOrRetract(op, n, a, v)), None => next.allocations.push(Term::AddOrRetract(op, Right(t), a, Left(v))), } }, Term::AddOrRetract(op, Left(e), a, Right(t)) => { match temp_id_map.get(&*t) { Some(&n) => next.resolved.push(Term::AddOrRetract(op, e, a, TypedValue::Ref(n.0))), None => next.allocations.push(Term::AddOrRetract(op, Left(e), a, Right(t))), } }, Term::AddOrRetract(_, Left(_), _, Left(_)) => unreachable!(), } } next } // Collect id->[a v] pairs that might upsert at this evolutionary step. pub(crate) fn temp_id_avs<'a>(&'a self) -> Vec<(TempIdHandle, AVPair)> { let mut temp_id_avs: Vec<(TempIdHandle, AVPair)> = vec![]; // TODO: map/collect. for &UpsertE(ref t, ref a, ref v) in &self.upserts_e { // TODO: figure out how to make this less expensive, i.e., don't require // clone() of an arbitrary value. temp_id_avs.push((t.clone(), (*a, v.clone()))); } temp_id_avs } /// Evolve potential upserts that haven't resolved into allocations. pub(crate) fn allocate_unresolved_upserts(&mut self) -> Result<()> { let mut upserts_ev = vec![]; ::std::mem::swap(&mut self.upserts_ev, &mut upserts_ev); self.allocations.extend(upserts_ev.into_iter().map(|UpsertEV(t1, a, t2)| Term::AddOrRetract(OpType::Add, Right(t1), a, Right(t2)))); Ok(()) } /// After evolution is complete, yield the set of tempids that require entid allocation. /// /// Some of the tempids may be identified, so we also provide a map from tempid to a dense set /// of contiguous integer labels. pub(crate) fn temp_ids_in_allocations(&self, schema: &Schema) -> Result<BTreeMap<TempIdHandle, usize>> { assert!(self.upserts_e.is_empty(), "All upserts should have been upserted, resolved, or moved to the allocated population!"); assert!(self.upserts_ev.is_empty(), "All upserts should have been upserted, resolved, or moved to the allocated population!"); let mut temp_ids: BTreeSet<TempIdHandle> = BTreeSet::default(); let mut tempid_avs: BTreeMap<(Entid, TypedValueOr<TempIdHandle>), Vec<TempIdHandle>> = BTreeMap::default(); for term in self.allocations.iter() { match term {
&Term::AddOrRetract(OpType::Add, Right(ref t1), a, Right(ref t2)) => { temp_ids.insert(t1.clone()); temp_ids.insert(t2.clone()); let attribute: &Attribute = schema.require_attribute_for_entid(a)?; if attribute.unique == Some(attribute::Unique::Identity) { tempid_avs.entry((a, Right(t2.clone()))).or_insert(vec![]).push(t1.clone()); } }, &Term::AddOrRetract(OpType::Add, Right(ref t), a, ref x @ Left(_)) => { temp_ids.insert(t.clone()); let attribute: &Attribute = schema.require_attribute_for_entid(a)?; if attribute.unique == Some(attribute::Unique::Identity) { tempid_avs.entry((a, x.clone())).or_insert(vec![]).push(t.clone()); } }, &Term::AddOrRetract(OpType::Add, Left(_), _, Right(ref t)) => { temp_ids.insert(t.clone()); }, &Term::AddOrRetract(OpType::Add, Left(_), _, Left(_)) => unreachable!(), &Term::AddOrRetract(OpType::Retract, _, _, _) => { // [:db/retract...] entities never allocate entids; they have to resolve due to // other upserts (or they fail the transaction). }, } } // Now we union-find all the known tempids. Two tempids are unioned if they both appear as // the entity of an `[a v]` upsert, including when the value column `v` is itself a tempid. let mut uf = unionfind::UnionFind::new(temp_ids.len()); // The union-find implementation from petgraph operates on contiguous indices, so we need to // maintain the map from our tempids to indices ourselves. let temp_ids: BTreeMap<TempIdHandle, usize> = temp_ids.into_iter().enumerate().map(|(i, tempid)| (tempid, i)).collect(); debug!("need to label tempids aggregated using tempid_avs {:?}", tempid_avs); for vs in tempid_avs.values() { vs.first().and_then(|first| temp_ids.get(first)).map(|&first_index| { for tempid in vs { temp_ids.get(tempid).map(|&i| uf.union(first_index, i)); } }); } debug!("union-find aggregation {:?}", uf.clone().into_labeling()); // Now that we have aggregated tempids, we need to label them using the smallest number of // contiguous labels possible. let mut tempid_map: BTreeMap<TempIdHandle, usize> = BTreeMap::default(); let mut dense_labels: indexmap::IndexSet<usize> = indexmap::IndexSet::default(); // We want to produce results that are as deterministic as possible, so we allocate labels // for tempids in sorted order. This has the effect of making "a" allocate before "b", // which is pleasant for testing. for (tempid, tempid_index) in temp_ids { let rep = uf.find_mut(tempid_index); dense_labels.insert(rep); dense_labels.get_full(&rep).map(|(dense_index, _)| tempid_map.insert(tempid.clone(), dense_index)); } debug!("labeled tempids using {} labels: {:?}", dense_labels.len(), tempid_map); Ok(tempid_map) } /// After evolution is complete, use the provided allocated entids to segment `self` into /// populations, each with no references to tempids. pub(crate) fn into_final_populations(self, temp_id_map: &TempIdMap) -> Result<FinalPopulations> { assert!(self.upserts_e.is_empty()); assert!(self.upserts_ev.is_empty()); let mut populations = FinalPopulations::default(); populations.upserted = self.upserted; populations.resolved = self.resolved; for term in self.allocations { let allocated = match term { // TODO: consider require implementing require on temp_id_map. Term::AddOrRetract(op, Right(t1), a, Right(t2)) => { match (op, temp_id_map.get(&*t1), temp_id_map.get(&*t2)) { (op, Some(&n1), Some(&n2)) => Term::AddOrRetract(op, n1, a, TypedValue::Ref(n2.0)), (OpType::Add, _, _) => unreachable!(), // This is a coding error -- every tempid in a :db/add entity should resolve or be allocated. (OpType::Retract, _, _) => bail!(DbErrorKind::NotYetImplemented(format!("[:db/retract...] entity referenced tempid that did not upsert: one of {}, {}", t1, t2))), } }, Term::AddOrRetract(op, Right(t), a, Left(v)) => { match (op, temp_id_map.get(&*t)) { (op, Some(&n)) => Term::AddOrRetract(op, n, a, v), (OpType::Add, _) => unreachable!(), // This is a coding error. (OpType::Retract, _) => bail!(DbErrorKind::NotYetImplemented(format!("[:db/retract...] entity referenced tempid that did not upsert: {}", t))), } }, Term::AddOrRetract(op, Left(e), a, Right(t)) => { match (op, temp_id_map.get(&*t)) { (op, Some(&n)) => Term::AddOrRetract(op, e, a, TypedValue::Ref(n.0)), (OpType::Add, _) => unreachable!(), // This is a coding error. (OpType::Retract, _) => bail!(DbErrorKind::NotYetImplemented(format!("[:db/retract...] entity referenced tempid that did not upsert: {}", t))), } }, Term::AddOrRetract(_, Left(_), _, Left(_)) => unreachable!(), // This is a coding error -- these should not be in allocations. }; populations.allocated.push(allocated); } Ok(populations) } }
random_line_split
upsert_resolution.rs
// Copyright 2016 Mozilla // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. #![allow(dead_code)] //! This module implements the upsert resolution algorithm described at //! https://github.com/mozilla/mentat/wiki/Transacting:-upsert-resolution-algorithm. use std::collections::{ BTreeMap, BTreeSet, }; use indexmap; use petgraph::unionfind; use errors::{ DbErrorKind, Result, }; use types::{ AVPair, }; use internal_types::{ Population, TempIdHandle, TempIdMap, Term, TermWithoutTempIds, TermWithTempIds, TypedValueOr, }; use mentat_core::util::Either::*; use mentat_core::{ attribute, Attribute, Entid, Schema, TypedValue, }; use edn::entities::OpType; use schema::SchemaBuilding; /// A "Simple upsert" that looks like [:db/add TEMPID a v], where a is :db.unique/identity. #[derive(Clone,Debug,Eq,Hash,Ord,PartialOrd,PartialEq)] struct UpsertE(TempIdHandle, Entid, TypedValue); /// A "Complex upsert" that looks like [:db/add TEMPID a OTHERID], where a is :db.unique/identity #[derive(Clone,Debug,Eq,Hash,Ord,PartialOrd,PartialEq)] struct UpsertEV(TempIdHandle, Entid, TempIdHandle); /// A generation collects entities into populations at a single evolutionary step in the upsert /// resolution evolution process. /// /// The upsert resolution process is only concerned with [:db/add...] entities until the final /// entid allocations. That's why we separate into special simple and complex upsert types /// immediately, and then collect the more general term types for final resolution. #[derive(Clone,Debug,Default,Eq,Hash,Ord,PartialOrd,PartialEq)] pub(crate) struct Generation { /// "Simple upserts" that look like [:db/add TEMPID a v], where a is :db.unique/identity. upserts_e: Vec<UpsertE>, /// "Complex upserts" that look like [:db/add TEMPID a OTHERID], where a is :db.unique/identity upserts_ev: Vec<UpsertEV>, /// Entities that look like: /// - [:db/add TEMPID b OTHERID]. b may be :db.unique/identity if it has failed to upsert. /// - [:db/add TEMPID b v]. b may be :db.unique/identity if it has failed to upsert. /// - [:db/add e b OTHERID]. allocations: Vec<TermWithTempIds>, /// Entities that upserted and no longer reference tempids. These assertions are guaranteed to /// be in the store. upserted: Vec<TermWithoutTempIds>, /// Entities that resolved due to other upserts and no longer reference tempids. These /// assertions may or may not be in the store. resolved: Vec<TermWithoutTempIds>, } #[derive(Clone,Debug,Default,Eq,Hash,Ord,PartialOrd,PartialEq)] pub(crate) struct FinalPopulations { /// Upserts that upserted. pub upserted: Vec<TermWithoutTempIds>, /// Allocations that resolved due to other upserts. pub resolved: Vec<TermWithoutTempIds>, /// Allocations that required new entid allocations. pub allocated: Vec<TermWithoutTempIds>, } impl Generation { /// Split entities into a generation of populations that need to evolve to have their tempids /// resolved or allocated, and a population of inert entities that do not reference tempids. pub(crate) fn from<I>(terms: I, schema: &Schema) -> Result<(Generation, Population)> where I: IntoIterator<Item=TermWithTempIds> { let mut generation = Generation::default(); let mut inert = vec![]; let is_unique = |a: Entid| -> Result<bool> { let attribute: &Attribute = schema.require_attribute_for_entid(a)?; Ok(attribute.unique == Some(attribute::Unique::Identity)) }; for term in terms.into_iter() { match term { Term::AddOrRetract(op, Right(e), a, Right(v)) => { if op == OpType::Add && is_unique(a)? { generation.upserts_ev.push(UpsertEV(e, a, v)); } else { generation.allocations.push(Term::AddOrRetract(op, Right(e), a, Right(v))); } }, Term::AddOrRetract(op, Right(e), a, Left(v)) => { if op == OpType::Add && is_unique(a)? { generation.upserts_e.push(UpsertE(e, a, v)); } else { generation.allocations.push(Term::AddOrRetract(op, Right(e), a, Left(v))); } }, Term::AddOrRetract(op, Left(e), a, Right(v)) => { generation.allocations.push(Term::AddOrRetract(op, Left(e), a, Right(v))); }, Term::AddOrRetract(op, Left(e), a, Left(v)) => { inert.push(Term::AddOrRetract(op, Left(e), a, Left(v))); }, } } Ok((generation, inert)) } /// Return true if it's possible to evolve this generation further. /// /// Note that there can be complex upserts but no simple upserts to help resolve them, and in /// this case, we cannot evolve further. pub(crate) fn
(&self) -> bool { !self.upserts_e.is_empty() } /// Evolve this generation one step further by rewriting the existing :db/add entities using the /// given temporary IDs. /// /// TODO: Considering doing this in place; the function already consumes `self`. pub(crate) fn evolve_one_step(self, temp_id_map: &TempIdMap) -> Generation { let mut next = Generation::default(); // We'll iterate our own allocations to resolve more things, but terms that have already // resolved stay resolved. next.resolved = self.resolved; for UpsertE(t, a, v) in self.upserts_e { match temp_id_map.get(&*t) { Some(&n) => next.upserted.push(Term::AddOrRetract(OpType::Add, n, a, v)), None => next.allocations.push(Term::AddOrRetract(OpType::Add, Right(t), a, Left(v))), } } for UpsertEV(t1, a, t2) in self.upserts_ev { match (temp_id_map.get(&*t1), temp_id_map.get(&*t2)) { (Some(_), Some(&n2)) => { // Even though we can resolve entirely, it's possible that the remaining upsert // could conflict. Moving straight to resolved doesn't give us a chance to // search the store for the conflict. next.upserts_e.push(UpsertE(t1, a, TypedValue::Ref(n2.0))) }, (None, Some(&n2)) => next.upserts_e.push(UpsertE(t1, a, TypedValue::Ref(n2.0))), (Some(&n1), None) => next.allocations.push(Term::AddOrRetract(OpType::Add, Left(n1), a, Right(t2))), (None, None) => next.upserts_ev.push(UpsertEV(t1, a, t2)) } } // There's no particular need to separate resolved from allocations right here and right // now, although it is convenient. for term in self.allocations { // TODO: find an expression that destructures less? I still expect this to be efficient // but it's a little verbose. match term { Term::AddOrRetract(op, Right(t1), a, Right(t2)) => { match (temp_id_map.get(&*t1), temp_id_map.get(&*t2)) { (Some(&n1), Some(&n2)) => next.resolved.push(Term::AddOrRetract(op, n1, a, TypedValue::Ref(n2.0))), (None, Some(&n2)) => next.allocations.push(Term::AddOrRetract(op, Right(t1), a, Left(TypedValue::Ref(n2.0)))), (Some(&n1), None) => next.allocations.push(Term::AddOrRetract(op, Left(n1), a, Right(t2))), (None, None) => next.allocations.push(Term::AddOrRetract(op, Right(t1), a, Right(t2))), } }, Term::AddOrRetract(op, Right(t), a, Left(v)) => { match temp_id_map.get(&*t) { Some(&n) => next.resolved.push(Term::AddOrRetract(op, n, a, v)), None => next.allocations.push(Term::AddOrRetract(op, Right(t), a, Left(v))), } }, Term::AddOrRetract(op, Left(e), a, Right(t)) => { match temp_id_map.get(&*t) { Some(&n) => next.resolved.push(Term::AddOrRetract(op, e, a, TypedValue::Ref(n.0))), None => next.allocations.push(Term::AddOrRetract(op, Left(e), a, Right(t))), } }, Term::AddOrRetract(_, Left(_), _, Left(_)) => unreachable!(), } } next } // Collect id->[a v] pairs that might upsert at this evolutionary step. pub(crate) fn temp_id_avs<'a>(&'a self) -> Vec<(TempIdHandle, AVPair)> { let mut temp_id_avs: Vec<(TempIdHandle, AVPair)> = vec![]; // TODO: map/collect. for &UpsertE(ref t, ref a, ref v) in &self.upserts_e { // TODO: figure out how to make this less expensive, i.e., don't require // clone() of an arbitrary value. temp_id_avs.push((t.clone(), (*a, v.clone()))); } temp_id_avs } /// Evolve potential upserts that haven't resolved into allocations. pub(crate) fn allocate_unresolved_upserts(&mut self) -> Result<()> { let mut upserts_ev = vec![]; ::std::mem::swap(&mut self.upserts_ev, &mut upserts_ev); self.allocations.extend(upserts_ev.into_iter().map(|UpsertEV(t1, a, t2)| Term::AddOrRetract(OpType::Add, Right(t1), a, Right(t2)))); Ok(()) } /// After evolution is complete, yield the set of tempids that require entid allocation. /// /// Some of the tempids may be identified, so we also provide a map from tempid to a dense set /// of contiguous integer labels. pub(crate) fn temp_ids_in_allocations(&self, schema: &Schema) -> Result<BTreeMap<TempIdHandle, usize>> { assert!(self.upserts_e.is_empty(), "All upserts should have been upserted, resolved, or moved to the allocated population!"); assert!(self.upserts_ev.is_empty(), "All upserts should have been upserted, resolved, or moved to the allocated population!"); let mut temp_ids: BTreeSet<TempIdHandle> = BTreeSet::default(); let mut tempid_avs: BTreeMap<(Entid, TypedValueOr<TempIdHandle>), Vec<TempIdHandle>> = BTreeMap::default(); for term in self.allocations.iter() { match term { &Term::AddOrRetract(OpType::Add, Right(ref t1), a, Right(ref t2)) => { temp_ids.insert(t1.clone()); temp_ids.insert(t2.clone()); let attribute: &Attribute = schema.require_attribute_for_entid(a)?; if attribute.unique == Some(attribute::Unique::Identity) { tempid_avs.entry((a, Right(t2.clone()))).or_insert(vec![]).push(t1.clone()); } }, &Term::AddOrRetract(OpType::Add, Right(ref t), a, ref x @ Left(_)) => { temp_ids.insert(t.clone()); let attribute: &Attribute = schema.require_attribute_for_entid(a)?; if attribute.unique == Some(attribute::Unique::Identity) { tempid_avs.entry((a, x.clone())).or_insert(vec![]).push(t.clone()); } }, &Term::AddOrRetract(OpType::Add, Left(_), _, Right(ref t)) => { temp_ids.insert(t.clone()); }, &Term::AddOrRetract(OpType::Add, Left(_), _, Left(_)) => unreachable!(), &Term::AddOrRetract(OpType::Retract, _, _, _) => { // [:db/retract...] entities never allocate entids; they have to resolve due to // other upserts (or they fail the transaction). }, } } // Now we union-find all the known tempids. Two tempids are unioned if they both appear as // the entity of an `[a v]` upsert, including when the value column `v` is itself a tempid. let mut uf = unionfind::UnionFind::new(temp_ids.len()); // The union-find implementation from petgraph operates on contiguous indices, so we need to // maintain the map from our tempids to indices ourselves. let temp_ids: BTreeMap<TempIdHandle, usize> = temp_ids.into_iter().enumerate().map(|(i, tempid)| (tempid, i)).collect(); debug!("need to label tempids aggregated using tempid_avs {:?}", tempid_avs); for vs in tempid_avs.values() { vs.first().and_then(|first| temp_ids.get(first)).map(|&first_index| { for tempid in vs { temp_ids.get(tempid).map(|&i| uf.union(first_index, i)); } }); } debug!("union-find aggregation {:?}", uf.clone().into_labeling()); // Now that we have aggregated tempids, we need to label them using the smallest number of // contiguous labels possible. let mut tempid_map: BTreeMap<TempIdHandle, usize> = BTreeMap::default(); let mut dense_labels: indexmap::IndexSet<usize> = indexmap::IndexSet::default(); // We want to produce results that are as deterministic as possible, so we allocate labels // for tempids in sorted order. This has the effect of making "a" allocate before "b", // which is pleasant for testing. for (tempid, tempid_index) in temp_ids { let rep = uf.find_mut(tempid_index); dense_labels.insert(rep); dense_labels.get_full(&rep).map(|(dense_index, _)| tempid_map.insert(tempid.clone(), dense_index)); } debug!("labeled tempids using {} labels: {:?}", dense_labels.len(), tempid_map); Ok(tempid_map) } /// After evolution is complete, use the provided allocated entids to segment `self` into /// populations, each with no references to tempids. pub(crate) fn into_final_populations(self, temp_id_map: &TempIdMap) -> Result<FinalPopulations> { assert!(self.upserts_e.is_empty()); assert!(self.upserts_ev.is_empty()); let mut populations = FinalPopulations::default(); populations.upserted = self.upserted; populations.resolved = self.resolved; for term in self.allocations { let allocated = match term { // TODO: consider require implementing require on temp_id_map. Term::AddOrRetract(op, Right(t1), a, Right(t2)) => { match (op, temp_id_map.get(&*t1), temp_id_map.get(&*t2)) { (op, Some(&n1), Some(&n2)) => Term::AddOrRetract(op, n1, a, TypedValue::Ref(n2.0)), (OpType::Add, _, _) => unreachable!(), // This is a coding error -- every tempid in a :db/add entity should resolve or be allocated. (OpType::Retract, _, _) => bail!(DbErrorKind::NotYetImplemented(format!("[:db/retract...] entity referenced tempid that did not upsert: one of {}, {}", t1, t2))), } }, Term::AddOrRetract(op, Right(t), a, Left(v)) => { match (op, temp_id_map.get(&*t)) { (op, Some(&n)) => Term::AddOrRetract(op, n, a, v), (OpType::Add, _) => unreachable!(), // This is a coding error. (OpType::Retract, _) => bail!(DbErrorKind::NotYetImplemented(format!("[:db/retract...] entity referenced tempid that did not upsert: {}", t))), } }, Term::AddOrRetract(op, Left(e), a, Right(t)) => { match (op, temp_id_map.get(&*t)) { (op, Some(&n)) => Term::AddOrRetract(op, e, a, TypedValue::Ref(n.0)), (OpType::Add, _) => unreachable!(), // This is a coding error. (OpType::Retract, _) => bail!(DbErrorKind::NotYetImplemented(format!("[:db/retract...] entity referenced tempid that did not upsert: {}", t))), } }, Term::AddOrRetract(_, Left(_), _, Left(_)) => unreachable!(), // This is a coding error -- these should not be in allocations. }; populations.allocated.push(allocated); } Ok(populations) } }
can_evolve
identifier_name
early-vtbl-resolution.rs
// Copyright 2012 The Rust Project Developers. See the 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. trait thing<A> { fn foo(&self) -> Option<A>; } impl<A> thing<A> for int { fn foo(&self) -> Option<A> { None } } fn foo_func<A, B: thing<A>>(x: B) -> Option<A> { x.foo() } struct A { a: int } pub fn main() { for old_iter::eachi(&(Some(A {a: 0}))) |i, a| { debug!("%u %d", i, a.a); } let _x: Option<float> = foo_func(0); }
// file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. //
random_line_split
early-vtbl-resolution.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. trait thing<A> { fn foo(&self) -> Option<A>; } impl<A> thing<A> for int { fn foo(&self) -> Option<A> { None } } fn
<A, B: thing<A>>(x: B) -> Option<A> { x.foo() } struct A { a: int } pub fn main() { for old_iter::eachi(&(Some(A {a: 0}))) |i, a| { debug!("%u %d", i, a.a); } let _x: Option<float> = foo_func(0); }
foo_func
identifier_name
early-vtbl-resolution.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. trait thing<A> { fn foo(&self) -> Option<A>; } impl<A> thing<A> for int { fn foo(&self) -> Option<A> { None } } fn foo_func<A, B: thing<A>>(x: B) -> Option<A> { x.foo() } struct A { a: int } pub fn main()
let _x: Option<float> = foo_func(0); }
{ for old_iter::eachi(&(Some(A {a: 0}))) |i, a| { debug!("%u %d", i, a.a); }
identifier_body
download.rs
use std::fmt::{self, Display, Formatter}; use uuid::Uuid; /// Details of a package for downloading. #[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)] pub struct Package { pub name: String, pub version: String } impl Display for Package { fn fmt(&self, f: &mut Formatter) -> fmt::Result { write!(f, "{} {}", self.name, self.version) } }
pub struct UpdateRequest { pub requestId: Uuid, pub status: RequestStatus, pub packageId: Package, pub installPos: i32, pub createdAt: String, } /// The current status of an `UpdateRequest`. #[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)] pub enum RequestStatus { Pending, InFlight, Canceled, Failed, Finished } /// A notification from RVI that a new update is available. #[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)] pub struct UpdateAvailable { pub update_id: String, pub signature: String, pub description: String, pub request_confirmation: bool, pub size: u64 } /// A notification to an external package manager that the package was downloaded. #[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)] pub struct DownloadComplete { pub update_id: Uuid, pub update_image: String, pub signature: String } /// A notification to an external package manager that the package download failed. #[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)] pub struct DownloadFailed { pub update_id: Uuid, pub reason: String }
/// A request for the device to install a new update. #[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)] #[allow(non_snake_case)]
random_line_split
download.rs
use std::fmt::{self, Display, Formatter}; use uuid::Uuid; /// Details of a package for downloading. #[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)] pub struct Package { pub name: String, pub version: String } impl Display for Package { fn fmt(&self, f: &mut Formatter) -> fmt::Result
} /// A request for the device to install a new update. #[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)] #[allow(non_snake_case)] pub struct UpdateRequest { pub requestId: Uuid, pub status: RequestStatus, pub packageId: Package, pub installPos: i32, pub createdAt: String, } /// The current status of an `UpdateRequest`. #[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)] pub enum RequestStatus { Pending, InFlight, Canceled, Failed, Finished } /// A notification from RVI that a new update is available. #[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)] pub struct UpdateAvailable { pub update_id: String, pub signature: String, pub description: String, pub request_confirmation: bool, pub size: u64 } /// A notification to an external package manager that the package was downloaded. #[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)] pub struct DownloadComplete { pub update_id: Uuid, pub update_image: String, pub signature: String } /// A notification to an external package manager that the package download failed. #[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)] pub struct DownloadFailed { pub update_id: Uuid, pub reason: String }
{ write!(f, "{} {}", self.name, self.version) }
identifier_body
download.rs
use std::fmt::{self, Display, Formatter}; use uuid::Uuid; /// Details of a package for downloading. #[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)] pub struct Package { pub name: String, pub version: String } impl Display for Package { fn
(&self, f: &mut Formatter) -> fmt::Result { write!(f, "{} {}", self.name, self.version) } } /// A request for the device to install a new update. #[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)] #[allow(non_snake_case)] pub struct UpdateRequest { pub requestId: Uuid, pub status: RequestStatus, pub packageId: Package, pub installPos: i32, pub createdAt: String, } /// The current status of an `UpdateRequest`. #[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)] pub enum RequestStatus { Pending, InFlight, Canceled, Failed, Finished } /// A notification from RVI that a new update is available. #[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)] pub struct UpdateAvailable { pub update_id: String, pub signature: String, pub description: String, pub request_confirmation: bool, pub size: u64 } /// A notification to an external package manager that the package was downloaded. #[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)] pub struct DownloadComplete { pub update_id: Uuid, pub update_image: String, pub signature: String } /// A notification to an external package manager that the package download failed. #[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)] pub struct DownloadFailed { pub update_id: Uuid, pub reason: String }
fmt
identifier_name
imgwin.rs
use glium; use glium::index::PrimitiveType; use glium::Surface; use image; use std::time::{Duration, Instant}; use glium::glutin::event::{ElementState, Event, StartCause, VirtualKeyCode, WindowEvent}; use glium::glutin::event_loop::{ControlFlow, EventLoop}; use glium::glutin::window::WindowBuilder; use glium::glutin::ContextBuilder; use glium::texture::{CompressedSrgbTexture2d, RawImage2d}; use glium::{implement_vertex, program, uniform}; #[derive(Copy, Clone)] struct Vertex { position: [f32; 2], tex_coords: [f32; 2], } implement_vertex!(Vertex, position, tex_coords); /// An Application creates windows and runs a main loop pub struct Application { main_loop: EventLoop<()>, } impl Application { pub fn new() -> Application
pub fn new_window(&self, title: impl Into<String>) -> ImgWindow { ImgWindow::new(title, &self.main_loop) } /// Execute the main loop without ever returning. Events are delegated to the given `handler` /// and `handler.next_frame` is called `fps` times per seconds. /// Whenever `handler.should_exit` turns true, the program exit. pub fn run<T: MainloopHandler +'static>(self, mut handler: T, fps: u32) ->! { self.main_loop.run(move |event, _, control_flow| { let now = Instant::now(); match event { Event::WindowEvent { event: win_event,.. } => match win_event { WindowEvent::CloseRequested => { handler.close_event(); } WindowEvent::KeyboardInput { input,.. } if input.state == ElementState::Pressed => { handler.key_event(input.virtual_keycode) } _ => (), }, Event::NewEvents(StartCause::ResumeTimeReached {.. }) | Event::NewEvents(StartCause::Init) => handler.next_frame(), _ => (), } if handler.should_exit() { *control_flow = ControlFlow::Exit; handler.on_exit(); } else { *control_flow = ControlFlow::WaitUntil(now + Duration::from_secs_f32(1f32 / fps as f32)); } }); } } /// Shows a image with help of opengl (glium) pub struct ImgWindow { texture: Option<CompressedSrgbTexture2d>, pub facade: glium::Display, vertex_buffer: glium::VertexBuffer<Vertex>, index_buffer: glium::IndexBuffer<u16>, program: glium::Program, } /// Implement this trait for handling events that occurs in the main loop /// and control when the main loop exit. pub trait MainloopHandler { /// Get called whenever a window is closed. fn close_event(&mut self); /// Get called whenever a key is pressed. fn key_event(&mut self, inp: Option<VirtualKeyCode>); /// Should return true if the main loop should exit. /// Get called after every other event. fn should_exit(&self) -> bool; /// Get called when the next frame should be drawn. fn next_frame(&mut self); /// Get called before the main loops end fn on_exit(&mut self); } impl ImgWindow { fn new<T: Into<String>>(title: T, main_loop: &EventLoop<()>) -> ImgWindow { let wb = WindowBuilder::new().with_title(title.into()); let cb = ContextBuilder::new().with_vsync(true); let display = glium::Display::new(wb, cb, &main_loop).unwrap(); // vertex for a rect for drawing an image to the whole window let vertex_buffer = glium::VertexBuffer::new( &display, &[ Vertex { position: [-1.0, -1.0], tex_coords: [0.0, 0.0], }, Vertex { position: [-1.0, 1.0], tex_coords: [0.0, 1.0], }, Vertex { position: [1.0, 1.0], tex_coords: [1.0, 1.0], }, Vertex { position: [1.0, -1.0], tex_coords: [1.0, 0.0], }, ], ) .unwrap(); let index_buffer = glium::IndexBuffer::new(&display, PrimitiveType::TriangleStrip, &[1 as u16, 2, 0, 3]) .unwrap(); // just enough shader for drawing images let program = program!(&display, 140 => { vertex: " #version 140 uniform lowp mat4 matrix; in vec2 position; in vec2 tex_coords; out vec2 v_tex_coords; void main(){ gl_Position = matrix * vec4(position, 0.0, 1.0); v_tex_coords = tex_coords; } ", fragment: " #version 140 uniform sampler2D tex; in vec2 v_tex_coords; out vec4 f_color; void main(){ f_color = texture(tex, v_tex_coords); } " },) .unwrap(); ImgWindow { texture: None, facade: display, vertex_buffer: vertex_buffer, index_buffer: index_buffer, program: program, } } /// Changes the image which should be drawn to this window. Call `redraw` to show this image /// to the user. pub fn set_img(&mut self, img: image::RgbaImage) { let dim = img.dimensions(); let text = RawImage2d::from_raw_rgba_reversed(&img.into_raw(), dim); self.texture = CompressedSrgbTexture2d::new(&self.facade, text).ok(); } /// Redraws using opengl pub fn redraw(&self) { let mut target = self.facade.draw(); target.clear_color(0.0, 0.0, 0.0, 0.0); if let Some(ref texture) = self.texture { let uniforms = uniform! { matrix: [ [1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0f32] ], tex: texture }; target .draw( &self.vertex_buffer, &self.index_buffer, &self.program, &uniforms, &Default::default(), ) .unwrap(); } target.finish().unwrap(); // self.facade.swap_buffers().unwrap(); } }
{ Application { main_loop: EventLoop::new(), } }
identifier_body
imgwin.rs
use glium; use glium::index::PrimitiveType; use glium::Surface; use image; use std::time::{Duration, Instant}; use glium::glutin::event::{ElementState, Event, StartCause, VirtualKeyCode, WindowEvent}; use glium::glutin::event_loop::{ControlFlow, EventLoop}; use glium::glutin::window::WindowBuilder; use glium::glutin::ContextBuilder; use glium::texture::{CompressedSrgbTexture2d, RawImage2d}; use glium::{implement_vertex, program, uniform}; #[derive(Copy, Clone)] struct Vertex { position: [f32; 2], tex_coords: [f32; 2], } implement_vertex!(Vertex, position, tex_coords); /// An Application creates windows and runs a main loop pub struct Application { main_loop: EventLoop<()>, } impl Application { pub fn new() -> Application { Application { main_loop: EventLoop::new(), } } pub fn new_window(&self, title: impl Into<String>) -> ImgWindow { ImgWindow::new(title, &self.main_loop) } /// Execute the main loop without ever returning. Events are delegated to the given `handler` /// and `handler.next_frame` is called `fps` times per seconds. /// Whenever `handler.should_exit` turns true, the program exit. pub fn run<T: MainloopHandler +'static>(self, mut handler: T, fps: u32) ->! { self.main_loop.run(move |event, _, control_flow| { let now = Instant::now(); match event { Event::WindowEvent { event: win_event,.. } => match win_event { WindowEvent::CloseRequested => { handler.close_event(); } WindowEvent::KeyboardInput { input,.. } if input.state == ElementState::Pressed =>
_ => (), }, Event::NewEvents(StartCause::ResumeTimeReached {.. }) | Event::NewEvents(StartCause::Init) => handler.next_frame(), _ => (), } if handler.should_exit() { *control_flow = ControlFlow::Exit; handler.on_exit(); } else { *control_flow = ControlFlow::WaitUntil(now + Duration::from_secs_f32(1f32 / fps as f32)); } }); } } /// Shows a image with help of opengl (glium) pub struct ImgWindow { texture: Option<CompressedSrgbTexture2d>, pub facade: glium::Display, vertex_buffer: glium::VertexBuffer<Vertex>, index_buffer: glium::IndexBuffer<u16>, program: glium::Program, } /// Implement this trait for handling events that occurs in the main loop /// and control when the main loop exit. pub trait MainloopHandler { /// Get called whenever a window is closed. fn close_event(&mut self); /// Get called whenever a key is pressed. fn key_event(&mut self, inp: Option<VirtualKeyCode>); /// Should return true if the main loop should exit. /// Get called after every other event. fn should_exit(&self) -> bool; /// Get called when the next frame should be drawn. fn next_frame(&mut self); /// Get called before the main loops end fn on_exit(&mut self); } impl ImgWindow { fn new<T: Into<String>>(title: T, main_loop: &EventLoop<()>) -> ImgWindow { let wb = WindowBuilder::new().with_title(title.into()); let cb = ContextBuilder::new().with_vsync(true); let display = glium::Display::new(wb, cb, &main_loop).unwrap(); // vertex for a rect for drawing an image to the whole window let vertex_buffer = glium::VertexBuffer::new( &display, &[ Vertex { position: [-1.0, -1.0], tex_coords: [0.0, 0.0], }, Vertex { position: [-1.0, 1.0], tex_coords: [0.0, 1.0], }, Vertex { position: [1.0, 1.0], tex_coords: [1.0, 1.0], }, Vertex { position: [1.0, -1.0], tex_coords: [1.0, 0.0], }, ], ) .unwrap(); let index_buffer = glium::IndexBuffer::new(&display, PrimitiveType::TriangleStrip, &[1 as u16, 2, 0, 3]) .unwrap(); // just enough shader for drawing images let program = program!(&display, 140 => { vertex: " #version 140 uniform lowp mat4 matrix; in vec2 position; in vec2 tex_coords; out vec2 v_tex_coords; void main(){ gl_Position = matrix * vec4(position, 0.0, 1.0); v_tex_coords = tex_coords; } ", fragment: " #version 140 uniform sampler2D tex; in vec2 v_tex_coords; out vec4 f_color; void main(){ f_color = texture(tex, v_tex_coords); } " },) .unwrap(); ImgWindow { texture: None, facade: display, vertex_buffer: vertex_buffer, index_buffer: index_buffer, program: program, } } /// Changes the image which should be drawn to this window. Call `redraw` to show this image /// to the user. pub fn set_img(&mut self, img: image::RgbaImage) { let dim = img.dimensions(); let text = RawImage2d::from_raw_rgba_reversed(&img.into_raw(), dim); self.texture = CompressedSrgbTexture2d::new(&self.facade, text).ok(); } /// Redraws using opengl pub fn redraw(&self) { let mut target = self.facade.draw(); target.clear_color(0.0, 0.0, 0.0, 0.0); if let Some(ref texture) = self.texture { let uniforms = uniform! { matrix: [ [1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0f32] ], tex: texture }; target .draw( &self.vertex_buffer, &self.index_buffer, &self.program, &uniforms, &Default::default(), ) .unwrap(); } target.finish().unwrap(); // self.facade.swap_buffers().unwrap(); } }
{ handler.key_event(input.virtual_keycode) }
conditional_block
imgwin.rs
use glium; use glium::index::PrimitiveType; use glium::Surface; use image; use std::time::{Duration, Instant}; use glium::glutin::event::{ElementState, Event, StartCause, VirtualKeyCode, WindowEvent}; use glium::glutin::event_loop::{ControlFlow, EventLoop}; use glium::glutin::window::WindowBuilder; use glium::glutin::ContextBuilder;
struct Vertex { position: [f32; 2], tex_coords: [f32; 2], } implement_vertex!(Vertex, position, tex_coords); /// An Application creates windows and runs a main loop pub struct Application { main_loop: EventLoop<()>, } impl Application { pub fn new() -> Application { Application { main_loop: EventLoop::new(), } } pub fn new_window(&self, title: impl Into<String>) -> ImgWindow { ImgWindow::new(title, &self.main_loop) } /// Execute the main loop without ever returning. Events are delegated to the given `handler` /// and `handler.next_frame` is called `fps` times per seconds. /// Whenever `handler.should_exit` turns true, the program exit. pub fn run<T: MainloopHandler +'static>(self, mut handler: T, fps: u32) ->! { self.main_loop.run(move |event, _, control_flow| { let now = Instant::now(); match event { Event::WindowEvent { event: win_event,.. } => match win_event { WindowEvent::CloseRequested => { handler.close_event(); } WindowEvent::KeyboardInput { input,.. } if input.state == ElementState::Pressed => { handler.key_event(input.virtual_keycode) } _ => (), }, Event::NewEvents(StartCause::ResumeTimeReached {.. }) | Event::NewEvents(StartCause::Init) => handler.next_frame(), _ => (), } if handler.should_exit() { *control_flow = ControlFlow::Exit; handler.on_exit(); } else { *control_flow = ControlFlow::WaitUntil(now + Duration::from_secs_f32(1f32 / fps as f32)); } }); } } /// Shows a image with help of opengl (glium) pub struct ImgWindow { texture: Option<CompressedSrgbTexture2d>, pub facade: glium::Display, vertex_buffer: glium::VertexBuffer<Vertex>, index_buffer: glium::IndexBuffer<u16>, program: glium::Program, } /// Implement this trait for handling events that occurs in the main loop /// and control when the main loop exit. pub trait MainloopHandler { /// Get called whenever a window is closed. fn close_event(&mut self); /// Get called whenever a key is pressed. fn key_event(&mut self, inp: Option<VirtualKeyCode>); /// Should return true if the main loop should exit. /// Get called after every other event. fn should_exit(&self) -> bool; /// Get called when the next frame should be drawn. fn next_frame(&mut self); /// Get called before the main loops end fn on_exit(&mut self); } impl ImgWindow { fn new<T: Into<String>>(title: T, main_loop: &EventLoop<()>) -> ImgWindow { let wb = WindowBuilder::new().with_title(title.into()); let cb = ContextBuilder::new().with_vsync(true); let display = glium::Display::new(wb, cb, &main_loop).unwrap(); // vertex for a rect for drawing an image to the whole window let vertex_buffer = glium::VertexBuffer::new( &display, &[ Vertex { position: [-1.0, -1.0], tex_coords: [0.0, 0.0], }, Vertex { position: [-1.0, 1.0], tex_coords: [0.0, 1.0], }, Vertex { position: [1.0, 1.0], tex_coords: [1.0, 1.0], }, Vertex { position: [1.0, -1.0], tex_coords: [1.0, 0.0], }, ], ) .unwrap(); let index_buffer = glium::IndexBuffer::new(&display, PrimitiveType::TriangleStrip, &[1 as u16, 2, 0, 3]) .unwrap(); // just enough shader for drawing images let program = program!(&display, 140 => { vertex: " #version 140 uniform lowp mat4 matrix; in vec2 position; in vec2 tex_coords; out vec2 v_tex_coords; void main(){ gl_Position = matrix * vec4(position, 0.0, 1.0); v_tex_coords = tex_coords; } ", fragment: " #version 140 uniform sampler2D tex; in vec2 v_tex_coords; out vec4 f_color; void main(){ f_color = texture(tex, v_tex_coords); } " },) .unwrap(); ImgWindow { texture: None, facade: display, vertex_buffer: vertex_buffer, index_buffer: index_buffer, program: program, } } /// Changes the image which should be drawn to this window. Call `redraw` to show this image /// to the user. pub fn set_img(&mut self, img: image::RgbaImage) { let dim = img.dimensions(); let text = RawImage2d::from_raw_rgba_reversed(&img.into_raw(), dim); self.texture = CompressedSrgbTexture2d::new(&self.facade, text).ok(); } /// Redraws using opengl pub fn redraw(&self) { let mut target = self.facade.draw(); target.clear_color(0.0, 0.0, 0.0, 0.0); if let Some(ref texture) = self.texture { let uniforms = uniform! { matrix: [ [1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0f32] ], tex: texture }; target .draw( &self.vertex_buffer, &self.index_buffer, &self.program, &uniforms, &Default::default(), ) .unwrap(); } target.finish().unwrap(); // self.facade.swap_buffers().unwrap(); } }
use glium::texture::{CompressedSrgbTexture2d, RawImage2d}; use glium::{implement_vertex, program, uniform}; #[derive(Copy, Clone)]
random_line_split
imgwin.rs
use glium; use glium::index::PrimitiveType; use glium::Surface; use image; use std::time::{Duration, Instant}; use glium::glutin::event::{ElementState, Event, StartCause, VirtualKeyCode, WindowEvent}; use glium::glutin::event_loop::{ControlFlow, EventLoop}; use glium::glutin::window::WindowBuilder; use glium::glutin::ContextBuilder; use glium::texture::{CompressedSrgbTexture2d, RawImage2d}; use glium::{implement_vertex, program, uniform}; #[derive(Copy, Clone)] struct Vertex { position: [f32; 2], tex_coords: [f32; 2], } implement_vertex!(Vertex, position, tex_coords); /// An Application creates windows and runs a main loop pub struct Application { main_loop: EventLoop<()>, } impl Application { pub fn new() -> Application { Application { main_loop: EventLoop::new(), } } pub fn new_window(&self, title: impl Into<String>) -> ImgWindow { ImgWindow::new(title, &self.main_loop) } /// Execute the main loop without ever returning. Events are delegated to the given `handler` /// and `handler.next_frame` is called `fps` times per seconds. /// Whenever `handler.should_exit` turns true, the program exit. pub fn run<T: MainloopHandler +'static>(self, mut handler: T, fps: u32) ->! { self.main_loop.run(move |event, _, control_flow| { let now = Instant::now(); match event { Event::WindowEvent { event: win_event,.. } => match win_event { WindowEvent::CloseRequested => { handler.close_event(); } WindowEvent::KeyboardInput { input,.. } if input.state == ElementState::Pressed => { handler.key_event(input.virtual_keycode) } _ => (), }, Event::NewEvents(StartCause::ResumeTimeReached {.. }) | Event::NewEvents(StartCause::Init) => handler.next_frame(), _ => (), } if handler.should_exit() { *control_flow = ControlFlow::Exit; handler.on_exit(); } else { *control_flow = ControlFlow::WaitUntil(now + Duration::from_secs_f32(1f32 / fps as f32)); } }); } } /// Shows a image with help of opengl (glium) pub struct ImgWindow { texture: Option<CompressedSrgbTexture2d>, pub facade: glium::Display, vertex_buffer: glium::VertexBuffer<Vertex>, index_buffer: glium::IndexBuffer<u16>, program: glium::Program, } /// Implement this trait for handling events that occurs in the main loop /// and control when the main loop exit. pub trait MainloopHandler { /// Get called whenever a window is closed. fn close_event(&mut self); /// Get called whenever a key is pressed. fn key_event(&mut self, inp: Option<VirtualKeyCode>); /// Should return true if the main loop should exit. /// Get called after every other event. fn should_exit(&self) -> bool; /// Get called when the next frame should be drawn. fn next_frame(&mut self); /// Get called before the main loops end fn on_exit(&mut self); } impl ImgWindow { fn new<T: Into<String>>(title: T, main_loop: &EventLoop<()>) -> ImgWindow { let wb = WindowBuilder::new().with_title(title.into()); let cb = ContextBuilder::new().with_vsync(true); let display = glium::Display::new(wb, cb, &main_loop).unwrap(); // vertex for a rect for drawing an image to the whole window let vertex_buffer = glium::VertexBuffer::new( &display, &[ Vertex { position: [-1.0, -1.0], tex_coords: [0.0, 0.0], }, Vertex { position: [-1.0, 1.0], tex_coords: [0.0, 1.0], }, Vertex { position: [1.0, 1.0], tex_coords: [1.0, 1.0], }, Vertex { position: [1.0, -1.0], tex_coords: [1.0, 0.0], }, ], ) .unwrap(); let index_buffer = glium::IndexBuffer::new(&display, PrimitiveType::TriangleStrip, &[1 as u16, 2, 0, 3]) .unwrap(); // just enough shader for drawing images let program = program!(&display, 140 => { vertex: " #version 140 uniform lowp mat4 matrix; in vec2 position; in vec2 tex_coords; out vec2 v_tex_coords; void main(){ gl_Position = matrix * vec4(position, 0.0, 1.0); v_tex_coords = tex_coords; } ", fragment: " #version 140 uniform sampler2D tex; in vec2 v_tex_coords; out vec4 f_color; void main(){ f_color = texture(tex, v_tex_coords); } " },) .unwrap(); ImgWindow { texture: None, facade: display, vertex_buffer: vertex_buffer, index_buffer: index_buffer, program: program, } } /// Changes the image which should be drawn to this window. Call `redraw` to show this image /// to the user. pub fn set_img(&mut self, img: image::RgbaImage) { let dim = img.dimensions(); let text = RawImage2d::from_raw_rgba_reversed(&img.into_raw(), dim); self.texture = CompressedSrgbTexture2d::new(&self.facade, text).ok(); } /// Redraws using opengl pub fn
(&self) { let mut target = self.facade.draw(); target.clear_color(0.0, 0.0, 0.0, 0.0); if let Some(ref texture) = self.texture { let uniforms = uniform! { matrix: [ [1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0f32] ], tex: texture }; target .draw( &self.vertex_buffer, &self.index_buffer, &self.program, &uniforms, &Default::default(), ) .unwrap(); } target.finish().unwrap(); // self.facade.swap_buffers().unwrap(); } }
redraw
identifier_name
f23.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(unreachable_code)] pub fn
() { let mut x = 23; let mut y = 23; let mut z = 23; while x > 0 { x -= 1; while y > 0 { y -= 1; while z > 0 { z -= 1; } if x > 10 { return; "unreachable"; } } } }
expr_while_23
identifier_name
f23.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(unreachable_code)] pub fn expr_while_23() { let mut x = 23; let mut y = 23; let mut z = 23; while x > 0 { x -= 1; while y > 0 { y -= 1; while z > 0 { z -= 1; } if x > 10
} } }
{ return; "unreachable"; }
conditional_block
f23.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
#[allow(unreachable_code)] pub fn expr_while_23() { let mut x = 23; let mut y = 23; let mut z = 23; while x > 0 { x -= 1; while y > 0 { y -= 1; while z > 0 { z -= 1; } if x > 10 { return; "unreachable"; } } } }
// option. This file may not be copied, modified, or distributed // except according to those terms.
random_line_split
f23.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(unreachable_code)] pub fn expr_while_23()
{ let mut x = 23; let mut y = 23; let mut z = 23; while x > 0 { x -= 1; while y > 0 { y -= 1; while z > 0 { z -= 1; } if x > 10 { return; "unreachable"; } } } }
identifier_body
plugins.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![allow(deprecated)] // old path, used for compatibility with dynamic lib use clean; use std::dynamic_lib as dl; use serialize::json; use std::mem; use std::string::String; use std::path::PathBuf; pub type PluginJson = Option<(String, json::Json)>; pub type PluginResult = (clean::Crate, PluginJson); pub type PluginCallback = fn (clean::Crate) -> PluginResult; /// Manages loading and running of plugins pub struct PluginManager { dylibs: Vec<dl::DynamicLibrary>, callbacks: Vec<PluginCallback>, /// The directory plugins will be loaded from pub prefix: PathBuf, } impl PluginManager { /// Create a new plugin manager pub fn new(prefix: PathBuf) -> PluginManager { PluginManager { dylibs: Vec::new(), callbacks: Vec::new(), prefix: prefix, } } /// Load a plugin with the given name. /// /// Turns `name` into the proper dynamic library filename for the given /// platform. On windows, it turns into name.dll, on OS X, name.dylib, and /// elsewhere, libname.so. pub fn load_plugin(&mut self, name: String) { let x = self.prefix.join(libname(name)); let lib_result = dl::DynamicLibrary::open(Some(&x)); let lib = lib_result.unwrap(); unsafe { let plugin = lib.symbol("rustdoc_plugin_entrypoint").unwrap(); self.callbacks.push(mem::transmute::<*mut u8,PluginCallback>(plugin)); } self.dylibs.push(lib); } /// Load a normal Rust function as a plugin. /// /// This is to run passes over the cleaned crate. Plugins run this way /// correspond to the A-aux tag on Github. pub fn add_plugin(&mut self, plugin: PluginCallback) { self.callbacks.push(plugin); } /// Run all the loaded plugins over the crate, returning their results pub fn run_plugins(&self, krate: clean::Crate) -> (clean::Crate, Vec<PluginJson> ) { let mut out_json = Vec::new(); let mut krate = krate; for &callback in &self.callbacks { let (c, res) = callback(krate); krate = c; out_json.push(res); } (krate, out_json) } }
n.push_str(".dll"); n } #[cfg(target_os="macos")] fn libname(mut n: String) -> String { n.push_str(".dylib"); n } #[cfg(all(not(target_os="windows"), not(target_os="macos")))] fn libname(n: String) -> String { let mut i = String::from_str("lib"); i.push_str(&n); i.push_str(".so"); i }
#[cfg(target_os = "windows")] fn libname(mut n: String) -> String {
random_line_split
plugins.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![allow(deprecated)] // old path, used for compatibility with dynamic lib use clean; use std::dynamic_lib as dl; use serialize::json; use std::mem; use std::string::String; use std::path::PathBuf; pub type PluginJson = Option<(String, json::Json)>; pub type PluginResult = (clean::Crate, PluginJson); pub type PluginCallback = fn (clean::Crate) -> PluginResult; /// Manages loading and running of plugins pub struct PluginManager { dylibs: Vec<dl::DynamicLibrary>, callbacks: Vec<PluginCallback>, /// The directory plugins will be loaded from pub prefix: PathBuf, } impl PluginManager { /// Create a new plugin manager pub fn new(prefix: PathBuf) -> PluginManager
/// Load a plugin with the given name. /// /// Turns `name` into the proper dynamic library filename for the given /// platform. On windows, it turns into name.dll, on OS X, name.dylib, and /// elsewhere, libname.so. pub fn load_plugin(&mut self, name: String) { let x = self.prefix.join(libname(name)); let lib_result = dl::DynamicLibrary::open(Some(&x)); let lib = lib_result.unwrap(); unsafe { let plugin = lib.symbol("rustdoc_plugin_entrypoint").unwrap(); self.callbacks.push(mem::transmute::<*mut u8,PluginCallback>(plugin)); } self.dylibs.push(lib); } /// Load a normal Rust function as a plugin. /// /// This is to run passes over the cleaned crate. Plugins run this way /// correspond to the A-aux tag on Github. pub fn add_plugin(&mut self, plugin: PluginCallback) { self.callbacks.push(plugin); } /// Run all the loaded plugins over the crate, returning their results pub fn run_plugins(&self, krate: clean::Crate) -> (clean::Crate, Vec<PluginJson> ) { let mut out_json = Vec::new(); let mut krate = krate; for &callback in &self.callbacks { let (c, res) = callback(krate); krate = c; out_json.push(res); } (krate, out_json) } } #[cfg(target_os = "windows")] fn libname(mut n: String) -> String { n.push_str(".dll"); n } #[cfg(target_os="macos")] fn libname(mut n: String) -> String { n.push_str(".dylib"); n } #[cfg(all(not(target_os="windows"), not(target_os="macos")))] fn libname(n: String) -> String { let mut i = String::from_str("lib"); i.push_str(&n); i.push_str(".so"); i }
{ PluginManager { dylibs: Vec::new(), callbacks: Vec::new(), prefix: prefix, } }
identifier_body
plugins.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![allow(deprecated)] // old path, used for compatibility with dynamic lib use clean; use std::dynamic_lib as dl; use serialize::json; use std::mem; use std::string::String; use std::path::PathBuf; pub type PluginJson = Option<(String, json::Json)>; pub type PluginResult = (clean::Crate, PluginJson); pub type PluginCallback = fn (clean::Crate) -> PluginResult; /// Manages loading and running of plugins pub struct PluginManager { dylibs: Vec<dl::DynamicLibrary>, callbacks: Vec<PluginCallback>, /// The directory plugins will be loaded from pub prefix: PathBuf, } impl PluginManager { /// Create a new plugin manager pub fn
(prefix: PathBuf) -> PluginManager { PluginManager { dylibs: Vec::new(), callbacks: Vec::new(), prefix: prefix, } } /// Load a plugin with the given name. /// /// Turns `name` into the proper dynamic library filename for the given /// platform. On windows, it turns into name.dll, on OS X, name.dylib, and /// elsewhere, libname.so. pub fn load_plugin(&mut self, name: String) { let x = self.prefix.join(libname(name)); let lib_result = dl::DynamicLibrary::open(Some(&x)); let lib = lib_result.unwrap(); unsafe { let plugin = lib.symbol("rustdoc_plugin_entrypoint").unwrap(); self.callbacks.push(mem::transmute::<*mut u8,PluginCallback>(plugin)); } self.dylibs.push(lib); } /// Load a normal Rust function as a plugin. /// /// This is to run passes over the cleaned crate. Plugins run this way /// correspond to the A-aux tag on Github. pub fn add_plugin(&mut self, plugin: PluginCallback) { self.callbacks.push(plugin); } /// Run all the loaded plugins over the crate, returning their results pub fn run_plugins(&self, krate: clean::Crate) -> (clean::Crate, Vec<PluginJson> ) { let mut out_json = Vec::new(); let mut krate = krate; for &callback in &self.callbacks { let (c, res) = callback(krate); krate = c; out_json.push(res); } (krate, out_json) } } #[cfg(target_os = "windows")] fn libname(mut n: String) -> String { n.push_str(".dll"); n } #[cfg(target_os="macos")] fn libname(mut n: String) -> String { n.push_str(".dylib"); n } #[cfg(all(not(target_os="windows"), not(target_os="macos")))] fn libname(n: String) -> String { let mut i = String::from_str("lib"); i.push_str(&n); i.push_str(".so"); i }
new
identifier_name
const-enum-vector.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. enum
{ V1(int), V0 } static C: [E; 3] = [E::V0, E::V1(0xDEADBEE), E::V0]; pub fn main() { match C[1] { E::V1(n) => assert!(n == 0xDEADBEE), _ => panic!() } match C[2] { E::V0 => (), _ => panic!() } }
E
identifier_name
const-enum-vector.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at
// 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. enum E { V1(int), V0 } static C: [E; 3] = [E::V0, E::V1(0xDEADBEE), E::V0]; pub fn main() { match C[1] { E::V1(n) => assert!(n == 0xDEADBEE), _ => panic!() } match C[2] { E::V0 => (), _ => panic!() } }
// http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
random_line_split
const-enum-vector.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. enum E { V1(int), V0 } static C: [E; 3] = [E::V0, E::V1(0xDEADBEE), E::V0]; pub fn main()
{ match C[1] { E::V1(n) => assert!(n == 0xDEADBEE), _ => panic!() } match C[2] { E::V0 => (), _ => panic!() } }
identifier_body
hessenberg.rs
use std::cmp; use nl::Hessenberg; use na::{DMatrix, Matrix4}; quickcheck!{ fn hessenberg(n: usize) -> bool { if n!= 0 { let n = cmp::min(n, 25); let m = DMatrix::<f64>::new_random(n, n); match Hessenberg::new(m.clone()) { Some(hess) => { let h = hess.h(); let p = hess.p(); relative_eq!(m, &p * h * p.transpose(), epsilon = 1.0e-7) }, None => true } } else { true } } fn hessenberg_static(m: Matrix4<f64>) -> bool { match Hessenberg::new(m) { Some(hess) => { let h = hess.h(); let p = hess.p();
} } }
relative_eq!(m, p * h * p.transpose(), epsilon = 1.0e-7) }, None => true
random_line_split
mpq.rs
use std::fs::File; use std::io::Read; use std::ptr::copy_nonoverlapping; // Result: // 11011010100010101000001001101 // 1101101010001 fn sp(){ let bytes: [u8; 4] = [77, 80, 81, 27]; let buf_a: [u8; 2] = [77, 80]; let buf_b: [u8; 2] = [81, 27]; let mut num_a: u32 = 0; let mut num_b: u32 = 0; unsafe { copy_nonoverlapping(buf_a.as_ptr(), &mut num_a as *mut u32 as *mut u8, 2); copy_nonoverlapping(buf_b.as_ptr(), &mut num_b as *mut u32 as *mut u8, 2); } println!("SP Bits: {:16b} {:16b}", num_a.to_le(), num_b.to_le()); } fn main()
{ sp(); let mut f: File = File::open("test.replay").unwrap(); let mut buf = [0u8; 4]; let size = f.read(&mut buf).unwrap(); let mut data: u32 = 0; unsafe { copy_nonoverlapping(buf.as_ptr(), &mut data as *mut u32 as *mut u8, 4) } let bits = data.to_le(); let _string = std::str::from_utf8(&buf).unwrap().to_owned(); println!("String: {:?} ", _string ); println!("Bytes: {:?} Size: {:?}", buf, size); println!("U32: {:?} Bits: {:b}", bits, bits ); }
identifier_body
mpq.rs
use std::fs::File; use std::io::Read; use std::ptr::copy_nonoverlapping; // Result: // 11011010100010101000001001101 // 1101101010001 fn
(){ let bytes: [u8; 4] = [77, 80, 81, 27]; let buf_a: [u8; 2] = [77, 80]; let buf_b: [u8; 2] = [81, 27]; let mut num_a: u32 = 0; let mut num_b: u32 = 0; unsafe { copy_nonoverlapping(buf_a.as_ptr(), &mut num_a as *mut u32 as *mut u8, 2); copy_nonoverlapping(buf_b.as_ptr(), &mut num_b as *mut u32 as *mut u8, 2); } println!("SP Bits: {:16b} {:16b}", num_a.to_le(), num_b.to_le()); } fn main() { sp(); let mut f: File = File::open("test.replay").unwrap(); let mut buf = [0u8; 4]; let size = f.read(&mut buf).unwrap(); let mut data: u32 = 0; unsafe { copy_nonoverlapping(buf.as_ptr(), &mut data as *mut u32 as *mut u8, 4) } let bits = data.to_le(); let _string = std::str::from_utf8(&buf).unwrap().to_owned(); println!("String: {:?} ", _string ); println!("Bytes: {:?} Size: {:?}", buf, size); println!("U32: {:?} Bits: {:b}", bits, bits ); }
sp
identifier_name
mpq.rs
use std::fs::File; use std::io::Read; use std::ptr::copy_nonoverlapping; // Result:
let bytes: [u8; 4] = [77, 80, 81, 27]; let buf_a: [u8; 2] = [77, 80]; let buf_b: [u8; 2] = [81, 27]; let mut num_a: u32 = 0; let mut num_b: u32 = 0; unsafe { copy_nonoverlapping(buf_a.as_ptr(), &mut num_a as *mut u32 as *mut u8, 2); copy_nonoverlapping(buf_b.as_ptr(), &mut num_b as *mut u32 as *mut u8, 2); } println!("SP Bits: {:16b} {:16b}", num_a.to_le(), num_b.to_le()); } fn main() { sp(); let mut f: File = File::open("test.replay").unwrap(); let mut buf = [0u8; 4]; let size = f.read(&mut buf).unwrap(); let mut data: u32 = 0; unsafe { copy_nonoverlapping(buf.as_ptr(), &mut data as *mut u32 as *mut u8, 4) } let bits = data.to_le(); let _string = std::str::from_utf8(&buf).unwrap().to_owned(); println!("String: {:?} ", _string ); println!("Bytes: {:?} Size: {:?}", buf, size); println!("U32: {:?} Bits: {:b}", bits, bits ); }
// 11011010100010101000001001101 // 1101101010001 fn sp(){
random_line_split
lib.rs
/*! # Kiss3d Keep It Simple, Stupid 3d graphics engine. This library is born from the frustration in front of the fact that today’s 3D graphics library are: * either too low level: you have to write your own shaders and opening a window steals you 8 hours, 300 lines of code and 10L of coffee. * or high level but too hard to understand/use: those are libraries made to write beautiful animations or games. They have a lot of feature; too much feature if you only want to draw a few geometries on the screen. **kiss3d** is not designed to be feature-complete or fast. It is designed to be able to draw simple geometric figures and play with them with one-liners. An on-line version of this documentation is available [here](http://kiss3d.org). ## Features Most features are one-liners. * WASM compatibility. * open a window with a default arc-ball camera and a point light. * a first-person camera is available too and user-defined cameras are possible. * display boxes, spheres, cones, cylinders, quads and lines. * change an object color or texture. * change an object transform (we use the [nalgebra](http://nalgebra.org) library to do that). * create basic post-processing effects. As an example, having a red, rotating cube with the light attached to the camera is as simple as (NOTE: this will **not** compile when targeting WASM): ```no_run extern crate kiss3d; extern crate nalgebra as na; use na::{Vector3, UnitQuaternion}; use kiss3d::window::Window; use kiss3d::light::Light; fn main() { let mut window = Window::new("Kiss3d: cube"); let mut c = window.add_cube(1.0, 1.0, 1.0);
c.set_color(1.0, 0.0, 0.0); window.set_light(Light::StickToCamera); let rot = UnitQuaternion::from_axis_angle(&Vector3::y_axis(), 0.014); while window.render() { c.prepend_to_local_rotation(&rot); } } ``` The same example, but that will compile for both WASM and native platforms is slightly more complicated because **kiss3d** must control the render loop: ```no_run extern crate kiss3d; extern crate nalgebra as na; use kiss3d::light::Light; use kiss3d::scene::SceneNode; use kiss3d::window::{State, Window}; use na::{UnitQuaternion, Vector3}; struct AppState { c: SceneNode, rot: UnitQuaternion<f32>, } impl State for AppState { fn step(&mut self, _: &mut Window) { self.c.prepend_to_local_rotation(&self.rot) } } fn main() { let mut window = Window::new("Kiss3d: wasm example"); let mut c = window.add_cube(1.0, 1.0, 1.0); c.set_color(1.0, 0.0, 0.0); window.set_light(Light::StickToCamera); let rot = UnitQuaternion::from_axis_angle(&Vector3::y_axis(), 0.014); let state = AppState { c, rot }; window.render_loop(state) } ``` Some controls are handled by default by the engine (they can be overridden by the user): * `scroll`: zoom in / zoom out. * `left click + drag`: look around. * `right click + drag`: translate the view point. * `enter`: look at the origin (0.0, 0.0, 0.0). ## Compilation You will need the last stable build of the [rust compiler](http://www.rust-lang.org) and the official package manager: [cargo](https://github.com/rust-lang/cargo). Simply add the following to your `Cargo.toml` file: ```text [dependencies] kiss3d = "0.24" ``` ## Contributions I’d love to see people improving this library for their own needs. However, keep in mind that **kiss3d** is KISS. One-liner features (from the user point of view) are preferred. ## Acknowledgements Thanks to all the Rustaceans for their help, and their OpenGL bindings. */ #![deny(non_camel_case_types)] #![deny(unused_parens)] #![allow(non_upper_case_globals)] #![deny(unused_qualifications)] #![warn(missing_docs)] // FIXME: should be denied. #![warn(unused_results)] #![allow(unused_unsafe)] // FIXME: should be denied #![allow(missing_copy_implementations)] #![doc(html_root_url = "http://kiss3d.org/doc")] #[macro_use] extern crate bitflags; extern crate nalgebra as na; extern crate num_traits as num; extern crate rusttype; #[macro_use] extern crate serde_derive; extern crate serde; #[cfg(feature = "conrod")] pub extern crate conrod_core as conrod; #[cfg(not(target_arch = "wasm32"))] extern crate glutin; extern crate instant; #[cfg(feature = "conrod")] pub use conrod::widget_ids; pub use nalgebra; pub use ncollide3d; #[deprecated(note = "Use the `renderer` module instead.")] pub use crate::renderer::line_renderer; #[deprecated(note = "Use the `renderer` module instead.")] pub use crate::renderer::point_renderer; pub mod builtin; pub mod camera; pub mod context; mod error; pub mod event; pub mod light; pub mod loader; pub mod planar_camera; pub mod planar_line_renderer; pub mod post_processing; pub mod renderer; pub mod resource; pub mod scene; pub mod text; pub mod window;
random_line_split
interpreter.rs
use std::io::{Read, stdin}; use operations::Op; pub struct Interpreter { memory: Vec<u8>, pointer: i64, ops: Vec<Op>, } impl Interpreter { pub fn new(ops: Vec<Op>) -> Interpreter { let m = (0.. 30000).map(|_| 0).collect(); Interpreter { memory: m, pointer: 0, ops: ops } } pub fn run(&mut self) { let mut program_counter = 0; while program_counter < self.ops.len() { match self.ops[program_counter] { Op::Increment => self.increment(), Op::Decrement => self.decrement(), Op::Output => self.output(), Op::Right => self.right(), Op::Left => self.left(), Op::Input => self.input(), Op::Jump => self.jump(&mut program_counter), Op::JumpBack => self.jump_back(&mut program_counter), _ => panic!("boom"), } program_counter += 1; } println!(""); } fn left(&mut self) { self.pointer -= 1; } fn right(&mut self) { self.pointer += 1; } fn input(&mut self) { let mut input = String::new(); stdin() .read_line(&mut input).ok().expect("Error reading user input"); self.memory[self.pointer as usize] = input.bytes().next().expect("no byte read") as u8; } fn increment(&mut self) { self.memory[self.pointer as usize] += 1; } fn decrement(&mut self) { self.memory[self.pointer as usize] -= 1; } fn output(&self) { print!("{}", (self.memory[self.pointer as usize]) as char); } fn jump(&mut self, program_counter: &mut usize) { let mut bal = 1i32; if self.memory[self.pointer as usize] == 0u8 { loop { *program_counter += 1; if self.ops[*program_counter] == Op::Jump { bal += 1; } else if self.ops[*program_counter] == Op::JumpBack { bal -= 1; } if bal == 0 { break; } } } } fn jump_back(&mut self, program_counter: &mut usize)
}
{ let mut bal = 0i32; loop { if self.ops[*program_counter] == Op::Jump { bal += 1; } else if self.ops[*program_counter] == Op::JumpBack { bal -= 1; } *program_counter -= 1; if bal == 0 { break; } } }
identifier_body
interpreter.rs
use std::io::{Read, stdin}; use operations::Op; pub struct Interpreter { memory: Vec<u8>, pointer: i64, ops: Vec<Op>, } impl Interpreter { pub fn new(ops: Vec<Op>) -> Interpreter { let m = (0.. 30000).map(|_| 0).collect(); Interpreter { memory: m, pointer: 0, ops: ops } } pub fn run(&mut self) { let mut program_counter = 0; while program_counter < self.ops.len() { match self.ops[program_counter] { Op::Increment => self.increment(), Op::Decrement => self.decrement(), Op::Output => self.output(), Op::Right => self.right(), Op::Left => self.left(), Op::Input => self.input(), Op::Jump => self.jump(&mut program_counter), Op::JumpBack => self.jump_back(&mut program_counter), _ => panic!("boom"), } program_counter += 1; } println!(""); } fn left(&mut self) { self.pointer -= 1; } fn right(&mut self) { self.pointer += 1; } fn input(&mut self) { let mut input = String::new(); stdin() .read_line(&mut input).ok().expect("Error reading user input"); self.memory[self.pointer as usize] = input.bytes().next().expect("no byte read") as u8; } fn increment(&mut self) { self.memory[self.pointer as usize] += 1; } fn
(&mut self) { self.memory[self.pointer as usize] -= 1; } fn output(&self) { print!("{}", (self.memory[self.pointer as usize]) as char); } fn jump(&mut self, program_counter: &mut usize) { let mut bal = 1i32; if self.memory[self.pointer as usize] == 0u8 { loop { *program_counter += 1; if self.ops[*program_counter] == Op::Jump { bal += 1; } else if self.ops[*program_counter] == Op::JumpBack { bal -= 1; } if bal == 0 { break; } } } } fn jump_back(&mut self, program_counter: &mut usize) { let mut bal = 0i32; loop { if self.ops[*program_counter] == Op::Jump { bal += 1; } else if self.ops[*program_counter] == Op::JumpBack { bal -= 1; } *program_counter -= 1; if bal == 0 { break; } } } }
decrement
identifier_name
interpreter.rs
use std::io::{Read, stdin}; use operations::Op; pub struct Interpreter { memory: Vec<u8>, pointer: i64, ops: Vec<Op>, } impl Interpreter { pub fn new(ops: Vec<Op>) -> Interpreter { let m = (0.. 30000).map(|_| 0).collect(); Interpreter { memory: m, pointer: 0, ops: ops } } pub fn run(&mut self) { let mut program_counter = 0; while program_counter < self.ops.len() { match self.ops[program_counter] { Op::Increment => self.increment(), Op::Decrement => self.decrement(), Op::Output => self.output(), Op::Right => self.right(), Op::Left => self.left(), Op::Input => self.input(), Op::Jump => self.jump(&mut program_counter), Op::JumpBack => self.jump_back(&mut program_counter), _ => panic!("boom"), } program_counter += 1; } println!("");
self.pointer -= 1; } fn right(&mut self) { self.pointer += 1; } fn input(&mut self) { let mut input = String::new(); stdin() .read_line(&mut input).ok().expect("Error reading user input"); self.memory[self.pointer as usize] = input.bytes().next().expect("no byte read") as u8; } fn increment(&mut self) { self.memory[self.pointer as usize] += 1; } fn decrement(&mut self) { self.memory[self.pointer as usize] -= 1; } fn output(&self) { print!("{}", (self.memory[self.pointer as usize]) as char); } fn jump(&mut self, program_counter: &mut usize) { let mut bal = 1i32; if self.memory[self.pointer as usize] == 0u8 { loop { *program_counter += 1; if self.ops[*program_counter] == Op::Jump { bal += 1; } else if self.ops[*program_counter] == Op::JumpBack { bal -= 1; } if bal == 0 { break; } } } } fn jump_back(&mut self, program_counter: &mut usize) { let mut bal = 0i32; loop { if self.ops[*program_counter] == Op::Jump { bal += 1; } else if self.ops[*program_counter] == Op::JumpBack { bal -= 1; } *program_counter -= 1; if bal == 0 { break; } } } }
} fn left(&mut self) {
random_line_split
contracts.rs
// Copyright (C) 2013-2020 Blockstack PBC, a public benefit corporation // Copyright (C) 2020 Stacks Open Internet Foundation // // This program 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. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. use std::convert::TryInto; use vm::ast::ContractAST; use vm::callables::CallableType; use vm::contexts::{ContractContext, Environment, GlobalContext, LocalContext}; use vm::errors::InterpreterResult as Result; use vm::representations::SymbolicExpression; use vm::types::QualifiedContractIdentifier; use vm::{apply, eval_all, Value}; #[derive(Serialize, Deserialize)] pub struct Contract { pub contract_context: ContractContext, } // AARON: this is an increasingly useless wrapper around a ContractContext struct. // will probably be removed soon. impl Contract { pub fn initialize_from_ast( contract_identifier: QualifiedContractIdentifier, contract: &ContractAST, global_context: &mut GlobalContext, ) -> Result<Contract> { let mut contract_context = ContractContext::new(contract_identifier); eval_all(&contract.expressions, &mut contract_context, global_context)?; Ok(Contract { contract_context: contract_context, }) } }
random_line_split
contracts.rs
// Copyright (C) 2013-2020 Blockstack PBC, a public benefit corporation // Copyright (C) 2020 Stacks Open Internet Foundation // // This program 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. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. use std::convert::TryInto; use vm::ast::ContractAST; use vm::callables::CallableType; use vm::contexts::{ContractContext, Environment, GlobalContext, LocalContext}; use vm::errors::InterpreterResult as Result; use vm::representations::SymbolicExpression; use vm::types::QualifiedContractIdentifier; use vm::{apply, eval_all, Value}; #[derive(Serialize, Deserialize)] pub struct
{ pub contract_context: ContractContext, } // AARON: this is an increasingly useless wrapper around a ContractContext struct. // will probably be removed soon. impl Contract { pub fn initialize_from_ast( contract_identifier: QualifiedContractIdentifier, contract: &ContractAST, global_context: &mut GlobalContext, ) -> Result<Contract> { let mut contract_context = ContractContext::new(contract_identifier); eval_all(&contract.expressions, &mut contract_context, global_context)?; Ok(Contract { contract_context: contract_context, }) } }
Contract
identifier_name
regression_fuzz.rs
// These tests are only run for the "default" test target because some of them // can take quite a long time. Some of them take long enough that it's not // practical to run them in debug mode. :-/ // See: https://oss-fuzz.com/testcase-detail/5673225499181056 // // Ignored by default since it takes too long in debug mode (almost a minute). #[test] #[ignore] fn fuzz1()
// See: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=26505 // See: https://github.com/rust-lang/regex/issues/722 #[test] fn empty_any_errors_no_panic() { assert!(regex_new!(r"\P{any}").is_err()); } // This tests that a very large regex errors during compilation instead of // using gratuitous amounts of memory. The specific problem is that the // compiler wasn't accounting for the memory used by Unicode character classes // correctly. // // See: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=33579 #[test] fn big_regex_fails_to_compile() { let pat = "[\u{0}\u{e}\u{2}\\w~~>[l\t\u{0}]p?<]{971158}"; assert!(regex_new!(pat).is_err()); }
{ regex!(r"1}{55}{0}*{1}{55}{55}{5}*{1}{55}+{56}|;**"); }
identifier_body
regression_fuzz.rs
// These tests are only run for the "default" test target because some of them // can take quite a long time. Some of them take long enough that it's not // practical to run them in debug mode. :-/
#[test] #[ignore] fn fuzz1() { regex!(r"1}{55}{0}*{1}{55}{55}{5}*{1}{55}+{56}|;**"); } // See: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=26505 // See: https://github.com/rust-lang/regex/issues/722 #[test] fn empty_any_errors_no_panic() { assert!(regex_new!(r"\P{any}").is_err()); } // This tests that a very large regex errors during compilation instead of // using gratuitous amounts of memory. The specific problem is that the // compiler wasn't accounting for the memory used by Unicode character classes // correctly. // // See: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=33579 #[test] fn big_regex_fails_to_compile() { let pat = "[\u{0}\u{e}\u{2}\\w~~>[l\t\u{0}]p?<]{971158}"; assert!(regex_new!(pat).is_err()); }
// See: https://oss-fuzz.com/testcase-detail/5673225499181056 // // Ignored by default since it takes too long in debug mode (almost a minute).
random_line_split
regression_fuzz.rs
// These tests are only run for the "default" test target because some of them // can take quite a long time. Some of them take long enough that it's not // practical to run them in debug mode. :-/ // See: https://oss-fuzz.com/testcase-detail/5673225499181056 // // Ignored by default since it takes too long in debug mode (almost a minute). #[test] #[ignore] fn
() { regex!(r"1}{55}{0}*{1}{55}{55}{5}*{1}{55}+{56}|;**"); } // See: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=26505 // See: https://github.com/rust-lang/regex/issues/722 #[test] fn empty_any_errors_no_panic() { assert!(regex_new!(r"\P{any}").is_err()); } // This tests that a very large regex errors during compilation instead of // using gratuitous amounts of memory. The specific problem is that the // compiler wasn't accounting for the memory used by Unicode character classes // correctly. // // See: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=33579 #[test] fn big_regex_fails_to_compile() { let pat = "[\u{0}\u{e}\u{2}\\w~~>[l\t\u{0}]p?<]{971158}"; assert!(regex_new!(pat).is_err()); }
fuzz1
identifier_name
lexer.rs
pub type Spanned<Tok, Loc, Error> = Result<(Loc, Tok, Loc), Error>; #[derive(Debug)] pub enum Tok { Space, Tab, Linefeed, } #[derive(Debug)] pub enum LexicalError { // Not possible } use std::str::CharIndices; pub struct
<'input> { chars: CharIndices<'input>, } impl<'input> Lexer<'input> { pub fn new(input: &'input str) -> Self { Lexer { chars: input.char_indices() } } } impl<'input> Iterator for Lexer<'input> { type Item = Spanned<Tok, usize, LexicalError>; fn next(&mut self) -> Option<Self::Item> { loop { match self.chars.next() { Some((i,'')) => return Some(Ok((i, Tok::Space, i+1))), Some((i, '\t')) => return Some(Ok((i, Tok::Tab, i+1))), Some((i, '\n')) => return Some(Ok((i, Tok::Linefeed, i+1))), None => return None, // End of file _ => continue, // Comment; skip this character } } } } #[test] fn skip_comments() { let source = "The quick brown fox jumped over the lazy dog"; assert_eq!(Lexer::new(source).count(), 8); assert!(Lexer::new(source).all(|tok| match tok { Ok((_, Tok::Space, _)) => true, _ => false, })); }
Lexer
identifier_name
lexer.rs
pub type Spanned<Tok, Loc, Error> = Result<(Loc, Tok, Loc), Error>; #[derive(Debug)] pub enum Tok { Space, Tab, Linefeed, } #[derive(Debug)] pub enum LexicalError { // Not possible } use std::str::CharIndices; pub struct Lexer<'input> { chars: CharIndices<'input>, } impl<'input> Lexer<'input> { pub fn new(input: &'input str) -> Self {
} } impl<'input> Iterator for Lexer<'input> { type Item = Spanned<Tok, usize, LexicalError>; fn next(&mut self) -> Option<Self::Item> { loop { match self.chars.next() { Some((i,'')) => return Some(Ok((i, Tok::Space, i+1))), Some((i, '\t')) => return Some(Ok((i, Tok::Tab, i+1))), Some((i, '\n')) => return Some(Ok((i, Tok::Linefeed, i+1))), None => return None, // End of file _ => continue, // Comment; skip this character } } } } #[test] fn skip_comments() { let source = "The quick brown fox jumped over the lazy dog"; assert_eq!(Lexer::new(source).count(), 8); assert!(Lexer::new(source).all(|tok| match tok { Ok((_, Tok::Space, _)) => true, _ => false, })); }
Lexer { chars: input.char_indices() }
random_line_split
lib.rs
#![deny(missing_docs, missing_debug_implementations, missing_copy_implementations, trivial_casts, trivial_numeric_casts, unsafe_code, unstable_features, unused_import_braces, unused_qualifications)] #![doc(html_root_url = "https://cannon10100.github.io/factor_graph/")] //! Crate allowing creation and manipulation of probabilistic factor graphs. extern crate dot; mod render; pub mod variable; pub mod factor; pub mod tree; use std::collections::HashMap; use std::collections::VecDeque; use std::io::Write; pub use variable::{Variable, DiscreteVariable}; pub use factor::Factor; pub use tree::{SpanningTree, TreeNode}; type PotentialFunc = fn(&[u32]) -> i32; /// Trait representing a generic item stored in the factor graph. pub trait FactorGraphItem : std::fmt::Debug { /// Get the name of this item. fn get_name(&self) -> String; /// Get this item's id. fn get_id(&self) -> u32; /// Return whether the item is a factor. fn is_factor(&self) -> bool; /// Add this node to the spanning tree. fn add_to_tree(&self, parent_id: u32, tree: &mut SpanningTree); } /// Struct representing the full factor graph. #[derive(Debug)] pub struct FactorGraph { variables: HashMap<String, Box<Variable>>, factors: Vec<Factor>, next_id: u32, all_names: Vec<String>, is_factor: Vec<bool>, } impl FactorGraph { /// Create an empty FactorGraph pub fn new() -> FactorGraph { FactorGraph { variables: HashMap::new(), factors: vec!(), next_id: 0, all_names: vec!(), is_factor: vec!(), } } /// Add a new variable with the specified name to the factor graph. pub fn add_discrete_var<T : std::fmt::Debug + Clone +'static>(&mut self, name: &str, val_names: Vec<T>) { let new_var = DiscreteVariable::new(self.next_id, name, val_names.clone()); self.variables.insert(String::from(name), Box::new(new_var)); self.all_names.insert(self.next_id as usize, String::from(name)); self.is_factor.insert(self.next_id as usize, false); self.next_id += 1; } /// Add a new factor with the specified variables to the factor graph. pub fn add_factor<T: std::fmt::Debug +'static>(&mut self, variables: Vec<String>, func: PotentialFunc)
/// Render this graph to a Graphviz file pub fn render_to<W: Write>(&self, output: &mut W) { match dot::render(self, output) { Ok(_) => println!("Wrote factor graph"), Err(_) => panic!("An error occurred writing the factor graph"), } } /// Make a spanning tree from the current factor graph with the specified root variable. pub fn make_spanning_tree(&self, var: &str) -> SpanningTree { let root = match self.variables.get(var) { Some(v) => v, None => panic!("Root variable not found") }; let mut spanning_tree = SpanningTree::new(root.get_id(), &root.get_name(), self.variables.values().len()); let mut var_iteration = true; let mut var_queue: VecDeque<&Box<Variable>> = VecDeque::new(); let mut factor_queue: VecDeque<&Factor> = VecDeque::new(); var_queue.push_back(root); // BFS through the graph, recording the spanning tree. while!var_queue.is_empty() ||!factor_queue.is_empty() { if var_iteration { let node = match var_queue.pop_front() { Some(x) => x, None => panic!("Queue is unexpectedly empty") }; for factor in node.get_factors() { if!spanning_tree.has_node(factor.get_id()) { spanning_tree.add_child((*node).get_id(), factor.get_id(), &factor.get_name()); if factor_queue.iter().filter(|x| (*x).get_id() == factor.get_id()).count() == 0 { factor_queue.push_back(factor); } } } if var_queue.is_empty() { var_iteration = false; } } else { let node = match factor_queue.pop_front() { Some(x) => x, None => panic!("Queue is unexpectedly empty") }; for var_name in node.get_variables() { let var = match self.variables.get(var_name) { Some(x) => x, None => panic!("Could not find variable with name {}", var_name) }; if!spanning_tree.has_node(var.get_id()) { spanning_tree.add_child(node.get_id(), var.get_id(), &var.get_name()); if var_queue.iter().filter(|x| x.get_id() == var.get_id()).count() == 0 { var_queue.push_back(var); } } } if factor_queue.is_empty() { var_iteration = true; } } } spanning_tree } /// Render a spanning tree for the factor graph to the input file, starting from the input variable. pub fn render_spanning_tree_to<W: Write>(&self, root_var: &str, output: &mut W) { self.make_spanning_tree(root_var).render_to(output) } } #[cfg(test)] mod tests { use super::*; fn dummy_func(args: &[u32]) -> i32 { args.len() as i32 } #[test] #[should_panic] fn factor_with_nonexistent_var() { let mut graph = FactorGraph::new(); graph.add_discrete_var("first", vec![1, 2]); graph.add_factor::<i32>(vec!(String::from("second")), dummy_func); } #[test] fn factor_is_added_to_var() { let mut graph = FactorGraph::new(); graph.add_discrete_var("first", vec![1, 2]); graph.add_factor::<i32>(vec!(String::from("first")), dummy_func); assert_eq!(graph.variables.get("first").unwrap().get_factors()[0].get_variables(), graph.factors[0].get_variables()) } }
{ for var in variables.iter() { match self.variables.get_mut(var) { Some(var_obj) => { var_obj.add_factor(Factor::new(self.next_id,variables.clone(), func)); }, None => panic!("The variable {} was not found in the factor graph.", var) } } self.factors.push(Factor::new(self.next_id, variables.clone(), func)); self.all_names.insert(self.next_id as usize, String::from(format!("factor<{:?}>", variables.clone()))); self.is_factor.insert(self.next_id as usize, true); self.next_id += 1; }
identifier_body
lib.rs
#![deny(missing_docs, missing_debug_implementations, missing_copy_implementations, trivial_casts, trivial_numeric_casts, unsafe_code, unstable_features, unused_import_braces, unused_qualifications)] #![doc(html_root_url = "https://cannon10100.github.io/factor_graph/")] //! Crate allowing creation and manipulation of probabilistic factor graphs. extern crate dot; mod render; pub mod variable; pub mod factor; pub mod tree; use std::collections::HashMap; use std::collections::VecDeque; use std::io::Write; pub use variable::{Variable, DiscreteVariable}; pub use factor::Factor; pub use tree::{SpanningTree, TreeNode}; type PotentialFunc = fn(&[u32]) -> i32; /// Trait representing a generic item stored in the factor graph. pub trait FactorGraphItem : std::fmt::Debug { /// Get the name of this item. fn get_name(&self) -> String; /// Get this item's id. fn get_id(&self) -> u32; /// Return whether the item is a factor. fn is_factor(&self) -> bool; /// Add this node to the spanning tree. fn add_to_tree(&self, parent_id: u32, tree: &mut SpanningTree); } /// Struct representing the full factor graph. #[derive(Debug)] pub struct FactorGraph { variables: HashMap<String, Box<Variable>>, factors: Vec<Factor>, next_id: u32, all_names: Vec<String>, is_factor: Vec<bool>, } impl FactorGraph { /// Create an empty FactorGraph pub fn new() -> FactorGraph { FactorGraph { variables: HashMap::new(), factors: vec!(), next_id: 0, all_names: vec!(), is_factor: vec!(), } } /// Add a new variable with the specified name to the factor graph. pub fn add_discrete_var<T : std::fmt::Debug + Clone +'static>(&mut self, name: &str, val_names: Vec<T>) { let new_var = DiscreteVariable::new(self.next_id, name, val_names.clone()); self.variables.insert(String::from(name), Box::new(new_var)); self.all_names.insert(self.next_id as usize, String::from(name)); self.is_factor.insert(self.next_id as usize, false); self.next_id += 1; } /// Add a new factor with the specified variables to the factor graph. pub fn add_factor<T: std::fmt::Debug +'static>(&mut self, variables: Vec<String>, func: PotentialFunc) { for var in variables.iter() { match self.variables.get_mut(var) { Some(var_obj) => { var_obj.add_factor(Factor::new(self.next_id,variables.clone(), func)); }, None => panic!("The variable {} was not found in the factor graph.", var) } } self.factors.push(Factor::new(self.next_id, variables.clone(), func)); self.all_names.insert(self.next_id as usize, String::from(format!("factor<{:?}>", variables.clone()))); self.is_factor.insert(self.next_id as usize, true); self.next_id += 1; } /// Render this graph to a Graphviz file pub fn render_to<W: Write>(&self, output: &mut W) { match dot::render(self, output) { Ok(_) => println!("Wrote factor graph"), Err(_) => panic!("An error occurred writing the factor graph"), } } /// Make a spanning tree from the current factor graph with the specified root variable. pub fn make_spanning_tree(&self, var: &str) -> SpanningTree { let root = match self.variables.get(var) { Some(v) => v, None => panic!("Root variable not found") }; let mut spanning_tree = SpanningTree::new(root.get_id(), &root.get_name(), self.variables.values().len()); let mut var_iteration = true; let mut var_queue: VecDeque<&Box<Variable>> = VecDeque::new(); let mut factor_queue: VecDeque<&Factor> = VecDeque::new(); var_queue.push_back(root); // BFS through the graph, recording the spanning tree. while!var_queue.is_empty() ||!factor_queue.is_empty() { if var_iteration { let node = match var_queue.pop_front() { Some(x) => x, None => panic!("Queue is unexpectedly empty") }; for factor in node.get_factors() { if!spanning_tree.has_node(factor.get_id()) { spanning_tree.add_child((*node).get_id(), factor.get_id(), &factor.get_name()); if factor_queue.iter().filter(|x| (*x).get_id() == factor.get_id()).count() == 0 { factor_queue.push_back(factor); } } } if var_queue.is_empty() { var_iteration = false; } } else { let node = match factor_queue.pop_front() { Some(x) => x, None => panic!("Queue is unexpectedly empty") }; for var_name in node.get_variables() { let var = match self.variables.get(var_name) { Some(x) => x, None => panic!("Could not find variable with name {}", var_name) }; if!spanning_tree.has_node(var.get_id()) { spanning_tree.add_child(node.get_id(), var.get_id(), &var.get_name()); if var_queue.iter().filter(|x| x.get_id() == var.get_id()).count() == 0 { var_queue.push_back(var); } } } if factor_queue.is_empty() { var_iteration = true; } } } spanning_tree } /// Render a spanning tree for the factor graph to the input file, starting from the input variable. pub fn render_spanning_tree_to<W: Write>(&self, root_var: &str, output: &mut W) { self.make_spanning_tree(root_var).render_to(output) } } #[cfg(test)]
mod tests { use super::*; fn dummy_func(args: &[u32]) -> i32 { args.len() as i32 } #[test] #[should_panic] fn factor_with_nonexistent_var() { let mut graph = FactorGraph::new(); graph.add_discrete_var("first", vec![1, 2]); graph.add_factor::<i32>(vec!(String::from("second")), dummy_func); } #[test] fn factor_is_added_to_var() { let mut graph = FactorGraph::new(); graph.add_discrete_var("first", vec![1, 2]); graph.add_factor::<i32>(vec!(String::from("first")), dummy_func); assert_eq!(graph.variables.get("first").unwrap().get_factors()[0].get_variables(), graph.factors[0].get_variables()) } }
random_line_split
lib.rs
#![deny(missing_docs, missing_debug_implementations, missing_copy_implementations, trivial_casts, trivial_numeric_casts, unsafe_code, unstable_features, unused_import_braces, unused_qualifications)] #![doc(html_root_url = "https://cannon10100.github.io/factor_graph/")] //! Crate allowing creation and manipulation of probabilistic factor graphs. extern crate dot; mod render; pub mod variable; pub mod factor; pub mod tree; use std::collections::HashMap; use std::collections::VecDeque; use std::io::Write; pub use variable::{Variable, DiscreteVariable}; pub use factor::Factor; pub use tree::{SpanningTree, TreeNode}; type PotentialFunc = fn(&[u32]) -> i32; /// Trait representing a generic item stored in the factor graph. pub trait FactorGraphItem : std::fmt::Debug { /// Get the name of this item. fn get_name(&self) -> String; /// Get this item's id. fn get_id(&self) -> u32; /// Return whether the item is a factor. fn is_factor(&self) -> bool; /// Add this node to the spanning tree. fn add_to_tree(&self, parent_id: u32, tree: &mut SpanningTree); } /// Struct representing the full factor graph. #[derive(Debug)] pub struct FactorGraph { variables: HashMap<String, Box<Variable>>, factors: Vec<Factor>, next_id: u32, all_names: Vec<String>, is_factor: Vec<bool>, } impl FactorGraph { /// Create an empty FactorGraph pub fn new() -> FactorGraph { FactorGraph { variables: HashMap::new(), factors: vec!(), next_id: 0, all_names: vec!(), is_factor: vec!(), } } /// Add a new variable with the specified name to the factor graph. pub fn add_discrete_var<T : std::fmt::Debug + Clone +'static>(&mut self, name: &str, val_names: Vec<T>) { let new_var = DiscreteVariable::new(self.next_id, name, val_names.clone()); self.variables.insert(String::from(name), Box::new(new_var)); self.all_names.insert(self.next_id as usize, String::from(name)); self.is_factor.insert(self.next_id as usize, false); self.next_id += 1; } /// Add a new factor with the specified variables to the factor graph. pub fn add_factor<T: std::fmt::Debug +'static>(&mut self, variables: Vec<String>, func: PotentialFunc) { for var in variables.iter() { match self.variables.get_mut(var) { Some(var_obj) => { var_obj.add_factor(Factor::new(self.next_id,variables.clone(), func)); }, None => panic!("The variable {} was not found in the factor graph.", var) } } self.factors.push(Factor::new(self.next_id, variables.clone(), func)); self.all_names.insert(self.next_id as usize, String::from(format!("factor<{:?}>", variables.clone()))); self.is_factor.insert(self.next_id as usize, true); self.next_id += 1; } /// Render this graph to a Graphviz file pub fn render_to<W: Write>(&self, output: &mut W) { match dot::render(self, output) { Ok(_) => println!("Wrote factor graph"), Err(_) => panic!("An error occurred writing the factor graph"), } } /// Make a spanning tree from the current factor graph with the specified root variable. pub fn make_spanning_tree(&self, var: &str) -> SpanningTree { let root = match self.variables.get(var) { Some(v) => v, None => panic!("Root variable not found") }; let mut spanning_tree = SpanningTree::new(root.get_id(), &root.get_name(), self.variables.values().len()); let mut var_iteration = true; let mut var_queue: VecDeque<&Box<Variable>> = VecDeque::new(); let mut factor_queue: VecDeque<&Factor> = VecDeque::new(); var_queue.push_back(root); // BFS through the graph, recording the spanning tree. while!var_queue.is_empty() ||!factor_queue.is_empty() { if var_iteration { let node = match var_queue.pop_front() { Some(x) => x, None => panic!("Queue is unexpectedly empty") }; for factor in node.get_factors() { if!spanning_tree.has_node(factor.get_id()) { spanning_tree.add_child((*node).get_id(), factor.get_id(), &factor.get_name()); if factor_queue.iter().filter(|x| (*x).get_id() == factor.get_id()).count() == 0 { factor_queue.push_back(factor); } } } if var_queue.is_empty() { var_iteration = false; } } else { let node = match factor_queue.pop_front() { Some(x) => x, None => panic!("Queue is unexpectedly empty") }; for var_name in node.get_variables() { let var = match self.variables.get(var_name) { Some(x) => x, None => panic!("Could not find variable with name {}", var_name) }; if!spanning_tree.has_node(var.get_id()) { spanning_tree.add_child(node.get_id(), var.get_id(), &var.get_name()); if var_queue.iter().filter(|x| x.get_id() == var.get_id()).count() == 0 { var_queue.push_back(var); } } } if factor_queue.is_empty() { var_iteration = true; } } } spanning_tree } /// Render a spanning tree for the factor graph to the input file, starting from the input variable. pub fn
<W: Write>(&self, root_var: &str, output: &mut W) { self.make_spanning_tree(root_var).render_to(output) } } #[cfg(test)] mod tests { use super::*; fn dummy_func(args: &[u32]) -> i32 { args.len() as i32 } #[test] #[should_panic] fn factor_with_nonexistent_var() { let mut graph = FactorGraph::new(); graph.add_discrete_var("first", vec![1, 2]); graph.add_factor::<i32>(vec!(String::from("second")), dummy_func); } #[test] fn factor_is_added_to_var() { let mut graph = FactorGraph::new(); graph.add_discrete_var("first", vec![1, 2]); graph.add_factor::<i32>(vec!(String::from("first")), dummy_func); assert_eq!(graph.variables.get("first").unwrap().get_factors()[0].get_variables(), graph.factors[0].get_variables()) } }
render_spanning_tree_to
identifier_name
aliased.rs
use backend::Backend; use expression::{Expression, NonAggregate, SelectableExpression}; use query_builder::*; use query_builder::nodes::{Identifier, InfixNode}; use query_source::*; #[derive(Debug, Clone, Copy)] pub struct
<'a, Expr> { expr: Expr, alias: &'a str, } impl<'a, Expr> Aliased<'a, Expr> { pub fn new(expr: Expr, alias: &'a str) -> Self { Aliased { expr: expr, alias: alias, } } } pub struct FromEverywhere; impl<'a, T> Expression for Aliased<'a, T> where T: Expression, { type SqlType = T::SqlType; } impl<'a, T, DB> QueryFragment<DB> for Aliased<'a, T> where DB: Backend, T: QueryFragment<DB>, { fn to_sql(&self, out: &mut DB::QueryBuilder) -> BuildQueryResult { out.push_identifier(&self.alias) } } // FIXME This is incorrect, should only be selectable from WithQuerySource impl<'a, T, QS> SelectableExpression<QS> for Aliased<'a, T> where Aliased<'a, T>: Expression, { } impl<'a, T: Expression + Copy> QuerySource for Aliased<'a, T> { type FromClause = InfixNode<'static, T, Identifier<'a>>; fn from_clause(&self) -> Self::FromClause { InfixNode::new(self.expr, Identifier(self.alias), " ") } } impl<'a, T> NonAggregate for Aliased<'a, T> where Aliased<'a, T>: Expression { }
Aliased
identifier_name
aliased.rs
use backend::Backend; use expression::{Expression, NonAggregate, SelectableExpression}; use query_builder::*; use query_builder::nodes::{Identifier, InfixNode}; use query_source::*; #[derive(Debug, Clone, Copy)] pub struct Aliased<'a, Expr> { expr: Expr, alias: &'a str, } impl<'a, Expr> Aliased<'a, Expr> { pub fn new(expr: Expr, alias: &'a str) -> Self { Aliased { expr: expr, alias: alias, } } } pub struct FromEverywhere; impl<'a, T> Expression for Aliased<'a, T> where T: Expression, { type SqlType = T::SqlType; }
fn to_sql(&self, out: &mut DB::QueryBuilder) -> BuildQueryResult { out.push_identifier(&self.alias) } } // FIXME This is incorrect, should only be selectable from WithQuerySource impl<'a, T, QS> SelectableExpression<QS> for Aliased<'a, T> where Aliased<'a, T>: Expression, { } impl<'a, T: Expression + Copy> QuerySource for Aliased<'a, T> { type FromClause = InfixNode<'static, T, Identifier<'a>>; fn from_clause(&self) -> Self::FromClause { InfixNode::new(self.expr, Identifier(self.alias), " ") } } impl<'a, T> NonAggregate for Aliased<'a, T> where Aliased<'a, T>: Expression { }
impl<'a, T, DB> QueryFragment<DB> for Aliased<'a, T> where DB: Backend, T: QueryFragment<DB>, {
random_line_split
aliased.rs
use backend::Backend; use expression::{Expression, NonAggregate, SelectableExpression}; use query_builder::*; use query_builder::nodes::{Identifier, InfixNode}; use query_source::*; #[derive(Debug, Clone, Copy)] pub struct Aliased<'a, Expr> { expr: Expr, alias: &'a str, } impl<'a, Expr> Aliased<'a, Expr> { pub fn new(expr: Expr, alias: &'a str) -> Self
} pub struct FromEverywhere; impl<'a, T> Expression for Aliased<'a, T> where T: Expression, { type SqlType = T::SqlType; } impl<'a, T, DB> QueryFragment<DB> for Aliased<'a, T> where DB: Backend, T: QueryFragment<DB>, { fn to_sql(&self, out: &mut DB::QueryBuilder) -> BuildQueryResult { out.push_identifier(&self.alias) } } // FIXME This is incorrect, should only be selectable from WithQuerySource impl<'a, T, QS> SelectableExpression<QS> for Aliased<'a, T> where Aliased<'a, T>: Expression, { } impl<'a, T: Expression + Copy> QuerySource for Aliased<'a, T> { type FromClause = InfixNode<'static, T, Identifier<'a>>; fn from_clause(&self) -> Self::FromClause { InfixNode::new(self.expr, Identifier(self.alias), " ") } } impl<'a, T> NonAggregate for Aliased<'a, T> where Aliased<'a, T>: Expression { }
{ Aliased { expr: expr, alias: alias, } }
identifier_body
font.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 euclid::{Point2D, Rect, Size2D}; use smallvec::SmallVec; use std::borrow::ToOwned; use std::cell::RefCell; use std::mem; use std::rc::Rc; use std::slice; use std::sync::Arc; use style::computed_values::{font_stretch, font_variant, font_weight}; use style::properties::style_structs::Font as FontStyle; use util::cache::HashCache; use font_template::FontTemplateDescriptor; use platform::font::{FontHandle, FontTable}; use platform::font_context::FontContextHandle; use platform::font_template::FontTemplateData; use text::Shaper; use text::glyph::{GlyphStore, GlyphId}; use text::shaping::ShaperMethods; use util::geometry::Au; // FontHandle encapsulates access to the platform's font API, // e.g. quartz, FreeType. It provides access to metrics and tables // needed by the text shaper as well as access to the underlying font // resources needed by the graphics layer to draw glyphs. pub trait FontHandleMethods { fn new_from_template(fctx: &FontContextHandle, template: Arc<FontTemplateData>, pt_size: Option<Au>) -> Result<Self,()>; fn template(&self) -> Arc<FontTemplateData>; fn family_name(&self) -> String; fn face_name(&self) -> String; fn is_italic(&self) -> bool; fn boldness(&self) -> font_weight::T; fn stretchiness(&self) -> font_stretch::T; fn glyph_index(&self, codepoint: char) -> Option<GlyphId>; fn glyph_h_advance(&self, GlyphId) -> Option<FractionalPixel>; fn glyph_h_kerning(&self, GlyphId, GlyphId) -> FractionalPixel; fn metrics(&self) -> FontMetrics; fn get_table_for_tag(&self, FontTableTag) -> Option<FontTable>; } // Used to abstract over the shaper's choice of fixed int representation. pub type FractionalPixel = f64; pub type FontTableTag = u32; pub trait FontTableTagConversions { fn tag_to_str(&self) -> String; } impl FontTableTagConversions for FontTableTag { fn tag_to_str(&self) -> String { unsafe { let pointer = mem::transmute::<&u32, *const u8>(self); let mut bytes = slice::from_raw_parts(pointer, 4).to_vec(); bytes.reverse(); String::from_utf8_unchecked(bytes) } } } pub trait FontTableMethods { fn with_buffer<F>(&self, F) where F: FnOnce(*const u8, usize); } #[derive(Clone, Debug, Deserialize, Serialize)] pub struct FontMetrics { pub underline_size: Au, pub underline_offset: Au, pub strikeout_size: Au, pub strikeout_offset: Au, pub leading: Au, pub x_height: Au, pub em_size: Au, pub ascent: Au, pub descent: Au, pub max_advance: Au, pub average_advance: Au, pub line_gap: Au, } pub type SpecifiedFontStyle = FontStyle; pub struct Font { pub handle: FontHandle, pub metrics: FontMetrics, pub variant: font_variant::T, pub descriptor: FontTemplateDescriptor, pub requested_pt_size: Au, pub actual_pt_size: Au, pub shaper: Option<Shaper>, pub shape_cache: HashCache<ShapeCacheEntry, Arc<GlyphStore>>, pub glyph_advance_cache: HashCache<u32, FractionalPixel>, } bitflags! { flags ShapingFlags: u8 { #[doc = "Set if the text is entirely whitespace."] const IS_WHITESPACE_SHAPING_FLAG = 0x01, #[doc = "Set if we are to ignore ligatures."] const IGNORE_LIGATURES_SHAPING_FLAG = 0x02, #[doc = "Set if we are to disable kerning."] const DISABLE_KERNING_SHAPING_FLAG = 0x04, #[doc = "Text direction is right-to-left."] const RTL_FLAG = 0x08, } } /// Various options that control text shaping. #[derive(Clone, Eq, PartialEq, Hash, Copy)] pub struct
{ /// Spacing to add between each letter. Corresponds to the CSS 2.1 `letter-spacing` property. /// NB: You will probably want to set the `IGNORE_LIGATURES_SHAPING_FLAG` if this is non-null. pub letter_spacing: Option<Au>, /// Spacing to add between each word. Corresponds to the CSS 2.1 `word-spacing` property. pub word_spacing: Au, /// Various flags. pub flags: ShapingFlags, } /// An entry in the shape cache. #[derive(Clone, Eq, PartialEq, Hash)] pub struct ShapeCacheEntry { text: String, options: ShapingOptions, } impl Font { pub fn shape_text(&mut self, text: &str, options: &ShapingOptions) -> Arc<GlyphStore> { self.make_shaper(options); //FIXME: find the equivalent of Equiv and the old ShapeCacheEntryRef let shaper = &self.shaper; let lookup_key = ShapeCacheEntry { text: text.to_owned(), options: options.clone(), }; if let Some(glyphs) = self.shape_cache.find(&lookup_key) { return glyphs.clone(); } let mut glyphs = GlyphStore::new(text.chars().count(), options.flags.contains(IS_WHITESPACE_SHAPING_FLAG), options.flags.contains(RTL_FLAG)); shaper.as_ref().unwrap().shape_text(text, options, &mut glyphs); let glyphs = Arc::new(glyphs); self.shape_cache.insert(ShapeCacheEntry { text: text.to_owned(), options: *options, }, glyphs.clone()); glyphs } fn make_shaper<'a>(&'a mut self, options: &ShapingOptions) -> &'a Shaper { // fast path: already created a shaper if let Some(ref mut shaper) = self.shaper { shaper.set_options(options); return shaper } let shaper = Shaper::new(self, options); self.shaper = Some(shaper); self.shaper.as_ref().unwrap() } pub fn get_table_for_tag(&self, tag: FontTableTag) -> Option<FontTable> { let result = self.handle.get_table_for_tag(tag); let status = if result.is_some() { "Found" } else { "Didn't find" }; debug!("{} font table[{}] with family={}, face={}", status, tag.tag_to_str(), self.handle.family_name(), self.handle.face_name()); return result; } #[inline] pub fn glyph_index(&self, codepoint: char) -> Option<GlyphId> { let codepoint = match self.variant { font_variant::T::small_caps => codepoint.to_uppercase().next().unwrap(), //FIXME: #5938 font_variant::T::normal => codepoint, }; self.handle.glyph_index(codepoint) } pub fn glyph_h_kerning(&mut self, first_glyph: GlyphId, second_glyph: GlyphId) -> FractionalPixel { self.handle.glyph_h_kerning(first_glyph, second_glyph) } pub fn glyph_h_advance(&mut self, glyph: GlyphId) -> FractionalPixel { let handle = &self.handle; self.glyph_advance_cache.find_or_create(&glyph, |glyph| { match handle.glyph_h_advance(*glyph) { Some(adv) => adv, None => 10f64 as FractionalPixel // FIXME: Need fallback strategy } }) } } pub struct FontGroup { pub fonts: SmallVec<[Rc<RefCell<Font>>; 8]>, } impl FontGroup { pub fn new(fonts: SmallVec<[Rc<RefCell<Font>>; 8]>) -> FontGroup { FontGroup { fonts: fonts, } } } pub struct RunMetrics { // may be negative due to negative width (i.e., kerning of '.' in 'P.T.') pub advance_width: Au, pub ascent: Au, // nonzero pub descent: Au, // nonzero // this bounding box is relative to the left origin baseline. // so, bounding_box.position.y = -ascent pub bounding_box: Rect<Au> } impl RunMetrics { pub fn new(advance: Au, ascent: Au, descent: Au) -> RunMetrics { let bounds = Rect::new(Point2D::new(Au(0), -ascent), Size2D::new(advance, ascent + descent)); // TODO(Issue #125): support loose and tight bounding boxes; using the // ascent+descent and advance is sometimes too generous and // looking at actual glyph extents can yield a tighter box. RunMetrics { advance_width: advance, bounding_box: bounds, ascent: ascent, descent: descent, } } }
ShapingOptions
identifier_name
font.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 euclid::{Point2D, Rect, Size2D}; use smallvec::SmallVec; use std::borrow::ToOwned; use std::cell::RefCell; use std::mem; use std::rc::Rc; use std::slice; use std::sync::Arc; use style::computed_values::{font_stretch, font_variant, font_weight}; use style::properties::style_structs::Font as FontStyle; use util::cache::HashCache; use font_template::FontTemplateDescriptor; use platform::font::{FontHandle, FontTable}; use platform::font_context::FontContextHandle; use platform::font_template::FontTemplateData; use text::Shaper; use text::glyph::{GlyphStore, GlyphId}; use text::shaping::ShaperMethods; use util::geometry::Au; // FontHandle encapsulates access to the platform's font API, // e.g. quartz, FreeType. It provides access to metrics and tables // needed by the text shaper as well as access to the underlying font // resources needed by the graphics layer to draw glyphs. pub trait FontHandleMethods { fn new_from_template(fctx: &FontContextHandle, template: Arc<FontTemplateData>, pt_size: Option<Au>) -> Result<Self,()>; fn template(&self) -> Arc<FontTemplateData>; fn family_name(&self) -> String; fn face_name(&self) -> String; fn is_italic(&self) -> bool; fn boldness(&self) -> font_weight::T; fn stretchiness(&self) -> font_stretch::T; fn glyph_index(&self, codepoint: char) -> Option<GlyphId>; fn glyph_h_advance(&self, GlyphId) -> Option<FractionalPixel>; fn glyph_h_kerning(&self, GlyphId, GlyphId) -> FractionalPixel; fn metrics(&self) -> FontMetrics; fn get_table_for_tag(&self, FontTableTag) -> Option<FontTable>; } // Used to abstract over the shaper's choice of fixed int representation. pub type FractionalPixel = f64; pub type FontTableTag = u32; pub trait FontTableTagConversions { fn tag_to_str(&self) -> String; } impl FontTableTagConversions for FontTableTag { fn tag_to_str(&self) -> String { unsafe { let pointer = mem::transmute::<&u32, *const u8>(self); let mut bytes = slice::from_raw_parts(pointer, 4).to_vec(); bytes.reverse(); String::from_utf8_unchecked(bytes) } } } pub trait FontTableMethods { fn with_buffer<F>(&self, F) where F: FnOnce(*const u8, usize); } #[derive(Clone, Debug, Deserialize, Serialize)] pub struct FontMetrics { pub underline_size: Au, pub underline_offset: Au, pub strikeout_size: Au, pub strikeout_offset: Au, pub leading: Au, pub x_height: Au, pub em_size: Au, pub ascent: Au, pub descent: Au, pub max_advance: Au, pub average_advance: Au, pub line_gap: Au, } pub type SpecifiedFontStyle = FontStyle; pub struct Font { pub handle: FontHandle, pub metrics: FontMetrics, pub variant: font_variant::T, pub descriptor: FontTemplateDescriptor, pub requested_pt_size: Au, pub actual_pt_size: Au, pub shaper: Option<Shaper>, pub shape_cache: HashCache<ShapeCacheEntry, Arc<GlyphStore>>, pub glyph_advance_cache: HashCache<u32, FractionalPixel>, } bitflags! { flags ShapingFlags: u8 { #[doc = "Set if the text is entirely whitespace."] const IS_WHITESPACE_SHAPING_FLAG = 0x01, #[doc = "Set if we are to ignore ligatures."] const IGNORE_LIGATURES_SHAPING_FLAG = 0x02, #[doc = "Set if we are to disable kerning."] const DISABLE_KERNING_SHAPING_FLAG = 0x04, #[doc = "Text direction is right-to-left."] const RTL_FLAG = 0x08, } } /// Various options that control text shaping. #[derive(Clone, Eq, PartialEq, Hash, Copy)] pub struct ShapingOptions { /// Spacing to add between each letter. Corresponds to the CSS 2.1 `letter-spacing` property. /// NB: You will probably want to set the `IGNORE_LIGATURES_SHAPING_FLAG` if this is non-null. pub letter_spacing: Option<Au>, /// Spacing to add between each word. Corresponds to the CSS 2.1 `word-spacing` property. pub word_spacing: Au, /// Various flags. pub flags: ShapingFlags, } /// An entry in the shape cache. #[derive(Clone, Eq, PartialEq, Hash)] pub struct ShapeCacheEntry { text: String, options: ShapingOptions, } impl Font { pub fn shape_text(&mut self, text: &str, options: &ShapingOptions) -> Arc<GlyphStore> { self.make_shaper(options); //FIXME: find the equivalent of Equiv and the old ShapeCacheEntryRef let shaper = &self.shaper; let lookup_key = ShapeCacheEntry { text: text.to_owned(), options: options.clone(), }; if let Some(glyphs) = self.shape_cache.find(&lookup_key) { return glyphs.clone(); } let mut glyphs = GlyphStore::new(text.chars().count(), options.flags.contains(IS_WHITESPACE_SHAPING_FLAG), options.flags.contains(RTL_FLAG)); shaper.as_ref().unwrap().shape_text(text, options, &mut glyphs); let glyphs = Arc::new(glyphs); self.shape_cache.insert(ShapeCacheEntry { text: text.to_owned(), options: *options, }, glyphs.clone()); glyphs } fn make_shaper<'a>(&'a mut self, options: &ShapingOptions) -> &'a Shaper { // fast path: already created a shaper if let Some(ref mut shaper) = self.shaper { shaper.set_options(options); return shaper } let shaper = Shaper::new(self, options); self.shaper = Some(shaper); self.shaper.as_ref().unwrap() } pub fn get_table_for_tag(&self, tag: FontTableTag) -> Option<FontTable> { let result = self.handle.get_table_for_tag(tag); let status = if result.is_some() { "Found" } else { "Didn't find" }; debug!("{} font table[{}] with family={}, face={}", status, tag.tag_to_str(), self.handle.family_name(), self.handle.face_name()); return result; } #[inline] pub fn glyph_index(&self, codepoint: char) -> Option<GlyphId> { let codepoint = match self.variant { font_variant::T::small_caps => codepoint.to_uppercase().next().unwrap(), //FIXME: #5938 font_variant::T::normal => codepoint, }; self.handle.glyph_index(codepoint) } pub fn glyph_h_kerning(&mut self, first_glyph: GlyphId, second_glyph: GlyphId) -> FractionalPixel { self.handle.glyph_h_kerning(first_glyph, second_glyph) } pub fn glyph_h_advance(&mut self, glyph: GlyphId) -> FractionalPixel { let handle = &self.handle; self.glyph_advance_cache.find_or_create(&glyph, |glyph| { match handle.glyph_h_advance(*glyph) { Some(adv) => adv, None => 10f64 as FractionalPixel // FIXME: Need fallback strategy } }) } } pub struct FontGroup { pub fonts: SmallVec<[Rc<RefCell<Font>>; 8]>, } impl FontGroup { pub fn new(fonts: SmallVec<[Rc<RefCell<Font>>; 8]>) -> FontGroup { FontGroup { fonts: fonts, } } } pub struct RunMetrics { // may be negative due to negative width (i.e., kerning of '.' in 'P.T.') pub advance_width: Au, pub ascent: Au, // nonzero pub descent: Au, // nonzero
} impl RunMetrics { pub fn new(advance: Au, ascent: Au, descent: Au) -> RunMetrics { let bounds = Rect::new(Point2D::new(Au(0), -ascent), Size2D::new(advance, ascent + descent)); // TODO(Issue #125): support loose and tight bounding boxes; using the // ascent+descent and advance is sometimes too generous and // looking at actual glyph extents can yield a tighter box. RunMetrics { advance_width: advance, bounding_box: bounds, ascent: ascent, descent: descent, } } }
// this bounding box is relative to the left origin baseline. // so, bounding_box.position.y = -ascent pub bounding_box: Rect<Au>
random_line_split
hint.rs
use std::slice; use std::sync::Arc; use super::*; #[derive(Debug)] #[allow(dead_code)] pub enum StateOperation { Remove = 0, // _NET_WM_STATE_REMOVE Add = 1, // _NET_WM_STATE_ADD Toggle = 2, // _NET_WM_STATE_TOGGLE } impl From<bool> for StateOperation { fn from(op: bool) -> Self { if op { StateOperation::Add } else { StateOperation::Remove } } } /// X window type. Maps directly to /// [`_NET_WM_WINDOW_TYPE`](https://specifications.freedesktop.org/wm-spec/wm-spec-1.5.html). #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub enum WindowType { /// A desktop feature. This can include a single window containing desktop icons with the same dimensions as the /// screen, allowing the desktop environment to have full control of the desktop, without the need for proxying /// root window clicks. Desktop, /// A dock or panel feature. Typically a Window Manager would keep such windows on top of all other windows. Dock, /// Toolbar windows. "Torn off" from the main application. Toolbar, /// Pinnable menu windows. "Torn off" from the main application. Menu, /// A small persistent utility window, such as a palette or toolbox. Utility, /// The window is a splash screen displayed as an application is starting up. Splash, /// This is a dialog window. Dialog, /// A dropdown menu that usually appears when the user clicks on an item in a menu bar. /// This property is typically used on override-redirect windows. DropdownMenu, /// A popup menu that usually appears when the user right clicks on an object. /// This property is typically used on override-redirect windows. PopupMenu, /// A tooltip window. Usually used to show additional information when hovering over an object with the cursor. /// This property is typically used on override-redirect windows. Tooltip, /// The window is a notification. /// This property is typically used on override-redirect windows. Notification, /// This should be used on the windows that are popped up by combo boxes. /// This property is typically used on override-redirect windows. Combo, /// This indicates the the window is being dragged. /// This property is typically used on override-redirect windows. Dnd, /// This is a normal, top-level window. Normal, } impl Default for WindowType { fn default() -> Self { WindowType::Normal } } impl WindowType { pub(crate) fn as_atom(&self, xconn: &Arc<XConnection>) -> ffi::Atom { use self::WindowType::*; let atom_name: &[u8] = match *self { Desktop => b"_NET_WM_WINDOW_TYPE_DESKTOP\0", Dock => b"_NET_WM_WINDOW_TYPE_DOCK\0", Toolbar => b"_NET_WM_WINDOW_TYPE_TOOLBAR\0", Menu => b"_NET_WM_WINDOW_TYPE_MENU\0", Utility => b"_NET_WM_WINDOW_TYPE_UTILITY\0", Splash => b"_NET_WM_WINDOW_TYPE_SPLASH\0", Dialog => b"_NET_WM_WINDOW_TYPE_DIALOG\0", DropdownMenu => b"_NET_WM_WINDOW_TYPE_DROPDOWN_MENU\0", PopupMenu => b"_NET_WM_WINDOW_TYPE_POPUP_MENU\0", Tooltip => b"_NET_WM_WINDOW_TYPE_TOOLTIP\0", Notification => b"_NET_WM_WINDOW_TYPE_NOTIFICATION\0", Combo => b"_NET_WM_WINDOW_TYPE_COMBO\0", Dnd => b"_NET_WM_WINDOW_TYPE_DND\0", Normal => b"_NET_WM_WINDOW_TYPE_NORMAL\0", }; unsafe { xconn.get_atom_unchecked(atom_name) } } } pub struct MotifHints { hints: MwmHints, } #[repr(C)] struct MwmHints { flags: c_ulong, functions: c_ulong, decorations: c_ulong, input_mode: c_long, status: c_ulong, } #[allow(dead_code)] mod mwm { use libc::c_ulong; // Motif WM hints are obsolete, but still widely supported. // https://stackoverflow.com/a/1909708 pub const MWM_HINTS_FUNCTIONS: c_ulong = 1 << 0; pub const MWM_HINTS_DECORATIONS: c_ulong = 1 << 1; pub const MWM_FUNC_ALL: c_ulong = 1 << 0; pub const MWM_FUNC_RESIZE: c_ulong = 1 << 1; pub const MWM_FUNC_MOVE: c_ulong = 1 << 2; pub const MWM_FUNC_MINIMIZE: c_ulong = 1 << 3; pub const MWM_FUNC_MAXIMIZE: c_ulong = 1 << 4; pub const MWM_FUNC_CLOSE: c_ulong = 1 << 5; } impl MotifHints { pub fn new() -> MotifHints { MotifHints { hints: MwmHints { flags: 0, functions: 0, decorations: 0, input_mode: 0, status: 0, }, } } pub fn set_decorations(&mut self, decorations: bool) { self.hints.flags |= mwm::MWM_HINTS_DECORATIONS; self.hints.decorations = decorations as c_ulong; } pub fn set_maximizable(&mut self, maximizable: bool) { if maximizable { self.add_func(mwm::MWM_FUNC_MAXIMIZE); } else { self.remove_func(mwm::MWM_FUNC_MAXIMIZE); } } fn add_func(&mut self, func: c_ulong) { if self.hints.flags & mwm::MWM_HINTS_FUNCTIONS!= 0 { if self.hints.functions & mwm::MWM_FUNC_ALL!= 0 { self.hints.functions &=!func; } else { self.hints.functions |= func; } } } fn remove_func(&mut self, func: c_ulong) { if self.hints.flags & mwm::MWM_HINTS_FUNCTIONS == 0 { self.hints.flags |= mwm::MWM_HINTS_FUNCTIONS; self.hints.functions = mwm::MWM_FUNC_ALL; } if self.hints.functions & mwm::MWM_FUNC_ALL!= 0 { self.hints.functions |= func; } else { self.hints.functions &=!func; } } } impl MwmHints { fn as_slice(&self) -> &[c_ulong] { unsafe { slice::from_raw_parts(self as *const _ as *const c_ulong, 5) } } } pub struct NormalHints<'a> { size_hints: XSmartPointer<'a, ffi::XSizeHints>, } impl<'a> NormalHints<'a> { pub fn new(xconn: &'a XConnection) -> Self { NormalHints { size_hints: xconn.alloc_size_hints(), } } pub fn get_position(&self) -> Option<(i32, i32)> { if has_flag(self.size_hints.flags, ffi::PPosition) { Some((self.size_hints.x as i32, self.size_hints.y as i32)) } else { None } } pub fn set_position(&mut self, position: Option<(i32, i32)>) { if let Some((x, y)) = position { self.size_hints.flags |= ffi::PPosition; self.size_hints.x = x as c_int; self.size_hints.y = y as c_int; } else { self.size_hints.flags &=!ffi::PPosition; } } // WARNING: This hint is obsolete pub fn set_size(&mut self, size: Option<(u32, u32)>) { if let Some((width, height)) = size { self.size_hints.flags |= ffi::PSize; self.size_hints.width = width as c_int; self.size_hints.height = height as c_int; } else { self.size_hints.flags &=!ffi::PSize; } } pub fn set_max_size(&mut self, max_size: Option<(u32, u32)>) { if let Some((max_width, max_height)) = max_size { self.size_hints.flags |= ffi::PMaxSize; self.size_hints.max_width = max_width as c_int; self.size_hints.max_height = max_height as c_int; } else { self.size_hints.flags &=!ffi::PMaxSize; } } pub fn set_min_size(&mut self, min_size: Option<(u32, u32)>) { if let Some((min_width, min_height)) = min_size { self.size_hints.flags |= ffi::PMinSize; self.size_hints.min_width = min_width as c_int; self.size_hints.min_height = min_height as c_int; } else { self.size_hints.flags &=!ffi::PMinSize; } } pub fn set_resize_increments(&mut self, resize_increments: Option<(u32, u32)>) { if let Some((width_inc, height_inc)) = resize_increments { self.size_hints.flags |= ffi::PResizeInc; self.size_hints.width_inc = width_inc as c_int; self.size_hints.height_inc = height_inc as c_int; } else { self.size_hints.flags &=!ffi::PResizeInc; } } pub fn set_base_size(&mut self, base_size: Option<(u32, u32)>) { if let Some((base_width, base_height)) = base_size { self.size_hints.flags |= ffi::PBaseSize; self.size_hints.base_width = base_width as c_int; self.size_hints.base_height = base_height as c_int; } else { self.size_hints.flags &=!ffi::PBaseSize; } } } impl XConnection { pub fn get_wm_hints( &self, window: ffi::Window, ) -> Result<XSmartPointer<'_, ffi::XWMHints>, XError>
pub fn set_wm_hints( &self, window: ffi::Window, wm_hints: XSmartPointer<'_, ffi::XWMHints>, ) -> Flusher<'_> { unsafe { (self.xlib.XSetWMHints)(self.display, window, wm_hints.ptr); } Flusher::new(self) } pub fn get_normal_hints(&self, window: ffi::Window) -> Result<NormalHints<'_>, XError> { let size_hints = self.alloc_size_hints(); let mut supplied_by_user = MaybeUninit::uninit(); unsafe { (self.xlib.XGetWMNormalHints)( self.display, window, size_hints.ptr, supplied_by_user.as_mut_ptr(), ); } self.check_errors().map(|_| NormalHints { size_hints }) } pub fn set_normal_hints( &self, window: ffi::Window, normal_hints: NormalHints<'_>, ) -> Flusher<'_> { unsafe { (self.xlib.XSetWMNormalHints)(self.display, window, normal_hints.size_hints.ptr); } Flusher::new(self) } pub fn get_motif_hints(&self, window: ffi::Window) -> MotifHints { let motif_hints = unsafe { self.get_atom_unchecked(b"_MOTIF_WM_HINTS\0") }; let mut hints = MotifHints::new(); if let Ok(props) = self.get_property::<c_ulong>(window, motif_hints, motif_hints) { hints.hints.flags = props.get(0).cloned().unwrap_or(0); hints.hints.functions = props.get(1).cloned().unwrap_or(0); hints.hints.decorations = props.get(2).cloned().unwrap_or(0); hints.hints.input_mode = props.get(3).cloned().unwrap_or(0) as c_long; hints.hints.status = props.get(4).cloned().unwrap_or(0); } hints } pub fn set_motif_hints(&self, window: ffi::Window, hints: &MotifHints) -> Flusher<'_> { let motif_hints = unsafe { self.get_atom_unchecked(b"_MOTIF_WM_HINTS\0") }; self.change_property( window, motif_hints, motif_hints, PropMode::Replace, hints.hints.as_slice(), ) } }
{ let wm_hints = unsafe { (self.xlib.XGetWMHints)(self.display, window) }; self.check_errors()?; let wm_hints = if wm_hints.is_null() { self.alloc_wm_hints() } else { XSmartPointer::new(self, wm_hints).unwrap() }; Ok(wm_hints) }
identifier_body
hint.rs
use std::slice; use std::sync::Arc; use super::*; #[derive(Debug)] #[allow(dead_code)] pub enum StateOperation { Remove = 0, // _NET_WM_STATE_REMOVE Add = 1, // _NET_WM_STATE_ADD Toggle = 2, // _NET_WM_STATE_TOGGLE } impl From<bool> for StateOperation { fn from(op: bool) -> Self { if op { StateOperation::Add } else { StateOperation::Remove } } } /// X window type. Maps directly to /// [`_NET_WM_WINDOW_TYPE`](https://specifications.freedesktop.org/wm-spec/wm-spec-1.5.html). #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub enum WindowType { /// A desktop feature. This can include a single window containing desktop icons with the same dimensions as the /// screen, allowing the desktop environment to have full control of the desktop, without the need for proxying /// root window clicks. Desktop, /// A dock or panel feature. Typically a Window Manager would keep such windows on top of all other windows. Dock, /// Toolbar windows. "Torn off" from the main application. Toolbar, /// Pinnable menu windows. "Torn off" from the main application. Menu, /// A small persistent utility window, such as a palette or toolbox. Utility, /// The window is a splash screen displayed as an application is starting up. Splash, /// This is a dialog window. Dialog, /// A dropdown menu that usually appears when the user clicks on an item in a menu bar. /// This property is typically used on override-redirect windows. DropdownMenu, /// A popup menu that usually appears when the user right clicks on an object. /// This property is typically used on override-redirect windows. PopupMenu, /// A tooltip window. Usually used to show additional information when hovering over an object with the cursor. /// This property is typically used on override-redirect windows. Tooltip, /// The window is a notification. /// This property is typically used on override-redirect windows. Notification, /// This should be used on the windows that are popped up by combo boxes. /// This property is typically used on override-redirect windows. Combo, /// This indicates the the window is being dragged. /// This property is typically used on override-redirect windows. Dnd, /// This is a normal, top-level window. Normal, } impl Default for WindowType { fn default() -> Self { WindowType::Normal } } impl WindowType { pub(crate) fn as_atom(&self, xconn: &Arc<XConnection>) -> ffi::Atom { use self::WindowType::*; let atom_name: &[u8] = match *self { Desktop => b"_NET_WM_WINDOW_TYPE_DESKTOP\0", Dock => b"_NET_WM_WINDOW_TYPE_DOCK\0", Toolbar => b"_NET_WM_WINDOW_TYPE_TOOLBAR\0", Menu => b"_NET_WM_WINDOW_TYPE_MENU\0", Utility => b"_NET_WM_WINDOW_TYPE_UTILITY\0", Splash => b"_NET_WM_WINDOW_TYPE_SPLASH\0", Dialog => b"_NET_WM_WINDOW_TYPE_DIALOG\0", DropdownMenu => b"_NET_WM_WINDOW_TYPE_DROPDOWN_MENU\0", PopupMenu => b"_NET_WM_WINDOW_TYPE_POPUP_MENU\0", Tooltip => b"_NET_WM_WINDOW_TYPE_TOOLTIP\0", Notification => b"_NET_WM_WINDOW_TYPE_NOTIFICATION\0", Combo => b"_NET_WM_WINDOW_TYPE_COMBO\0",
}; unsafe { xconn.get_atom_unchecked(atom_name) } } } pub struct MotifHints { hints: MwmHints, } #[repr(C)] struct MwmHints { flags: c_ulong, functions: c_ulong, decorations: c_ulong, input_mode: c_long, status: c_ulong, } #[allow(dead_code)] mod mwm { use libc::c_ulong; // Motif WM hints are obsolete, but still widely supported. // https://stackoverflow.com/a/1909708 pub const MWM_HINTS_FUNCTIONS: c_ulong = 1 << 0; pub const MWM_HINTS_DECORATIONS: c_ulong = 1 << 1; pub const MWM_FUNC_ALL: c_ulong = 1 << 0; pub const MWM_FUNC_RESIZE: c_ulong = 1 << 1; pub const MWM_FUNC_MOVE: c_ulong = 1 << 2; pub const MWM_FUNC_MINIMIZE: c_ulong = 1 << 3; pub const MWM_FUNC_MAXIMIZE: c_ulong = 1 << 4; pub const MWM_FUNC_CLOSE: c_ulong = 1 << 5; } impl MotifHints { pub fn new() -> MotifHints { MotifHints { hints: MwmHints { flags: 0, functions: 0, decorations: 0, input_mode: 0, status: 0, }, } } pub fn set_decorations(&mut self, decorations: bool) { self.hints.flags |= mwm::MWM_HINTS_DECORATIONS; self.hints.decorations = decorations as c_ulong; } pub fn set_maximizable(&mut self, maximizable: bool) { if maximizable { self.add_func(mwm::MWM_FUNC_MAXIMIZE); } else { self.remove_func(mwm::MWM_FUNC_MAXIMIZE); } } fn add_func(&mut self, func: c_ulong) { if self.hints.flags & mwm::MWM_HINTS_FUNCTIONS!= 0 { if self.hints.functions & mwm::MWM_FUNC_ALL!= 0 { self.hints.functions &=!func; } else { self.hints.functions |= func; } } } fn remove_func(&mut self, func: c_ulong) { if self.hints.flags & mwm::MWM_HINTS_FUNCTIONS == 0 { self.hints.flags |= mwm::MWM_HINTS_FUNCTIONS; self.hints.functions = mwm::MWM_FUNC_ALL; } if self.hints.functions & mwm::MWM_FUNC_ALL!= 0 { self.hints.functions |= func; } else { self.hints.functions &=!func; } } } impl MwmHints { fn as_slice(&self) -> &[c_ulong] { unsafe { slice::from_raw_parts(self as *const _ as *const c_ulong, 5) } } } pub struct NormalHints<'a> { size_hints: XSmartPointer<'a, ffi::XSizeHints>, } impl<'a> NormalHints<'a> { pub fn new(xconn: &'a XConnection) -> Self { NormalHints { size_hints: xconn.alloc_size_hints(), } } pub fn get_position(&self) -> Option<(i32, i32)> { if has_flag(self.size_hints.flags, ffi::PPosition) { Some((self.size_hints.x as i32, self.size_hints.y as i32)) } else { None } } pub fn set_position(&mut self, position: Option<(i32, i32)>) { if let Some((x, y)) = position { self.size_hints.flags |= ffi::PPosition; self.size_hints.x = x as c_int; self.size_hints.y = y as c_int; } else { self.size_hints.flags &=!ffi::PPosition; } } // WARNING: This hint is obsolete pub fn set_size(&mut self, size: Option<(u32, u32)>) { if let Some((width, height)) = size { self.size_hints.flags |= ffi::PSize; self.size_hints.width = width as c_int; self.size_hints.height = height as c_int; } else { self.size_hints.flags &=!ffi::PSize; } } pub fn set_max_size(&mut self, max_size: Option<(u32, u32)>) { if let Some((max_width, max_height)) = max_size { self.size_hints.flags |= ffi::PMaxSize; self.size_hints.max_width = max_width as c_int; self.size_hints.max_height = max_height as c_int; } else { self.size_hints.flags &=!ffi::PMaxSize; } } pub fn set_min_size(&mut self, min_size: Option<(u32, u32)>) { if let Some((min_width, min_height)) = min_size { self.size_hints.flags |= ffi::PMinSize; self.size_hints.min_width = min_width as c_int; self.size_hints.min_height = min_height as c_int; } else { self.size_hints.flags &=!ffi::PMinSize; } } pub fn set_resize_increments(&mut self, resize_increments: Option<(u32, u32)>) { if let Some((width_inc, height_inc)) = resize_increments { self.size_hints.flags |= ffi::PResizeInc; self.size_hints.width_inc = width_inc as c_int; self.size_hints.height_inc = height_inc as c_int; } else { self.size_hints.flags &=!ffi::PResizeInc; } } pub fn set_base_size(&mut self, base_size: Option<(u32, u32)>) { if let Some((base_width, base_height)) = base_size { self.size_hints.flags |= ffi::PBaseSize; self.size_hints.base_width = base_width as c_int; self.size_hints.base_height = base_height as c_int; } else { self.size_hints.flags &=!ffi::PBaseSize; } } } impl XConnection { pub fn get_wm_hints( &self, window: ffi::Window, ) -> Result<XSmartPointer<'_, ffi::XWMHints>, XError> { let wm_hints = unsafe { (self.xlib.XGetWMHints)(self.display, window) }; self.check_errors()?; let wm_hints = if wm_hints.is_null() { self.alloc_wm_hints() } else { XSmartPointer::new(self, wm_hints).unwrap() }; Ok(wm_hints) } pub fn set_wm_hints( &self, window: ffi::Window, wm_hints: XSmartPointer<'_, ffi::XWMHints>, ) -> Flusher<'_> { unsafe { (self.xlib.XSetWMHints)(self.display, window, wm_hints.ptr); } Flusher::new(self) } pub fn get_normal_hints(&self, window: ffi::Window) -> Result<NormalHints<'_>, XError> { let size_hints = self.alloc_size_hints(); let mut supplied_by_user = MaybeUninit::uninit(); unsafe { (self.xlib.XGetWMNormalHints)( self.display, window, size_hints.ptr, supplied_by_user.as_mut_ptr(), ); } self.check_errors().map(|_| NormalHints { size_hints }) } pub fn set_normal_hints( &self, window: ffi::Window, normal_hints: NormalHints<'_>, ) -> Flusher<'_> { unsafe { (self.xlib.XSetWMNormalHints)(self.display, window, normal_hints.size_hints.ptr); } Flusher::new(self) } pub fn get_motif_hints(&self, window: ffi::Window) -> MotifHints { let motif_hints = unsafe { self.get_atom_unchecked(b"_MOTIF_WM_HINTS\0") }; let mut hints = MotifHints::new(); if let Ok(props) = self.get_property::<c_ulong>(window, motif_hints, motif_hints) { hints.hints.flags = props.get(0).cloned().unwrap_or(0); hints.hints.functions = props.get(1).cloned().unwrap_or(0); hints.hints.decorations = props.get(2).cloned().unwrap_or(0); hints.hints.input_mode = props.get(3).cloned().unwrap_or(0) as c_long; hints.hints.status = props.get(4).cloned().unwrap_or(0); } hints } pub fn set_motif_hints(&self, window: ffi::Window, hints: &MotifHints) -> Flusher<'_> { let motif_hints = unsafe { self.get_atom_unchecked(b"_MOTIF_WM_HINTS\0") }; self.change_property( window, motif_hints, motif_hints, PropMode::Replace, hints.hints.as_slice(), ) } }
Dnd => b"_NET_WM_WINDOW_TYPE_DND\0", Normal => b"_NET_WM_WINDOW_TYPE_NORMAL\0",
random_line_split
hint.rs
use std::slice; use std::sync::Arc; use super::*; #[derive(Debug)] #[allow(dead_code)] pub enum StateOperation { Remove = 0, // _NET_WM_STATE_REMOVE Add = 1, // _NET_WM_STATE_ADD Toggle = 2, // _NET_WM_STATE_TOGGLE } impl From<bool> for StateOperation { fn from(op: bool) -> Self { if op { StateOperation::Add } else { StateOperation::Remove } } } /// X window type. Maps directly to /// [`_NET_WM_WINDOW_TYPE`](https://specifications.freedesktop.org/wm-spec/wm-spec-1.5.html). #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub enum WindowType { /// A desktop feature. This can include a single window containing desktop icons with the same dimensions as the /// screen, allowing the desktop environment to have full control of the desktop, without the need for proxying /// root window clicks. Desktop, /// A dock or panel feature. Typically a Window Manager would keep such windows on top of all other windows. Dock, /// Toolbar windows. "Torn off" from the main application. Toolbar, /// Pinnable menu windows. "Torn off" from the main application. Menu, /// A small persistent utility window, such as a palette or toolbox. Utility, /// The window is a splash screen displayed as an application is starting up. Splash, /// This is a dialog window. Dialog, /// A dropdown menu that usually appears when the user clicks on an item in a menu bar. /// This property is typically used on override-redirect windows. DropdownMenu, /// A popup menu that usually appears when the user right clicks on an object. /// This property is typically used on override-redirect windows. PopupMenu, /// A tooltip window. Usually used to show additional information when hovering over an object with the cursor. /// This property is typically used on override-redirect windows. Tooltip, /// The window is a notification. /// This property is typically used on override-redirect windows. Notification, /// This should be used on the windows that are popped up by combo boxes. /// This property is typically used on override-redirect windows. Combo, /// This indicates the the window is being dragged. /// This property is typically used on override-redirect windows. Dnd, /// This is a normal, top-level window. Normal, } impl Default for WindowType { fn default() -> Self { WindowType::Normal } } impl WindowType { pub(crate) fn as_atom(&self, xconn: &Arc<XConnection>) -> ffi::Atom { use self::WindowType::*; let atom_name: &[u8] = match *self { Desktop => b"_NET_WM_WINDOW_TYPE_DESKTOP\0", Dock => b"_NET_WM_WINDOW_TYPE_DOCK\0", Toolbar => b"_NET_WM_WINDOW_TYPE_TOOLBAR\0", Menu => b"_NET_WM_WINDOW_TYPE_MENU\0", Utility => b"_NET_WM_WINDOW_TYPE_UTILITY\0", Splash => b"_NET_WM_WINDOW_TYPE_SPLASH\0", Dialog => b"_NET_WM_WINDOW_TYPE_DIALOG\0", DropdownMenu => b"_NET_WM_WINDOW_TYPE_DROPDOWN_MENU\0", PopupMenu => b"_NET_WM_WINDOW_TYPE_POPUP_MENU\0", Tooltip => b"_NET_WM_WINDOW_TYPE_TOOLTIP\0", Notification => b"_NET_WM_WINDOW_TYPE_NOTIFICATION\0", Combo => b"_NET_WM_WINDOW_TYPE_COMBO\0", Dnd => b"_NET_WM_WINDOW_TYPE_DND\0", Normal => b"_NET_WM_WINDOW_TYPE_NORMAL\0", }; unsafe { xconn.get_atom_unchecked(atom_name) } } } pub struct MotifHints { hints: MwmHints, } #[repr(C)] struct MwmHints { flags: c_ulong, functions: c_ulong, decorations: c_ulong, input_mode: c_long, status: c_ulong, } #[allow(dead_code)] mod mwm { use libc::c_ulong; // Motif WM hints are obsolete, but still widely supported. // https://stackoverflow.com/a/1909708 pub const MWM_HINTS_FUNCTIONS: c_ulong = 1 << 0; pub const MWM_HINTS_DECORATIONS: c_ulong = 1 << 1; pub const MWM_FUNC_ALL: c_ulong = 1 << 0; pub const MWM_FUNC_RESIZE: c_ulong = 1 << 1; pub const MWM_FUNC_MOVE: c_ulong = 1 << 2; pub const MWM_FUNC_MINIMIZE: c_ulong = 1 << 3; pub const MWM_FUNC_MAXIMIZE: c_ulong = 1 << 4; pub const MWM_FUNC_CLOSE: c_ulong = 1 << 5; } impl MotifHints { pub fn new() -> MotifHints { MotifHints { hints: MwmHints { flags: 0, functions: 0, decorations: 0, input_mode: 0, status: 0, }, } } pub fn set_decorations(&mut self, decorations: bool) { self.hints.flags |= mwm::MWM_HINTS_DECORATIONS; self.hints.decorations = decorations as c_ulong; } pub fn set_maximizable(&mut self, maximizable: bool) { if maximizable { self.add_func(mwm::MWM_FUNC_MAXIMIZE); } else { self.remove_func(mwm::MWM_FUNC_MAXIMIZE); } } fn add_func(&mut self, func: c_ulong) { if self.hints.flags & mwm::MWM_HINTS_FUNCTIONS!= 0 { if self.hints.functions & mwm::MWM_FUNC_ALL!= 0 { self.hints.functions &=!func; } else { self.hints.functions |= func; } } } fn remove_func(&mut self, func: c_ulong) { if self.hints.flags & mwm::MWM_HINTS_FUNCTIONS == 0 { self.hints.flags |= mwm::MWM_HINTS_FUNCTIONS; self.hints.functions = mwm::MWM_FUNC_ALL; } if self.hints.functions & mwm::MWM_FUNC_ALL!= 0 { self.hints.functions |= func; } else { self.hints.functions &=!func; } } } impl MwmHints { fn as_slice(&self) -> &[c_ulong] { unsafe { slice::from_raw_parts(self as *const _ as *const c_ulong, 5) } } } pub struct NormalHints<'a> { size_hints: XSmartPointer<'a, ffi::XSizeHints>, } impl<'a> NormalHints<'a> { pub fn new(xconn: &'a XConnection) -> Self { NormalHints { size_hints: xconn.alloc_size_hints(), } } pub fn get_position(&self) -> Option<(i32, i32)> { if has_flag(self.size_hints.flags, ffi::PPosition) { Some((self.size_hints.x as i32, self.size_hints.y as i32)) } else { None } } pub fn set_position(&mut self, position: Option<(i32, i32)>) { if let Some((x, y)) = position { self.size_hints.flags |= ffi::PPosition; self.size_hints.x = x as c_int; self.size_hints.y = y as c_int; } else { self.size_hints.flags &=!ffi::PPosition; } } // WARNING: This hint is obsolete pub fn set_size(&mut self, size: Option<(u32, u32)>) { if let Some((width, height)) = size { self.size_hints.flags |= ffi::PSize; self.size_hints.width = width as c_int; self.size_hints.height = height as c_int; } else { self.size_hints.flags &=!ffi::PSize; } } pub fn set_max_size(&mut self, max_size: Option<(u32, u32)>) { if let Some((max_width, max_height)) = max_size { self.size_hints.flags |= ffi::PMaxSize; self.size_hints.max_width = max_width as c_int; self.size_hints.max_height = max_height as c_int; } else { self.size_hints.flags &=!ffi::PMaxSize; } } pub fn set_min_size(&mut self, min_size: Option<(u32, u32)>) { if let Some((min_width, min_height)) = min_size { self.size_hints.flags |= ffi::PMinSize; self.size_hints.min_width = min_width as c_int; self.size_hints.min_height = min_height as c_int; } else { self.size_hints.flags &=!ffi::PMinSize; } } pub fn set_resize_increments(&mut self, resize_increments: Option<(u32, u32)>) { if let Some((width_inc, height_inc)) = resize_increments { self.size_hints.flags |= ffi::PResizeInc; self.size_hints.width_inc = width_inc as c_int; self.size_hints.height_inc = height_inc as c_int; } else { self.size_hints.flags &=!ffi::PResizeInc; } } pub fn set_base_size(&mut self, base_size: Option<(u32, u32)>) { if let Some((base_width, base_height)) = base_size
else { self.size_hints.flags &=!ffi::PBaseSize; } } } impl XConnection { pub fn get_wm_hints( &self, window: ffi::Window, ) -> Result<XSmartPointer<'_, ffi::XWMHints>, XError> { let wm_hints = unsafe { (self.xlib.XGetWMHints)(self.display, window) }; self.check_errors()?; let wm_hints = if wm_hints.is_null() { self.alloc_wm_hints() } else { XSmartPointer::new(self, wm_hints).unwrap() }; Ok(wm_hints) } pub fn set_wm_hints( &self, window: ffi::Window, wm_hints: XSmartPointer<'_, ffi::XWMHints>, ) -> Flusher<'_> { unsafe { (self.xlib.XSetWMHints)(self.display, window, wm_hints.ptr); } Flusher::new(self) } pub fn get_normal_hints(&self, window: ffi::Window) -> Result<NormalHints<'_>, XError> { let size_hints = self.alloc_size_hints(); let mut supplied_by_user = MaybeUninit::uninit(); unsafe { (self.xlib.XGetWMNormalHints)( self.display, window, size_hints.ptr, supplied_by_user.as_mut_ptr(), ); } self.check_errors().map(|_| NormalHints { size_hints }) } pub fn set_normal_hints( &self, window: ffi::Window, normal_hints: NormalHints<'_>, ) -> Flusher<'_> { unsafe { (self.xlib.XSetWMNormalHints)(self.display, window, normal_hints.size_hints.ptr); } Flusher::new(self) } pub fn get_motif_hints(&self, window: ffi::Window) -> MotifHints { let motif_hints = unsafe { self.get_atom_unchecked(b"_MOTIF_WM_HINTS\0") }; let mut hints = MotifHints::new(); if let Ok(props) = self.get_property::<c_ulong>(window, motif_hints, motif_hints) { hints.hints.flags = props.get(0).cloned().unwrap_or(0); hints.hints.functions = props.get(1).cloned().unwrap_or(0); hints.hints.decorations = props.get(2).cloned().unwrap_or(0); hints.hints.input_mode = props.get(3).cloned().unwrap_or(0) as c_long; hints.hints.status = props.get(4).cloned().unwrap_or(0); } hints } pub fn set_motif_hints(&self, window: ffi::Window, hints: &MotifHints) -> Flusher<'_> { let motif_hints = unsafe { self.get_atom_unchecked(b"_MOTIF_WM_HINTS\0") }; self.change_property( window, motif_hints, motif_hints, PropMode::Replace, hints.hints.as_slice(), ) } }
{ self.size_hints.flags |= ffi::PBaseSize; self.size_hints.base_width = base_width as c_int; self.size_hints.base_height = base_height as c_int; }
conditional_block
hint.rs
use std::slice; use std::sync::Arc; use super::*; #[derive(Debug)] #[allow(dead_code)] pub enum StateOperation { Remove = 0, // _NET_WM_STATE_REMOVE Add = 1, // _NET_WM_STATE_ADD Toggle = 2, // _NET_WM_STATE_TOGGLE } impl From<bool> for StateOperation { fn from(op: bool) -> Self { if op { StateOperation::Add } else { StateOperation::Remove } } } /// X window type. Maps directly to /// [`_NET_WM_WINDOW_TYPE`](https://specifications.freedesktop.org/wm-spec/wm-spec-1.5.html). #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub enum WindowType { /// A desktop feature. This can include a single window containing desktop icons with the same dimensions as the /// screen, allowing the desktop environment to have full control of the desktop, without the need for proxying /// root window clicks. Desktop, /// A dock or panel feature. Typically a Window Manager would keep such windows on top of all other windows. Dock, /// Toolbar windows. "Torn off" from the main application. Toolbar, /// Pinnable menu windows. "Torn off" from the main application. Menu, /// A small persistent utility window, such as a palette or toolbox. Utility, /// The window is a splash screen displayed as an application is starting up. Splash, /// This is a dialog window. Dialog, /// A dropdown menu that usually appears when the user clicks on an item in a menu bar. /// This property is typically used on override-redirect windows. DropdownMenu, /// A popup menu that usually appears when the user right clicks on an object. /// This property is typically used on override-redirect windows. PopupMenu, /// A tooltip window. Usually used to show additional information when hovering over an object with the cursor. /// This property is typically used on override-redirect windows. Tooltip, /// The window is a notification. /// This property is typically used on override-redirect windows. Notification, /// This should be used on the windows that are popped up by combo boxes. /// This property is typically used on override-redirect windows. Combo, /// This indicates the the window is being dragged. /// This property is typically used on override-redirect windows. Dnd, /// This is a normal, top-level window. Normal, } impl Default for WindowType { fn default() -> Self { WindowType::Normal } } impl WindowType { pub(crate) fn as_atom(&self, xconn: &Arc<XConnection>) -> ffi::Atom { use self::WindowType::*; let atom_name: &[u8] = match *self { Desktop => b"_NET_WM_WINDOW_TYPE_DESKTOP\0", Dock => b"_NET_WM_WINDOW_TYPE_DOCK\0", Toolbar => b"_NET_WM_WINDOW_TYPE_TOOLBAR\0", Menu => b"_NET_WM_WINDOW_TYPE_MENU\0", Utility => b"_NET_WM_WINDOW_TYPE_UTILITY\0", Splash => b"_NET_WM_WINDOW_TYPE_SPLASH\0", Dialog => b"_NET_WM_WINDOW_TYPE_DIALOG\0", DropdownMenu => b"_NET_WM_WINDOW_TYPE_DROPDOWN_MENU\0", PopupMenu => b"_NET_WM_WINDOW_TYPE_POPUP_MENU\0", Tooltip => b"_NET_WM_WINDOW_TYPE_TOOLTIP\0", Notification => b"_NET_WM_WINDOW_TYPE_NOTIFICATION\0", Combo => b"_NET_WM_WINDOW_TYPE_COMBO\0", Dnd => b"_NET_WM_WINDOW_TYPE_DND\0", Normal => b"_NET_WM_WINDOW_TYPE_NORMAL\0", }; unsafe { xconn.get_atom_unchecked(atom_name) } } } pub struct MotifHints { hints: MwmHints, } #[repr(C)] struct MwmHints { flags: c_ulong, functions: c_ulong, decorations: c_ulong, input_mode: c_long, status: c_ulong, } #[allow(dead_code)] mod mwm { use libc::c_ulong; // Motif WM hints are obsolete, but still widely supported. // https://stackoverflow.com/a/1909708 pub const MWM_HINTS_FUNCTIONS: c_ulong = 1 << 0; pub const MWM_HINTS_DECORATIONS: c_ulong = 1 << 1; pub const MWM_FUNC_ALL: c_ulong = 1 << 0; pub const MWM_FUNC_RESIZE: c_ulong = 1 << 1; pub const MWM_FUNC_MOVE: c_ulong = 1 << 2; pub const MWM_FUNC_MINIMIZE: c_ulong = 1 << 3; pub const MWM_FUNC_MAXIMIZE: c_ulong = 1 << 4; pub const MWM_FUNC_CLOSE: c_ulong = 1 << 5; } impl MotifHints { pub fn new() -> MotifHints { MotifHints { hints: MwmHints { flags: 0, functions: 0, decorations: 0, input_mode: 0, status: 0, }, } } pub fn set_decorations(&mut self, decorations: bool) { self.hints.flags |= mwm::MWM_HINTS_DECORATIONS; self.hints.decorations = decorations as c_ulong; } pub fn
(&mut self, maximizable: bool) { if maximizable { self.add_func(mwm::MWM_FUNC_MAXIMIZE); } else { self.remove_func(mwm::MWM_FUNC_MAXIMIZE); } } fn add_func(&mut self, func: c_ulong) { if self.hints.flags & mwm::MWM_HINTS_FUNCTIONS!= 0 { if self.hints.functions & mwm::MWM_FUNC_ALL!= 0 { self.hints.functions &=!func; } else { self.hints.functions |= func; } } } fn remove_func(&mut self, func: c_ulong) { if self.hints.flags & mwm::MWM_HINTS_FUNCTIONS == 0 { self.hints.flags |= mwm::MWM_HINTS_FUNCTIONS; self.hints.functions = mwm::MWM_FUNC_ALL; } if self.hints.functions & mwm::MWM_FUNC_ALL!= 0 { self.hints.functions |= func; } else { self.hints.functions &=!func; } } } impl MwmHints { fn as_slice(&self) -> &[c_ulong] { unsafe { slice::from_raw_parts(self as *const _ as *const c_ulong, 5) } } } pub struct NormalHints<'a> { size_hints: XSmartPointer<'a, ffi::XSizeHints>, } impl<'a> NormalHints<'a> { pub fn new(xconn: &'a XConnection) -> Self { NormalHints { size_hints: xconn.alloc_size_hints(), } } pub fn get_position(&self) -> Option<(i32, i32)> { if has_flag(self.size_hints.flags, ffi::PPosition) { Some((self.size_hints.x as i32, self.size_hints.y as i32)) } else { None } } pub fn set_position(&mut self, position: Option<(i32, i32)>) { if let Some((x, y)) = position { self.size_hints.flags |= ffi::PPosition; self.size_hints.x = x as c_int; self.size_hints.y = y as c_int; } else { self.size_hints.flags &=!ffi::PPosition; } } // WARNING: This hint is obsolete pub fn set_size(&mut self, size: Option<(u32, u32)>) { if let Some((width, height)) = size { self.size_hints.flags |= ffi::PSize; self.size_hints.width = width as c_int; self.size_hints.height = height as c_int; } else { self.size_hints.flags &=!ffi::PSize; } } pub fn set_max_size(&mut self, max_size: Option<(u32, u32)>) { if let Some((max_width, max_height)) = max_size { self.size_hints.flags |= ffi::PMaxSize; self.size_hints.max_width = max_width as c_int; self.size_hints.max_height = max_height as c_int; } else { self.size_hints.flags &=!ffi::PMaxSize; } } pub fn set_min_size(&mut self, min_size: Option<(u32, u32)>) { if let Some((min_width, min_height)) = min_size { self.size_hints.flags |= ffi::PMinSize; self.size_hints.min_width = min_width as c_int; self.size_hints.min_height = min_height as c_int; } else { self.size_hints.flags &=!ffi::PMinSize; } } pub fn set_resize_increments(&mut self, resize_increments: Option<(u32, u32)>) { if let Some((width_inc, height_inc)) = resize_increments { self.size_hints.flags |= ffi::PResizeInc; self.size_hints.width_inc = width_inc as c_int; self.size_hints.height_inc = height_inc as c_int; } else { self.size_hints.flags &=!ffi::PResizeInc; } } pub fn set_base_size(&mut self, base_size: Option<(u32, u32)>) { if let Some((base_width, base_height)) = base_size { self.size_hints.flags |= ffi::PBaseSize; self.size_hints.base_width = base_width as c_int; self.size_hints.base_height = base_height as c_int; } else { self.size_hints.flags &=!ffi::PBaseSize; } } } impl XConnection { pub fn get_wm_hints( &self, window: ffi::Window, ) -> Result<XSmartPointer<'_, ffi::XWMHints>, XError> { let wm_hints = unsafe { (self.xlib.XGetWMHints)(self.display, window) }; self.check_errors()?; let wm_hints = if wm_hints.is_null() { self.alloc_wm_hints() } else { XSmartPointer::new(self, wm_hints).unwrap() }; Ok(wm_hints) } pub fn set_wm_hints( &self, window: ffi::Window, wm_hints: XSmartPointer<'_, ffi::XWMHints>, ) -> Flusher<'_> { unsafe { (self.xlib.XSetWMHints)(self.display, window, wm_hints.ptr); } Flusher::new(self) } pub fn get_normal_hints(&self, window: ffi::Window) -> Result<NormalHints<'_>, XError> { let size_hints = self.alloc_size_hints(); let mut supplied_by_user = MaybeUninit::uninit(); unsafe { (self.xlib.XGetWMNormalHints)( self.display, window, size_hints.ptr, supplied_by_user.as_mut_ptr(), ); } self.check_errors().map(|_| NormalHints { size_hints }) } pub fn set_normal_hints( &self, window: ffi::Window, normal_hints: NormalHints<'_>, ) -> Flusher<'_> { unsafe { (self.xlib.XSetWMNormalHints)(self.display, window, normal_hints.size_hints.ptr); } Flusher::new(self) } pub fn get_motif_hints(&self, window: ffi::Window) -> MotifHints { let motif_hints = unsafe { self.get_atom_unchecked(b"_MOTIF_WM_HINTS\0") }; let mut hints = MotifHints::new(); if let Ok(props) = self.get_property::<c_ulong>(window, motif_hints, motif_hints) { hints.hints.flags = props.get(0).cloned().unwrap_or(0); hints.hints.functions = props.get(1).cloned().unwrap_or(0); hints.hints.decorations = props.get(2).cloned().unwrap_or(0); hints.hints.input_mode = props.get(3).cloned().unwrap_or(0) as c_long; hints.hints.status = props.get(4).cloned().unwrap_or(0); } hints } pub fn set_motif_hints(&self, window: ffi::Window, hints: &MotifHints) -> Flusher<'_> { let motif_hints = unsafe { self.get_atom_unchecked(b"_MOTIF_WM_HINTS\0") }; self.change_property( window, motif_hints, motif_hints, PropMode::Replace, hints.hints.as_slice(), ) } }
set_maximizable
identifier_name
input.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Trie test input deserialization. use std::collections::BTreeMap; use std::str::FromStr; use bytes::Bytes; use serde::{Deserialize, Deserializer, Error}; use serde::de::{Visitor, MapVisitor, SeqVisitor}; /// Trie test input. #[derive(Debug, PartialEq)] pub struct Input { /// Input params. pub data: BTreeMap<Bytes, Option<Bytes>>, } impl Deserialize for Input { fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error> where D: Deserializer { deserializer.deserialize(InputVisitor) } } struct InputVisitor; impl Visitor for InputVisitor { type Value = Input; fn visit_map<V>(&mut self, mut visitor: V) -> Result<Self::Value, V::Error> where V: MapVisitor { let mut result = BTreeMap::new(); loop { let key_str: Option<String> = try!(visitor.visit_key()); let key = match key_str { Some(ref k) if k.starts_with("0x") => try!(Bytes::from_str(k).map_err(Error::custom)), Some(k) => Bytes::new(k.into_bytes()), None => { break; } }; let val_str: Option<String> = try!(visitor.visit_value()); let val = match val_str { Some(ref v) if v.starts_with("0x") => Some(try!(Bytes::from_str(v).map_err(Error::custom))), Some(v) => Some(Bytes::new(v.into_bytes())), None => None, }; result.insert(key, val); } try!(visitor.end()); let input = Input { data: result }; Ok(input) } fn visit_seq<V>(&mut self, mut visitor: V) -> Result<Self::Value, V::Error> where V: SeqVisitor { let mut result = BTreeMap::new(); loop { let keyval: Option<Vec<Option<String>>> = try!(visitor.visit()); let keyval = match keyval { Some(k) => k, _ => { break; }, }; if keyval.len()!= 2
let ref key_str: Option<String> = keyval[0]; let ref val_str: Option<String> = keyval[1]; let key = match *key_str { Some(ref k) if k.starts_with("0x") => try!(Bytes::from_str(k).map_err(Error::custom)), Some(ref k) => Bytes::new(k.clone().into_bytes()), None => { break; } }; let val = match *val_str { Some(ref v) if v.starts_with("0x") => Some(try!(Bytes::from_str(v).map_err(Error::custom))), Some(ref v) => Some(Bytes::new(v.clone().into_bytes())), None => None, }; result.insert(key, val); } try!(visitor.end()); let input = Input { data: result }; Ok(input) } } #[cfg(test)] mod tests { use std::collections::BTreeMap; use serde_json; use bytes::Bytes; use super::Input; #[test] fn input_deserialization_from_map() { let s = r#"{ "0x0045" : "0x0123456789", "be" : "e", "0x0a" : null }"#; let input: Input = serde_json::from_str(s).unwrap(); let mut map = BTreeMap::new(); map.insert(Bytes::new(vec![0, 0x45]), Some(Bytes::new(vec![0x01, 0x23, 0x45, 0x67, 0x89]))); map.insert(Bytes::new(vec![0x62, 0x65]), Some(Bytes::new(vec![0x65]))); map.insert(Bytes::new(vec![0x0a]), None); assert_eq!(input.data, map); } #[test] fn input_deserialization_from_array() { let s = r#"[ ["0x0045", "0x0123456789"], ["be", "e"], ["0x0a", null] ]"#; let input: Input = serde_json::from_str(s).unwrap(); let mut map = BTreeMap::new(); map.insert(Bytes::new(vec![0, 0x45]), Some(Bytes::new(vec![0x01, 0x23, 0x45, 0x67, 0x89]))); map.insert(Bytes::new(vec![0x62, 0x65]), Some(Bytes::new(vec![0x65]))); map.insert(Bytes::new(vec![0x0a]), None); assert_eq!(input.data, map); } }
{ return Err(Error::custom("Invalid key value pair.")); }
conditional_block
input.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Trie test input deserialization. use std::collections::BTreeMap; use std::str::FromStr; use bytes::Bytes; use serde::{Deserialize, Deserializer, Error}; use serde::de::{Visitor, MapVisitor, SeqVisitor}; /// Trie test input. #[derive(Debug, PartialEq)] pub struct Input { /// Input params. pub data: BTreeMap<Bytes, Option<Bytes>>, } impl Deserialize for Input { fn
<D>(deserializer: &mut D) -> Result<Self, D::Error> where D: Deserializer { deserializer.deserialize(InputVisitor) } } struct InputVisitor; impl Visitor for InputVisitor { type Value = Input; fn visit_map<V>(&mut self, mut visitor: V) -> Result<Self::Value, V::Error> where V: MapVisitor { let mut result = BTreeMap::new(); loop { let key_str: Option<String> = try!(visitor.visit_key()); let key = match key_str { Some(ref k) if k.starts_with("0x") => try!(Bytes::from_str(k).map_err(Error::custom)), Some(k) => Bytes::new(k.into_bytes()), None => { break; } }; let val_str: Option<String> = try!(visitor.visit_value()); let val = match val_str { Some(ref v) if v.starts_with("0x") => Some(try!(Bytes::from_str(v).map_err(Error::custom))), Some(v) => Some(Bytes::new(v.into_bytes())), None => None, }; result.insert(key, val); } try!(visitor.end()); let input = Input { data: result }; Ok(input) } fn visit_seq<V>(&mut self, mut visitor: V) -> Result<Self::Value, V::Error> where V: SeqVisitor { let mut result = BTreeMap::new(); loop { let keyval: Option<Vec<Option<String>>> = try!(visitor.visit()); let keyval = match keyval { Some(k) => k, _ => { break; }, }; if keyval.len()!= 2 { return Err(Error::custom("Invalid key value pair.")); } let ref key_str: Option<String> = keyval[0]; let ref val_str: Option<String> = keyval[1]; let key = match *key_str { Some(ref k) if k.starts_with("0x") => try!(Bytes::from_str(k).map_err(Error::custom)), Some(ref k) => Bytes::new(k.clone().into_bytes()), None => { break; } }; let val = match *val_str { Some(ref v) if v.starts_with("0x") => Some(try!(Bytes::from_str(v).map_err(Error::custom))), Some(ref v) => Some(Bytes::new(v.clone().into_bytes())), None => None, }; result.insert(key, val); } try!(visitor.end()); let input = Input { data: result }; Ok(input) } } #[cfg(test)] mod tests { use std::collections::BTreeMap; use serde_json; use bytes::Bytes; use super::Input; #[test] fn input_deserialization_from_map() { let s = r#"{ "0x0045" : "0x0123456789", "be" : "e", "0x0a" : null }"#; let input: Input = serde_json::from_str(s).unwrap(); let mut map = BTreeMap::new(); map.insert(Bytes::new(vec![0, 0x45]), Some(Bytes::new(vec![0x01, 0x23, 0x45, 0x67, 0x89]))); map.insert(Bytes::new(vec![0x62, 0x65]), Some(Bytes::new(vec![0x65]))); map.insert(Bytes::new(vec![0x0a]), None); assert_eq!(input.data, map); } #[test] fn input_deserialization_from_array() { let s = r#"[ ["0x0045", "0x0123456789"], ["be", "e"], ["0x0a", null] ]"#; let input: Input = serde_json::from_str(s).unwrap(); let mut map = BTreeMap::new(); map.insert(Bytes::new(vec![0, 0x45]), Some(Bytes::new(vec![0x01, 0x23, 0x45, 0x67, 0x89]))); map.insert(Bytes::new(vec![0x62, 0x65]), Some(Bytes::new(vec![0x65]))); map.insert(Bytes::new(vec![0x0a]), None); assert_eq!(input.data, map); } }
deserialize
identifier_name
input.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Trie test input deserialization. use std::collections::BTreeMap; use std::str::FromStr; use bytes::Bytes; use serde::{Deserialize, Deserializer, Error}; use serde::de::{Visitor, MapVisitor, SeqVisitor}; /// Trie test input. #[derive(Debug, PartialEq)] pub struct Input { /// Input params. pub data: BTreeMap<Bytes, Option<Bytes>>, } impl Deserialize for Input { fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error> where D: Deserializer { deserializer.deserialize(InputVisitor) } } struct InputVisitor; impl Visitor for InputVisitor { type Value = Input; fn visit_map<V>(&mut self, mut visitor: V) -> Result<Self::Value, V::Error> where V: MapVisitor { let mut result = BTreeMap::new(); loop { let key_str: Option<String> = try!(visitor.visit_key()); let key = match key_str { Some(ref k) if k.starts_with("0x") => try!(Bytes::from_str(k).map_err(Error::custom)), Some(k) => Bytes::new(k.into_bytes()), None => { break; } }; let val_str: Option<String> = try!(visitor.visit_value()); let val = match val_str { Some(ref v) if v.starts_with("0x") => Some(try!(Bytes::from_str(v).map_err(Error::custom))), Some(v) => Some(Bytes::new(v.into_bytes())), None => None, }; result.insert(key, val); } try!(visitor.end()); let input = Input { data: result }; Ok(input) } fn visit_seq<V>(&mut self, mut visitor: V) -> Result<Self::Value, V::Error> where V: SeqVisitor { let mut result = BTreeMap::new(); loop { let keyval: Option<Vec<Option<String>>> = try!(visitor.visit()); let keyval = match keyval { Some(k) => k, _ => { break; }, }; if keyval.len()!= 2 { return Err(Error::custom("Invalid key value pair.")); } let ref key_str: Option<String> = keyval[0]; let ref val_str: Option<String> = keyval[1]; let key = match *key_str { Some(ref k) if k.starts_with("0x") => try!(Bytes::from_str(k).map_err(Error::custom)), Some(ref k) => Bytes::new(k.clone().into_bytes()), None => { break; } }; let val = match *val_str { Some(ref v) if v.starts_with("0x") => Some(try!(Bytes::from_str(v).map_err(Error::custom))), Some(ref v) => Some(Bytes::new(v.clone().into_bytes())), None => None,
try!(visitor.end()); let input = Input { data: result }; Ok(input) } } #[cfg(test)] mod tests { use std::collections::BTreeMap; use serde_json; use bytes::Bytes; use super::Input; #[test] fn input_deserialization_from_map() { let s = r#"{ "0x0045" : "0x0123456789", "be" : "e", "0x0a" : null }"#; let input: Input = serde_json::from_str(s).unwrap(); let mut map = BTreeMap::new(); map.insert(Bytes::new(vec![0, 0x45]), Some(Bytes::new(vec![0x01, 0x23, 0x45, 0x67, 0x89]))); map.insert(Bytes::new(vec![0x62, 0x65]), Some(Bytes::new(vec![0x65]))); map.insert(Bytes::new(vec![0x0a]), None); assert_eq!(input.data, map); } #[test] fn input_deserialization_from_array() { let s = r#"[ ["0x0045", "0x0123456789"], ["be", "e"], ["0x0a", null] ]"#; let input: Input = serde_json::from_str(s).unwrap(); let mut map = BTreeMap::new(); map.insert(Bytes::new(vec![0, 0x45]), Some(Bytes::new(vec![0x01, 0x23, 0x45, 0x67, 0x89]))); map.insert(Bytes::new(vec![0x62, 0x65]), Some(Bytes::new(vec![0x65]))); map.insert(Bytes::new(vec![0x0a]), None); assert_eq!(input.data, map); } }
}; result.insert(key, val); }
random_line_split
htmlstyleelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::{Parser as CssParser, ParserInput}; use dom::bindings::cell::DomRefCell; use dom::bindings::codegen::Bindings::HTMLStyleElementBinding; use dom::bindings::codegen::Bindings::HTMLStyleElementBinding::HTMLStyleElementMethods; use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use dom::bindings::inheritance::Castable; use dom::bindings::root::{DomRoot, MutNullableDom}; use dom::cssstylesheet::CSSStyleSheet; use dom::document::Document; use dom::element::{Element, ElementCreator}; use dom::eventtarget::EventTarget; use dom::htmlelement::HTMLElement; use dom::node::{ChildrenMutation, Node, UnbindContext, document_from_node, window_from_node}; use dom::stylesheet::StyleSheet as DOMStyleSheet; use dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; use net_traits::ReferrerPolicy; use servo_arc::Arc; use std::cell::Cell; use style::media_queries::parse_media_query_list; use style::parser::ParserContext as CssParserContext; use style::stylesheets::{CssRuleType, Stylesheet, Origin}; use style_traits::PARSING_MODE_DEFAULT; use stylesheet_loader::{StylesheetLoader, StylesheetOwner}; #[dom_struct] pub struct HTMLStyleElement { htmlelement: HTMLElement, #[ignore_heap_size_of = "Arc"] stylesheet: DomRefCell<Option<Arc<Stylesheet>>>, cssom_stylesheet: MutNullableDom<CSSStyleSheet>, /// https://html.spec.whatwg.org/multipage/#a-style-sheet-that-is-blocking-scripts parser_inserted: Cell<bool>, in_stack_of_open_elements: Cell<bool>, pending_loads: Cell<u32>,
impl HTMLStyleElement { fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document, creator: ElementCreator) -> HTMLStyleElement { HTMLStyleElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), stylesheet: DomRefCell::new(None), cssom_stylesheet: MutNullableDom::new(None), parser_inserted: Cell::new(creator.is_parser_created()), in_stack_of_open_elements: Cell::new(creator.is_parser_created()), pending_loads: Cell::new(0), any_failed_load: Cell::new(false), line_number: creator.return_line_number(), } } #[allow(unrooted_must_root)] pub fn new(local_name: LocalName, prefix: Option<Prefix>, document: &Document, creator: ElementCreator) -> DomRoot<HTMLStyleElement> { Node::reflect_node(box HTMLStyleElement::new_inherited(local_name, prefix, document, creator), document, HTMLStyleElementBinding::Wrap) } pub fn parse_own_css(&self) { let node = self.upcast::<Node>(); let element = self.upcast::<Element>(); assert!(node.is_in_doc()); let window = window_from_node(node); let doc = document_from_node(self); let mq_attribute = element.get_attribute(&ns!(), &local_name!("media")); let mq_str = match mq_attribute { Some(a) => String::from(&**a.value()), None => String::new(), }; let data = node.GetTextContent().expect("Element.textContent must be a string"); let url = window.get_url(); let context = CssParserContext::new_for_cssom(&url, Some(CssRuleType::Media), PARSING_MODE_DEFAULT, doc.quirks_mode()); let shared_lock = node.owner_doc().style_shared_lock().clone(); let mut input = ParserInput::new(&mq_str); let css_error_reporter = window.css_error_reporter(); let mq = Arc::new(shared_lock.wrap(parse_media_query_list(&context, &mut CssParser::new(&mut input), css_error_reporter))); let loader = StylesheetLoader::for_element(self.upcast()); let sheet = Stylesheet::from_str(&data, window.get_url(), Origin::Author, mq, shared_lock, Some(&loader), css_error_reporter, doc.quirks_mode(), self.line_number as u32); let sheet = Arc::new(sheet); // No subresource loads were triggered, just fire the load event now. if self.pending_loads.get() == 0 { self.upcast::<EventTarget>().fire_event(atom!("load")); } self.set_stylesheet(sheet); } // FIXME(emilio): This is duplicated with HTMLLinkElement::set_stylesheet. pub fn set_stylesheet(&self, s: Arc<Stylesheet>) { let doc = document_from_node(self); if let Some(ref s) = *self.stylesheet.borrow() { doc.remove_stylesheet(self.upcast(), s) } *self.stylesheet.borrow_mut() = Some(s.clone()); self.cssom_stylesheet.set(None); doc.add_stylesheet(self.upcast(), s); } pub fn get_stylesheet(&self) -> Option<Arc<Stylesheet>> { self.stylesheet.borrow().clone() } pub fn get_cssom_stylesheet(&self) -> Option<DomRoot<CSSStyleSheet>> { self.get_stylesheet().map(|sheet| { self.cssom_stylesheet.or_init(|| { CSSStyleSheet::new(&window_from_node(self), self.upcast::<Element>(), "text/css".into(), None, // todo handle location None, // todo handle title sheet) }) }) } } impl VirtualMethods for HTMLStyleElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn children_changed(&self, mutation: &ChildrenMutation) { self.super_type().unwrap().children_changed(mutation); // https://html.spec.whatwg.org/multipage/#update-a-style-block // Handles the case when: // "The element is not on the stack of open elements of an HTML parser or XML parser, // and one of its child nodes is modified by a script." // TODO: Handle Text child contents being mutated. if self.upcast::<Node>().is_in_doc() &&!self.in_stack_of_open_elements.get() { self.parse_own_css(); } } fn bind_to_tree(&self, tree_in_doc: bool) { self.super_type().unwrap().bind_to_tree(tree_in_doc); // https://html.spec.whatwg.org/multipage/#update-a-style-block // Handles the case when: // "The element is not on the stack of open elements of an HTML parser or XML parser, // and it becomes connected or disconnected." if tree_in_doc &&!self.in_stack_of_open_elements.get() { self.parse_own_css(); } } fn pop(&self) { self.super_type().unwrap().pop(); // https://html.spec.whatwg.org/multipage/#update-a-style-block // Handles the case when: // "The element is popped off the stack of open elements of an HTML parser or XML parser." self.in_stack_of_open_elements.set(false); if self.upcast::<Node>().is_in_doc() { self.parse_own_css(); } } fn unbind_from_tree(&self, context: &UnbindContext) { if let Some(ref s) = self.super_type() { s.unbind_from_tree(context); } if context.tree_in_doc { if let Some(s) = self.stylesheet.borrow_mut().take() { document_from_node(self).remove_stylesheet(self.upcast(), &s) } } } } impl StylesheetOwner for HTMLStyleElement { fn increment_pending_loads_count(&self) { self.pending_loads.set(self.pending_loads.get() + 1) } fn load_finished(&self, succeeded: bool) -> Option<bool> { assert!(self.pending_loads.get() > 0, "What finished?"); if!succeeded { self.any_failed_load.set(true); } self.pending_loads.set(self.pending_loads.get() - 1); if self.pending_loads.get()!= 0 { return None; } let any_failed = self.any_failed_load.get(); self.any_failed_load.set(false); Some(any_failed) } fn parser_inserted(&self) -> bool { self.parser_inserted.get() } fn referrer_policy(&self) -> Option<ReferrerPolicy> { None } fn set_origin_clean(&self, origin_clean: bool) { if let Some(stylesheet) = self.get_cssom_stylesheet() { stylesheet.set_origin_clean(origin_clean); } } } impl HTMLStyleElementMethods for HTMLStyleElement { // https://drafts.csswg.org/cssom/#dom-linkstyle-sheet fn GetSheet(&self) -> Option<DomRoot<DOMStyleSheet>> { self.get_cssom_stylesheet().map(DomRoot::upcast) } }
any_failed_load: Cell<bool>, line_number: u64, }
random_line_split
htmlstyleelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::{Parser as CssParser, ParserInput}; use dom::bindings::cell::DomRefCell; use dom::bindings::codegen::Bindings::HTMLStyleElementBinding; use dom::bindings::codegen::Bindings::HTMLStyleElementBinding::HTMLStyleElementMethods; use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use dom::bindings::inheritance::Castable; use dom::bindings::root::{DomRoot, MutNullableDom}; use dom::cssstylesheet::CSSStyleSheet; use dom::document::Document; use dom::element::{Element, ElementCreator}; use dom::eventtarget::EventTarget; use dom::htmlelement::HTMLElement; use dom::node::{ChildrenMutation, Node, UnbindContext, document_from_node, window_from_node}; use dom::stylesheet::StyleSheet as DOMStyleSheet; use dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; use net_traits::ReferrerPolicy; use servo_arc::Arc; use std::cell::Cell; use style::media_queries::parse_media_query_list; use style::parser::ParserContext as CssParserContext; use style::stylesheets::{CssRuleType, Stylesheet, Origin}; use style_traits::PARSING_MODE_DEFAULT; use stylesheet_loader::{StylesheetLoader, StylesheetOwner}; #[dom_struct] pub struct HTMLStyleElement { htmlelement: HTMLElement, #[ignore_heap_size_of = "Arc"] stylesheet: DomRefCell<Option<Arc<Stylesheet>>>, cssom_stylesheet: MutNullableDom<CSSStyleSheet>, /// https://html.spec.whatwg.org/multipage/#a-style-sheet-that-is-blocking-scripts parser_inserted: Cell<bool>, in_stack_of_open_elements: Cell<bool>, pending_loads: Cell<u32>, any_failed_load: Cell<bool>, line_number: u64, } impl HTMLStyleElement { fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document, creator: ElementCreator) -> HTMLStyleElement { HTMLStyleElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), stylesheet: DomRefCell::new(None), cssom_stylesheet: MutNullableDom::new(None), parser_inserted: Cell::new(creator.is_parser_created()), in_stack_of_open_elements: Cell::new(creator.is_parser_created()), pending_loads: Cell::new(0), any_failed_load: Cell::new(false), line_number: creator.return_line_number(), } } #[allow(unrooted_must_root)] pub fn new(local_name: LocalName, prefix: Option<Prefix>, document: &Document, creator: ElementCreator) -> DomRoot<HTMLStyleElement> { Node::reflect_node(box HTMLStyleElement::new_inherited(local_name, prefix, document, creator), document, HTMLStyleElementBinding::Wrap) } pub fn parse_own_css(&self) { let node = self.upcast::<Node>(); let element = self.upcast::<Element>(); assert!(node.is_in_doc()); let window = window_from_node(node); let doc = document_from_node(self); let mq_attribute = element.get_attribute(&ns!(), &local_name!("media")); let mq_str = match mq_attribute { Some(a) => String::from(&**a.value()), None => String::new(), }; let data = node.GetTextContent().expect("Element.textContent must be a string"); let url = window.get_url(); let context = CssParserContext::new_for_cssom(&url, Some(CssRuleType::Media), PARSING_MODE_DEFAULT, doc.quirks_mode()); let shared_lock = node.owner_doc().style_shared_lock().clone(); let mut input = ParserInput::new(&mq_str); let css_error_reporter = window.css_error_reporter(); let mq = Arc::new(shared_lock.wrap(parse_media_query_list(&context, &mut CssParser::new(&mut input), css_error_reporter))); let loader = StylesheetLoader::for_element(self.upcast()); let sheet = Stylesheet::from_str(&data, window.get_url(), Origin::Author, mq, shared_lock, Some(&loader), css_error_reporter, doc.quirks_mode(), self.line_number as u32); let sheet = Arc::new(sheet); // No subresource loads were triggered, just fire the load event now. if self.pending_loads.get() == 0 { self.upcast::<EventTarget>().fire_event(atom!("load")); } self.set_stylesheet(sheet); } // FIXME(emilio): This is duplicated with HTMLLinkElement::set_stylesheet. pub fn set_stylesheet(&self, s: Arc<Stylesheet>) { let doc = document_from_node(self); if let Some(ref s) = *self.stylesheet.borrow() { doc.remove_stylesheet(self.upcast(), s) } *self.stylesheet.borrow_mut() = Some(s.clone()); self.cssom_stylesheet.set(None); doc.add_stylesheet(self.upcast(), s); } pub fn get_stylesheet(&self) -> Option<Arc<Stylesheet>> { self.stylesheet.borrow().clone() } pub fn get_cssom_stylesheet(&self) -> Option<DomRoot<CSSStyleSheet>> { self.get_stylesheet().map(|sheet| { self.cssom_stylesheet.or_init(|| { CSSStyleSheet::new(&window_from_node(self), self.upcast::<Element>(), "text/css".into(), None, // todo handle location None, // todo handle title sheet) }) }) } } impl VirtualMethods for HTMLStyleElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn children_changed(&self, mutation: &ChildrenMutation) { self.super_type().unwrap().children_changed(mutation); // https://html.spec.whatwg.org/multipage/#update-a-style-block // Handles the case when: // "The element is not on the stack of open elements of an HTML parser or XML parser, // and one of its child nodes is modified by a script." // TODO: Handle Text child contents being mutated. if self.upcast::<Node>().is_in_doc() &&!self.in_stack_of_open_elements.get() { self.parse_own_css(); } } fn bind_to_tree(&self, tree_in_doc: bool) { self.super_type().unwrap().bind_to_tree(tree_in_doc); // https://html.spec.whatwg.org/multipage/#update-a-style-block // Handles the case when: // "The element is not on the stack of open elements of an HTML parser or XML parser, // and it becomes connected or disconnected." if tree_in_doc &&!self.in_stack_of_open_elements.get() { self.parse_own_css(); } } fn pop(&self) { self.super_type().unwrap().pop(); // https://html.spec.whatwg.org/multipage/#update-a-style-block // Handles the case when: // "The element is popped off the stack of open elements of an HTML parser or XML parser." self.in_stack_of_open_elements.set(false); if self.upcast::<Node>().is_in_doc() { self.parse_own_css(); } } fn unbind_from_tree(&self, context: &UnbindContext) { if let Some(ref s) = self.super_type() { s.unbind_from_tree(context); } if context.tree_in_doc { if let Some(s) = self.stylesheet.borrow_mut().take() { document_from_node(self).remove_stylesheet(self.upcast(), &s) } } } } impl StylesheetOwner for HTMLStyleElement { fn increment_pending_loads_count(&self) { self.pending_loads.set(self.pending_loads.get() + 1) } fn
(&self, succeeded: bool) -> Option<bool> { assert!(self.pending_loads.get() > 0, "What finished?"); if!succeeded { self.any_failed_load.set(true); } self.pending_loads.set(self.pending_loads.get() - 1); if self.pending_loads.get()!= 0 { return None; } let any_failed = self.any_failed_load.get(); self.any_failed_load.set(false); Some(any_failed) } fn parser_inserted(&self) -> bool { self.parser_inserted.get() } fn referrer_policy(&self) -> Option<ReferrerPolicy> { None } fn set_origin_clean(&self, origin_clean: bool) { if let Some(stylesheet) = self.get_cssom_stylesheet() { stylesheet.set_origin_clean(origin_clean); } } } impl HTMLStyleElementMethods for HTMLStyleElement { // https://drafts.csswg.org/cssom/#dom-linkstyle-sheet fn GetSheet(&self) -> Option<DomRoot<DOMStyleSheet>> { self.get_cssom_stylesheet().map(DomRoot::upcast) } }
load_finished
identifier_name
htmlstyleelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::{Parser as CssParser, ParserInput}; use dom::bindings::cell::DomRefCell; use dom::bindings::codegen::Bindings::HTMLStyleElementBinding; use dom::bindings::codegen::Bindings::HTMLStyleElementBinding::HTMLStyleElementMethods; use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use dom::bindings::inheritance::Castable; use dom::bindings::root::{DomRoot, MutNullableDom}; use dom::cssstylesheet::CSSStyleSheet; use dom::document::Document; use dom::element::{Element, ElementCreator}; use dom::eventtarget::EventTarget; use dom::htmlelement::HTMLElement; use dom::node::{ChildrenMutation, Node, UnbindContext, document_from_node, window_from_node}; use dom::stylesheet::StyleSheet as DOMStyleSheet; use dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; use net_traits::ReferrerPolicy; use servo_arc::Arc; use std::cell::Cell; use style::media_queries::parse_media_query_list; use style::parser::ParserContext as CssParserContext; use style::stylesheets::{CssRuleType, Stylesheet, Origin}; use style_traits::PARSING_MODE_DEFAULT; use stylesheet_loader::{StylesheetLoader, StylesheetOwner}; #[dom_struct] pub struct HTMLStyleElement { htmlelement: HTMLElement, #[ignore_heap_size_of = "Arc"] stylesheet: DomRefCell<Option<Arc<Stylesheet>>>, cssom_stylesheet: MutNullableDom<CSSStyleSheet>, /// https://html.spec.whatwg.org/multipage/#a-style-sheet-that-is-blocking-scripts parser_inserted: Cell<bool>, in_stack_of_open_elements: Cell<bool>, pending_loads: Cell<u32>, any_failed_load: Cell<bool>, line_number: u64, } impl HTMLStyleElement { fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document, creator: ElementCreator) -> HTMLStyleElement { HTMLStyleElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), stylesheet: DomRefCell::new(None), cssom_stylesheet: MutNullableDom::new(None), parser_inserted: Cell::new(creator.is_parser_created()), in_stack_of_open_elements: Cell::new(creator.is_parser_created()), pending_loads: Cell::new(0), any_failed_load: Cell::new(false), line_number: creator.return_line_number(), } } #[allow(unrooted_must_root)] pub fn new(local_name: LocalName, prefix: Option<Prefix>, document: &Document, creator: ElementCreator) -> DomRoot<HTMLStyleElement> { Node::reflect_node(box HTMLStyleElement::new_inherited(local_name, prefix, document, creator), document, HTMLStyleElementBinding::Wrap) } pub fn parse_own_css(&self) { let node = self.upcast::<Node>(); let element = self.upcast::<Element>(); assert!(node.is_in_doc()); let window = window_from_node(node); let doc = document_from_node(self); let mq_attribute = element.get_attribute(&ns!(), &local_name!("media")); let mq_str = match mq_attribute { Some(a) => String::from(&**a.value()), None => String::new(), }; let data = node.GetTextContent().expect("Element.textContent must be a string"); let url = window.get_url(); let context = CssParserContext::new_for_cssom(&url, Some(CssRuleType::Media), PARSING_MODE_DEFAULT, doc.quirks_mode()); let shared_lock = node.owner_doc().style_shared_lock().clone(); let mut input = ParserInput::new(&mq_str); let css_error_reporter = window.css_error_reporter(); let mq = Arc::new(shared_lock.wrap(parse_media_query_list(&context, &mut CssParser::new(&mut input), css_error_reporter))); let loader = StylesheetLoader::for_element(self.upcast()); let sheet = Stylesheet::from_str(&data, window.get_url(), Origin::Author, mq, shared_lock, Some(&loader), css_error_reporter, doc.quirks_mode(), self.line_number as u32); let sheet = Arc::new(sheet); // No subresource loads were triggered, just fire the load event now. if self.pending_loads.get() == 0 { self.upcast::<EventTarget>().fire_event(atom!("load")); } self.set_stylesheet(sheet); } // FIXME(emilio): This is duplicated with HTMLLinkElement::set_stylesheet. pub fn set_stylesheet(&self, s: Arc<Stylesheet>) { let doc = document_from_node(self); if let Some(ref s) = *self.stylesheet.borrow() { doc.remove_stylesheet(self.upcast(), s) } *self.stylesheet.borrow_mut() = Some(s.clone()); self.cssom_stylesheet.set(None); doc.add_stylesheet(self.upcast(), s); } pub fn get_stylesheet(&self) -> Option<Arc<Stylesheet>> { self.stylesheet.borrow().clone() } pub fn get_cssom_stylesheet(&self) -> Option<DomRoot<CSSStyleSheet>> { self.get_stylesheet().map(|sheet| { self.cssom_stylesheet.or_init(|| { CSSStyleSheet::new(&window_from_node(self), self.upcast::<Element>(), "text/css".into(), None, // todo handle location None, // todo handle title sheet) }) }) } } impl VirtualMethods for HTMLStyleElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn children_changed(&self, mutation: &ChildrenMutation) { self.super_type().unwrap().children_changed(mutation); // https://html.spec.whatwg.org/multipage/#update-a-style-block // Handles the case when: // "The element is not on the stack of open elements of an HTML parser or XML parser, // and one of its child nodes is modified by a script." // TODO: Handle Text child contents being mutated. if self.upcast::<Node>().is_in_doc() &&!self.in_stack_of_open_elements.get() { self.parse_own_css(); } } fn bind_to_tree(&self, tree_in_doc: bool) { self.super_type().unwrap().bind_to_tree(tree_in_doc); // https://html.spec.whatwg.org/multipage/#update-a-style-block // Handles the case when: // "The element is not on the stack of open elements of an HTML parser or XML parser, // and it becomes connected or disconnected." if tree_in_doc &&!self.in_stack_of_open_elements.get() { self.parse_own_css(); } } fn pop(&self) { self.super_type().unwrap().pop(); // https://html.spec.whatwg.org/multipage/#update-a-style-block // Handles the case when: // "The element is popped off the stack of open elements of an HTML parser or XML parser." self.in_stack_of_open_elements.set(false); if self.upcast::<Node>().is_in_doc() { self.parse_own_css(); } } fn unbind_from_tree(&self, context: &UnbindContext) { if let Some(ref s) = self.super_type() { s.unbind_from_tree(context); } if context.tree_in_doc { if let Some(s) = self.stylesheet.borrow_mut().take() { document_from_node(self).remove_stylesheet(self.upcast(), &s) } } } } impl StylesheetOwner for HTMLStyleElement { fn increment_pending_loads_count(&self) { self.pending_loads.set(self.pending_loads.get() + 1) } fn load_finished(&self, succeeded: bool) -> Option<bool> { assert!(self.pending_loads.get() > 0, "What finished?"); if!succeeded { self.any_failed_load.set(true); } self.pending_loads.set(self.pending_loads.get() - 1); if self.pending_loads.get()!= 0 { return None; } let any_failed = self.any_failed_load.get(); self.any_failed_load.set(false); Some(any_failed) } fn parser_inserted(&self) -> bool { self.parser_inserted.get() } fn referrer_policy(&self) -> Option<ReferrerPolicy> { None } fn set_origin_clean(&self, origin_clean: bool) { if let Some(stylesheet) = self.get_cssom_stylesheet() { stylesheet.set_origin_clean(origin_clean); } } } impl HTMLStyleElementMethods for HTMLStyleElement { // https://drafts.csswg.org/cssom/#dom-linkstyle-sheet fn GetSheet(&self) -> Option<DomRoot<DOMStyleSheet>>
}
{ self.get_cssom_stylesheet().map(DomRoot::upcast) }
identifier_body
htmlstyleelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::{Parser as CssParser, ParserInput}; use dom::bindings::cell::DomRefCell; use dom::bindings::codegen::Bindings::HTMLStyleElementBinding; use dom::bindings::codegen::Bindings::HTMLStyleElementBinding::HTMLStyleElementMethods; use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use dom::bindings::inheritance::Castable; use dom::bindings::root::{DomRoot, MutNullableDom}; use dom::cssstylesheet::CSSStyleSheet; use dom::document::Document; use dom::element::{Element, ElementCreator}; use dom::eventtarget::EventTarget; use dom::htmlelement::HTMLElement; use dom::node::{ChildrenMutation, Node, UnbindContext, document_from_node, window_from_node}; use dom::stylesheet::StyleSheet as DOMStyleSheet; use dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; use net_traits::ReferrerPolicy; use servo_arc::Arc; use std::cell::Cell; use style::media_queries::parse_media_query_list; use style::parser::ParserContext as CssParserContext; use style::stylesheets::{CssRuleType, Stylesheet, Origin}; use style_traits::PARSING_MODE_DEFAULT; use stylesheet_loader::{StylesheetLoader, StylesheetOwner}; #[dom_struct] pub struct HTMLStyleElement { htmlelement: HTMLElement, #[ignore_heap_size_of = "Arc"] stylesheet: DomRefCell<Option<Arc<Stylesheet>>>, cssom_stylesheet: MutNullableDom<CSSStyleSheet>, /// https://html.spec.whatwg.org/multipage/#a-style-sheet-that-is-blocking-scripts parser_inserted: Cell<bool>, in_stack_of_open_elements: Cell<bool>, pending_loads: Cell<u32>, any_failed_load: Cell<bool>, line_number: u64, } impl HTMLStyleElement { fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document, creator: ElementCreator) -> HTMLStyleElement { HTMLStyleElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), stylesheet: DomRefCell::new(None), cssom_stylesheet: MutNullableDom::new(None), parser_inserted: Cell::new(creator.is_parser_created()), in_stack_of_open_elements: Cell::new(creator.is_parser_created()), pending_loads: Cell::new(0), any_failed_load: Cell::new(false), line_number: creator.return_line_number(), } } #[allow(unrooted_must_root)] pub fn new(local_name: LocalName, prefix: Option<Prefix>, document: &Document, creator: ElementCreator) -> DomRoot<HTMLStyleElement> { Node::reflect_node(box HTMLStyleElement::new_inherited(local_name, prefix, document, creator), document, HTMLStyleElementBinding::Wrap) } pub fn parse_own_css(&self) { let node = self.upcast::<Node>(); let element = self.upcast::<Element>(); assert!(node.is_in_doc()); let window = window_from_node(node); let doc = document_from_node(self); let mq_attribute = element.get_attribute(&ns!(), &local_name!("media")); let mq_str = match mq_attribute { Some(a) => String::from(&**a.value()), None => String::new(), }; let data = node.GetTextContent().expect("Element.textContent must be a string"); let url = window.get_url(); let context = CssParserContext::new_for_cssom(&url, Some(CssRuleType::Media), PARSING_MODE_DEFAULT, doc.quirks_mode()); let shared_lock = node.owner_doc().style_shared_lock().clone(); let mut input = ParserInput::new(&mq_str); let css_error_reporter = window.css_error_reporter(); let mq = Arc::new(shared_lock.wrap(parse_media_query_list(&context, &mut CssParser::new(&mut input), css_error_reporter))); let loader = StylesheetLoader::for_element(self.upcast()); let sheet = Stylesheet::from_str(&data, window.get_url(), Origin::Author, mq, shared_lock, Some(&loader), css_error_reporter, doc.quirks_mode(), self.line_number as u32); let sheet = Arc::new(sheet); // No subresource loads were triggered, just fire the load event now. if self.pending_loads.get() == 0 { self.upcast::<EventTarget>().fire_event(atom!("load")); } self.set_stylesheet(sheet); } // FIXME(emilio): This is duplicated with HTMLLinkElement::set_stylesheet. pub fn set_stylesheet(&self, s: Arc<Stylesheet>) { let doc = document_from_node(self); if let Some(ref s) = *self.stylesheet.borrow() { doc.remove_stylesheet(self.upcast(), s) } *self.stylesheet.borrow_mut() = Some(s.clone()); self.cssom_stylesheet.set(None); doc.add_stylesheet(self.upcast(), s); } pub fn get_stylesheet(&self) -> Option<Arc<Stylesheet>> { self.stylesheet.borrow().clone() } pub fn get_cssom_stylesheet(&self) -> Option<DomRoot<CSSStyleSheet>> { self.get_stylesheet().map(|sheet| { self.cssom_stylesheet.or_init(|| { CSSStyleSheet::new(&window_from_node(self), self.upcast::<Element>(), "text/css".into(), None, // todo handle location None, // todo handle title sheet) }) }) } } impl VirtualMethods for HTMLStyleElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn children_changed(&self, mutation: &ChildrenMutation) { self.super_type().unwrap().children_changed(mutation); // https://html.spec.whatwg.org/multipage/#update-a-style-block // Handles the case when: // "The element is not on the stack of open elements of an HTML parser or XML parser, // and one of its child nodes is modified by a script." // TODO: Handle Text child contents being mutated. if self.upcast::<Node>().is_in_doc() &&!self.in_stack_of_open_elements.get() { self.parse_own_css(); } } fn bind_to_tree(&self, tree_in_doc: bool) { self.super_type().unwrap().bind_to_tree(tree_in_doc); // https://html.spec.whatwg.org/multipage/#update-a-style-block // Handles the case when: // "The element is not on the stack of open elements of an HTML parser or XML parser, // and it becomes connected or disconnected." if tree_in_doc &&!self.in_stack_of_open_elements.get() { self.parse_own_css(); } } fn pop(&self) { self.super_type().unwrap().pop(); // https://html.spec.whatwg.org/multipage/#update-a-style-block // Handles the case when: // "The element is popped off the stack of open elements of an HTML parser or XML parser." self.in_stack_of_open_elements.set(false); if self.upcast::<Node>().is_in_doc() { self.parse_own_css(); } } fn unbind_from_tree(&self, context: &UnbindContext) { if let Some(ref s) = self.super_type() { s.unbind_from_tree(context); } if context.tree_in_doc { if let Some(s) = self.stylesheet.borrow_mut().take() { document_from_node(self).remove_stylesheet(self.upcast(), &s) } } } } impl StylesheetOwner for HTMLStyleElement { fn increment_pending_loads_count(&self) { self.pending_loads.set(self.pending_loads.get() + 1) } fn load_finished(&self, succeeded: bool) -> Option<bool> { assert!(self.pending_loads.get() > 0, "What finished?"); if!succeeded
self.pending_loads.set(self.pending_loads.get() - 1); if self.pending_loads.get()!= 0 { return None; } let any_failed = self.any_failed_load.get(); self.any_failed_load.set(false); Some(any_failed) } fn parser_inserted(&self) -> bool { self.parser_inserted.get() } fn referrer_policy(&self) -> Option<ReferrerPolicy> { None } fn set_origin_clean(&self, origin_clean: bool) { if let Some(stylesheet) = self.get_cssom_stylesheet() { stylesheet.set_origin_clean(origin_clean); } } } impl HTMLStyleElementMethods for HTMLStyleElement { // https://drafts.csswg.org/cssom/#dom-linkstyle-sheet fn GetSheet(&self) -> Option<DomRoot<DOMStyleSheet>> { self.get_cssom_stylesheet().map(DomRoot::upcast) } }
{ self.any_failed_load.set(true); }
conditional_block
crate-method-reexport-grrrrrrr.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // pretty-expanded FIXME #23616 #![allow(unknown_features)] #![feature(box_syntax)] // This is a regression test that the metadata for the // name_pool::methods impl in the other crate is reachable from this // crate. // aux-build:crate-method-reexport-grrrrrrr2.rs extern crate crate_method_reexport_grrrrrrr2; pub fn main()
{ use crate_method_reexport_grrrrrrr2::rust::add; use crate_method_reexport_grrrrrrr2::rust::cx; let x: Box<_> = box () (); x.cx(); let y = (); y.add("hi".to_string()); }
identifier_body
crate-method-reexport-grrrrrrr.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // pretty-expanded FIXME #23616 #![allow(unknown_features)] #![feature(box_syntax)]
// aux-build:crate-method-reexport-grrrrrrr2.rs extern crate crate_method_reexport_grrrrrrr2; pub fn main() { use crate_method_reexport_grrrrrrr2::rust::add; use crate_method_reexport_grrrrrrr2::rust::cx; let x: Box<_> = box () (); x.cx(); let y = (); y.add("hi".to_string()); }
// This is a regression test that the metadata for the // name_pool::methods impl in the other crate is reachable from this // crate.
random_line_split
crate-method-reexport-grrrrrrr.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // pretty-expanded FIXME #23616 #![allow(unknown_features)] #![feature(box_syntax)] // This is a regression test that the metadata for the // name_pool::methods impl in the other crate is reachable from this // crate. // aux-build:crate-method-reexport-grrrrrrr2.rs extern crate crate_method_reexport_grrrrrrr2; pub fn
() { use crate_method_reexport_grrrrrrr2::rust::add; use crate_method_reexport_grrrrrrr2::rust::cx; let x: Box<_> = box () (); x.cx(); let y = (); y.add("hi".to_string()); }
main
identifier_name
timer.rs
//! Timing and measurement functions. //! //! ggez does not try to do any framerate limitation by default. If //! you want to run at anything other than full-bore max speed all the //! time, call [`thread::yield_now()`](https://doc.rust-lang.org/std/thread/fn.yield_now.html) //! (or [`timer::yield_now()`](fn.yield_now.html) which does the same //! thing) to yield to the OS so it has a chance to breathe before continuing //! with your game. This should prevent it from using 100% CPU as much unless it //! really needs to. Enabling vsync by setting //! [`conf.window_setup.vsync`](../conf/struct.WindowSetup.html#structfield.vsync) //! in your [`Conf`](../conf/struct.Conf.html) object is generally the best //! way to cap your displayed framerate. //! //! For a more detailed tutorial in how to handle frame timings in games, //! see <http://gafferongames.com/game-physics/fix-your-timestep/> use crate::context::Context; use std::cmp; use std::convert::TryFrom; use std::f64; use std::thread; use std::time; /// A simple buffer that fills /// up to a limit and then holds the last /// N items that have been inserted into it, /// overwriting old ones in a round-robin fashion. /// /// It's not quite a ring buffer 'cause you can't /// remove items from it, it just holds the last N /// things. #[derive(Debug, Clone)] struct LogBuffer<T> where T: Clone, { head: usize, size: usize, /// The number of actual samples inserted, used for /// smarter averaging. samples: usize, contents: Vec<T>, } impl<T> LogBuffer<T> where T: Clone + Copy, { fn new(size: usize, init_val: T) -> LogBuffer<T> { LogBuffer { head: 0, size, contents: vec![init_val; size], // Never divide by 0 samples: 1, } } /// Pushes a new item into the `LogBuffer`, overwriting /// the oldest item in it. fn push(&mut self, item: T) { self.head = (self.head + 1) % self.contents.len(); self.contents[self.head] = item; self.size = cmp::min(self.size + 1, self.contents.len()); self.samples += 1; } /// Returns a slice pointing at the contents of the buffer. /// They are in *no particular order*, and if not all the /// slots are filled, the empty slots will be present but /// contain the initial value given to [`new()`](#method.new). /// /// We're only using this to log FPS for a short time, /// so we don't care for the second or so when it's inaccurate. fn contents(&self) -> &[T] { if self.samples > self.size { &self.contents } else { &self.contents[..self.samples] } } /// Returns the most recent value in the buffer. fn latest(&self) -> T { self.contents[self.head] } } /// A structure that contains our time-tracking state. #[derive(Debug)] pub struct TimeContext { init_instant: time::Instant, last_instant: time::Instant, frame_durations: LogBuffer<time::Duration>, residual_update_dt: time::Duration, frame_count: usize, } /// How many frames we log update times for. const TIME_LOG_FRAMES: usize = 200; impl TimeContext { /// Creates a new `TimeContext` and initializes the start to this instant. pub fn new() -> TimeContext { let initial_dt = time::Duration::from_millis(16); TimeContext { init_instant: time::Instant::now(), last_instant: time::Instant::now(), frame_durations: LogBuffer::new(TIME_LOG_FRAMES, initial_dt), residual_update_dt: time::Duration::from_secs(0), frame_count: 0, } } /// Update the state of the `TimeContext` to record that /// another frame has taken place. Necessary for the FPS /// tracking and [`check_update_time()`](fn.check_update_time.html) /// functions to work. /// /// It's usually not necessary to call this function yourself, /// [`event::run()`](../event/fn.run.html) will do it for you. pub fn tick(&mut self) { let now = time::Instant::now(); let time_since_last = now - self.last_instant; self.frame_durations.push(time_since_last); self.last_instant = now; self.frame_count += 1; self.residual_update_dt += time_since_last; } } impl Default for TimeContext { fn default() -> Self { Self::new() } } /// Get the time between the start of the last frame and the current one; /// in other words, the length of the last frame. pub fn delta(ctx: &Context) -> time::Duration { let tc = &ctx.timer_context; tc.frame_durations.latest() } /// Gets the average time of a frame, averaged /// over the last 200 frames. pub fn average_delta(ctx: &Context) -> time::Duration { let tc = &ctx.timer_context; let sum: time::Duration = tc.frame_durations.contents().iter().sum(); // If our buffer is actually full, divide by its size. // Otherwise divide by the number of samples we've added if tc.frame_durations.samples > tc.frame_durations.size { sum / u32::try_from(tc.frame_durations.size).unwrap() } else
} /// A convenience function to convert a Rust `Duration` type /// to a (less precise but more useful) `f64`. /// /// Does not make sure that the `Duration` is within the bounds /// of the `f64`. pub fn duration_to_f64(d: time::Duration) -> f64 { let seconds = d.as_secs() as f64; let nanos = f64::from(d.subsec_nanos()); seconds + (nanos * 1e-9) } /// A convenience function to create a Rust `Duration` type /// from a (less precise but more useful) `f64`. /// /// Only handles positive numbers correctly. pub fn f64_to_duration(t: f64) -> time::Duration { debug_assert!(t > 0.0, "f64_to_duration passed a negative number!"); let seconds = t.trunc(); let nanos = t.fract() * 1e9; time::Duration::new(seconds as u64, nanos as u32) } /// Returns a `Duration` representing how long each /// frame should be to match the given fps. /// /// Approximately. fn fps_as_duration(fps: u32) -> time::Duration { let target_dt_seconds = 1.0 / f64::from(fps); f64_to_duration(target_dt_seconds) } /// Gets the FPS of the game, averaged over the last /// 200 frames. pub fn fps(ctx: &Context) -> f64 { let duration_per_frame = average_delta(ctx); let seconds_per_frame = duration_to_f64(duration_per_frame); 1.0 / seconds_per_frame } /// Returns the time since the game was initialized, /// as reported by the system clock. pub fn time_since_start(ctx: &Context) -> time::Duration { let tc = &ctx.timer_context; time::Instant::now() - tc.init_instant } /// Check whether or not the desired amount of time has elapsed /// since the last frame. /// /// The intention is to use this in your `update` call to control /// how often game logic is updated per frame (see [the astroblasto example](https://github.com/ggez/ggez/blob/30ea4a4ead67557d2ebb39550e17339323fc9c58/examples/05_astroblasto.rs#L438-L442)). /// /// Calling this decreases a timer inside the context if the function returns true. /// If called in a loop it may therefore return true once, twice or not at all, depending on /// how much time elapsed since the last frame. /// /// For more info on the idea behind this see <http://gafferongames.com/game-physics/fix-your-timestep/>. /// /// Due to the global nature of this timer it's desirable to only use this function at one point /// of your code. If you want to limit the frame rate in both game logic and drawing consider writing /// your own event loop, or using a dirty bit for when to redraw graphics, which is set whenever the game /// logic runs. pub fn check_update_time(ctx: &mut Context, target_fps: u32) -> bool { let timedata = &mut ctx.timer_context; let target_dt = fps_as_duration(target_fps); if timedata.residual_update_dt > target_dt { timedata.residual_update_dt -= target_dt; true } else { false } } /// Returns the fractional amount of a frame not consumed /// by [`check_update_time()`](fn.check_update_time.html). /// For example, if the desired /// update frame time is 40 ms (25 fps), and 45 ms have /// passed since the last frame, [`check_update_time()`](fn.check_update_time.html) /// will return `true` and `remaining_update_time()` will /// return 5 ms -- the amount of time "overflowing" from one /// frame to the next. /// /// The intention is for it to be called in your /// [`draw()`](../event/trait.EventHandler.html#tymethod.draw) callback /// to interpolate physics states for smooth rendering. /// (see <http://gafferongames.com/game-physics/fix-your-timestep/>) pub fn remaining_update_time(ctx: &mut Context) -> time::Duration { ctx.timer_context.residual_update_dt } /// Pauses the current thread for the target duration. /// Just calls [`std::thread::sleep()`](https://doc.rust-lang.org/std/thread/fn.sleep.html) /// so it's as accurate as that is (which is usually not very). pub fn sleep(duration: time::Duration) { thread::sleep(duration); } /// Yields the current timeslice to the OS. /// /// This just calls [`std::thread::yield_now()`](https://doc.rust-lang.org/std/thread/fn.yield_now.html) /// but it's handy to have here. pub fn yield_now() { thread::yield_now(); } /// Gets the number of times the game has gone through its event loop. /// /// Specifically, the number of times that [`TimeContext::tick()`](struct.TimeContext.html#method.tick) /// has been called by it. pub fn ticks(ctx: &Context) -> usize { ctx.timer_context.frame_count }
{ sum / u32::try_from(tc.frame_durations.samples).unwrap() }
conditional_block
timer.rs
//! Timing and measurement functions. //! //! ggez does not try to do any framerate limitation by default. If //! you want to run at anything other than full-bore max speed all the //! time, call [`thread::yield_now()`](https://doc.rust-lang.org/std/thread/fn.yield_now.html) //! (or [`timer::yield_now()`](fn.yield_now.html) which does the same //! thing) to yield to the OS so it has a chance to breathe before continuing //! with your game. This should prevent it from using 100% CPU as much unless it //! really needs to. Enabling vsync by setting //! [`conf.window_setup.vsync`](../conf/struct.WindowSetup.html#structfield.vsync) //! in your [`Conf`](../conf/struct.Conf.html) object is generally the best //! way to cap your displayed framerate. //! //! For a more detailed tutorial in how to handle frame timings in games, //! see <http://gafferongames.com/game-physics/fix-your-timestep/> use crate::context::Context; use std::cmp; use std::convert::TryFrom; use std::f64; use std::thread; use std::time; /// A simple buffer that fills /// up to a limit and then holds the last /// N items that have been inserted into it, /// overwriting old ones in a round-robin fashion. /// /// It's not quite a ring buffer 'cause you can't /// remove items from it, it just holds the last N /// things. #[derive(Debug, Clone)] struct LogBuffer<T> where T: Clone, { head: usize, size: usize, /// The number of actual samples inserted, used for /// smarter averaging. samples: usize, contents: Vec<T>, } impl<T> LogBuffer<T> where T: Clone + Copy, { fn new(size: usize, init_val: T) -> LogBuffer<T> { LogBuffer { head: 0, size, contents: vec![init_val; size], // Never divide by 0 samples: 1, } } /// Pushes a new item into the `LogBuffer`, overwriting /// the oldest item in it. fn push(&mut self, item: T) { self.head = (self.head + 1) % self.contents.len(); self.contents[self.head] = item; self.size = cmp::min(self.size + 1, self.contents.len()); self.samples += 1; } /// Returns a slice pointing at the contents of the buffer. /// They are in *no particular order*, and if not all the /// slots are filled, the empty slots will be present but /// contain the initial value given to [`new()`](#method.new). /// /// We're only using this to log FPS for a short time, /// so we don't care for the second or so when it's inaccurate. fn contents(&self) -> &[T] { if self.samples > self.size { &self.contents } else { &self.contents[..self.samples] } } /// Returns the most recent value in the buffer. fn latest(&self) -> T { self.contents[self.head] } } /// A structure that contains our time-tracking state. #[derive(Debug)] pub struct TimeContext { init_instant: time::Instant, last_instant: time::Instant, frame_durations: LogBuffer<time::Duration>, residual_update_dt: time::Duration, frame_count: usize, } /// How many frames we log update times for. const TIME_LOG_FRAMES: usize = 200; impl TimeContext { /// Creates a new `TimeContext` and initializes the start to this instant. pub fn new() -> TimeContext {
frame_durations: LogBuffer::new(TIME_LOG_FRAMES, initial_dt), residual_update_dt: time::Duration::from_secs(0), frame_count: 0, } } /// Update the state of the `TimeContext` to record that /// another frame has taken place. Necessary for the FPS /// tracking and [`check_update_time()`](fn.check_update_time.html) /// functions to work. /// /// It's usually not necessary to call this function yourself, /// [`event::run()`](../event/fn.run.html) will do it for you. pub fn tick(&mut self) { let now = time::Instant::now(); let time_since_last = now - self.last_instant; self.frame_durations.push(time_since_last); self.last_instant = now; self.frame_count += 1; self.residual_update_dt += time_since_last; } } impl Default for TimeContext { fn default() -> Self { Self::new() } } /// Get the time between the start of the last frame and the current one; /// in other words, the length of the last frame. pub fn delta(ctx: &Context) -> time::Duration { let tc = &ctx.timer_context; tc.frame_durations.latest() } /// Gets the average time of a frame, averaged /// over the last 200 frames. pub fn average_delta(ctx: &Context) -> time::Duration { let tc = &ctx.timer_context; let sum: time::Duration = tc.frame_durations.contents().iter().sum(); // If our buffer is actually full, divide by its size. // Otherwise divide by the number of samples we've added if tc.frame_durations.samples > tc.frame_durations.size { sum / u32::try_from(tc.frame_durations.size).unwrap() } else { sum / u32::try_from(tc.frame_durations.samples).unwrap() } } /// A convenience function to convert a Rust `Duration` type /// to a (less precise but more useful) `f64`. /// /// Does not make sure that the `Duration` is within the bounds /// of the `f64`. pub fn duration_to_f64(d: time::Duration) -> f64 { let seconds = d.as_secs() as f64; let nanos = f64::from(d.subsec_nanos()); seconds + (nanos * 1e-9) } /// A convenience function to create a Rust `Duration` type /// from a (less precise but more useful) `f64`. /// /// Only handles positive numbers correctly. pub fn f64_to_duration(t: f64) -> time::Duration { debug_assert!(t > 0.0, "f64_to_duration passed a negative number!"); let seconds = t.trunc(); let nanos = t.fract() * 1e9; time::Duration::new(seconds as u64, nanos as u32) } /// Returns a `Duration` representing how long each /// frame should be to match the given fps. /// /// Approximately. fn fps_as_duration(fps: u32) -> time::Duration { let target_dt_seconds = 1.0 / f64::from(fps); f64_to_duration(target_dt_seconds) } /// Gets the FPS of the game, averaged over the last /// 200 frames. pub fn fps(ctx: &Context) -> f64 { let duration_per_frame = average_delta(ctx); let seconds_per_frame = duration_to_f64(duration_per_frame); 1.0 / seconds_per_frame } /// Returns the time since the game was initialized, /// as reported by the system clock. pub fn time_since_start(ctx: &Context) -> time::Duration { let tc = &ctx.timer_context; time::Instant::now() - tc.init_instant } /// Check whether or not the desired amount of time has elapsed /// since the last frame. /// /// The intention is to use this in your `update` call to control /// how often game logic is updated per frame (see [the astroblasto example](https://github.com/ggez/ggez/blob/30ea4a4ead67557d2ebb39550e17339323fc9c58/examples/05_astroblasto.rs#L438-L442)). /// /// Calling this decreases a timer inside the context if the function returns true. /// If called in a loop it may therefore return true once, twice or not at all, depending on /// how much time elapsed since the last frame. /// /// For more info on the idea behind this see <http://gafferongames.com/game-physics/fix-your-timestep/>. /// /// Due to the global nature of this timer it's desirable to only use this function at one point /// of your code. If you want to limit the frame rate in both game logic and drawing consider writing /// your own event loop, or using a dirty bit for when to redraw graphics, which is set whenever the game /// logic runs. pub fn check_update_time(ctx: &mut Context, target_fps: u32) -> bool { let timedata = &mut ctx.timer_context; let target_dt = fps_as_duration(target_fps); if timedata.residual_update_dt > target_dt { timedata.residual_update_dt -= target_dt; true } else { false } } /// Returns the fractional amount of a frame not consumed /// by [`check_update_time()`](fn.check_update_time.html). /// For example, if the desired /// update frame time is 40 ms (25 fps), and 45 ms have /// passed since the last frame, [`check_update_time()`](fn.check_update_time.html) /// will return `true` and `remaining_update_time()` will /// return 5 ms -- the amount of time "overflowing" from one /// frame to the next. /// /// The intention is for it to be called in your /// [`draw()`](../event/trait.EventHandler.html#tymethod.draw) callback /// to interpolate physics states for smooth rendering. /// (see <http://gafferongames.com/game-physics/fix-your-timestep/>) pub fn remaining_update_time(ctx: &mut Context) -> time::Duration { ctx.timer_context.residual_update_dt } /// Pauses the current thread for the target duration. /// Just calls [`std::thread::sleep()`](https://doc.rust-lang.org/std/thread/fn.sleep.html) /// so it's as accurate as that is (which is usually not very). pub fn sleep(duration: time::Duration) { thread::sleep(duration); } /// Yields the current timeslice to the OS. /// /// This just calls [`std::thread::yield_now()`](https://doc.rust-lang.org/std/thread/fn.yield_now.html) /// but it's handy to have here. pub fn yield_now() { thread::yield_now(); } /// Gets the number of times the game has gone through its event loop. /// /// Specifically, the number of times that [`TimeContext::tick()`](struct.TimeContext.html#method.tick) /// has been called by it. pub fn ticks(ctx: &Context) -> usize { ctx.timer_context.frame_count }
let initial_dt = time::Duration::from_millis(16); TimeContext { init_instant: time::Instant::now(), last_instant: time::Instant::now(),
random_line_split
timer.rs
//! Timing and measurement functions. //! //! ggez does not try to do any framerate limitation by default. If //! you want to run at anything other than full-bore max speed all the //! time, call [`thread::yield_now()`](https://doc.rust-lang.org/std/thread/fn.yield_now.html) //! (or [`timer::yield_now()`](fn.yield_now.html) which does the same //! thing) to yield to the OS so it has a chance to breathe before continuing //! with your game. This should prevent it from using 100% CPU as much unless it //! really needs to. Enabling vsync by setting //! [`conf.window_setup.vsync`](../conf/struct.WindowSetup.html#structfield.vsync) //! in your [`Conf`](../conf/struct.Conf.html) object is generally the best //! way to cap your displayed framerate. //! //! For a more detailed tutorial in how to handle frame timings in games, //! see <http://gafferongames.com/game-physics/fix-your-timestep/> use crate::context::Context; use std::cmp; use std::convert::TryFrom; use std::f64; use std::thread; use std::time; /// A simple buffer that fills /// up to a limit and then holds the last /// N items that have been inserted into it, /// overwriting old ones in a round-robin fashion. /// /// It's not quite a ring buffer 'cause you can't /// remove items from it, it just holds the last N /// things. #[derive(Debug, Clone)] struct LogBuffer<T> where T: Clone, { head: usize, size: usize, /// The number of actual samples inserted, used for /// smarter averaging. samples: usize, contents: Vec<T>, } impl<T> LogBuffer<T> where T: Clone + Copy, { fn new(size: usize, init_val: T) -> LogBuffer<T> { LogBuffer { head: 0, size, contents: vec![init_val; size], // Never divide by 0 samples: 1, } } /// Pushes a new item into the `LogBuffer`, overwriting /// the oldest item in it. fn push(&mut self, item: T) { self.head = (self.head + 1) % self.contents.len(); self.contents[self.head] = item; self.size = cmp::min(self.size + 1, self.contents.len()); self.samples += 1; } /// Returns a slice pointing at the contents of the buffer. /// They are in *no particular order*, and if not all the /// slots are filled, the empty slots will be present but /// contain the initial value given to [`new()`](#method.new). /// /// We're only using this to log FPS for a short time, /// so we don't care for the second or so when it's inaccurate. fn contents(&self) -> &[T] { if self.samples > self.size { &self.contents } else { &self.contents[..self.samples] } } /// Returns the most recent value in the buffer. fn latest(&self) -> T { self.contents[self.head] } } /// A structure that contains our time-tracking state. #[derive(Debug)] pub struct TimeContext { init_instant: time::Instant, last_instant: time::Instant, frame_durations: LogBuffer<time::Duration>, residual_update_dt: time::Duration, frame_count: usize, } /// How many frames we log update times for. const TIME_LOG_FRAMES: usize = 200; impl TimeContext { /// Creates a new `TimeContext` and initializes the start to this instant. pub fn
() -> TimeContext { let initial_dt = time::Duration::from_millis(16); TimeContext { init_instant: time::Instant::now(), last_instant: time::Instant::now(), frame_durations: LogBuffer::new(TIME_LOG_FRAMES, initial_dt), residual_update_dt: time::Duration::from_secs(0), frame_count: 0, } } /// Update the state of the `TimeContext` to record that /// another frame has taken place. Necessary for the FPS /// tracking and [`check_update_time()`](fn.check_update_time.html) /// functions to work. /// /// It's usually not necessary to call this function yourself, /// [`event::run()`](../event/fn.run.html) will do it for you. pub fn tick(&mut self) { let now = time::Instant::now(); let time_since_last = now - self.last_instant; self.frame_durations.push(time_since_last); self.last_instant = now; self.frame_count += 1; self.residual_update_dt += time_since_last; } } impl Default for TimeContext { fn default() -> Self { Self::new() } } /// Get the time between the start of the last frame and the current one; /// in other words, the length of the last frame. pub fn delta(ctx: &Context) -> time::Duration { let tc = &ctx.timer_context; tc.frame_durations.latest() } /// Gets the average time of a frame, averaged /// over the last 200 frames. pub fn average_delta(ctx: &Context) -> time::Duration { let tc = &ctx.timer_context; let sum: time::Duration = tc.frame_durations.contents().iter().sum(); // If our buffer is actually full, divide by its size. // Otherwise divide by the number of samples we've added if tc.frame_durations.samples > tc.frame_durations.size { sum / u32::try_from(tc.frame_durations.size).unwrap() } else { sum / u32::try_from(tc.frame_durations.samples).unwrap() } } /// A convenience function to convert a Rust `Duration` type /// to a (less precise but more useful) `f64`. /// /// Does not make sure that the `Duration` is within the bounds /// of the `f64`. pub fn duration_to_f64(d: time::Duration) -> f64 { let seconds = d.as_secs() as f64; let nanos = f64::from(d.subsec_nanos()); seconds + (nanos * 1e-9) } /// A convenience function to create a Rust `Duration` type /// from a (less precise but more useful) `f64`. /// /// Only handles positive numbers correctly. pub fn f64_to_duration(t: f64) -> time::Duration { debug_assert!(t > 0.0, "f64_to_duration passed a negative number!"); let seconds = t.trunc(); let nanos = t.fract() * 1e9; time::Duration::new(seconds as u64, nanos as u32) } /// Returns a `Duration` representing how long each /// frame should be to match the given fps. /// /// Approximately. fn fps_as_duration(fps: u32) -> time::Duration { let target_dt_seconds = 1.0 / f64::from(fps); f64_to_duration(target_dt_seconds) } /// Gets the FPS of the game, averaged over the last /// 200 frames. pub fn fps(ctx: &Context) -> f64 { let duration_per_frame = average_delta(ctx); let seconds_per_frame = duration_to_f64(duration_per_frame); 1.0 / seconds_per_frame } /// Returns the time since the game was initialized, /// as reported by the system clock. pub fn time_since_start(ctx: &Context) -> time::Duration { let tc = &ctx.timer_context; time::Instant::now() - tc.init_instant } /// Check whether or not the desired amount of time has elapsed /// since the last frame. /// /// The intention is to use this in your `update` call to control /// how often game logic is updated per frame (see [the astroblasto example](https://github.com/ggez/ggez/blob/30ea4a4ead67557d2ebb39550e17339323fc9c58/examples/05_astroblasto.rs#L438-L442)). /// /// Calling this decreases a timer inside the context if the function returns true. /// If called in a loop it may therefore return true once, twice or not at all, depending on /// how much time elapsed since the last frame. /// /// For more info on the idea behind this see <http://gafferongames.com/game-physics/fix-your-timestep/>. /// /// Due to the global nature of this timer it's desirable to only use this function at one point /// of your code. If you want to limit the frame rate in both game logic and drawing consider writing /// your own event loop, or using a dirty bit for when to redraw graphics, which is set whenever the game /// logic runs. pub fn check_update_time(ctx: &mut Context, target_fps: u32) -> bool { let timedata = &mut ctx.timer_context; let target_dt = fps_as_duration(target_fps); if timedata.residual_update_dt > target_dt { timedata.residual_update_dt -= target_dt; true } else { false } } /// Returns the fractional amount of a frame not consumed /// by [`check_update_time()`](fn.check_update_time.html). /// For example, if the desired /// update frame time is 40 ms (25 fps), and 45 ms have /// passed since the last frame, [`check_update_time()`](fn.check_update_time.html) /// will return `true` and `remaining_update_time()` will /// return 5 ms -- the amount of time "overflowing" from one /// frame to the next. /// /// The intention is for it to be called in your /// [`draw()`](../event/trait.EventHandler.html#tymethod.draw) callback /// to interpolate physics states for smooth rendering. /// (see <http://gafferongames.com/game-physics/fix-your-timestep/>) pub fn remaining_update_time(ctx: &mut Context) -> time::Duration { ctx.timer_context.residual_update_dt } /// Pauses the current thread for the target duration. /// Just calls [`std::thread::sleep()`](https://doc.rust-lang.org/std/thread/fn.sleep.html) /// so it's as accurate as that is (which is usually not very). pub fn sleep(duration: time::Duration) { thread::sleep(duration); } /// Yields the current timeslice to the OS. /// /// This just calls [`std::thread::yield_now()`](https://doc.rust-lang.org/std/thread/fn.yield_now.html) /// but it's handy to have here. pub fn yield_now() { thread::yield_now(); } /// Gets the number of times the game has gone through its event loop. /// /// Specifically, the number of times that [`TimeContext::tick()`](struct.TimeContext.html#method.tick) /// has been called by it. pub fn ticks(ctx: &Context) -> usize { ctx.timer_context.frame_count }
new
identifier_name
reference.rs
use crate::real_std::{any::Any, fmt, marker::PhantomData, sync::Mutex}; use crate::{ api::{generic::A, Generic, Unrooted, Userdata, WithVM, IO}, gc::{CloneUnrooted, GcPtr, GcRef, Move, Trace}, thread::ThreadInternal, value::{Cloner, Value}, vm::Thread, ExternModule, Result, }; #[derive(VmType)] #[gluon(gluon_vm)] #[gluon(vm_type = "std.reference.Reference")] pub struct Reference<T> { value: Mutex<Value>, thread: GcPtr<Thread>, _marker: PhantomData<T>, } impl<T> Userdata for Reference<T> where T: Any + Send + Sync, { fn deep_clone<'gc>( &self, deep_cloner: &'gc mut Cloner, ) -> Result<GcRef<'gc, Box<dyn Userdata>>> { let value = self.value.lock().unwrap(); // SAFETY During the `alloc` call the unrooted values are scanned through the `DataDef` unsafe { let cloned_value = deep_cloner.deep_clone(&value)?.unrooted(); let data: Box<dyn Userdata> = Box::new(Reference { value: Mutex::new(cloned_value), thread: GcPtr::from_raw(deep_cloner.thread()), _marker: PhantomData::<A>, }); deep_cloner.gc().alloc(Move(data)) } } } impl<T> fmt::Debug for Reference<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Ref({:?})", *self.value.lock().unwrap()) } } unsafe impl<T> Trace for Reference<T> { impl_trace_fields! { self, gc; value } } fn set(r: &Reference<A>, a: Generic<A>) -> IO<()> { match r.thread.deep_clone_value(&r.thread, a.get_value()) { // SAFETY Rooted when stored in the reference Ok(a) => unsafe { *r.value.lock().unwrap() = a.get_value().clone_unrooted(); IO::Value(()) }, Err(err) => IO::Exception(format!("{}", err)), } } fn get(r: &Reference<A>) -> IO<Unrooted<A>> { // SAFETY The returned, unrooted value gets pushed immediately to the stack IO::Value(unsafe { Unrooted::from(r.value.lock().unwrap().clone_unrooted()) }) } fn make_ref(a: WithVM<Generic<A>>) -> IO<Reference<A>> { // SAFETY The returned, unrooted value gets pushed immediately to the stack unsafe { IO::Value(Reference { value: Mutex::new(a.value.get_value().clone_unrooted()), thread: GcPtr::from_raw(a.vm), _marker: PhantomData, }) } }
pub mod reference { pub use crate::reference as prim; } } pub fn load(vm: &Thread) -> Result<ExternModule> { let _ = vm.register_type::<Reference<A>>("std.reference.Reference", &["a"]); ExternModule::new( vm, record! { type Reference a => Reference<A>, (store "<-") => primitive!(2, "std.reference.prim.(<-)", std::reference::prim::set), load => primitive!(1, "std.reference.prim.load", std::reference::prim::get), (ref_ "ref") => primitive!(1, "std.reference.prim.ref", std::reference::prim::make_ref), }, ) } pub mod st { use super::*; use crate::api::RuntimeResult; fn set(r: &Reference<A>, a: Generic<A>) -> RuntimeResult<(), String> { match r.thread.deep_clone_value(&r.thread, a.get_value()) { // SAFETY Rooted when stored in the reference Ok(a) => unsafe { *r.value.lock().unwrap() = a.get_value().clone_unrooted(); RuntimeResult::Return(()) }, Err(err) => RuntimeResult::Panic(format!("{}", err)), } } fn get(r: &Reference<A>) -> Unrooted<A> { // SAFETY The returned, unrooted value gets pushed immediately to the stack unsafe { Unrooted::from(r.value.lock().unwrap().clone_unrooted()) } } fn make_ref(a: WithVM<Generic<A>>) -> Reference<A> { // SAFETY The returned, unrooted value gets pushed immediately to the stack unsafe { Reference { value: Mutex::new(a.value.get_value().clone_unrooted()), thread: GcPtr::from_raw(a.vm), _marker: PhantomData, } } } mod std { pub mod st { pub mod reference { pub use crate::reference::st as prim; } } } pub fn load(vm: &Thread) -> Result<ExternModule> { ExternModule::new( vm, record! { type Reference a => Reference<A>, (store "<-") => primitive!(2, "std.st.reference.prim.(<-)", std::st::reference::prim::set), load => primitive!(1, "std.st.reference.prim.load", std::st::reference::prim::get), (ref_ "ref") => primitive!(1, "std.st.reference.prim.ref", std::st::reference::prim::make_ref), }, ) } }
mod std {
random_line_split
reference.rs
use crate::real_std::{any::Any, fmt, marker::PhantomData, sync::Mutex}; use crate::{ api::{generic::A, Generic, Unrooted, Userdata, WithVM, IO}, gc::{CloneUnrooted, GcPtr, GcRef, Move, Trace}, thread::ThreadInternal, value::{Cloner, Value}, vm::Thread, ExternModule, Result, }; #[derive(VmType)] #[gluon(gluon_vm)] #[gluon(vm_type = "std.reference.Reference")] pub struct Reference<T> { value: Mutex<Value>, thread: GcPtr<Thread>, _marker: PhantomData<T>, } impl<T> Userdata for Reference<T> where T: Any + Send + Sync, { fn deep_clone<'gc>( &self, deep_cloner: &'gc mut Cloner, ) -> Result<GcRef<'gc, Box<dyn Userdata>>> { let value = self.value.lock().unwrap(); // SAFETY During the `alloc` call the unrooted values are scanned through the `DataDef` unsafe { let cloned_value = deep_cloner.deep_clone(&value)?.unrooted(); let data: Box<dyn Userdata> = Box::new(Reference { value: Mutex::new(cloned_value), thread: GcPtr::from_raw(deep_cloner.thread()), _marker: PhantomData::<A>, }); deep_cloner.gc().alloc(Move(data)) } } } impl<T> fmt::Debug for Reference<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Ref({:?})", *self.value.lock().unwrap()) } } unsafe impl<T> Trace for Reference<T> { impl_trace_fields! { self, gc; value } } fn set(r: &Reference<A>, a: Generic<A>) -> IO<()> { match r.thread.deep_clone_value(&r.thread, a.get_value()) { // SAFETY Rooted when stored in the reference Ok(a) => unsafe { *r.value.lock().unwrap() = a.get_value().clone_unrooted(); IO::Value(()) }, Err(err) => IO::Exception(format!("{}", err)), } } fn get(r: &Reference<A>) -> IO<Unrooted<A>> { // SAFETY The returned, unrooted value gets pushed immediately to the stack IO::Value(unsafe { Unrooted::from(r.value.lock().unwrap().clone_unrooted()) }) } fn
(a: WithVM<Generic<A>>) -> IO<Reference<A>> { // SAFETY The returned, unrooted value gets pushed immediately to the stack unsafe { IO::Value(Reference { value: Mutex::new(a.value.get_value().clone_unrooted()), thread: GcPtr::from_raw(a.vm), _marker: PhantomData, }) } } mod std { pub mod reference { pub use crate::reference as prim; } } pub fn load(vm: &Thread) -> Result<ExternModule> { let _ = vm.register_type::<Reference<A>>("std.reference.Reference", &["a"]); ExternModule::new( vm, record! { type Reference a => Reference<A>, (store "<-") => primitive!(2, "std.reference.prim.(<-)", std::reference::prim::set), load => primitive!(1, "std.reference.prim.load", std::reference::prim::get), (ref_ "ref") => primitive!(1, "std.reference.prim.ref", std::reference::prim::make_ref), }, ) } pub mod st { use super::*; use crate::api::RuntimeResult; fn set(r: &Reference<A>, a: Generic<A>) -> RuntimeResult<(), String> { match r.thread.deep_clone_value(&r.thread, a.get_value()) { // SAFETY Rooted when stored in the reference Ok(a) => unsafe { *r.value.lock().unwrap() = a.get_value().clone_unrooted(); RuntimeResult::Return(()) }, Err(err) => RuntimeResult::Panic(format!("{}", err)), } } fn get(r: &Reference<A>) -> Unrooted<A> { // SAFETY The returned, unrooted value gets pushed immediately to the stack unsafe { Unrooted::from(r.value.lock().unwrap().clone_unrooted()) } } fn make_ref(a: WithVM<Generic<A>>) -> Reference<A> { // SAFETY The returned, unrooted value gets pushed immediately to the stack unsafe { Reference { value: Mutex::new(a.value.get_value().clone_unrooted()), thread: GcPtr::from_raw(a.vm), _marker: PhantomData, } } } mod std { pub mod st { pub mod reference { pub use crate::reference::st as prim; } } } pub fn load(vm: &Thread) -> Result<ExternModule> { ExternModule::new( vm, record! { type Reference a => Reference<A>, (store "<-") => primitive!(2, "std.st.reference.prim.(<-)", std::st::reference::prim::set), load => primitive!(1, "std.st.reference.prim.load", std::st::reference::prim::get), (ref_ "ref") => primitive!(1, "std.st.reference.prim.ref", std::st::reference::prim::make_ref), }, ) } }
make_ref
identifier_name
remove.rs
use cli::parse_args; use Slate; use message::Message; use results::CommandResult; use errors::CommandError; const USAGE: &'static str = " Slate: Remove an element. Usage: slate remove ([options] | <key>) Options: -h --help Show this screen. -a --all Remove all keys. Examples: slate remove --all #=> All keys have been removed slate remove foo #=> The key has been removed "; #[derive(Debug, Deserialize)] struct Args { arg_key: Option<String>, flag_all: bool, } pub fn
(slate: &Slate, argv: &Vec<String>) -> CommandResult { let args: Args = parse_args(USAGE, argv).unwrap_or_else(|e| e.exit()); if args.flag_all { try!(slate.clear()); Ok(Some(Message::Info("All keys have been removed".to_string()))) } else { let key: String = match args.arg_key { Some(string) => string, None => { return Err(CommandError::Argument("You must provide the name of a key".to_string())) } }; try!(slate.remove(&key)); Ok(Some(Message::Info("The key has been removed".to_string()))) } }
run
identifier_name
remove.rs
use cli::parse_args; use Slate; use message::Message; use results::CommandResult; use errors::CommandError; const USAGE: &'static str = " Slate: Remove an element. Usage: slate remove ([options] | <key>) Options: -h --help Show this screen. -a --all Remove all keys. Examples: slate remove --all #=> All keys have been removed slate remove foo #=> The key has been removed "; #[derive(Debug, Deserialize)] struct Args { arg_key: Option<String>, flag_all: bool, } pub fn run(slate: &Slate, argv: &Vec<String>) -> CommandResult
{ let args: Args = parse_args(USAGE, argv).unwrap_or_else(|e| e.exit()); if args.flag_all { try!(slate.clear()); Ok(Some(Message::Info("All keys have been removed".to_string()))) } else { let key: String = match args.arg_key { Some(string) => string, None => { return Err(CommandError::Argument("You must provide the name of a key".to_string())) } }; try!(slate.remove(&key)); Ok(Some(Message::Info("The key has been removed".to_string()))) } }
identifier_body
remove.rs
use cli::parse_args; use Slate; use message::Message; use results::CommandResult; use errors::CommandError; const USAGE: &'static str = " Slate: Remove an element. Usage: slate remove ([options] | <key>) Options: -h --help Show this screen. -a --all Remove all keys. Examples:
slate remove foo #=> The key has been removed "; #[derive(Debug, Deserialize)] struct Args { arg_key: Option<String>, flag_all: bool, } pub fn run(slate: &Slate, argv: &Vec<String>) -> CommandResult { let args: Args = parse_args(USAGE, argv).unwrap_or_else(|e| e.exit()); if args.flag_all { try!(slate.clear()); Ok(Some(Message::Info("All keys have been removed".to_string()))) } else { let key: String = match args.arg_key { Some(string) => string, None => { return Err(CommandError::Argument("You must provide the name of a key".to_string())) } }; try!(slate.remove(&key)); Ok(Some(Message::Info("The key has been removed".to_string()))) } }
slate remove --all #=> All keys have been removed
random_line_split
transform.rs
use geometry::Transformable; use math; #[derive(Deserialize, Debug)] #[serde(tag = "type")] pub enum Transform { Translate { value: [f32; 3] }, Scale { value: [f32; 3] }, RotateX { value: f32 }, RotateY { value: f32 }, RotateZ { value: f32 }, } impl Transform { pub fn to_transform(&self) -> math::Transform { match *self { Transform::Translate { value } => { math::Transform::new(math::Matrix4::translate(value[0], value[1], value[2])) } Transform::Scale { value } => { math::Transform::new(math::Matrix4::scale(value[0], value[1], value[2])) } Transform::RotateX { value } => math::Transform::new(math::Matrix4::rot_x(value)), Transform::RotateY { value } => math::Transform::new(math::Matrix4::rot_y(value)), Transform::RotateZ { value } => math::Transform::new(math::Matrix4::rot_z(value)), } } pub fn perform(&self, transformable: &mut dyn Transformable)
}
{ let transform = self.to_transform(); transformable.transform(&transform); }
identifier_body
transform.rs
use geometry::Transformable; use math; #[derive(Deserialize, Debug)] #[serde(tag = "type")] pub enum Transform { Translate { value: [f32; 3] }, Scale { value: [f32; 3] }, RotateX { value: f32 }, RotateY { value: f32 }, RotateZ { value: f32 }, } impl Transform { pub fn
(&self) -> math::Transform { match *self { Transform::Translate { value } => { math::Transform::new(math::Matrix4::translate(value[0], value[1], value[2])) } Transform::Scale { value } => { math::Transform::new(math::Matrix4::scale(value[0], value[1], value[2])) } Transform::RotateX { value } => math::Transform::new(math::Matrix4::rot_x(value)), Transform::RotateY { value } => math::Transform::new(math::Matrix4::rot_y(value)), Transform::RotateZ { value } => math::Transform::new(math::Matrix4::rot_z(value)), } } pub fn perform(&self, transformable: &mut dyn Transformable) { let transform = self.to_transform(); transformable.transform(&transform); } }
to_transform
identifier_name
transform.rs
use geometry::Transformable; use math; #[derive(Deserialize, Debug)] #[serde(tag = "type")] pub enum Transform { Translate { value: [f32; 3] }, Scale { value: [f32; 3] }, RotateX { value: f32 }, RotateY { value: f32 }, RotateZ { value: f32 }, } impl Transform { pub fn to_transform(&self) -> math::Transform { match *self { Transform::Translate { value } => { math::Transform::new(math::Matrix4::translate(value[0], value[1], value[2])) } Transform::Scale { value } =>
Transform::RotateX { value } => math::Transform::new(math::Matrix4::rot_x(value)), Transform::RotateY { value } => math::Transform::new(math::Matrix4::rot_y(value)), Transform::RotateZ { value } => math::Transform::new(math::Matrix4::rot_z(value)), } } pub fn perform(&self, transformable: &mut dyn Transformable) { let transform = self.to_transform(); transformable.transform(&transform); } }
{ math::Transform::new(math::Matrix4::scale(value[0], value[1], value[2])) }
conditional_block
transform.rs
use geometry::Transformable; use math; #[derive(Deserialize, Debug)] #[serde(tag = "type")] pub enum Transform { Translate { value: [f32; 3] }, Scale { value: [f32; 3] }, RotateX { value: f32 }, RotateY { value: f32 }, RotateZ { value: f32 }, } impl Transform { pub fn to_transform(&self) -> math::Transform { match *self { Transform::Translate { value } => { math::Transform::new(math::Matrix4::translate(value[0], value[1], value[2])) } Transform::Scale { value } => { math::Transform::new(math::Matrix4::scale(value[0], value[1], value[2])) } Transform::RotateX { value } => math::Transform::new(math::Matrix4::rot_x(value)), Transform::RotateY { value } => math::Transform::new(math::Matrix4::rot_y(value)), Transform::RotateZ { value } => math::Transform::new(math::Matrix4::rot_z(value)), } }
pub fn perform(&self, transformable: &mut dyn Transformable) { let transform = self.to_transform(); transformable.transform(&transform); } }
random_line_split
rt.rs
// Copyright 2013-2015, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> //! General — Library initialization and miscellaneous functions use std::cell::Cell; use std::ptr; use std::sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT, Ordering}; use glib::translate::*; use ffi; thread_local! { static IS_MAIN_THREAD: Cell<bool> = Cell::new(false) } static INITIALIZED: AtomicBool = ATOMIC_BOOL_INIT; /// Asserts that this is the main thread and either `gdk::init` or `gtk::init` has been called. macro_rules! assert_initialized_main_thread { () => ( if!::rt::is_initialized_main_thread() { if ::rt::is_initialized() { panic!("GDK may only be used from the main thread."); } else { panic!("GDK has not been initialized. Call `gdk::init` or `gtk::init` first."); } } ) } /// No-op. macro_rules! skip_assert_initialized { () => () } /// Asserts that neither `gdk::init` nor `gtk::init` has been called. macro_rules! assert_not_initialized { () => ( if ::rt::is_initialized() { panic!("This function has to be called before `gdk::init` or `gtk::init`."); } ) } /// Returns `true` if GDK has been initialized. #[inline] pub fn is_initialized() -> bool { skip_assert_initialized!(); INITIALIZED.load(Ordering::Acquire) } /// Returns `true` if GDK has been initialized and this is the main thread. #[inline] pub fn is_initialized_main_thread() -> bool { skip_assert_initialized!(); IS_MAIN_THREAD.with(|c| c.get()) } /// Informs this crate that GDK has been initialized and the current thread is the main one. pub unsafe fn set_initialized() { skip_assert_initialized!(); if is_initialized_main_thread() { return; } else if is_initialized() { panic!("Attempted to initialize GDK from two different threads."); } INITIALIZED.store(true, Ordering::Release); IS_MAIN_THREAD.with(|c| c.set(true)); } pub fn init() { assert_not_initialized!(); unsafe { ffi::gdk_init(ptr::null_mut(), ptr::null_mut()); set_initialized(); } } pub fn get_display_arg_name() -> Option<String> { assert_initialized_main_thread!(); unsafe { from_glib_none(ffi::gdk_get_display_arg_name()) } } pub fn notify_startup_complete() { assert_initialized_main_thread!(); unsafe { ffi::gdk_notify_startup_complete() } } pub fn notify_startup_complete_with_id(startup_id: &str) { assert_initialized_main_thread!(); unsafe { ffi::gdk_notify_startup_complete_with_id(startup_id.to_glib_none().0); } } #[cfg(feature = "3.10")] pub fn set_allowed_backends(backends: &str) { assert_not_initialized!(); unsafe { ffi::gdk_set_allowed_backends(backends.to_glib_none().0) } } pub fn get_program_class() -> Option<String> { assert_initialized_main_thread!(); unsafe { from_glib_none(ffi::gdk_get_program_class()) } } pub fn set_program_class(program_class: &str) { assert_initialized_main_thread!(); unsafe { ffi::gdk_set_program_class(program_class.to_glib_none().0) } } pub fn flush() { assert_initialized_main_thread!(); unsafe { ffi::gdk_flush() } } pub fn screen_width() -> i32 { assert_initialized_main_thread!(); unsafe { ffi::gdk_screen_width() } } pub fn screen_height() -> i32 { assert_initialized_main_thread!(); unsafe { ffi::gdk_screen_height() } } pub fn screen_width_mm() -> i32 { assert_initialized_main_thread!();
assert_initialized_main_thread!(); unsafe { ffi::gdk_screen_height_mm() } } pub fn beep() { assert_initialized_main_thread!(); unsafe { ffi::gdk_flush() } } pub fn error_trap_push() { assert_initialized_main_thread!(); unsafe { ffi::gdk_error_trap_push() } } pub fn error_trap_pop() -> i32 { assert_initialized_main_thread!(); unsafe { ffi::gdk_error_trap_pop() } } pub fn error_trap_pop_ignored() { assert_initialized_main_thread!(); unsafe { ffi::gdk_error_trap_pop_ignored() } }
unsafe { ffi::gdk_screen_width_mm() } } pub fn screen_height_mm() -> i32 {
random_line_split
rt.rs
// Copyright 2013-2015, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> //! General — Library initialization and miscellaneous functions use std::cell::Cell; use std::ptr; use std::sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT, Ordering}; use glib::translate::*; use ffi; thread_local! { static IS_MAIN_THREAD: Cell<bool> = Cell::new(false) } static INITIALIZED: AtomicBool = ATOMIC_BOOL_INIT; /// Asserts that this is the main thread and either `gdk::init` or `gtk::init` has been called. macro_rules! assert_initialized_main_thread { () => ( if!::rt::is_initialized_main_thread() { if ::rt::is_initialized() { panic!("GDK may only be used from the main thread."); } else { panic!("GDK has not been initialized. Call `gdk::init` or `gtk::init` first."); } } ) } /// No-op. macro_rules! skip_assert_initialized { () => () } /// Asserts that neither `gdk::init` nor `gtk::init` has been called. macro_rules! assert_not_initialized { () => ( if ::rt::is_initialized() { panic!("This function has to be called before `gdk::init` or `gtk::init`."); } ) } /// Returns `true` if GDK has been initialized. #[inline] pub fn is_initialized() -> bool { skip_assert_initialized!(); INITIALIZED.load(Ordering::Acquire) } /// Returns `true` if GDK has been initialized and this is the main thread. #[inline] pub fn is_initialized_main_thread() -> bool { skip_assert_initialized!(); IS_MAIN_THREAD.with(|c| c.get()) } /// Informs this crate that GDK has been initialized and the current thread is the main one. pub unsafe fn set_initialized() { skip_assert_initialized!(); if is_initialized_main_thread() { return; } else if is_initialized() { panic!("Attempted to initialize GDK from two different threads."); } INITIALIZED.store(true, Ordering::Release); IS_MAIN_THREAD.with(|c| c.set(true)); } pub fn init() { assert_not_initialized!(); unsafe { ffi::gdk_init(ptr::null_mut(), ptr::null_mut()); set_initialized(); } } pub fn ge
-> Option<String> { assert_initialized_main_thread!(); unsafe { from_glib_none(ffi::gdk_get_display_arg_name()) } } pub fn notify_startup_complete() { assert_initialized_main_thread!(); unsafe { ffi::gdk_notify_startup_complete() } } pub fn notify_startup_complete_with_id(startup_id: &str) { assert_initialized_main_thread!(); unsafe { ffi::gdk_notify_startup_complete_with_id(startup_id.to_glib_none().0); } } #[cfg(feature = "3.10")] pub fn set_allowed_backends(backends: &str) { assert_not_initialized!(); unsafe { ffi::gdk_set_allowed_backends(backends.to_glib_none().0) } } pub fn get_program_class() -> Option<String> { assert_initialized_main_thread!(); unsafe { from_glib_none(ffi::gdk_get_program_class()) } } pub fn set_program_class(program_class: &str) { assert_initialized_main_thread!(); unsafe { ffi::gdk_set_program_class(program_class.to_glib_none().0) } } pub fn flush() { assert_initialized_main_thread!(); unsafe { ffi::gdk_flush() } } pub fn screen_width() -> i32 { assert_initialized_main_thread!(); unsafe { ffi::gdk_screen_width() } } pub fn screen_height() -> i32 { assert_initialized_main_thread!(); unsafe { ffi::gdk_screen_height() } } pub fn screen_width_mm() -> i32 { assert_initialized_main_thread!(); unsafe { ffi::gdk_screen_width_mm() } } pub fn screen_height_mm() -> i32 { assert_initialized_main_thread!(); unsafe { ffi::gdk_screen_height_mm() } } pub fn beep() { assert_initialized_main_thread!(); unsafe { ffi::gdk_flush() } } pub fn error_trap_push() { assert_initialized_main_thread!(); unsafe { ffi::gdk_error_trap_push() } } pub fn error_trap_pop() -> i32 { assert_initialized_main_thread!(); unsafe { ffi::gdk_error_trap_pop() } } pub fn error_trap_pop_ignored() { assert_initialized_main_thread!(); unsafe { ffi::gdk_error_trap_pop_ignored() } }
t_display_arg_name()
identifier_name
rt.rs
// Copyright 2013-2015, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> //! General — Library initialization and miscellaneous functions use std::cell::Cell; use std::ptr; use std::sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT, Ordering}; use glib::translate::*; use ffi; thread_local! { static IS_MAIN_THREAD: Cell<bool> = Cell::new(false) } static INITIALIZED: AtomicBool = ATOMIC_BOOL_INIT; /// Asserts that this is the main thread and either `gdk::init` or `gtk::init` has been called. macro_rules! assert_initialized_main_thread { () => ( if!::rt::is_initialized_main_thread() { if ::rt::is_initialized() { panic!("GDK may only be used from the main thread."); } else { panic!("GDK has not been initialized. Call `gdk::init` or `gtk::init` first."); } } ) } /// No-op. macro_rules! skip_assert_initialized { () => () } /// Asserts that neither `gdk::init` nor `gtk::init` has been called. macro_rules! assert_not_initialized { () => ( if ::rt::is_initialized() { panic!("This function has to be called before `gdk::init` or `gtk::init`."); } ) } /// Returns `true` if GDK has been initialized. #[inline] pub fn is_initialized() -> bool { skip_assert_initialized!(); INITIALIZED.load(Ordering::Acquire) } /// Returns `true` if GDK has been initialized and this is the main thread. #[inline] pub fn is_initialized_main_thread() -> bool { skip_assert_initialized!(); IS_MAIN_THREAD.with(|c| c.get()) } /// Informs this crate that GDK has been initialized and the current thread is the main one. pub unsafe fn set_initialized() { skip_assert_initialized!(); if is_initialized_main_thread() {
else if is_initialized() { panic!("Attempted to initialize GDK from two different threads."); } INITIALIZED.store(true, Ordering::Release); IS_MAIN_THREAD.with(|c| c.set(true)); } pub fn init() { assert_not_initialized!(); unsafe { ffi::gdk_init(ptr::null_mut(), ptr::null_mut()); set_initialized(); } } pub fn get_display_arg_name() -> Option<String> { assert_initialized_main_thread!(); unsafe { from_glib_none(ffi::gdk_get_display_arg_name()) } } pub fn notify_startup_complete() { assert_initialized_main_thread!(); unsafe { ffi::gdk_notify_startup_complete() } } pub fn notify_startup_complete_with_id(startup_id: &str) { assert_initialized_main_thread!(); unsafe { ffi::gdk_notify_startup_complete_with_id(startup_id.to_glib_none().0); } } #[cfg(feature = "3.10")] pub fn set_allowed_backends(backends: &str) { assert_not_initialized!(); unsafe { ffi::gdk_set_allowed_backends(backends.to_glib_none().0) } } pub fn get_program_class() -> Option<String> { assert_initialized_main_thread!(); unsafe { from_glib_none(ffi::gdk_get_program_class()) } } pub fn set_program_class(program_class: &str) { assert_initialized_main_thread!(); unsafe { ffi::gdk_set_program_class(program_class.to_glib_none().0) } } pub fn flush() { assert_initialized_main_thread!(); unsafe { ffi::gdk_flush() } } pub fn screen_width() -> i32 { assert_initialized_main_thread!(); unsafe { ffi::gdk_screen_width() } } pub fn screen_height() -> i32 { assert_initialized_main_thread!(); unsafe { ffi::gdk_screen_height() } } pub fn screen_width_mm() -> i32 { assert_initialized_main_thread!(); unsafe { ffi::gdk_screen_width_mm() } } pub fn screen_height_mm() -> i32 { assert_initialized_main_thread!(); unsafe { ffi::gdk_screen_height_mm() } } pub fn beep() { assert_initialized_main_thread!(); unsafe { ffi::gdk_flush() } } pub fn error_trap_push() { assert_initialized_main_thread!(); unsafe { ffi::gdk_error_trap_push() } } pub fn error_trap_pop() -> i32 { assert_initialized_main_thread!(); unsafe { ffi::gdk_error_trap_pop() } } pub fn error_trap_pop_ignored() { assert_initialized_main_thread!(); unsafe { ffi::gdk_error_trap_pop_ignored() } }
return; }
conditional_block
rt.rs
// Copyright 2013-2015, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> //! General — Library initialization and miscellaneous functions use std::cell::Cell; use std::ptr; use std::sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT, Ordering}; use glib::translate::*; use ffi; thread_local! { static IS_MAIN_THREAD: Cell<bool> = Cell::new(false) } static INITIALIZED: AtomicBool = ATOMIC_BOOL_INIT; /// Asserts that this is the main thread and either `gdk::init` or `gtk::init` has been called. macro_rules! assert_initialized_main_thread { () => ( if!::rt::is_initialized_main_thread() { if ::rt::is_initialized() { panic!("GDK may only be used from the main thread."); } else { panic!("GDK has not been initialized. Call `gdk::init` or `gtk::init` first."); } } ) } /// No-op. macro_rules! skip_assert_initialized { () => () } /// Asserts that neither `gdk::init` nor `gtk::init` has been called. macro_rules! assert_not_initialized { () => ( if ::rt::is_initialized() { panic!("This function has to be called before `gdk::init` or `gtk::init`."); } ) } /// Returns `true` if GDK has been initialized. #[inline] pub fn is_initialized() -> bool { skip_assert_initialized!(); INITIALIZED.load(Ordering::Acquire) } /// Returns `true` if GDK has been initialized and this is the main thread. #[inline] pub fn is_initialized_main_thread() -> bool { skip_assert_initialized!(); IS_MAIN_THREAD.with(|c| c.get()) } /// Informs this crate that GDK has been initialized and the current thread is the main one. pub unsafe fn set_initialized() {
pub fn init() { assert_not_initialized!(); unsafe { ffi::gdk_init(ptr::null_mut(), ptr::null_mut()); set_initialized(); } } pub fn get_display_arg_name() -> Option<String> { assert_initialized_main_thread!(); unsafe { from_glib_none(ffi::gdk_get_display_arg_name()) } } pub fn notify_startup_complete() { assert_initialized_main_thread!(); unsafe { ffi::gdk_notify_startup_complete() } } pub fn notify_startup_complete_with_id(startup_id: &str) { assert_initialized_main_thread!(); unsafe { ffi::gdk_notify_startup_complete_with_id(startup_id.to_glib_none().0); } } #[cfg(feature = "3.10")] pub fn set_allowed_backends(backends: &str) { assert_not_initialized!(); unsafe { ffi::gdk_set_allowed_backends(backends.to_glib_none().0) } } pub fn get_program_class() -> Option<String> { assert_initialized_main_thread!(); unsafe { from_glib_none(ffi::gdk_get_program_class()) } } pub fn set_program_class(program_class: &str) { assert_initialized_main_thread!(); unsafe { ffi::gdk_set_program_class(program_class.to_glib_none().0) } } pub fn flush() { assert_initialized_main_thread!(); unsafe { ffi::gdk_flush() } } pub fn screen_width() -> i32 { assert_initialized_main_thread!(); unsafe { ffi::gdk_screen_width() } } pub fn screen_height() -> i32 { assert_initialized_main_thread!(); unsafe { ffi::gdk_screen_height() } } pub fn screen_width_mm() -> i32 { assert_initialized_main_thread!(); unsafe { ffi::gdk_screen_width_mm() } } pub fn screen_height_mm() -> i32 { assert_initialized_main_thread!(); unsafe { ffi::gdk_screen_height_mm() } } pub fn beep() { assert_initialized_main_thread!(); unsafe { ffi::gdk_flush() } } pub fn error_trap_push() { assert_initialized_main_thread!(); unsafe { ffi::gdk_error_trap_push() } } pub fn error_trap_pop() -> i32 { assert_initialized_main_thread!(); unsafe { ffi::gdk_error_trap_pop() } } pub fn error_trap_pop_ignored() { assert_initialized_main_thread!(); unsafe { ffi::gdk_error_trap_pop_ignored() } }
skip_assert_initialized!(); if is_initialized_main_thread() { return; } else if is_initialized() { panic!("Attempted to initialize GDK from two different threads."); } INITIALIZED.store(true, Ordering::Release); IS_MAIN_THREAD.with(|c| c.set(true)); }
identifier_body
basic_client.rs
// use std::io::prelude::*; use std::net::{Shutdown, TcpStream}; use std::ffi::CString; use std::thread; use std::str; extern crate mbedtls; use mbedtls::mbed; use mbedtls::mbed::ssl::error::SSLError; const TO_WRITE : &'static [u8] = b"GET / HTTP/1.1\r\n\r\n"; fn main() { let mut stream = TcpStream::connect("216.58.210.78:443").unwrap(); { let mut entropy = mbedtls::mbed::entropy::EntropyContext::new(); let mut entropy_func = |d : &mut[u8] | entropy.entropy_func(d); let mut ctr_drbg = mbed::ctr_drbg::CtrDrbgContext::with_seed( &mut entropy_func, None ).unwrap(); let mut random_func = |f: &mut[u8] | ctr_drbg.random(f); let mut ssl_config = mbed::ssl::SSLConfig::new(); let mut ssl_context = mbed::ssl::SSLContext::new(); ssl_config.set_rng(&mut random_func); ssl_config.set_defaults( mbed::ssl::EndpointType::Client, mbed::ssl::TransportType::Stream, mbed::ssl::SSLPreset::Default, ).unwrap(); ssl_config.set_authmode(mbed::ssl::AuthMode::VerifyNone); ssl_context.setup(&ssl_config).unwrap(); ssl_context.set_hostname(&CString::new("mbed TLS Server 1").unwrap()).unwrap(); ssl_context.set_bio_async(&mut stream); attempt_io(|| ssl_context.handshake()); let size_written = attempt_io(|| ssl_context.write(TO_WRITE)); assert!(size_written == TO_WRITE.len()); let mut buffer = [0; 4096]; let size_read = attempt_io(|| ssl_context.read(&mut buffer)); println!( "Read: {} bytes:\n---\n{}\n---", size_read, str::from_utf8(&buffer[..size_read]).unwrap()
stream.shutdown(Shutdown::Both).unwrap(); } fn attempt_io<I, F: FnMut() -> Result<I, SSLError>>(mut f: F) -> I { loop { match f() { Ok(i) => return i, Err(SSLError::WantRead) | Err(SSLError::WantWrite) => { thread::sleep_ms(100); continue }, Err(e) => panic!("Got error: {}", e), } } }
); attempt_io(|| ssl_context.close_notify()); }
random_line_split
basic_client.rs
// use std::io::prelude::*; use std::net::{Shutdown, TcpStream}; use std::ffi::CString; use std::thread; use std::str; extern crate mbedtls; use mbedtls::mbed; use mbedtls::mbed::ssl::error::SSLError; const TO_WRITE : &'static [u8] = b"GET / HTTP/1.1\r\n\r\n"; fn
() { let mut stream = TcpStream::connect("216.58.210.78:443").unwrap(); { let mut entropy = mbedtls::mbed::entropy::EntropyContext::new(); let mut entropy_func = |d : &mut[u8] | entropy.entropy_func(d); let mut ctr_drbg = mbed::ctr_drbg::CtrDrbgContext::with_seed( &mut entropy_func, None ).unwrap(); let mut random_func = |f: &mut[u8] | ctr_drbg.random(f); let mut ssl_config = mbed::ssl::SSLConfig::new(); let mut ssl_context = mbed::ssl::SSLContext::new(); ssl_config.set_rng(&mut random_func); ssl_config.set_defaults( mbed::ssl::EndpointType::Client, mbed::ssl::TransportType::Stream, mbed::ssl::SSLPreset::Default, ).unwrap(); ssl_config.set_authmode(mbed::ssl::AuthMode::VerifyNone); ssl_context.setup(&ssl_config).unwrap(); ssl_context.set_hostname(&CString::new("mbed TLS Server 1").unwrap()).unwrap(); ssl_context.set_bio_async(&mut stream); attempt_io(|| ssl_context.handshake()); let size_written = attempt_io(|| ssl_context.write(TO_WRITE)); assert!(size_written == TO_WRITE.len()); let mut buffer = [0; 4096]; let size_read = attempt_io(|| ssl_context.read(&mut buffer)); println!( "Read: {} bytes:\n---\n{}\n---", size_read, str::from_utf8(&buffer[..size_read]).unwrap() ); attempt_io(|| ssl_context.close_notify()); } stream.shutdown(Shutdown::Both).unwrap(); } fn attempt_io<I, F: FnMut() -> Result<I, SSLError>>(mut f: F) -> I { loop { match f() { Ok(i) => return i, Err(SSLError::WantRead) | Err(SSLError::WantWrite) => { thread::sleep_ms(100); continue }, Err(e) => panic!("Got error: {}", e), } } }
main
identifier_name
basic_client.rs
// use std::io::prelude::*; use std::net::{Shutdown, TcpStream}; use std::ffi::CString; use std::thread; use std::str; extern crate mbedtls; use mbedtls::mbed; use mbedtls::mbed::ssl::error::SSLError; const TO_WRITE : &'static [u8] = b"GET / HTTP/1.1\r\n\r\n"; fn main() { let mut stream = TcpStream::connect("216.58.210.78:443").unwrap(); { let mut entropy = mbedtls::mbed::entropy::EntropyContext::new(); let mut entropy_func = |d : &mut[u8] | entropy.entropy_func(d); let mut ctr_drbg = mbed::ctr_drbg::CtrDrbgContext::with_seed( &mut entropy_func, None ).unwrap(); let mut random_func = |f: &mut[u8] | ctr_drbg.random(f); let mut ssl_config = mbed::ssl::SSLConfig::new(); let mut ssl_context = mbed::ssl::SSLContext::new(); ssl_config.set_rng(&mut random_func); ssl_config.set_defaults( mbed::ssl::EndpointType::Client, mbed::ssl::TransportType::Stream, mbed::ssl::SSLPreset::Default, ).unwrap(); ssl_config.set_authmode(mbed::ssl::AuthMode::VerifyNone); ssl_context.setup(&ssl_config).unwrap(); ssl_context.set_hostname(&CString::new("mbed TLS Server 1").unwrap()).unwrap(); ssl_context.set_bio_async(&mut stream); attempt_io(|| ssl_context.handshake()); let size_written = attempt_io(|| ssl_context.write(TO_WRITE)); assert!(size_written == TO_WRITE.len()); let mut buffer = [0; 4096]; let size_read = attempt_io(|| ssl_context.read(&mut buffer)); println!( "Read: {} bytes:\n---\n{}\n---", size_read, str::from_utf8(&buffer[..size_read]).unwrap() ); attempt_io(|| ssl_context.close_notify()); } stream.shutdown(Shutdown::Both).unwrap(); } fn attempt_io<I, F: FnMut() -> Result<I, SSLError>>(mut f: F) -> I
{ loop { match f() { Ok(i) => return i, Err(SSLError::WantRead) | Err(SSLError::WantWrite) => { thread::sleep_ms(100); continue }, Err(e) => panic!("Got error: {}", e), } } }
identifier_body
lib.rs
//! Prime number generator and related functions. #![warn( bad_style, missing_docs, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results )] #![cfg_attr(all(test, feature = "unstable"), feature(test))] #[cfg(all(test, feature = "unstable"))] extern crate test; use num_integer::Integer; use num_traits::{FromPrimitive, One, Zero}; use std::{ cell::RefCell, cmp, collections::{ hash_map::Entry::{Occupied, Vacant}, HashMap, }, hash::Hash, iter::IntoIterator, mem, rc::Rc, }; const SMALL_PRIMES: &[u64] = &[ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, ]; const INITIAL_CAPACITY: usize = 10000; struct PrimeInner { data: Vec<u64>, } impl PrimeInner { #[inline] fn new() -> PrimeInner { PrimeInner::with_capacity(INITIAL_CAPACITY) } #[inline] fn new_empty() -> PrimeInner { let mut data = Vec::with_capacity(INITIAL_CAPACITY); data.push(2); data.push(3); PrimeInner { data } } #[inline] fn with_capacity(capacity: usize) -> PrimeInner { let mut data = Vec::with_capacity(capacity + SMALL_PRIMES.len()); data.extend(SMALL_PRIMES.iter().cloned()); PrimeInner { data } } #[inline] fn max_prime(&self) -> u64 { *self.data.last().unwrap() } #[inline] fn nth(&mut self, n: usize) -> u64 { self.grow(n + 1); self.data[n] } #[inline] fn contains(&mut self, n: u64) -> bool { if n < self.max_prime() { return self.data.binary_search(&n).is_ok(); } if!self.is_coprime(n) { return false; } (self.data.len()..) .map(|i| self.nth(i)) .take_while(|&p| p * p <= n) .all(|p|!n.is_multiple_of(&p)) } #[inline] fn is_coprime(&self, n: u64) -> bool { self.data .iter() .take_while(|&&p| p * p <= n) .all(|&p|!n.is_multiple_of(&p)) } #[inline] fn grow(&mut self, len: usize) { if self.data.len() >= len { return; } for n in (self.max_prime() + 2..).step_by(2) { if self.is_coprime(n) { self.data.push(n); } if self.data.len() >= len { return; } } } } /// Prime number set #[derive(Clone)] pub struct PrimeSet { data: Rc<RefCell<PrimeInner>>, } impl Default for PrimeSet { fn default() -> Self { Self::new() } } impl PrimeSet { /// Create a new prime number generator. #[inline] pub fn new() -> Self { Self::from_inner(PrimeInner::new()) } /// Create a new prime number generator with empty buffers. #[inline] pub fn new_empty() -> Self { Self::from_inner(PrimeInner::new_empty()) } /// Create a new prime number generator with specifying buffer capacity. #[inline] pub fn with_capacity(capacity: usize) -> Self { Self::from_inner(PrimeInner::with_capacity(capacity)) } /// Get nth prime. /// /// # Example /// /// ``` /// use prime::PrimeSet; /// let ps = PrimeSet::new(); /// assert_eq!(2, ps.nth(0)); /// assert_eq!(3, ps.nth(1)); /// assert_eq!(5, ps.nth(2)); /// assert_eq!(743, ps.nth(131)); /// ``` #[inline] pub fn nth(&self, n: usize) -> u64 { self.data.borrow_mut().nth(n) } /// An iterator visiting all prime numbers in ascending order. /// /// # Example /// /// ``` /// use prime::PrimeSet; /// let mut it = PrimeSet::new().iter(); /// assert_eq!(Some(2), it.next()); /// assert_eq!(Some(3), it.next()); /// assert_eq!(Some(5), it.next()); /// assert_eq!(Some(7), it.next()); /// ``` #[inline] pub fn iter(&self) -> Nums { Nums { idx: 0, data: self.data.clone(), } } /// Return `true` if the given number is prime. #[inline] pub fn contains(&self, n: u64) -> bool { self.data.borrow_mut().contains(n) } /// Calculates the combination of the number #[inline] pub fn combination(&self, n: u64, r: u64) -> u64 { let mut fac = Factorized::<u64>::new(self); for n in (r + 1)..(n + 1) { fac.mul_assign(n); } for n in 1..(n - r + 1) { fac.div_assign(n); } fac.into_integer() } fn from_inner(inner: PrimeInner) -> PrimeSet { PrimeSet { data: Rc::new(RefCell::new(inner)), } } } impl<'a> IntoIterator for &'a PrimeSet { type Item = u64; type IntoIter = Nums; fn into_iter(self) -> Nums { self.iter() } } /// Prime number iterator pub struct Nums { idx: usize, data: Rc<RefCell<PrimeInner>>, } impl Iterator for Nums { type Item = u64; #[inline] fn next(&mut self) -> Option<u64> { let p = self.data.borrow_mut().nth(self.idx); self.idx += 1; Some(p) } } /// The base and exponent that represents factor. pub type Factor<T> = (T, i32); /// Numbers which can be factorized. pub trait Factorize: Integer + FromPrimitive + Clone { /// An iterator visiting all factors in ascending order. fn factorize(&self, ps: &PrimeSet) -> Factors<Self>; /// Calculates the number of all positive divisors. fn num_of_divisor(&self, ps: &PrimeSet) -> u64 { if self.is_zero() { return Zero::zero(); } self.factorize(ps) .map(|(_base, exp)| (exp as u64) + 1) .product() } /// Calculates the sum of all positive divisors. fn sum_of_divisor(&self, ps: &PrimeSet) -> Self { if self.is_zero() { return Zero::zero(); } let one: Self = One::one(); self.factorize(ps) .map(|(base, exp)| { let denom = base.clone() - one.clone(); (num_traits::pow(base, (exp as usize) + 1) - one.clone()) / denom }) .fold(num_traits::one::<Self>(), |acc, n| acc * n) } /// Calculates the number of proper positive divisors. #[inline] fn num_of_proper_divisor(&self, ps: &PrimeSet) -> u64 { self.num_of_divisor(ps) - 1 } /// Caluculates the sum of all positive divisors. #[inline] fn sum_of_proper_divisor(&self, ps: &PrimeSet) -> Self { self.sum_of_divisor(ps) - self.clone() } } macro_rules! trait_impl_unsigned { ($($t:ty)*) => ($( impl Factorize for $t { #[inline] fn factorize(&self, ps: &PrimeSet) -> Factors<$t> { Factors { num: *self, iter: ps.iter() } } } )*) } macro_rules! trait_impl_signed { ($($t:ty)*) => ($( impl Factorize for $t { #[inline] fn factorize(&self, ps: &PrimeSet) -> Factors<$t> { if *self < 0 { Factors { num: -*self, iter: ps.iter() } } else { Factors { num: *self, iter: ps.iter() } } } } )*) } trait_impl_unsigned!(usize u8 u16 u32 u64); trait_impl_signed!(isize i8 i16 i32 i64); /// Factors iterator. pub struct Factors<T> { num: T, iter: Nums, } impl<T: Integer + FromPrimitive + Clone> Iterator for Factors<T> { type Item = Factor<T>; #[inline] fn next(&mut self) -> Option<Factor<T>> { if self.num <= One::one()
while let Some(p) = self.iter.next() { let p: T = FromPrimitive::from_u64(p).unwrap(); if p.clone() * p.clone() > self.num { let n = mem::replace(&mut self.num, One::one()); return Some((n, 1)); } if self.num.is_multiple_of(&p) { let mut exp = 1; self.num = self.num.clone() / p.clone(); while self.num.is_multiple_of(&p) { exp += 1; self.num = self.num.clone() / p.clone(); } return Some((p, exp)); } } unreachable!() } } /// Factorized number providing multiple or divide operation without causing /// overflow. /// /// # Example /// /// ``` /// use prime::{Factorized, PrimeSet}; /// use std::iter; /// /// // Calculates 40C20 /// let ps = PrimeSet::new(); /// let mut fac = Factorized::<u64>::new(&ps); /// for n in 21..41 { /// fac.mul_assign(n); /// } /// for n in 1..21 { /// fac.div_assign(n); /// } /// assert_eq!(137846528820, fac.into_integer()); /// ``` pub struct Factorized<'a, T> { ps: &'a PrimeSet, map: HashMap<T, i32>, } impl<'a, T: Factorize + Eq + Hash> Factorized<'a, T> { /// Creates new empty factorized number. /// /// The empty factorized number represents `1`. pub fn new(ps: &PrimeSet) -> Factorized<'_, T> { Factorized { ps, map: HashMap::new(), } } /// Creates a factorized number from an integer type. pub fn from_integer(ps: &PrimeSet, n: T) -> Factorized<'_, T> { Factorized { ps, map: n.factorize(ps).collect(), } } /// Converts the factorized number into an integer type. pub fn into_integer(self) -> T { self.map .into_iter() .fold::<T, _>(One::one(), |prod, (base, exp)| { if exp > 0 { prod * num_traits::pow(base, exp as usize) } else { prod / num_traits::pow(base, (-exp) as usize) } }) } /// Takes LCM (lowest common multiple) with given number and the factorized /// number. pub fn lcm_with(&mut self, n: T) { for (b, e) in n.factorize(self.ps) { match self.map.entry(b) { Vacant(entry) => { let _ = entry.insert(e); } Occupied(entry) => { let p = entry.into_mut(); *p = cmp::max(e, *p); } } } } /// Multiples the factorized number and given number. pub fn mul_assign(&mut self, n: T) { for (b, e) in n.factorize(self.ps) { match self.map.entry(b) { Vacant(entry) => { let _ = entry.insert(e); } Occupied(entry) => { *entry.into_mut() += e; } } } } /// Divides the factorized number by given number. pub fn div_assign(&mut self, n: T) { for (b, e) in n.factorize(self.ps) { match self.map.entry(b) { Vacant(entry) => { let _ = entry.insert(-e); } Occupied(entry) => { *entry.into_mut() -= e; } } } } } #[cfg(test)] mod tests { use super::{Factor, Factorize, PrimeSet}; #[test] fn iter() { let p1 = PrimeSet::new_empty(); assert_eq!( super::SMALL_PRIMES, &p1.iter() .take(super::SMALL_PRIMES.len()) .collect::<Vec<_>>()[..] ) } #[test] fn contains() { let ps = PrimeSet::new(); assert!(!ps.contains(0)); assert!(!ps.contains(1)); assert!(ps.contains(2)); assert!(ps.contains(3)); assert!(!ps.contains(4)); assert!(ps.contains(5)); assert!(!ps.contains(6)); assert!(ps.contains(7)); assert!(!ps.contains(100)); } #[test] fn multi_iter() { let ps = PrimeSet::new(); for (p1, p2) in ps.iter().zip(ps.iter()).take(500) { assert_eq!(p1, p2); } } #[test] fn clone_clones_data() { let p1 = PrimeSet::new_empty(); let p2 = p1.clone(); let _ = p1.nth(5000); let l1 = p1.data.borrow().data.len(); let l2 = p2.data.borrow().data.len(); assert_eq!(l1, l2); } #[test] fn factorize() { fn check(n: u32, fs: &[Factor<u32>]) { let ps = PrimeSet::new(); assert_eq!(fs, &n.factorize(&ps).collect::<Vec<_>>()[..]); } check(0, &[]); check(1, &[]); check(2, &[(2, 1)]); check(3, &[(3, 1)]); check(4, &[(2, 2)]); check(5, &[(5, 1)]); check(6, &[(2, 1), (3, 1)]); check(7, &[(7, 1)]); check(8, &[(2, 3)]); check(9, &[(3, 2)]); check(10, &[(2, 1), (5, 1)]); check(8 * 27, &[(2, 3), (3, 3)]); check(97, &[(97, 1)]); check(97 * 41, &[(41, 1), (97, 1)]); } #[test] fn num_of_divisor() { let pairs = &[ (0, 0), (1, 1), (2, 2), (3, 2), (4, 3), (5, 2), (6, 4), (7, 2), (8, 4), (9, 3), (10, 4), (11, 2), (12, 6), (24, 8), (36, 9), (48, 10), (60, 12), (50, 6), ]; let ps = PrimeSet::new(); for &(n, num_div) in pairs { assert_eq!(num_div, n.num_of_divisor(&ps)); assert_eq!(num_div, (-n).num_of_divisor(&ps)); } } #[test] fn sum_of_divisor() { let pairs = &[ (0, 0), (1, 1), (2, 3), (3, 4), (4, 7), (5, 6), (6, 12), (7, 8), (8, 15), (9, 13), (10, 18), (11, 12), (12, 28), (24, 60), (36, 91), (48, 124), (60, 168), (50, 93), ]; let ps = PrimeSet::new(); for &(n, sum_div) in pairs { assert_eq!(sum_div, n.sum_of_divisor(&ps)); assert_eq!(sum_div, (-n).sum_of_divisor(&ps)); } } #[test] fn combination() { let ps = PrimeSet::new(); assert_eq!(1, ps.combination(2, 2)); assert_eq!(3, ps.combination(3, 2)); assert_eq!(6, ps.combination(4, 2)); assert_eq!(10, ps.combination(5, 2)); assert_eq!(137846528820, ps.combination(40, 20)); } } #[cfg(all(test, feature = "unstable"))] mod bench { use super::PrimeSet; use test::Bencher; #[bench] fn get_5000th(bh: &mut Bencher) { bh.iter(|| PrimeSet::new().nth(5000)); } #[bench] fn get_below_5000th(bh: &mut Bencher) { bh.iter(|| { let ps = PrimeSet::new(); for _p in ps.iter().take(5000) {} }); } }
{ return None; }
conditional_block
lib.rs
//! Prime number generator and related functions. #![warn( bad_style, missing_docs, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results )] #![cfg_attr(all(test, feature = "unstable"), feature(test))] #[cfg(all(test, feature = "unstable"))] extern crate test; use num_integer::Integer; use num_traits::{FromPrimitive, One, Zero}; use std::{ cell::RefCell, cmp, collections::{ hash_map::Entry::{Occupied, Vacant}, HashMap, }, hash::Hash, iter::IntoIterator, mem, rc::Rc, }; const SMALL_PRIMES: &[u64] = &[ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, ]; const INITIAL_CAPACITY: usize = 10000; struct PrimeInner { data: Vec<u64>, } impl PrimeInner { #[inline] fn new() -> PrimeInner { PrimeInner::with_capacity(INITIAL_CAPACITY) } #[inline] fn new_empty() -> PrimeInner { let mut data = Vec::with_capacity(INITIAL_CAPACITY); data.push(2); data.push(3); PrimeInner { data } } #[inline] fn with_capacity(capacity: usize) -> PrimeInner { let mut data = Vec::with_capacity(capacity + SMALL_PRIMES.len()); data.extend(SMALL_PRIMES.iter().cloned()); PrimeInner { data } } #[inline] fn max_prime(&self) -> u64 { *self.data.last().unwrap() } #[inline] fn nth(&mut self, n: usize) -> u64 { self.grow(n + 1); self.data[n] } #[inline] fn contains(&mut self, n: u64) -> bool { if n < self.max_prime() { return self.data.binary_search(&n).is_ok(); } if!self.is_coprime(n) { return false; } (self.data.len()..) .map(|i| self.nth(i)) .take_while(|&p| p * p <= n) .all(|p|!n.is_multiple_of(&p)) } #[inline] fn is_coprime(&self, n: u64) -> bool { self.data .iter() .take_while(|&&p| p * p <= n) .all(|&p|!n.is_multiple_of(&p)) } #[inline] fn grow(&mut self, len: usize) { if self.data.len() >= len { return; } for n in (self.max_prime() + 2..).step_by(2) { if self.is_coprime(n) { self.data.push(n); } if self.data.len() >= len { return; } } } } /// Prime number set #[derive(Clone)] pub struct PrimeSet { data: Rc<RefCell<PrimeInner>>, } impl Default for PrimeSet { fn default() -> Self { Self::new() } } impl PrimeSet { /// Create a new prime number generator. #[inline] pub fn new() -> Self { Self::from_inner(PrimeInner::new()) } /// Create a new prime number generator with empty buffers. #[inline] pub fn new_empty() -> Self { Self::from_inner(PrimeInner::new_empty()) } /// Create a new prime number generator with specifying buffer capacity. #[inline] pub fn with_capacity(capacity: usize) -> Self { Self::from_inner(PrimeInner::with_capacity(capacity)) } /// Get nth prime. /// /// # Example /// /// ``` /// use prime::PrimeSet; /// let ps = PrimeSet::new(); /// assert_eq!(2, ps.nth(0)); /// assert_eq!(3, ps.nth(1)); /// assert_eq!(5, ps.nth(2)); /// assert_eq!(743, ps.nth(131)); /// ``` #[inline] pub fn nth(&self, n: usize) -> u64 { self.data.borrow_mut().nth(n) } /// An iterator visiting all prime numbers in ascending order. /// /// # Example /// /// ``` /// use prime::PrimeSet; /// let mut it = PrimeSet::new().iter(); /// assert_eq!(Some(2), it.next()); /// assert_eq!(Some(3), it.next()); /// assert_eq!(Some(5), it.next()); /// assert_eq!(Some(7), it.next()); /// ``` #[inline] pub fn iter(&self) -> Nums { Nums { idx: 0, data: self.data.clone(), } } /// Return `true` if the given number is prime. #[inline] pub fn contains(&self, n: u64) -> bool { self.data.borrow_mut().contains(n) } /// Calculates the combination of the number #[inline] pub fn combination(&self, n: u64, r: u64) -> u64 { let mut fac = Factorized::<u64>::new(self); for n in (r + 1)..(n + 1) { fac.mul_assign(n); } for n in 1..(n - r + 1) { fac.div_assign(n); } fac.into_integer() } fn from_inner(inner: PrimeInner) -> PrimeSet { PrimeSet { data: Rc::new(RefCell::new(inner)), } } } impl<'a> IntoIterator for &'a PrimeSet { type Item = u64; type IntoIter = Nums; fn into_iter(self) -> Nums { self.iter() } } /// Prime number iterator pub struct Nums { idx: usize, data: Rc<RefCell<PrimeInner>>, } impl Iterator for Nums { type Item = u64; #[inline] fn next(&mut self) -> Option<u64> { let p = self.data.borrow_mut().nth(self.idx); self.idx += 1; Some(p) } } /// The base and exponent that represents factor. pub type Factor<T> = (T, i32); /// Numbers which can be factorized. pub trait Factorize: Integer + FromPrimitive + Clone { /// An iterator visiting all factors in ascending order. fn factorize(&self, ps: &PrimeSet) -> Factors<Self>; /// Calculates the number of all positive divisors. fn num_of_divisor(&self, ps: &PrimeSet) -> u64 { if self.is_zero() { return Zero::zero(); } self.factorize(ps) .map(|(_base, exp)| (exp as u64) + 1) .product() } /// Calculates the sum of all positive divisors. fn sum_of_divisor(&self, ps: &PrimeSet) -> Self { if self.is_zero() { return Zero::zero(); } let one: Self = One::one(); self.factorize(ps) .map(|(base, exp)| { let denom = base.clone() - one.clone(); (num_traits::pow(base, (exp as usize) + 1) - one.clone()) / denom }) .fold(num_traits::one::<Self>(), |acc, n| acc * n) } /// Calculates the number of proper positive divisors. #[inline] fn num_of_proper_divisor(&self, ps: &PrimeSet) -> u64 { self.num_of_divisor(ps) - 1 } /// Caluculates the sum of all positive divisors. #[inline] fn sum_of_proper_divisor(&self, ps: &PrimeSet) -> Self { self.sum_of_divisor(ps) - self.clone() } } macro_rules! trait_impl_unsigned { ($($t:ty)*) => ($( impl Factorize for $t { #[inline] fn factorize(&self, ps: &PrimeSet) -> Factors<$t> { Factors { num: *self, iter: ps.iter() } } } )*) } macro_rules! trait_impl_signed { ($($t:ty)*) => ($( impl Factorize for $t { #[inline] fn factorize(&self, ps: &PrimeSet) -> Factors<$t> { if *self < 0 { Factors { num: -*self, iter: ps.iter() } } else { Factors { num: *self, iter: ps.iter() } } } } )*) } trait_impl_unsigned!(usize u8 u16 u32 u64); trait_impl_signed!(isize i8 i16 i32 i64); /// Factors iterator. pub struct Factors<T> { num: T, iter: Nums, } impl<T: Integer + FromPrimitive + Clone> Iterator for Factors<T> { type Item = Factor<T>; #[inline] fn next(&mut self) -> Option<Factor<T>> { if self.num <= One::one() { return None; } while let Some(p) = self.iter.next() { let p: T = FromPrimitive::from_u64(p).unwrap(); if p.clone() * p.clone() > self.num { let n = mem::replace(&mut self.num, One::one()); return Some((n, 1)); } if self.num.is_multiple_of(&p) { let mut exp = 1; self.num = self.num.clone() / p.clone(); while self.num.is_multiple_of(&p) { exp += 1; self.num = self.num.clone() / p.clone(); } return Some((p, exp)); } } unreachable!() } } /// Factorized number providing multiple or divide operation without causing /// overflow. /// /// # Example /// /// ``` /// use prime::{Factorized, PrimeSet}; /// use std::iter; /// /// // Calculates 40C20 /// let ps = PrimeSet::new(); /// let mut fac = Factorized::<u64>::new(&ps); /// for n in 21..41 { /// fac.mul_assign(n); /// } /// for n in 1..21 { /// fac.div_assign(n); /// } /// assert_eq!(137846528820, fac.into_integer()); /// ``` pub struct Factorized<'a, T> { ps: &'a PrimeSet, map: HashMap<T, i32>, } impl<'a, T: Factorize + Eq + Hash> Factorized<'a, T> { /// Creates new empty factorized number. /// /// The empty factorized number represents `1`. pub fn new(ps: &PrimeSet) -> Factorized<'_, T> { Factorized { ps, map: HashMap::new(), } } /// Creates a factorized number from an integer type. pub fn from_integer(ps: &PrimeSet, n: T) -> Factorized<'_, T> { Factorized { ps, map: n.factorize(ps).collect(), } } /// Converts the factorized number into an integer type. pub fn into_integer(self) -> T { self.map .into_iter() .fold::<T, _>(One::one(), |prod, (base, exp)| { if exp > 0 { prod * num_traits::pow(base, exp as usize) } else { prod / num_traits::pow(base, (-exp) as usize) } }) } /// Takes LCM (lowest common multiple) with given number and the factorized /// number. pub fn
(&mut self, n: T) { for (b, e) in n.factorize(self.ps) { match self.map.entry(b) { Vacant(entry) => { let _ = entry.insert(e); } Occupied(entry) => { let p = entry.into_mut(); *p = cmp::max(e, *p); } } } } /// Multiples the factorized number and given number. pub fn mul_assign(&mut self, n: T) { for (b, e) in n.factorize(self.ps) { match self.map.entry(b) { Vacant(entry) => { let _ = entry.insert(e); } Occupied(entry) => { *entry.into_mut() += e; } } } } /// Divides the factorized number by given number. pub fn div_assign(&mut self, n: T) { for (b, e) in n.factorize(self.ps) { match self.map.entry(b) { Vacant(entry) => { let _ = entry.insert(-e); } Occupied(entry) => { *entry.into_mut() -= e; } } } } } #[cfg(test)] mod tests { use super::{Factor, Factorize, PrimeSet}; #[test] fn iter() { let p1 = PrimeSet::new_empty(); assert_eq!( super::SMALL_PRIMES, &p1.iter() .take(super::SMALL_PRIMES.len()) .collect::<Vec<_>>()[..] ) } #[test] fn contains() { let ps = PrimeSet::new(); assert!(!ps.contains(0)); assert!(!ps.contains(1)); assert!(ps.contains(2)); assert!(ps.contains(3)); assert!(!ps.contains(4)); assert!(ps.contains(5)); assert!(!ps.contains(6)); assert!(ps.contains(7)); assert!(!ps.contains(100)); } #[test] fn multi_iter() { let ps = PrimeSet::new(); for (p1, p2) in ps.iter().zip(ps.iter()).take(500) { assert_eq!(p1, p2); } } #[test] fn clone_clones_data() { let p1 = PrimeSet::new_empty(); let p2 = p1.clone(); let _ = p1.nth(5000); let l1 = p1.data.borrow().data.len(); let l2 = p2.data.borrow().data.len(); assert_eq!(l1, l2); } #[test] fn factorize() { fn check(n: u32, fs: &[Factor<u32>]) { let ps = PrimeSet::new(); assert_eq!(fs, &n.factorize(&ps).collect::<Vec<_>>()[..]); } check(0, &[]); check(1, &[]); check(2, &[(2, 1)]); check(3, &[(3, 1)]); check(4, &[(2, 2)]); check(5, &[(5, 1)]); check(6, &[(2, 1), (3, 1)]); check(7, &[(7, 1)]); check(8, &[(2, 3)]); check(9, &[(3, 2)]); check(10, &[(2, 1), (5, 1)]); check(8 * 27, &[(2, 3), (3, 3)]); check(97, &[(97, 1)]); check(97 * 41, &[(41, 1), (97, 1)]); } #[test] fn num_of_divisor() { let pairs = &[ (0, 0), (1, 1), (2, 2), (3, 2), (4, 3), (5, 2), (6, 4), (7, 2), (8, 4), (9, 3), (10, 4), (11, 2), (12, 6), (24, 8), (36, 9), (48, 10), (60, 12), (50, 6), ]; let ps = PrimeSet::new(); for &(n, num_div) in pairs { assert_eq!(num_div, n.num_of_divisor(&ps)); assert_eq!(num_div, (-n).num_of_divisor(&ps)); } } #[test] fn sum_of_divisor() { let pairs = &[ (0, 0), (1, 1), (2, 3), (3, 4), (4, 7), (5, 6), (6, 12), (7, 8), (8, 15), (9, 13), (10, 18), (11, 12), (12, 28), (24, 60), (36, 91), (48, 124), (60, 168), (50, 93), ]; let ps = PrimeSet::new(); for &(n, sum_div) in pairs { assert_eq!(sum_div, n.sum_of_divisor(&ps)); assert_eq!(sum_div, (-n).sum_of_divisor(&ps)); } } #[test] fn combination() { let ps = PrimeSet::new(); assert_eq!(1, ps.combination(2, 2)); assert_eq!(3, ps.combination(3, 2)); assert_eq!(6, ps.combination(4, 2)); assert_eq!(10, ps.combination(5, 2)); assert_eq!(137846528820, ps.combination(40, 20)); } } #[cfg(all(test, feature = "unstable"))] mod bench { use super::PrimeSet; use test::Bencher; #[bench] fn get_5000th(bh: &mut Bencher) { bh.iter(|| PrimeSet::new().nth(5000)); } #[bench] fn get_below_5000th(bh: &mut Bencher) { bh.iter(|| { let ps = PrimeSet::new(); for _p in ps.iter().take(5000) {} }); } }
lcm_with
identifier_name
lib.rs
//! Prime number generator and related functions. #![warn( bad_style, missing_docs, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results )] #![cfg_attr(all(test, feature = "unstable"), feature(test))] #[cfg(all(test, feature = "unstable"))] extern crate test; use num_integer::Integer; use num_traits::{FromPrimitive, One, Zero}; use std::{ cell::RefCell, cmp, collections::{ hash_map::Entry::{Occupied, Vacant}, HashMap, }, hash::Hash, iter::IntoIterator, mem, rc::Rc, }; const SMALL_PRIMES: &[u64] = &[ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, ]; const INITIAL_CAPACITY: usize = 10000; struct PrimeInner { data: Vec<u64>, } impl PrimeInner { #[inline] fn new() -> PrimeInner { PrimeInner::with_capacity(INITIAL_CAPACITY) } #[inline] fn new_empty() -> PrimeInner { let mut data = Vec::with_capacity(INITIAL_CAPACITY); data.push(2); data.push(3); PrimeInner { data } } #[inline] fn with_capacity(capacity: usize) -> PrimeInner { let mut data = Vec::with_capacity(capacity + SMALL_PRIMES.len()); data.extend(SMALL_PRIMES.iter().cloned()); PrimeInner { data } } #[inline] fn max_prime(&self) -> u64 { *self.data.last().unwrap() } #[inline] fn nth(&mut self, n: usize) -> u64 { self.grow(n + 1); self.data[n] } #[inline] fn contains(&mut self, n: u64) -> bool { if n < self.max_prime() { return self.data.binary_search(&n).is_ok(); } if!self.is_coprime(n) { return false; } (self.data.len()..) .map(|i| self.nth(i)) .take_while(|&p| p * p <= n) .all(|p|!n.is_multiple_of(&p)) } #[inline] fn is_coprime(&self, n: u64) -> bool { self.data .iter() .take_while(|&&p| p * p <= n) .all(|&p|!n.is_multiple_of(&p)) } #[inline] fn grow(&mut self, len: usize) { if self.data.len() >= len { return; } for n in (self.max_prime() + 2..).step_by(2) { if self.is_coprime(n) { self.data.push(n); } if self.data.len() >= len { return; } } } } /// Prime number set #[derive(Clone)] pub struct PrimeSet { data: Rc<RefCell<PrimeInner>>, } impl Default for PrimeSet { fn default() -> Self { Self::new() } } impl PrimeSet { /// Create a new prime number generator. #[inline] pub fn new() -> Self { Self::from_inner(PrimeInner::new()) } /// Create a new prime number generator with empty buffers. #[inline] pub fn new_empty() -> Self { Self::from_inner(PrimeInner::new_empty()) } /// Create a new prime number generator with specifying buffer capacity. #[inline] pub fn with_capacity(capacity: usize) -> Self { Self::from_inner(PrimeInner::with_capacity(capacity)) } /// Get nth prime. /// /// # Example /// /// ``` /// use prime::PrimeSet; /// let ps = PrimeSet::new(); /// assert_eq!(2, ps.nth(0)); /// assert_eq!(3, ps.nth(1)); /// assert_eq!(5, ps.nth(2)); /// assert_eq!(743, ps.nth(131)); /// ``` #[inline] pub fn nth(&self, n: usize) -> u64 { self.data.borrow_mut().nth(n) } /// An iterator visiting all prime numbers in ascending order. /// /// # Example /// /// ``` /// use prime::PrimeSet; /// let mut it = PrimeSet::new().iter(); /// assert_eq!(Some(2), it.next()); /// assert_eq!(Some(3), it.next()); /// assert_eq!(Some(5), it.next()); /// assert_eq!(Some(7), it.next()); /// ``` #[inline] pub fn iter(&self) -> Nums { Nums { idx: 0, data: self.data.clone(), } } /// Return `true` if the given number is prime. #[inline] pub fn contains(&self, n: u64) -> bool { self.data.borrow_mut().contains(n) } /// Calculates the combination of the number #[inline] pub fn combination(&self, n: u64, r: u64) -> u64 { let mut fac = Factorized::<u64>::new(self); for n in (r + 1)..(n + 1) { fac.mul_assign(n); } for n in 1..(n - r + 1) { fac.div_assign(n); } fac.into_integer() } fn from_inner(inner: PrimeInner) -> PrimeSet { PrimeSet { data: Rc::new(RefCell::new(inner)), } } } impl<'a> IntoIterator for &'a PrimeSet { type Item = u64; type IntoIter = Nums; fn into_iter(self) -> Nums { self.iter() } } /// Prime number iterator pub struct Nums { idx: usize, data: Rc<RefCell<PrimeInner>>, } impl Iterator for Nums { type Item = u64; #[inline] fn next(&mut self) -> Option<u64> { let p = self.data.borrow_mut().nth(self.idx); self.idx += 1; Some(p) } } /// The base and exponent that represents factor. pub type Factor<T> = (T, i32); /// Numbers which can be factorized. pub trait Factorize: Integer + FromPrimitive + Clone { /// An iterator visiting all factors in ascending order. fn factorize(&self, ps: &PrimeSet) -> Factors<Self>; /// Calculates the number of all positive divisors. fn num_of_divisor(&self, ps: &PrimeSet) -> u64 { if self.is_zero() { return Zero::zero(); } self.factorize(ps) .map(|(_base, exp)| (exp as u64) + 1) .product() } /// Calculates the sum of all positive divisors. fn sum_of_divisor(&self, ps: &PrimeSet) -> Self { if self.is_zero() { return Zero::zero(); } let one: Self = One::one(); self.factorize(ps) .map(|(base, exp)| { let denom = base.clone() - one.clone(); (num_traits::pow(base, (exp as usize) + 1) - one.clone()) / denom }) .fold(num_traits::one::<Self>(), |acc, n| acc * n) } /// Calculates the number of proper positive divisors. #[inline] fn num_of_proper_divisor(&self, ps: &PrimeSet) -> u64 { self.num_of_divisor(ps) - 1 } /// Caluculates the sum of all positive divisors. #[inline] fn sum_of_proper_divisor(&self, ps: &PrimeSet) -> Self { self.sum_of_divisor(ps) - self.clone() } } macro_rules! trait_impl_unsigned { ($($t:ty)*) => ($( impl Factorize for $t { #[inline] fn factorize(&self, ps: &PrimeSet) -> Factors<$t> { Factors { num: *self, iter: ps.iter() } } } )*) } macro_rules! trait_impl_signed { ($($t:ty)*) => ($( impl Factorize for $t { #[inline] fn factorize(&self, ps: &PrimeSet) -> Factors<$t> { if *self < 0 { Factors { num: -*self, iter: ps.iter() } } else { Factors { num: *self, iter: ps.iter() } } } } )*) } trait_impl_unsigned!(usize u8 u16 u32 u64); trait_impl_signed!(isize i8 i16 i32 i64); /// Factors iterator. pub struct Factors<T> { num: T, iter: Nums, } impl<T: Integer + FromPrimitive + Clone> Iterator for Factors<T> { type Item = Factor<T>; #[inline] fn next(&mut self) -> Option<Factor<T>> { if self.num <= One::one() { return None; } while let Some(p) = self.iter.next() { let p: T = FromPrimitive::from_u64(p).unwrap(); if p.clone() * p.clone() > self.num { let n = mem::replace(&mut self.num, One::one()); return Some((n, 1)); } if self.num.is_multiple_of(&p) { let mut exp = 1; self.num = self.num.clone() / p.clone(); while self.num.is_multiple_of(&p) { exp += 1; self.num = self.num.clone() / p.clone(); } return Some((p, exp)); } } unreachable!() } } /// Factorized number providing multiple or divide operation without causing /// overflow. /// /// # Example /// /// ``` /// use prime::{Factorized, PrimeSet}; /// use std::iter; /// /// // Calculates 40C20 /// let ps = PrimeSet::new(); /// let mut fac = Factorized::<u64>::new(&ps); /// for n in 21..41 { /// fac.mul_assign(n); /// } /// for n in 1..21 { /// fac.div_assign(n); /// } /// assert_eq!(137846528820, fac.into_integer()); /// ``` pub struct Factorized<'a, T> { ps: &'a PrimeSet, map: HashMap<T, i32>, } impl<'a, T: Factorize + Eq + Hash> Factorized<'a, T> { /// Creates new empty factorized number. /// /// The empty factorized number represents `1`. pub fn new(ps: &PrimeSet) -> Factorized<'_, T> { Factorized { ps, map: HashMap::new(), } } /// Creates a factorized number from an integer type. pub fn from_integer(ps: &PrimeSet, n: T) -> Factorized<'_, T> { Factorized { ps, map: n.factorize(ps).collect(), } } /// Converts the factorized number into an integer type. pub fn into_integer(self) -> T { self.map .into_iter() .fold::<T, _>(One::one(), |prod, (base, exp)| { if exp > 0 { prod * num_traits::pow(base, exp as usize) } else { prod / num_traits::pow(base, (-exp) as usize) } }) } /// Takes LCM (lowest common multiple) with given number and the factorized /// number. pub fn lcm_with(&mut self, n: T) { for (b, e) in n.factorize(self.ps) { match self.map.entry(b) { Vacant(entry) => { let _ = entry.insert(e); } Occupied(entry) => { let p = entry.into_mut(); *p = cmp::max(e, *p); } } } } /// Multiples the factorized number and given number. pub fn mul_assign(&mut self, n: T) { for (b, e) in n.factorize(self.ps) { match self.map.entry(b) { Vacant(entry) => { let _ = entry.insert(e); } Occupied(entry) => { *entry.into_mut() += e; } } } } /// Divides the factorized number by given number. pub fn div_assign(&mut self, n: T) { for (b, e) in n.factorize(self.ps) { match self.map.entry(b) { Vacant(entry) => { let _ = entry.insert(-e); } Occupied(entry) => { *entry.into_mut() -= e; } } } } } #[cfg(test)] mod tests { use super::{Factor, Factorize, PrimeSet}; #[test] fn iter() { let p1 = PrimeSet::new_empty(); assert_eq!( super::SMALL_PRIMES, &p1.iter() .take(super::SMALL_PRIMES.len()) .collect::<Vec<_>>()[..] ) } #[test] fn contains()
#[test] fn multi_iter() { let ps = PrimeSet::new(); for (p1, p2) in ps.iter().zip(ps.iter()).take(500) { assert_eq!(p1, p2); } } #[test] fn clone_clones_data() { let p1 = PrimeSet::new_empty(); let p2 = p1.clone(); let _ = p1.nth(5000); let l1 = p1.data.borrow().data.len(); let l2 = p2.data.borrow().data.len(); assert_eq!(l1, l2); } #[test] fn factorize() { fn check(n: u32, fs: &[Factor<u32>]) { let ps = PrimeSet::new(); assert_eq!(fs, &n.factorize(&ps).collect::<Vec<_>>()[..]); } check(0, &[]); check(1, &[]); check(2, &[(2, 1)]); check(3, &[(3, 1)]); check(4, &[(2, 2)]); check(5, &[(5, 1)]); check(6, &[(2, 1), (3, 1)]); check(7, &[(7, 1)]); check(8, &[(2, 3)]); check(9, &[(3, 2)]); check(10, &[(2, 1), (5, 1)]); check(8 * 27, &[(2, 3), (3, 3)]); check(97, &[(97, 1)]); check(97 * 41, &[(41, 1), (97, 1)]); } #[test] fn num_of_divisor() { let pairs = &[ (0, 0), (1, 1), (2, 2), (3, 2), (4, 3), (5, 2), (6, 4), (7, 2), (8, 4), (9, 3), (10, 4), (11, 2), (12, 6), (24, 8), (36, 9), (48, 10), (60, 12), (50, 6), ]; let ps = PrimeSet::new(); for &(n, num_div) in pairs { assert_eq!(num_div, n.num_of_divisor(&ps)); assert_eq!(num_div, (-n).num_of_divisor(&ps)); } } #[test] fn sum_of_divisor() { let pairs = &[ (0, 0), (1, 1), (2, 3), (3, 4), (4, 7), (5, 6), (6, 12), (7, 8), (8, 15), (9, 13), (10, 18), (11, 12), (12, 28), (24, 60), (36, 91), (48, 124), (60, 168), (50, 93), ]; let ps = PrimeSet::new(); for &(n, sum_div) in pairs { assert_eq!(sum_div, n.sum_of_divisor(&ps)); assert_eq!(sum_div, (-n).sum_of_divisor(&ps)); } } #[test] fn combination() { let ps = PrimeSet::new(); assert_eq!(1, ps.combination(2, 2)); assert_eq!(3, ps.combination(3, 2)); assert_eq!(6, ps.combination(4, 2)); assert_eq!(10, ps.combination(5, 2)); assert_eq!(137846528820, ps.combination(40, 20)); } } #[cfg(all(test, feature = "unstable"))] mod bench { use super::PrimeSet; use test::Bencher; #[bench] fn get_5000th(bh: &mut Bencher) { bh.iter(|| PrimeSet::new().nth(5000)); } #[bench] fn get_below_5000th(bh: &mut Bencher) { bh.iter(|| { let ps = PrimeSet::new(); for _p in ps.iter().take(5000) {} }); } }
{ let ps = PrimeSet::new(); assert!(!ps.contains(0)); assert!(!ps.contains(1)); assert!(ps.contains(2)); assert!(ps.contains(3)); assert!(!ps.contains(4)); assert!(ps.contains(5)); assert!(!ps.contains(6)); assert!(ps.contains(7)); assert!(!ps.contains(100)); }
identifier_body
lib.rs
//! Prime number generator and related functions. #![warn( bad_style, missing_docs, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results )] #![cfg_attr(all(test, feature = "unstable"), feature(test))] #[cfg(all(test, feature = "unstable"))] extern crate test; use num_integer::Integer; use num_traits::{FromPrimitive, One, Zero}; use std::{ cell::RefCell, cmp, collections::{ hash_map::Entry::{Occupied, Vacant}, HashMap, }, hash::Hash, iter::IntoIterator, mem, rc::Rc, }; const SMALL_PRIMES: &[u64] = &[ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, ]; const INITIAL_CAPACITY: usize = 10000; struct PrimeInner { data: Vec<u64>, } impl PrimeInner { #[inline] fn new() -> PrimeInner { PrimeInner::with_capacity(INITIAL_CAPACITY) } #[inline] fn new_empty() -> PrimeInner { let mut data = Vec::with_capacity(INITIAL_CAPACITY); data.push(2); data.push(3); PrimeInner { data } } #[inline] fn with_capacity(capacity: usize) -> PrimeInner { let mut data = Vec::with_capacity(capacity + SMALL_PRIMES.len()); data.extend(SMALL_PRIMES.iter().cloned()); PrimeInner { data } } #[inline] fn max_prime(&self) -> u64 { *self.data.last().unwrap() } #[inline] fn nth(&mut self, n: usize) -> u64 { self.grow(n + 1); self.data[n] } #[inline] fn contains(&mut self, n: u64) -> bool { if n < self.max_prime() { return self.data.binary_search(&n).is_ok(); } if!self.is_coprime(n) { return false; } (self.data.len()..) .map(|i| self.nth(i)) .take_while(|&p| p * p <= n) .all(|p|!n.is_multiple_of(&p)) } #[inline] fn is_coprime(&self, n: u64) -> bool { self.data .iter() .take_while(|&&p| p * p <= n) .all(|&p|!n.is_multiple_of(&p)) } #[inline] fn grow(&mut self, len: usize) { if self.data.len() >= len { return; } for n in (self.max_prime() + 2..).step_by(2) { if self.is_coprime(n) { self.data.push(n); } if self.data.len() >= len { return; } } } } /// Prime number set #[derive(Clone)] pub struct PrimeSet { data: Rc<RefCell<PrimeInner>>, } impl Default for PrimeSet { fn default() -> Self { Self::new() } } impl PrimeSet { /// Create a new prime number generator. #[inline] pub fn new() -> Self { Self::from_inner(PrimeInner::new()) } /// Create a new prime number generator with empty buffers. #[inline] pub fn new_empty() -> Self { Self::from_inner(PrimeInner::new_empty()) } /// Create a new prime number generator with specifying buffer capacity. #[inline] pub fn with_capacity(capacity: usize) -> Self { Self::from_inner(PrimeInner::with_capacity(capacity)) } /// Get nth prime. /// /// # Example /// /// ``` /// use prime::PrimeSet; /// let ps = PrimeSet::new(); /// assert_eq!(2, ps.nth(0)); /// assert_eq!(3, ps.nth(1)); /// assert_eq!(5, ps.nth(2)); /// assert_eq!(743, ps.nth(131)); /// ``` #[inline] pub fn nth(&self, n: usize) -> u64 { self.data.borrow_mut().nth(n) } /// An iterator visiting all prime numbers in ascending order. /// /// # Example /// /// ``` /// use prime::PrimeSet; /// let mut it = PrimeSet::new().iter(); /// assert_eq!(Some(2), it.next()); /// assert_eq!(Some(3), it.next()); /// assert_eq!(Some(5), it.next()); /// assert_eq!(Some(7), it.next()); /// ``` #[inline] pub fn iter(&self) -> Nums { Nums { idx: 0, data: self.data.clone(), } } /// Return `true` if the given number is prime. #[inline] pub fn contains(&self, n: u64) -> bool { self.data.borrow_mut().contains(n) } /// Calculates the combination of the number #[inline] pub fn combination(&self, n: u64, r: u64) -> u64 { let mut fac = Factorized::<u64>::new(self); for n in (r + 1)..(n + 1) { fac.mul_assign(n); } for n in 1..(n - r + 1) { fac.div_assign(n); } fac.into_integer() } fn from_inner(inner: PrimeInner) -> PrimeSet { PrimeSet { data: Rc::new(RefCell::new(inner)), } } } impl<'a> IntoIterator for &'a PrimeSet { type Item = u64; type IntoIter = Nums; fn into_iter(self) -> Nums { self.iter() } } /// Prime number iterator pub struct Nums { idx: usize, data: Rc<RefCell<PrimeInner>>, } impl Iterator for Nums { type Item = u64; #[inline] fn next(&mut self) -> Option<u64> { let p = self.data.borrow_mut().nth(self.idx); self.idx += 1; Some(p) } } /// The base and exponent that represents factor. pub type Factor<T> = (T, i32); /// Numbers which can be factorized. pub trait Factorize: Integer + FromPrimitive + Clone { /// An iterator visiting all factors in ascending order. fn factorize(&self, ps: &PrimeSet) -> Factors<Self>; /// Calculates the number of all positive divisors. fn num_of_divisor(&self, ps: &PrimeSet) -> u64 { if self.is_zero() { return Zero::zero(); } self.factorize(ps) .map(|(_base, exp)| (exp as u64) + 1) .product() } /// Calculates the sum of all positive divisors. fn sum_of_divisor(&self, ps: &PrimeSet) -> Self { if self.is_zero() { return Zero::zero(); } let one: Self = One::one(); self.factorize(ps) .map(|(base, exp)| { let denom = base.clone() - one.clone(); (num_traits::pow(base, (exp as usize) + 1) - one.clone()) / denom }) .fold(num_traits::one::<Self>(), |acc, n| acc * n) } /// Calculates the number of proper positive divisors. #[inline] fn num_of_proper_divisor(&self, ps: &PrimeSet) -> u64 { self.num_of_divisor(ps) - 1 } /// Caluculates the sum of all positive divisors. #[inline] fn sum_of_proper_divisor(&self, ps: &PrimeSet) -> Self { self.sum_of_divisor(ps) - self.clone() } } macro_rules! trait_impl_unsigned { ($($t:ty)*) => ($( impl Factorize for $t { #[inline] fn factorize(&self, ps: &PrimeSet) -> Factors<$t> { Factors { num: *self, iter: ps.iter() } } } )*) } macro_rules! trait_impl_signed { ($($t:ty)*) => ($( impl Factorize for $t { #[inline] fn factorize(&self, ps: &PrimeSet) -> Factors<$t> { if *self < 0 { Factors { num: -*self, iter: ps.iter() } } else { Factors { num: *self, iter: ps.iter() } } } } )*) } trait_impl_unsigned!(usize u8 u16 u32 u64); trait_impl_signed!(isize i8 i16 i32 i64); /// Factors iterator. pub struct Factors<T> { num: T, iter: Nums, } impl<T: Integer + FromPrimitive + Clone> Iterator for Factors<T> { type Item = Factor<T>; #[inline] fn next(&mut self) -> Option<Factor<T>> { if self.num <= One::one() { return None; } while let Some(p) = self.iter.next() { let p: T = FromPrimitive::from_u64(p).unwrap(); if p.clone() * p.clone() > self.num { let n = mem::replace(&mut self.num, One::one()); return Some((n, 1)); } if self.num.is_multiple_of(&p) { let mut exp = 1; self.num = self.num.clone() / p.clone(); while self.num.is_multiple_of(&p) { exp += 1; self.num = self.num.clone() / p.clone(); } return Some((p, exp)); } } unreachable!() } } /// Factorized number providing multiple or divide operation without causing /// overflow. /// /// # Example /// /// ``` /// use prime::{Factorized, PrimeSet}; /// use std::iter; /// /// // Calculates 40C20 /// let ps = PrimeSet::new(); /// let mut fac = Factorized::<u64>::new(&ps); /// for n in 21..41 { /// fac.mul_assign(n); /// } /// for n in 1..21 { /// fac.div_assign(n); /// } /// assert_eq!(137846528820, fac.into_integer()); /// ``` pub struct Factorized<'a, T> { ps: &'a PrimeSet, map: HashMap<T, i32>, } impl<'a, T: Factorize + Eq + Hash> Factorized<'a, T> { /// Creates new empty factorized number. /// /// The empty factorized number represents `1`. pub fn new(ps: &PrimeSet) -> Factorized<'_, T> { Factorized { ps, map: HashMap::new(), } } /// Creates a factorized number from an integer type. pub fn from_integer(ps: &PrimeSet, n: T) -> Factorized<'_, T> { Factorized { ps, map: n.factorize(ps).collect(), } } /// Converts the factorized number into an integer type. pub fn into_integer(self) -> T { self.map .into_iter() .fold::<T, _>(One::one(), |prod, (base, exp)| { if exp > 0 { prod * num_traits::pow(base, exp as usize) } else { prod / num_traits::pow(base, (-exp) as usize) } }) } /// Takes LCM (lowest common multiple) with given number and the factorized /// number. pub fn lcm_with(&mut self, n: T) { for (b, e) in n.factorize(self.ps) { match self.map.entry(b) { Vacant(entry) => { let _ = entry.insert(e); } Occupied(entry) => { let p = entry.into_mut(); *p = cmp::max(e, *p); } } } } /// Multiples the factorized number and given number. pub fn mul_assign(&mut self, n: T) { for (b, e) in n.factorize(self.ps) { match self.map.entry(b) { Vacant(entry) => { let _ = entry.insert(e); } Occupied(entry) => { *entry.into_mut() += e; } } } } /// Divides the factorized number by given number. pub fn div_assign(&mut self, n: T) { for (b, e) in n.factorize(self.ps) { match self.map.entry(b) { Vacant(entry) => { let _ = entry.insert(-e); } Occupied(entry) => { *entry.into_mut() -= e; } } } } } #[cfg(test)] mod tests { use super::{Factor, Factorize, PrimeSet}; #[test] fn iter() { let p1 = PrimeSet::new_empty(); assert_eq!( super::SMALL_PRIMES, &p1.iter() .take(super::SMALL_PRIMES.len()) .collect::<Vec<_>>()[..] ) } #[test] fn contains() { let ps = PrimeSet::new(); assert!(!ps.contains(0)); assert!(!ps.contains(1)); assert!(ps.contains(2)); assert!(ps.contains(3)); assert!(!ps.contains(4)); assert!(ps.contains(5)); assert!(!ps.contains(6)); assert!(ps.contains(7)); assert!(!ps.contains(100)); } #[test] fn multi_iter() { let ps = PrimeSet::new(); for (p1, p2) in ps.iter().zip(ps.iter()).take(500) { assert_eq!(p1, p2); } } #[test] fn clone_clones_data() { let p1 = PrimeSet::new_empty(); let p2 = p1.clone(); let _ = p1.nth(5000); let l1 = p1.data.borrow().data.len(); let l2 = p2.data.borrow().data.len(); assert_eq!(l1, l2); } #[test] fn factorize() { fn check(n: u32, fs: &[Factor<u32>]) { let ps = PrimeSet::new(); assert_eq!(fs, &n.factorize(&ps).collect::<Vec<_>>()[..]); } check(0, &[]); check(1, &[]); check(2, &[(2, 1)]); check(3, &[(3, 1)]); check(4, &[(2, 2)]); check(5, &[(5, 1)]); check(6, &[(2, 1), (3, 1)]); check(7, &[(7, 1)]); check(8, &[(2, 3)]); check(9, &[(3, 2)]); check(10, &[(2, 1), (5, 1)]); check(8 * 27, &[(2, 3), (3, 3)]); check(97, &[(97, 1)]); check(97 * 41, &[(41, 1), (97, 1)]); } #[test] fn num_of_divisor() { let pairs = &[ (0, 0), (1, 1), (2, 2), (3, 2), (4, 3), (5, 2), (6, 4), (7, 2), (8, 4), (9, 3), (10, 4), (11, 2), (12, 6),
(48, 10), (60, 12), (50, 6), ]; let ps = PrimeSet::new(); for &(n, num_div) in pairs { assert_eq!(num_div, n.num_of_divisor(&ps)); assert_eq!(num_div, (-n).num_of_divisor(&ps)); } } #[test] fn sum_of_divisor() { let pairs = &[ (0, 0), (1, 1), (2, 3), (3, 4), (4, 7), (5, 6), (6, 12), (7, 8), (8, 15), (9, 13), (10, 18), (11, 12), (12, 28), (24, 60), (36, 91), (48, 124), (60, 168), (50, 93), ]; let ps = PrimeSet::new(); for &(n, sum_div) in pairs { assert_eq!(sum_div, n.sum_of_divisor(&ps)); assert_eq!(sum_div, (-n).sum_of_divisor(&ps)); } } #[test] fn combination() { let ps = PrimeSet::new(); assert_eq!(1, ps.combination(2, 2)); assert_eq!(3, ps.combination(3, 2)); assert_eq!(6, ps.combination(4, 2)); assert_eq!(10, ps.combination(5, 2)); assert_eq!(137846528820, ps.combination(40, 20)); } } #[cfg(all(test, feature = "unstable"))] mod bench { use super::PrimeSet; use test::Bencher; #[bench] fn get_5000th(bh: &mut Bencher) { bh.iter(|| PrimeSet::new().nth(5000)); } #[bench] fn get_below_5000th(bh: &mut Bencher) { bh.iter(|| { let ps = PrimeSet::new(); for _p in ps.iter().take(5000) {} }); } }
(24, 8), (36, 9),
random_line_split
init-res-into-things.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. // Resources can't be copied, but storing into data structures counts // as a move unless the stored thing is used afterwards. struct r { i: @mut int, } struct Box { x: r } #[unsafe_destructor] impl Drop for r { fn drop(&self) { unsafe { *(self.i) = *(self.i) + 1; } } } fn r(i: @mut int) -> r { r { i: i } } fn test_box()
fn test_rec() { let i = @mut 0; { let a = Box {x: r(i)}; } assert_eq!(*i, 1); } fn test_tag() { enum t { t0(r), } let i = @mut 0; { let a = t0(r(i)); } assert_eq!(*i, 1); } fn test_tup() { let i = @mut 0; { let a = (r(i), 0); } assert_eq!(*i, 1); } fn test_unique() { let i = @mut 0; { let a = ~r(i); } assert_eq!(*i, 1); } fn test_box_rec() { let i = @mut 0; { let a = @Box { x: r(i) }; } assert_eq!(*i, 1); } pub fn main() { test_box(); test_rec(); test_tag(); test_tup(); test_unique(); test_box_rec(); }
{ let i = @mut 0; { let a = @r(i); } assert_eq!(*i, 1); }
identifier_body
init-res-into-things.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. // Resources can't be copied, but storing into data structures counts // as a move unless the stored thing is used afterwards.
struct Box { x: r } #[unsafe_destructor] impl Drop for r { fn drop(&self) { unsafe { *(self.i) = *(self.i) + 1; } } } fn r(i: @mut int) -> r { r { i: i } } fn test_box() { let i = @mut 0; { let a = @r(i); } assert_eq!(*i, 1); } fn test_rec() { let i = @mut 0; { let a = Box {x: r(i)}; } assert_eq!(*i, 1); } fn test_tag() { enum t { t0(r), } let i = @mut 0; { let a = t0(r(i)); } assert_eq!(*i, 1); } fn test_tup() { let i = @mut 0; { let a = (r(i), 0); } assert_eq!(*i, 1); } fn test_unique() { let i = @mut 0; { let a = ~r(i); } assert_eq!(*i, 1); } fn test_box_rec() { let i = @mut 0; { let a = @Box { x: r(i) }; } assert_eq!(*i, 1); } pub fn main() { test_box(); test_rec(); test_tag(); test_tup(); test_unique(); test_box_rec(); }
struct r { i: @mut int, }
random_line_split
init-res-into-things.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. // Resources can't be copied, but storing into data structures counts // as a move unless the stored thing is used afterwards. struct r { i: @mut int, } struct Box { x: r } #[unsafe_destructor] impl Drop for r { fn drop(&self) { unsafe { *(self.i) = *(self.i) + 1; } } } fn r(i: @mut int) -> r { r { i: i } } fn test_box() { let i = @mut 0; { let a = @r(i); } assert_eq!(*i, 1); } fn test_rec() { let i = @mut 0; { let a = Box {x: r(i)}; } assert_eq!(*i, 1); } fn test_tag() { enum t { t0(r), } let i = @mut 0; { let a = t0(r(i)); } assert_eq!(*i, 1); } fn
() { let i = @mut 0; { let a = (r(i), 0); } assert_eq!(*i, 1); } fn test_unique() { let i = @mut 0; { let a = ~r(i); } assert_eq!(*i, 1); } fn test_box_rec() { let i = @mut 0; { let a = @Box { x: r(i) }; } assert_eq!(*i, 1); } pub fn main() { test_box(); test_rec(); test_tag(); test_tup(); test_unique(); test_box_rec(); }
test_tup
identifier_name
keyframes.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::{AtRuleParser, Parser, QualifiedRuleParser, RuleListParser}; use cssparser::{DeclarationListParser, DeclarationParser, parse_one_rule}; use parking_lot::RwLock; use parser::{ParserContext, ParserContextExtraData, log_css_error}; use properties::{Importance, PropertyDeclaration, PropertyDeclarationBlock}; use properties::PropertyDeclarationParseResult; use properties::animated_properties::TransitionProperty; use servo_url::ServoUrl; use std::fmt; use std::sync::Arc; use style_traits::ToCss; use stylesheets::{MemoryHoleReporter, Origin}; /// A number from 1 to 100, indicating the percentage of the animation where /// this keyframe should run. #[derive(Debug, Copy, Clone, PartialEq, PartialOrd)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct KeyframePercentage(pub f32); impl ::std::cmp::Ord for KeyframePercentage { #[inline] fn cmp(&self, other: &Self) -> ::std::cmp::Ordering { // We know we have a number from 0 to 1, so unwrap() here is safe. self.0.partial_cmp(&other.0).unwrap() } } impl ::std::cmp::Eq for KeyframePercentage { } impl KeyframePercentage { #[inline] pub fn new(value: f32) -> KeyframePercentage { debug_assert!(value >= 0. && value <= 1.); KeyframePercentage(value) } fn parse(input: &mut Parser) -> Result<KeyframePercentage, ()> { let percentage = if input.try(|input| input.expect_ident_matching("from")).is_ok() { KeyframePercentage::new(0.) } else if input.try(|input| input.expect_ident_matching("to")).is_ok() { KeyframePercentage::new(1.) } else { let percentage = try!(input.expect_percentage()); if percentage > 1. || percentage < 0. { return Err(()); } KeyframePercentage::new(percentage) }; Ok(percentage) } } /// A keyframes selector is a list of percentages or from/to symbols, which are /// converted at parse time to percentages. #[derive(Debug, Clone, PartialEq)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct KeyframeSelector(Vec<KeyframePercentage>); impl KeyframeSelector { #[inline] pub fn percentages(&self) -> &[KeyframePercentage] { &self.0 } /// A dummy public function so we can write a unit test for this. pub fn new_for_unit_testing(percentages: Vec<KeyframePercentage>) -> KeyframeSelector { KeyframeSelector(percentages) } pub fn parse(input: &mut Parser) -> Result<Self, ()> { input.parse_comma_separated(KeyframePercentage::parse) .map(KeyframeSelector) } } /// A keyframe. #[derive(Debug, Clone)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct
{ pub selector: KeyframeSelector, /// `!important` is not allowed in keyframe declarations, /// so the second value of these tuples is always `Importance::Normal`. /// But including them enables `compute_style_for_animation_step` to create a `ApplicableDeclarationBlock` /// by cloning an `Arc<_>` (incrementing a reference count) rather than re-creating a `Vec<_>`. #[cfg_attr(feature = "servo", ignore_heap_size_of = "Arc")] pub block: Arc<RwLock<PropertyDeclarationBlock>>, } impl ToCss for Keyframe { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { let mut iter = self.selector.percentages().iter(); try!(write!(dest, "{}%", iter.next().unwrap().0)); for percentage in iter { try!(write!(dest, ", ")); try!(write!(dest, "{}%", percentage.0)); } try!(dest.write_str(" { ")); try!(self.block.read().to_css(dest)); try!(dest.write_str(" }")); Ok(()) } } impl Keyframe { pub fn parse(css: &str, origin: Origin, base_url: ServoUrl, extra_data: ParserContextExtraData) -> Result<Arc<RwLock<Self>>, ()> { let error_reporter = Box::new(MemoryHoleReporter); let context = ParserContext::new_with_extra_data(origin, &base_url, error_reporter, extra_data); let mut input = Parser::new(css); let mut rule_parser = KeyframeListParser { context: &context, }; parse_one_rule(&mut input, &mut rule_parser) } } /// A keyframes step value. This can be a synthetised keyframes animation, that /// is, one autogenerated from the current computed values, or a list of /// declarations to apply. // TODO: Find a better name for this? #[derive(Debug, Clone)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub enum KeyframesStepValue { /// See `Keyframe::declarations`’s docs about the presence of `Importance`. Declarations { #[cfg_attr(feature = "servo", ignore_heap_size_of = "Arc")] block: Arc<RwLock<PropertyDeclarationBlock>> }, ComputedValues, } /// A single step from a keyframe animation. #[derive(Debug, Clone)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct KeyframesStep { /// The percentage of the animation duration when this step starts. pub start_percentage: KeyframePercentage, /// Declarations that will determine the final style during the step, or /// `ComputedValues` if this is an autogenerated step. pub value: KeyframesStepValue, /// Wether a animation-timing-function declaration exists in the list of /// declarations. /// /// This is used to know when to override the keyframe animation style. pub declared_timing_function: bool, } impl KeyframesStep { #[allow(unsafe_code)] #[inline] fn new(percentage: KeyframePercentage, value: KeyframesStepValue) -> Self { let declared_timing_function = match value { KeyframesStepValue::Declarations { ref block } => { block.read().declarations.iter().any(|&(ref prop_decl, _)| { match *prop_decl { PropertyDeclaration::AnimationTimingFunction(..) => true, _ => false, } }) } _ => false, }; KeyframesStep { start_percentage: percentage, value: value, declared_timing_function: declared_timing_function, } } } /// This structure represents a list of animation steps computed from the list /// of keyframes, in order. /// /// It only takes into account animable properties. #[derive(Debug, Clone)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct KeyframesAnimation { pub steps: Vec<KeyframesStep>, /// The properties that change in this animation. pub properties_changed: Vec<TransitionProperty>, } /// Get all the animated properties in a keyframes animation. Note that it's not /// defined what happens when a property is not on a keyframe, so we only peek /// the props of the first one. /// /// In practice, browsers seem to try to do their best job at it, so we might /// want to go through all the actual keyframes and deduplicate properties. #[allow(unsafe_code)] fn get_animated_properties(keyframe: &Keyframe) -> Vec<TransitionProperty> { let mut ret = vec![]; // NB: declarations are already deduplicated, so we don't have to check for // it here. for &(ref declaration, _) in keyframe.block.read().declarations.iter() { if let Some(property) = TransitionProperty::from_declaration(declaration) { ret.push(property); } } ret } impl KeyframesAnimation { pub fn from_keyframes(keyframes: &[Arc<RwLock<Keyframe>>]) -> Option<Self> { if keyframes.is_empty() { return None; } let animated_properties = get_animated_properties(&keyframes[0].read()); if animated_properties.is_empty() { return None; } let mut steps = vec![]; for keyframe in keyframes { let keyframe = keyframe.read(); for percentage in keyframe.selector.0.iter() { steps.push(KeyframesStep::new(*percentage, KeyframesStepValue::Declarations { block: keyframe.block.clone(), })); } } // Sort by the start percentage, so we can easily find a frame. steps.sort_by_key(|step| step.start_percentage); // Prepend autogenerated keyframes if appropriate. if steps[0].start_percentage.0!= 0. { steps.insert(0, KeyframesStep::new(KeyframePercentage::new(0.), KeyframesStepValue::ComputedValues)); } if steps.last().unwrap().start_percentage.0!= 1. { steps.push(KeyframesStep::new(KeyframePercentage::new(0.), KeyframesStepValue::ComputedValues)); } Some(KeyframesAnimation { steps: steps, properties_changed: animated_properties, }) } } /// Parses a keyframes list, like: /// 0%, 50% { /// width: 50%; /// } /// /// 40%, 60%, 100% { /// width: 100%; /// } struct KeyframeListParser<'a> { context: &'a ParserContext<'a>, } pub fn parse_keyframe_list(context: &ParserContext, input: &mut Parser) -> Vec<Arc<RwLock<Keyframe>>> { RuleListParser::new_for_nested_rule(input, KeyframeListParser { context: context }) .filter_map(Result::ok) .collect() } enum Void {} impl<'a> AtRuleParser for KeyframeListParser<'a> { type Prelude = Void; type AtRule = Arc<RwLock<Keyframe>>; } impl<'a> QualifiedRuleParser for KeyframeListParser<'a> { type Prelude = KeyframeSelector; type QualifiedRule = Arc<RwLock<Keyframe>>; fn parse_prelude(&mut self, input: &mut Parser) -> Result<Self::Prelude, ()> { let start = input.position(); match KeyframeSelector::parse(input) { Ok(sel) => Ok(sel), Err(()) => { let message = format!("Invalid keyframe rule: '{}'", input.slice_from(start)); log_css_error(input, start, &message, self.context); Err(()) } } } fn parse_block(&mut self, prelude: Self::Prelude, input: &mut Parser) -> Result<Self::QualifiedRule, ()> { let mut declarations = Vec::new(); let parser = KeyframeDeclarationParser { context: self.context, }; let mut iter = DeclarationListParser::new(input, parser); while let Some(declaration) = iter.next() { match declaration { Ok(d) => declarations.extend(d.into_iter().map(|d| (d, Importance::Normal))), Err(range) => { let pos = range.start; let message = format!("Unsupported keyframe property declaration: '{}'", iter.input.slice(range)); log_css_error(iter.input, pos, &*message, self.context); } } // `parse_important` is not called here, `!important` is not allowed in keyframe blocks. } Ok(Arc::new(RwLock::new(Keyframe { selector: prelude, block: Arc::new(RwLock::new(PropertyDeclarationBlock { declarations: declarations, important_count: 0, })), }))) } } struct KeyframeDeclarationParser<'a, 'b: 'a> { context: &'a ParserContext<'b>, } /// Default methods reject all at rules. impl<'a, 'b> AtRuleParser for KeyframeDeclarationParser<'a, 'b> { type Prelude = (); type AtRule = Vec<PropertyDeclaration>; } impl<'a, 'b> DeclarationParser for KeyframeDeclarationParser<'a, 'b> { type Declaration = Vec<PropertyDeclaration>; fn parse_value(&mut self, name: &str, input: &mut Parser) -> Result<Vec<PropertyDeclaration>, ()> { let mut results = Vec::new(); match PropertyDeclaration::parse(name, self.context, input, &mut results, true) { PropertyDeclarationParseResult::ValidOrIgnoredDeclaration => {} _ => return Err(()) } Ok(results) } }
Keyframe
identifier_name
keyframes.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::{AtRuleParser, Parser, QualifiedRuleParser, RuleListParser}; use cssparser::{DeclarationListParser, DeclarationParser, parse_one_rule}; use parking_lot::RwLock; use parser::{ParserContext, ParserContextExtraData, log_css_error}; use properties::{Importance, PropertyDeclaration, PropertyDeclarationBlock}; use properties::PropertyDeclarationParseResult; use properties::animated_properties::TransitionProperty; use servo_url::ServoUrl; use std::fmt; use std::sync::Arc; use style_traits::ToCss; use stylesheets::{MemoryHoleReporter, Origin}; /// A number from 1 to 100, indicating the percentage of the animation where /// this keyframe should run. #[derive(Debug, Copy, Clone, PartialEq, PartialOrd)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct KeyframePercentage(pub f32); impl ::std::cmp::Ord for KeyframePercentage { #[inline] fn cmp(&self, other: &Self) -> ::std::cmp::Ordering { // We know we have a number from 0 to 1, so unwrap() here is safe. self.0.partial_cmp(&other.0).unwrap() } } impl ::std::cmp::Eq for KeyframePercentage { } impl KeyframePercentage { #[inline] pub fn new(value: f32) -> KeyframePercentage { debug_assert!(value >= 0. && value <= 1.); KeyframePercentage(value) } fn parse(input: &mut Parser) -> Result<KeyframePercentage, ()> { let percentage = if input.try(|input| input.expect_ident_matching("from")).is_ok() { KeyframePercentage::new(0.) } else if input.try(|input| input.expect_ident_matching("to")).is_ok() { KeyframePercentage::new(1.) } else { let percentage = try!(input.expect_percentage()); if percentage > 1. || percentage < 0. { return Err(()); } KeyframePercentage::new(percentage) }; Ok(percentage) } } /// A keyframes selector is a list of percentages or from/to symbols, which are /// converted at parse time to percentages. #[derive(Debug, Clone, PartialEq)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct KeyframeSelector(Vec<KeyframePercentage>); impl KeyframeSelector { #[inline] pub fn percentages(&self) -> &[KeyframePercentage] { &self.0 } /// A dummy public function so we can write a unit test for this. pub fn new_for_unit_testing(percentages: Vec<KeyframePercentage>) -> KeyframeSelector { KeyframeSelector(percentages) } pub fn parse(input: &mut Parser) -> Result<Self, ()> { input.parse_comma_separated(KeyframePercentage::parse) .map(KeyframeSelector) } } /// A keyframe. #[derive(Debug, Clone)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct Keyframe { pub selector: KeyframeSelector, /// `!important` is not allowed in keyframe declarations, /// so the second value of these tuples is always `Importance::Normal`. /// But including them enables `compute_style_for_animation_step` to create a `ApplicableDeclarationBlock` /// by cloning an `Arc<_>` (incrementing a reference count) rather than re-creating a `Vec<_>`. #[cfg_attr(feature = "servo", ignore_heap_size_of = "Arc")] pub block: Arc<RwLock<PropertyDeclarationBlock>>, } impl ToCss for Keyframe { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { let mut iter = self.selector.percentages().iter(); try!(write!(dest, "{}%", iter.next().unwrap().0)); for percentage in iter { try!(write!(dest, ", ")); try!(write!(dest, "{}%", percentage.0)); } try!(dest.write_str(" { ")); try!(self.block.read().to_css(dest)); try!(dest.write_str(" }")); Ok(()) } } impl Keyframe { pub fn parse(css: &str, origin: Origin, base_url: ServoUrl, extra_data: ParserContextExtraData) -> Result<Arc<RwLock<Self>>, ()> { let error_reporter = Box::new(MemoryHoleReporter); let context = ParserContext::new_with_extra_data(origin, &base_url, error_reporter, extra_data); let mut input = Parser::new(css); let mut rule_parser = KeyframeListParser { context: &context, }; parse_one_rule(&mut input, &mut rule_parser) } } /// A keyframes step value. This can be a synthetised keyframes animation, that /// is, one autogenerated from the current computed values, or a list of /// declarations to apply. // TODO: Find a better name for this? #[derive(Debug, Clone)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub enum KeyframesStepValue { /// See `Keyframe::declarations`’s docs about the presence of `Importance`. Declarations { #[cfg_attr(feature = "servo", ignore_heap_size_of = "Arc")] block: Arc<RwLock<PropertyDeclarationBlock>> }, ComputedValues, } /// A single step from a keyframe animation. #[derive(Debug, Clone)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct KeyframesStep { /// The percentage of the animation duration when this step starts. pub start_percentage: KeyframePercentage, /// Declarations that will determine the final style during the step, or /// `ComputedValues` if this is an autogenerated step. pub value: KeyframesStepValue, /// Wether a animation-timing-function declaration exists in the list of /// declarations. /// /// This is used to know when to override the keyframe animation style. pub declared_timing_function: bool, } impl KeyframesStep { #[allow(unsafe_code)] #[inline] fn new(percentage: KeyframePercentage, value: KeyframesStepValue) -> Self { let declared_timing_function = match value { KeyframesStepValue::Declarations { ref block } => { block.read().declarations.iter().any(|&(ref prop_decl, _)| { match *prop_decl { PropertyDeclaration::AnimationTimingFunction(..) => true, _ => false, } }) } _ => false, }; KeyframesStep { start_percentage: percentage, value: value, declared_timing_function: declared_timing_function, } } } /// This structure represents a list of animation steps computed from the list /// of keyframes, in order. /// /// It only takes into account animable properties. #[derive(Debug, Clone)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct KeyframesAnimation { pub steps: Vec<KeyframesStep>, /// The properties that change in this animation. pub properties_changed: Vec<TransitionProperty>, } /// Get all the animated properties in a keyframes animation. Note that it's not /// defined what happens when a property is not on a keyframe, so we only peek /// the props of the first one. /// /// In practice, browsers seem to try to do their best job at it, so we might /// want to go through all the actual keyframes and deduplicate properties. #[allow(unsafe_code)] fn get_animated_properties(keyframe: &Keyframe) -> Vec<TransitionProperty> { let mut ret = vec![]; // NB: declarations are already deduplicated, so we don't have to check for // it here. for &(ref declaration, _) in keyframe.block.read().declarations.iter() { if let Some(property) = TransitionProperty::from_declaration(declaration) { ret.push(property); } } ret } impl KeyframesAnimation { pub fn from_keyframes(keyframes: &[Arc<RwLock<Keyframe>>]) -> Option<Self> { if keyframes.is_empty() { return None; } let animated_properties = get_animated_properties(&keyframes[0].read()); if animated_properties.is_empty() { return None; } let mut steps = vec![]; for keyframe in keyframes { let keyframe = keyframe.read(); for percentage in keyframe.selector.0.iter() { steps.push(KeyframesStep::new(*percentage, KeyframesStepValue::Declarations { block: keyframe.block.clone(), })); } } // Sort by the start percentage, so we can easily find a frame. steps.sort_by_key(|step| step.start_percentage); // Prepend autogenerated keyframes if appropriate. if steps[0].start_percentage.0!= 0. { steps.insert(0, KeyframesStep::new(KeyframePercentage::new(0.), KeyframesStepValue::ComputedValues)); } if steps.last().unwrap().start_percentage.0!= 1. { steps.push(KeyframesStep::new(KeyframePercentage::new(0.), KeyframesStepValue::ComputedValues)); } Some(KeyframesAnimation { steps: steps, properties_changed: animated_properties, }) } } /// Parses a keyframes list, like: /// 0%, 50% { /// width: 50%; /// } /// /// 40%, 60%, 100% { /// width: 100%; /// } struct KeyframeListParser<'a> { context: &'a ParserContext<'a>, } pub fn parse_keyframe_list(context: &ParserContext, input: &mut Parser) -> Vec<Arc<RwLock<Keyframe>>> { RuleListParser::new_for_nested_rule(input, KeyframeListParser { context: context }) .filter_map(Result::ok) .collect() } enum Void {} impl<'a> AtRuleParser for KeyframeListParser<'a> { type Prelude = Void; type AtRule = Arc<RwLock<Keyframe>>; } impl<'a> QualifiedRuleParser for KeyframeListParser<'a> { type Prelude = KeyframeSelector; type QualifiedRule = Arc<RwLock<Keyframe>>; fn parse_prelude(&mut self, input: &mut Parser) -> Result<Self::Prelude, ()> { let start = input.position(); match KeyframeSelector::parse(input) { Ok(sel) => Ok(sel), Err(()) => { let message = format!("Invalid keyframe rule: '{}'", input.slice_from(start)); log_css_error(input, start, &message, self.context); Err(()) } } } fn parse_block(&mut self, prelude: Self::Prelude, input: &mut Parser) -> Result<Self::QualifiedRule, ()> { let mut declarations = Vec::new(); let parser = KeyframeDeclarationParser { context: self.context, }; let mut iter = DeclarationListParser::new(input, parser); while let Some(declaration) = iter.next() { match declaration { Ok(d) => declarations.extend(d.into_iter().map(|d| (d, Importance::Normal))), Err(range) => { let pos = range.start; let message = format!("Unsupported keyframe property declaration: '{}'", iter.input.slice(range)); log_css_error(iter.input, pos, &*message, self.context); } } // `parse_important` is not called here, `!important` is not allowed in keyframe blocks. } Ok(Arc::new(RwLock::new(Keyframe { selector: prelude, block: Arc::new(RwLock::new(PropertyDeclarationBlock { declarations: declarations, important_count: 0, })), }))) } } struct KeyframeDeclarationParser<'a, 'b: 'a> { context: &'a ParserContext<'b>, } /// Default methods reject all at rules. impl<'a, 'b> AtRuleParser for KeyframeDeclarationParser<'a, 'b> { type Prelude = (); type AtRule = Vec<PropertyDeclaration>; } impl<'a, 'b> DeclarationParser for KeyframeDeclarationParser<'a, 'b> { type Declaration = Vec<PropertyDeclaration>; fn parse_value(&mut self, name: &str, input: &mut Parser) -> Result<Vec<PropertyDeclaration>, ()> {
let mut results = Vec::new(); match PropertyDeclaration::parse(name, self.context, input, &mut results, true) { PropertyDeclarationParseResult::ValidOrIgnoredDeclaration => {} _ => return Err(()) } Ok(results) } }
identifier_body
keyframes.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::{AtRuleParser, Parser, QualifiedRuleParser, RuleListParser}; use cssparser::{DeclarationListParser, DeclarationParser, parse_one_rule}; use parking_lot::RwLock; use parser::{ParserContext, ParserContextExtraData, log_css_error}; use properties::{Importance, PropertyDeclaration, PropertyDeclarationBlock}; use properties::PropertyDeclarationParseResult; use properties::animated_properties::TransitionProperty; use servo_url::ServoUrl; use std::fmt; use std::sync::Arc; use style_traits::ToCss; use stylesheets::{MemoryHoleReporter, Origin}; /// A number from 1 to 100, indicating the percentage of the animation where /// this keyframe should run. #[derive(Debug, Copy, Clone, PartialEq, PartialOrd)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct KeyframePercentage(pub f32); impl ::std::cmp::Ord for KeyframePercentage { #[inline] fn cmp(&self, other: &Self) -> ::std::cmp::Ordering { // We know we have a number from 0 to 1, so unwrap() here is safe. self.0.partial_cmp(&other.0).unwrap() } } impl ::std::cmp::Eq for KeyframePercentage { } impl KeyframePercentage { #[inline] pub fn new(value: f32) -> KeyframePercentage { debug_assert!(value >= 0. && value <= 1.); KeyframePercentage(value) } fn parse(input: &mut Parser) -> Result<KeyframePercentage, ()> { let percentage = if input.try(|input| input.expect_ident_matching("from")).is_ok() { KeyframePercentage::new(0.) } else if input.try(|input| input.expect_ident_matching("to")).is_ok() { KeyframePercentage::new(1.) } else { let percentage = try!(input.expect_percentage()); if percentage > 1. || percentage < 0. { return Err(()); } KeyframePercentage::new(percentage) }; Ok(percentage) } } /// A keyframes selector is a list of percentages or from/to symbols, which are /// converted at parse time to percentages. #[derive(Debug, Clone, PartialEq)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct KeyframeSelector(Vec<KeyframePercentage>); impl KeyframeSelector { #[inline] pub fn percentages(&self) -> &[KeyframePercentage] { &self.0 } /// A dummy public function so we can write a unit test for this. pub fn new_for_unit_testing(percentages: Vec<KeyframePercentage>) -> KeyframeSelector { KeyframeSelector(percentages) } pub fn parse(input: &mut Parser) -> Result<Self, ()> { input.parse_comma_separated(KeyframePercentage::parse) .map(KeyframeSelector) } } /// A keyframe. #[derive(Debug, Clone)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct Keyframe { pub selector: KeyframeSelector, /// `!important` is not allowed in keyframe declarations, /// so the second value of these tuples is always `Importance::Normal`. /// But including them enables `compute_style_for_animation_step` to create a `ApplicableDeclarationBlock` /// by cloning an `Arc<_>` (incrementing a reference count) rather than re-creating a `Vec<_>`. #[cfg_attr(feature = "servo", ignore_heap_size_of = "Arc")] pub block: Arc<RwLock<PropertyDeclarationBlock>>, } impl ToCss for Keyframe { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { let mut iter = self.selector.percentages().iter(); try!(write!(dest, "{}%", iter.next().unwrap().0)); for percentage in iter { try!(write!(dest, ", ")); try!(write!(dest, "{}%", percentage.0)); } try!(dest.write_str(" { ")); try!(self.block.read().to_css(dest)); try!(dest.write_str(" }")); Ok(()) } } impl Keyframe { pub fn parse(css: &str, origin: Origin, base_url: ServoUrl, extra_data: ParserContextExtraData) -> Result<Arc<RwLock<Self>>, ()> { let error_reporter = Box::new(MemoryHoleReporter); let context = ParserContext::new_with_extra_data(origin, &base_url, error_reporter, extra_data); let mut input = Parser::new(css); let mut rule_parser = KeyframeListParser { context: &context, }; parse_one_rule(&mut input, &mut rule_parser) } } /// A keyframes step value. This can be a synthetised keyframes animation, that /// is, one autogenerated from the current computed values, or a list of /// declarations to apply. // TODO: Find a better name for this? #[derive(Debug, Clone)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub enum KeyframesStepValue { /// See `Keyframe::declarations`’s docs about the presence of `Importance`. Declarations { #[cfg_attr(feature = "servo", ignore_heap_size_of = "Arc")] block: Arc<RwLock<PropertyDeclarationBlock>> }, ComputedValues, } /// A single step from a keyframe animation. #[derive(Debug, Clone)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct KeyframesStep { /// The percentage of the animation duration when this step starts. pub start_percentage: KeyframePercentage, /// Declarations that will determine the final style during the step, or /// `ComputedValues` if this is an autogenerated step. pub value: KeyframesStepValue, /// Wether a animation-timing-function declaration exists in the list of /// declarations. /// /// This is used to know when to override the keyframe animation style. pub declared_timing_function: bool, } impl KeyframesStep { #[allow(unsafe_code)] #[inline] fn new(percentage: KeyframePercentage, value: KeyframesStepValue) -> Self { let declared_timing_function = match value { KeyframesStepValue::Declarations { ref block } => {
_ => false, }; KeyframesStep { start_percentage: percentage, value: value, declared_timing_function: declared_timing_function, } } } /// This structure represents a list of animation steps computed from the list /// of keyframes, in order. /// /// It only takes into account animable properties. #[derive(Debug, Clone)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct KeyframesAnimation { pub steps: Vec<KeyframesStep>, /// The properties that change in this animation. pub properties_changed: Vec<TransitionProperty>, } /// Get all the animated properties in a keyframes animation. Note that it's not /// defined what happens when a property is not on a keyframe, so we only peek /// the props of the first one. /// /// In practice, browsers seem to try to do their best job at it, so we might /// want to go through all the actual keyframes and deduplicate properties. #[allow(unsafe_code)] fn get_animated_properties(keyframe: &Keyframe) -> Vec<TransitionProperty> { let mut ret = vec![]; // NB: declarations are already deduplicated, so we don't have to check for // it here. for &(ref declaration, _) in keyframe.block.read().declarations.iter() { if let Some(property) = TransitionProperty::from_declaration(declaration) { ret.push(property); } } ret } impl KeyframesAnimation { pub fn from_keyframes(keyframes: &[Arc<RwLock<Keyframe>>]) -> Option<Self> { if keyframes.is_empty() { return None; } let animated_properties = get_animated_properties(&keyframes[0].read()); if animated_properties.is_empty() { return None; } let mut steps = vec![]; for keyframe in keyframes { let keyframe = keyframe.read(); for percentage in keyframe.selector.0.iter() { steps.push(KeyframesStep::new(*percentage, KeyframesStepValue::Declarations { block: keyframe.block.clone(), })); } } // Sort by the start percentage, so we can easily find a frame. steps.sort_by_key(|step| step.start_percentage); // Prepend autogenerated keyframes if appropriate. if steps[0].start_percentage.0!= 0. { steps.insert(0, KeyframesStep::new(KeyframePercentage::new(0.), KeyframesStepValue::ComputedValues)); } if steps.last().unwrap().start_percentage.0!= 1. { steps.push(KeyframesStep::new(KeyframePercentage::new(0.), KeyframesStepValue::ComputedValues)); } Some(KeyframesAnimation { steps: steps, properties_changed: animated_properties, }) } } /// Parses a keyframes list, like: /// 0%, 50% { /// width: 50%; /// } /// /// 40%, 60%, 100% { /// width: 100%; /// } struct KeyframeListParser<'a> { context: &'a ParserContext<'a>, } pub fn parse_keyframe_list(context: &ParserContext, input: &mut Parser) -> Vec<Arc<RwLock<Keyframe>>> { RuleListParser::new_for_nested_rule(input, KeyframeListParser { context: context }) .filter_map(Result::ok) .collect() } enum Void {} impl<'a> AtRuleParser for KeyframeListParser<'a> { type Prelude = Void; type AtRule = Arc<RwLock<Keyframe>>; } impl<'a> QualifiedRuleParser for KeyframeListParser<'a> { type Prelude = KeyframeSelector; type QualifiedRule = Arc<RwLock<Keyframe>>; fn parse_prelude(&mut self, input: &mut Parser) -> Result<Self::Prelude, ()> { let start = input.position(); match KeyframeSelector::parse(input) { Ok(sel) => Ok(sel), Err(()) => { let message = format!("Invalid keyframe rule: '{}'", input.slice_from(start)); log_css_error(input, start, &message, self.context); Err(()) } } } fn parse_block(&mut self, prelude: Self::Prelude, input: &mut Parser) -> Result<Self::QualifiedRule, ()> { let mut declarations = Vec::new(); let parser = KeyframeDeclarationParser { context: self.context, }; let mut iter = DeclarationListParser::new(input, parser); while let Some(declaration) = iter.next() { match declaration { Ok(d) => declarations.extend(d.into_iter().map(|d| (d, Importance::Normal))), Err(range) => { let pos = range.start; let message = format!("Unsupported keyframe property declaration: '{}'", iter.input.slice(range)); log_css_error(iter.input, pos, &*message, self.context); } } // `parse_important` is not called here, `!important` is not allowed in keyframe blocks. } Ok(Arc::new(RwLock::new(Keyframe { selector: prelude, block: Arc::new(RwLock::new(PropertyDeclarationBlock { declarations: declarations, important_count: 0, })), }))) } } struct KeyframeDeclarationParser<'a, 'b: 'a> { context: &'a ParserContext<'b>, } /// Default methods reject all at rules. impl<'a, 'b> AtRuleParser for KeyframeDeclarationParser<'a, 'b> { type Prelude = (); type AtRule = Vec<PropertyDeclaration>; } impl<'a, 'b> DeclarationParser for KeyframeDeclarationParser<'a, 'b> { type Declaration = Vec<PropertyDeclaration>; fn parse_value(&mut self, name: &str, input: &mut Parser) -> Result<Vec<PropertyDeclaration>, ()> { let mut results = Vec::new(); match PropertyDeclaration::parse(name, self.context, input, &mut results, true) { PropertyDeclarationParseResult::ValidOrIgnoredDeclaration => {} _ => return Err(()) } Ok(results) } }
block.read().declarations.iter().any(|&(ref prop_decl, _)| { match *prop_decl { PropertyDeclaration::AnimationTimingFunction(..) => true, _ => false, } }) }
conditional_block
keyframes.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::{AtRuleParser, Parser, QualifiedRuleParser, RuleListParser}; use cssparser::{DeclarationListParser, DeclarationParser, parse_one_rule}; use parking_lot::RwLock; use parser::{ParserContext, ParserContextExtraData, log_css_error}; use properties::{Importance, PropertyDeclaration, PropertyDeclarationBlock}; use properties::PropertyDeclarationParseResult; use properties::animated_properties::TransitionProperty; use servo_url::ServoUrl; use std::fmt; use std::sync::Arc; use style_traits::ToCss; use stylesheets::{MemoryHoleReporter, Origin}; /// A number from 1 to 100, indicating the percentage of the animation where /// this keyframe should run. #[derive(Debug, Copy, Clone, PartialEq, PartialOrd)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct KeyframePercentage(pub f32); impl ::std::cmp::Ord for KeyframePercentage { #[inline] fn cmp(&self, other: &Self) -> ::std::cmp::Ordering { // We know we have a number from 0 to 1, so unwrap() here is safe. self.0.partial_cmp(&other.0).unwrap() } } impl ::std::cmp::Eq for KeyframePercentage { } impl KeyframePercentage { #[inline] pub fn new(value: f32) -> KeyframePercentage { debug_assert!(value >= 0. && value <= 1.); KeyframePercentage(value) } fn parse(input: &mut Parser) -> Result<KeyframePercentage, ()> { let percentage = if input.try(|input| input.expect_ident_matching("from")).is_ok() { KeyframePercentage::new(0.) } else if input.try(|input| input.expect_ident_matching("to")).is_ok() { KeyframePercentage::new(1.) } else { let percentage = try!(input.expect_percentage()); if percentage > 1. || percentage < 0. { return Err(()); } KeyframePercentage::new(percentage) }; Ok(percentage) } } /// A keyframes selector is a list of percentages or from/to symbols, which are /// converted at parse time to percentages. #[derive(Debug, Clone, PartialEq)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct KeyframeSelector(Vec<KeyframePercentage>); impl KeyframeSelector { #[inline] pub fn percentages(&self) -> &[KeyframePercentage] { &self.0 } /// A dummy public function so we can write a unit test for this. pub fn new_for_unit_testing(percentages: Vec<KeyframePercentage>) -> KeyframeSelector { KeyframeSelector(percentages) } pub fn parse(input: &mut Parser) -> Result<Self, ()> { input.parse_comma_separated(KeyframePercentage::parse) .map(KeyframeSelector) } } /// A keyframe. #[derive(Debug, Clone)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct Keyframe { pub selector: KeyframeSelector, /// `!important` is not allowed in keyframe declarations, /// so the second value of these tuples is always `Importance::Normal`. /// But including them enables `compute_style_for_animation_step` to create a `ApplicableDeclarationBlock` /// by cloning an `Arc<_>` (incrementing a reference count) rather than re-creating a `Vec<_>`. #[cfg_attr(feature = "servo", ignore_heap_size_of = "Arc")] pub block: Arc<RwLock<PropertyDeclarationBlock>>, } impl ToCss for Keyframe { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { let mut iter = self.selector.percentages().iter(); try!(write!(dest, "{}%", iter.next().unwrap().0)); for percentage in iter { try!(write!(dest, ", ")); try!(write!(dest, "{}%", percentage.0)); } try!(dest.write_str(" { ")); try!(self.block.read().to_css(dest)); try!(dest.write_str(" }")); Ok(()) } } impl Keyframe { pub fn parse(css: &str, origin: Origin, base_url: ServoUrl, extra_data: ParserContextExtraData) -> Result<Arc<RwLock<Self>>, ()> { let error_reporter = Box::new(MemoryHoleReporter); let context = ParserContext::new_with_extra_data(origin, &base_url, error_reporter, extra_data); let mut input = Parser::new(css); let mut rule_parser = KeyframeListParser { context: &context, }; parse_one_rule(&mut input, &mut rule_parser) } } /// A keyframes step value. This can be a synthetised keyframes animation, that /// is, one autogenerated from the current computed values, or a list of /// declarations to apply. // TODO: Find a better name for this? #[derive(Debug, Clone)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub enum KeyframesStepValue { /// See `Keyframe::declarations`’s docs about the presence of `Importance`. Declarations { #[cfg_attr(feature = "servo", ignore_heap_size_of = "Arc")] block: Arc<RwLock<PropertyDeclarationBlock>> }, ComputedValues, } /// A single step from a keyframe animation. #[derive(Debug, Clone)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct KeyframesStep { /// The percentage of the animation duration when this step starts. pub start_percentage: KeyframePercentage, /// Declarations that will determine the final style during the step, or /// `ComputedValues` if this is an autogenerated step. pub value: KeyframesStepValue, /// Wether a animation-timing-function declaration exists in the list of /// declarations. /// /// This is used to know when to override the keyframe animation style. pub declared_timing_function: bool, } impl KeyframesStep { #[allow(unsafe_code)] #[inline] fn new(percentage: KeyframePercentage, value: KeyframesStepValue) -> Self { let declared_timing_function = match value { KeyframesStepValue::Declarations { ref block } => { block.read().declarations.iter().any(|&(ref prop_decl, _)| { match *prop_decl { PropertyDeclaration::AnimationTimingFunction(..) => true, _ => false, } }) } _ => false, }; KeyframesStep { start_percentage: percentage, value: value, declared_timing_function: declared_timing_function, } } } /// This structure represents a list of animation steps computed from the list /// of keyframes, in order. /// /// It only takes into account animable properties. #[derive(Debug, Clone)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct KeyframesAnimation { pub steps: Vec<KeyframesStep>, /// The properties that change in this animation. pub properties_changed: Vec<TransitionProperty>, } /// Get all the animated properties in a keyframes animation. Note that it's not /// defined what happens when a property is not on a keyframe, so we only peek /// the props of the first one. /// /// In practice, browsers seem to try to do their best job at it, so we might /// want to go through all the actual keyframes and deduplicate properties. #[allow(unsafe_code)] fn get_animated_properties(keyframe: &Keyframe) -> Vec<TransitionProperty> { let mut ret = vec![]; // NB: declarations are already deduplicated, so we don't have to check for // it here. for &(ref declaration, _) in keyframe.block.read().declarations.iter() { if let Some(property) = TransitionProperty::from_declaration(declaration) { ret.push(property); } } ret } impl KeyframesAnimation { pub fn from_keyframes(keyframes: &[Arc<RwLock<Keyframe>>]) -> Option<Self> { if keyframes.is_empty() { return None; } let animated_properties = get_animated_properties(&keyframes[0].read()); if animated_properties.is_empty() { return None; } let mut steps = vec![]; for keyframe in keyframes { let keyframe = keyframe.read(); for percentage in keyframe.selector.0.iter() { steps.push(KeyframesStep::new(*percentage, KeyframesStepValue::Declarations { block: keyframe.block.clone(), })); } } // Sort by the start percentage, so we can easily find a frame. steps.sort_by_key(|step| step.start_percentage); // Prepend autogenerated keyframes if appropriate. if steps[0].start_percentage.0!= 0. { steps.insert(0, KeyframesStep::new(KeyframePercentage::new(0.), KeyframesStepValue::ComputedValues)); }
Some(KeyframesAnimation { steps: steps, properties_changed: animated_properties, }) } } /// Parses a keyframes list, like: /// 0%, 50% { /// width: 50%; /// } /// /// 40%, 60%, 100% { /// width: 100%; /// } struct KeyframeListParser<'a> { context: &'a ParserContext<'a>, } pub fn parse_keyframe_list(context: &ParserContext, input: &mut Parser) -> Vec<Arc<RwLock<Keyframe>>> { RuleListParser::new_for_nested_rule(input, KeyframeListParser { context: context }) .filter_map(Result::ok) .collect() } enum Void {} impl<'a> AtRuleParser for KeyframeListParser<'a> { type Prelude = Void; type AtRule = Arc<RwLock<Keyframe>>; } impl<'a> QualifiedRuleParser for KeyframeListParser<'a> { type Prelude = KeyframeSelector; type QualifiedRule = Arc<RwLock<Keyframe>>; fn parse_prelude(&mut self, input: &mut Parser) -> Result<Self::Prelude, ()> { let start = input.position(); match KeyframeSelector::parse(input) { Ok(sel) => Ok(sel), Err(()) => { let message = format!("Invalid keyframe rule: '{}'", input.slice_from(start)); log_css_error(input, start, &message, self.context); Err(()) } } } fn parse_block(&mut self, prelude: Self::Prelude, input: &mut Parser) -> Result<Self::QualifiedRule, ()> { let mut declarations = Vec::new(); let parser = KeyframeDeclarationParser { context: self.context, }; let mut iter = DeclarationListParser::new(input, parser); while let Some(declaration) = iter.next() { match declaration { Ok(d) => declarations.extend(d.into_iter().map(|d| (d, Importance::Normal))), Err(range) => { let pos = range.start; let message = format!("Unsupported keyframe property declaration: '{}'", iter.input.slice(range)); log_css_error(iter.input, pos, &*message, self.context); } } // `parse_important` is not called here, `!important` is not allowed in keyframe blocks. } Ok(Arc::new(RwLock::new(Keyframe { selector: prelude, block: Arc::new(RwLock::new(PropertyDeclarationBlock { declarations: declarations, important_count: 0, })), }))) } } struct KeyframeDeclarationParser<'a, 'b: 'a> { context: &'a ParserContext<'b>, } /// Default methods reject all at rules. impl<'a, 'b> AtRuleParser for KeyframeDeclarationParser<'a, 'b> { type Prelude = (); type AtRule = Vec<PropertyDeclaration>; } impl<'a, 'b> DeclarationParser for KeyframeDeclarationParser<'a, 'b> { type Declaration = Vec<PropertyDeclaration>; fn parse_value(&mut self, name: &str, input: &mut Parser) -> Result<Vec<PropertyDeclaration>, ()> { let mut results = Vec::new(); match PropertyDeclaration::parse(name, self.context, input, &mut results, true) { PropertyDeclarationParseResult::ValidOrIgnoredDeclaration => {} _ => return Err(()) } Ok(results) } }
if steps.last().unwrap().start_percentage.0 != 1. { steps.push(KeyframesStep::new(KeyframePercentage::new(0.), KeyframesStepValue::ComputedValues)); }
random_line_split
p074.rs
//! [Problem 74](https://projecteuler.net/problem=74) solver. #![warn( bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results )] use std::collections::HashMap; #[derive(Clone)] enum Length { Loop(usize), Chain(usize), Unknown, } fn fact_sum(mut n: u32, fs: &[u32; 10]) -> u32 { if n == 0 { return 1; } let mut sum = 0; while n > 0 { sum += fs[(n % 10) as usize]; n /= 10; } sum } fn get_chain_len(n: u32, map: &mut [Length], fs: &[u32; 10]) -> usize { let mut chain_map = HashMap::new(); let mut idx = n; let mut chain_len = 0; let mut loop_len = 0; loop { match map[idx as usize] { Length::Loop(c) => { loop_len += c; break; } Length::Chain(c) => { chain_len += c; break; } Length::Unknown => match chain_map.get(&idx) { Some(&chain_idx) => { loop_len = chain_len - chain_idx; chain_len = chain_idx; break; } None => { let _ = chain_map.insert(idx, chain_len); idx = fact_sum(idx, fs); chain_len += 1; } }, } } for (&key, &idx) in &chain_map { if idx >= chain_len { map[key as usize] = Length::Loop(loop_len); } else { map[key as usize] = Length::Chain(loop_len + chain_len - idx); } } chain_len + loop_len } fn solve() -> String { let limit = 1000000; let factorial = { let mut val = [1; 10]; for i in 1..10 { val[i] = val[i - 1] * (i as u32); } val }; let mut map = vec![Length::Unknown; (factorial[9] * 6 + 1) as usize]; let mut cnt = 0; for n in 1..(limit + 1) { let len = get_chain_len(n, &mut map, &factorial); if len == 60 { cnt += 1; } } cnt.to_string() } common::problem!("402", solve); #[cfg(test)] mod tests { use std::iter; #[test] fn
() { let factorial = { let mut val = [1; 10]; for i in 1..10 { val[i] = val[i - 1] * (i as u32); } val }; let mut map = iter::repeat(super::Length::Unknown) .take((factorial[9] * 6 + 1) as usize) .collect::<Vec<_>>(); assert_eq!(3, super::get_chain_len(169, &mut map, &factorial)); assert_eq!(2, super::get_chain_len(871, &mut map, &factorial)); assert_eq!(2, super::get_chain_len(872, &mut map, &factorial)); assert_eq!(5, super::get_chain_len(69, &mut map, &factorial)); assert_eq!(4, super::get_chain_len(78, &mut map, &factorial)); assert_eq!(2, super::get_chain_len(540, &mut map, &factorial)); } }
len
identifier_name
p074.rs
//! [Problem 74](https://projecteuler.net/problem=74) solver. #![warn( bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results )] use std::collections::HashMap; #[derive(Clone)] enum Length { Loop(usize), Chain(usize), Unknown,
fn fact_sum(mut n: u32, fs: &[u32; 10]) -> u32 { if n == 0 { return 1; } let mut sum = 0; while n > 0 { sum += fs[(n % 10) as usize]; n /= 10; } sum } fn get_chain_len(n: u32, map: &mut [Length], fs: &[u32; 10]) -> usize { let mut chain_map = HashMap::new(); let mut idx = n; let mut chain_len = 0; let mut loop_len = 0; loop { match map[idx as usize] { Length::Loop(c) => { loop_len += c; break; } Length::Chain(c) => { chain_len += c; break; } Length::Unknown => match chain_map.get(&idx) { Some(&chain_idx) => { loop_len = chain_len - chain_idx; chain_len = chain_idx; break; } None => { let _ = chain_map.insert(idx, chain_len); idx = fact_sum(idx, fs); chain_len += 1; } }, } } for (&key, &idx) in &chain_map { if idx >= chain_len { map[key as usize] = Length::Loop(loop_len); } else { map[key as usize] = Length::Chain(loop_len + chain_len - idx); } } chain_len + loop_len } fn solve() -> String { let limit = 1000000; let factorial = { let mut val = [1; 10]; for i in 1..10 { val[i] = val[i - 1] * (i as u32); } val }; let mut map = vec![Length::Unknown; (factorial[9] * 6 + 1) as usize]; let mut cnt = 0; for n in 1..(limit + 1) { let len = get_chain_len(n, &mut map, &factorial); if len == 60 { cnt += 1; } } cnt.to_string() } common::problem!("402", solve); #[cfg(test)] mod tests { use std::iter; #[test] fn len() { let factorial = { let mut val = [1; 10]; for i in 1..10 { val[i] = val[i - 1] * (i as u32); } val }; let mut map = iter::repeat(super::Length::Unknown) .take((factorial[9] * 6 + 1) as usize) .collect::<Vec<_>>(); assert_eq!(3, super::get_chain_len(169, &mut map, &factorial)); assert_eq!(2, super::get_chain_len(871, &mut map, &factorial)); assert_eq!(2, super::get_chain_len(872, &mut map, &factorial)); assert_eq!(5, super::get_chain_len(69, &mut map, &factorial)); assert_eq!(4, super::get_chain_len(78, &mut map, &factorial)); assert_eq!(2, super::get_chain_len(540, &mut map, &factorial)); } }
}
random_line_split