atlatl-0.1.2/.gitignore010064400007650000024000000000221313622600100131660ustar0000000000000000target Cargo.lock atlatl-0.1.2/benches/lib.rs010064400007650000024000000145071335244537100137530ustar0000000000000000#![feature(test)] #![allow(non_upper_case_globals, unused_must_use)] extern crate atlatl; extern crate fnv; extern crate fst; extern crate rand; extern crate test; #[macro_use] extern crate lazy_static; use fnv::FnvHashMap; use rand::distributions::{Distribution, Standard, Uniform}; use rand::prelude::*; use std::collections::{BTreeMap, HashMap}; use std::iter::FromIterator; use test::{Bencher, black_box}; use atlatl::fst::*; lazy_static! { static ref small : Vec<(Vec, u32)> = pairs(1000, (0, 16)); static ref sample_s_s : Vec<&'static [u8]> = key_sample(small.iter(), 4, 16); static ref sample_s_m : Vec<&'static [u8]> = key_sample(small.iter(), 8, 16); static ref sample_s_l : Vec<&'static [u8]> = key_sample(small.iter(), 16, 16); static ref medium : Vec<(Vec, u32)> = pairs(10000, (0, 16)); static ref sample_m_s : Vec<&'static [u8]> = key_sample(medium.iter(), 4, 16); static ref sample_m_m : Vec<&'static [u8]> = key_sample(medium.iter(), 8, 16); static ref sample_m_l : Vec<&'static [u8]> = key_sample(medium.iter(), 16, 16); static ref large : Vec<(Vec, u32)> = pairs(50000, (0, 16)); static ref sample_l_s : Vec<&'static [u8]> = key_sample(large.iter(), 4, 16); static ref sample_l_m : Vec<&'static [u8]> = key_sample(large.iter(), 8, 16); static ref sample_l_l : Vec<&'static [u8]> = key_sample(large.iter(), 16, 16); } fn pairs(n : usize, (l, r) : (usize, usize)) -> Vec<(Vec, U)> where Standard : Distribution, U : Ord { let key_length = Uniform::from(l .. r); let gen_key = |k_l| thread_rng().sample_iter::(&Standard).take(k_l).collect(); let mut v : Vec<(Vec, U)> = thread_rng().sample_iter(&key_length).take(n) .map(|k_l| (gen_key(k_l), rand::random())) .collect(); v.sort(); v.dedup_by(|a, b| a.0 == b.0); v } fn key_sample<'a, I, T>(kvs : I, max_len : usize, amount : usize) -> Vec<&'a [u8]> where I : Iterator, T)> , T : 'a { let keys = kvs.map(|&(ref k, _)| k.as_slice()) .filter(|k| k.len() <= max_len); rand::seq::sample_iter(&mut thread_rng(), keys, amount).unwrap() } macro_rules! _bench_coll { ($name:ident, $collection:ident, $source:ident, $sample:ident) => { #[bench] fn $name(b: &mut Bencher) { let iter = $source.iter().map(|&(ref k, v)| (k.as_slice(), v)); let map : $collection<_, _> = $collection::from_iter(iter); let key = $sample[0]; b.iter(|| { black_box(map.get(key)); }); } } } macro_rules! bench_fst { ($name:ident, $source:ident, $sample:ident) => { #[bench] fn $name(b: &mut Bencher) { let iter = $source.iter().map(|&(ref k, v)| (k.as_slice(), v)); let fst_b = atlatl::fst::Builder::from_iter(iter).unwrap(); let fst : FST = FST::from_builder(&fst_b).unwrap(); let key = $sample[0]; b.iter(|| black_box(fst.get(key))); } } } macro_rules! bench_rawfst { ($name:ident, $source:ident, $sample:ident) => { #[bench] fn $name(b: &mut Bencher) { use fst::raw::{Fst, Output}; let mut fst_b = fst::raw::Builder::memory(); let iter = $source.iter().map(|&(ref k, v)| (k.as_slice(), Output::new(v as u64))); fst_b.extend_iter(iter); let fst = Fst::from_bytes(fst_b.into_inner().unwrap()).unwrap(); let key = $sample[0]; b.iter(|| black_box(fst.get(key))); } } } macro_rules! bench_coll { ( $collection:ident , $id_small_short:ident, $id_small_mid:ident, $id_small_long:ident , $id_medium_short:ident, $id_medium_mid:ident, $id_medium_long:ident , $id_large_short:ident, $id_large_mid:ident, $id_large_long:ident ) => { _bench_coll! { $id_small_short, $collection, small, sample_s_s } _bench_coll! { $id_small_mid, $collection, small, sample_s_m } _bench_coll! { $id_small_long, $collection, small, sample_s_l } _bench_coll! { $id_medium_short, $collection, medium, sample_m_s } _bench_coll! { $id_medium_mid, $collection, medium, sample_m_m } _bench_coll! { $id_medium_long, $collection, medium, sample_m_l } _bench_coll! { $id_large_short, $collection, large, sample_l_s } _bench_coll! { $id_large_mid, $collection, large, sample_l_m } _bench_coll! { $id_large_long, $collection, large, sample_l_l } } } bench_coll! { HashMap , get_small_short_hashmap, get_small_mid_hashmap, get_small_long_hashmap , get_medium_short_hashmap, get_medium_mid_hashmap, get_medium_long_hashmap , get_large_short_hashmap, get_large_mid_hashmap, get_large_long_hashmap } bench_coll! { FnvHashMap , get_small_short_fnvhashmap, get_small_mid_fnvhashmap, get_small_long_fnvhashmap , get_medium_short_fnvhashmap, get_medium_mid_fnvhashmap, get_medium_long_fnvhashmap , get_large_short_fnvhashmap, get_large_mid_fnvhashmap, get_large_long_fnvhashmap } bench_coll! { BTreeMap , get_small_short_btree, get_small_mid_btree, get_small_long_btree , get_medium_short_btree, get_medium_mid_btree, get_medium_long_btree , get_large_short_btree, get_large_mid_btree, get_large_long_btree } bench_fst! { get_small_short_fst, small, sample_s_s } bench_fst! { get_small_mid_fst, small, sample_s_m } bench_fst! { get_small_long_fst, small, sample_s_l } bench_fst! { get_medium_short_fst, medium, sample_m_s } bench_fst! { get_medium_mid_fst, medium, sample_m_m } bench_fst! { get_medium_long_fst, medium, sample_m_l } bench_fst! { get_large_short_fst, large, sample_l_s } bench_fst! { get_large_mid_fst, large, sample_l_m } bench_fst! { get_large_long_fst, large, sample_l_l } bench_rawfst! { get_small_short_rawfst, small, sample_s_s } bench_rawfst! { get_small_mid_rawfst, small, sample_s_m } bench_rawfst! { get_small_long_rawfst, small, sample_s_l } bench_rawfst! { get_medium_short_rawfst, medium, sample_m_s } bench_rawfst! { get_medium_mid_rawfst, medium, sample_m_m } bench_rawfst! { get_medium_long_rawfst, medium, sample_m_l } bench_rawfst! { get_large_short_rawfst, large, sample_l_s } bench_rawfst! { get_large_mid_rawfst, large, sample_l_m } bench_rawfst! { get_large_long_rawfst, large, sample_l_l } atlatl-0.1.2/Cargo.toml.orig010064400007650000024000000011241335244616500141100ustar0000000000000000[package] name = "atlatl" version = "0.1.2" authors = ["tapeinosyne "] license = "Apache-2.0/MIT" repository = "https://github.com/tapeinosyne/atlatl" homepage = "https://github.com/tapeinosyne/atlatl" # documentation = "https://docs.rs/atlatl" readme = "README.md" description = "Double-array tries." # categories = ["data-structures"] keywords = ["double-array", "trie"] [dependencies] fnv = "1.0" num-traits = "0.2" serde = { version = "1.0", optional = true, features = ["derive"] } [dev-dependencies] fst = "0.1" lazy_static = "1.1" quickcheck = "0.7" rand = "0.5" atlatl-0.1.2/Cargo.toml0000644000000022210000000000000103470ustar00# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g. crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] name = "atlatl" version = "0.1.2" authors = ["tapeinosyne "] description = "Double-array tries." homepage = "https://github.com/tapeinosyne/atlatl" readme = "README.md" keywords = ["double-array", "trie"] license = "Apache-2.0/MIT" repository = "https://github.com/tapeinosyne/atlatl" [dependencies.fnv] version = "1.0" [dependencies.num-traits] version = "0.2" [dependencies.serde] version = "1.0" features = ["derive"] optional = true [dev-dependencies.fst] version = "0.1" [dev-dependencies.lazy_static] version = "1.1" [dev-dependencies.quickcheck] version = "0.7" [dev-dependencies.rand] version = "0.5" atlatl-0.1.2/CHANGELOG.md010064400007650000024000000005221335230144500130220ustar0000000000000000# `atlatl` ## 0.1.2 ### Dependencies - `lazy_static` → 1.1 - `num-traits` → 0.2 - `quickcheck` → 0.7 - `rand` → 0.5 ## 0.1.1 ### Changes - The `serialization` feature has been renamed to `serde`, in accordance with the [Rust API guidelines](https://github.com/rust-lang-nursery/api-guidelines). ## 0.1.0 Initial release. atlatl-0.1.2/LICENSE-APACHE010064400007650000024000000240171313622610100131350ustar0000000000000000Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} 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. atlatl-0.1.2/LICENSE-MIT010064400007650000024000000020661313622610100126450ustar0000000000000000The MIT License (MIT) Copyright (c) 2017 tapeinosyne Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. atlatl-0.1.2/README.md010064400007650000024000000017011335230074600124730ustar0000000000000000# Atlatl Preliminary work on Rust double-array tries – which is to say, DARTs. Presently, only a limited-capability Dart representation of minimal finite subsequential transducers. ## References - Stoyan Mihov, Denis Maurel, *Direct Construction of Minimal Acyclic Subsequential Transducers* - Jan Daciuk, Bruce W. Watson, Stoyan Mihov, Richard E. Watson, *Incremental Construction of Minimal Acyclic Finite-State Automata* - Jan Daciuk, *Incremental Construction of Finite-State Automata and Transducers, and their Use in Natural Language Processing* - Theppitak Karoonboonyanan, [An Implementation of Double-Array Trie](https://linux.thai.net/~thep/datrie/datrie.html#References) - Andrew Gallant, [`fst`](https://github.com/BurntSushi/fst) - Susumu Yata, [`Darts-clone`](https://github.com/s-yata/darts-clone) ## License `atlatl` © 2017 tapeinosyne, dual-licensed under the terms of either: - the Apache License, Version 2.0 - the MIT license atlatl-0.1.2/src/fst/builder.rs010064400007650000024000000175231314715105500146030ustar0000000000000000use fnv::FnvHashMap; use std::cmp; use std::collections::hash_map::Entry; use fst::error::{Error, Result}; use fst::output::Output; use index::Index; pub type Label = u8; #[derive(Copy, Clone, Debug, Default, Hash, Eq, PartialEq)] pub struct Transition { pub label : Label, pub output : O, pub destination : I, } #[derive(Clone, Debug, Default, Hash, Eq, PartialEq)] pub struct State { pub terminal : bool, pub final_output : O, pub transitions : Vec> } /// A transition without a fixed destination state. #[derive(Copy, Clone, Debug, Default, Eq, PartialEq)] struct DanglingArc { label : Label, output : O } impl DanglingArc where O : Output { fn from_label(label : Label) -> DanglingArc { DanglingArc { label, ..DanglingArc::default() } } } #[derive(Clone, Debug, Default, Eq, PartialEq)] struct DanglingState { pub state : State, pub last_arc : Option> } impl DanglingState where I : Index, O : Output { fn from_label(label : Label) -> DanglingState { DanglingState { last_arc : Some(DanglingArc::from_label(label)), state : State::default() } } fn empty_terminal() -> DanglingState { DanglingState { state : State { terminal : true, ..State::default() }, last_arc : None } } fn affix_last(&mut self, destination : I) { if let Some(DanglingArc { label, output }) = self.last_arc.take() { self.state.transitions.push(Transition { destination, label, output }); } } fn redistribute_output(&mut self, diff : O) { if diff != O::zero() { if self.state.terminal { self.state.final_output.mappend_assign(diff) } if let Some(ref mut t) = self.last_arc { t.output.mappend_assign(diff) } for t in &mut self.state.transitions { t.output.mappend_assign(diff) } } } } #[derive(Clone, Debug, Default, Eq, PartialEq)] struct DanglingPath { stack : Vec> } impl DanglingPath where I : Index, O : Output { fn new() -> DanglingPath { let mut dangling = DanglingPath { stack : Vec::with_capacity(64) }; dangling.append_empty(); dangling } fn append_empty(&mut self) { self.stack.push(DanglingState::default()); } fn pop_empty(&mut self) -> State { let dangling = self.stack.pop().unwrap(); assert!(dangling.last_arc.is_none()); dangling.state } fn pop_root(&mut self) -> State { assert!(self.stack.len() == 1); assert!(self.stack[0].last_arc.is_none()); self.stack.pop().unwrap().state } fn set_root_output(&mut self, output : O) { self.stack[0].state.terminal = true; self.stack[0].state.final_output = output; } fn finalize(&mut self, index : I) -> State { let mut dangling = self.stack.pop().unwrap(); dangling.affix_last(index); dangling.state } fn finalize_last(&mut self, index : I) { let last = self.stack.len() - 1; self.stack[last].affix_last(index); } fn add_suffix(&mut self, suffix : &[u8], output : O) { if suffix.is_empty() { return; } let last = self.stack.len() - 1; assert!(self.stack[last].last_arc.is_none()); self.stack[last].last_arc = Some(DanglingArc { output, label : suffix[0] }); self.stack.extend(suffix[1..].iter().map(|&l| DanglingState::from_label(l))); self.stack.push(DanglingState::empty_terminal()); } fn redistribute_prefix(&mut self, key : &[u8], mut out : O) -> (usize, O) { let mut i = 0; while i < key.len() { let diff = match self.stack[i].last_arc.as_mut() { Some(ref mut t) if t.label == key[i] => { i += 1; let prefix = t.output.prefix(out); let diff = t.output.inverse(prefix); out.inverse_assign(prefix); t.output = prefix; diff } _ => break, }; self.stack[i].redistribute_output(diff); } (i, out) } fn len(&self) -> usize { self.stack.len() } } type Registry = FnvHashMap, I>; #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct Builder where I : Index, O : Output { pub registry : Registry, dangling : DanglingPath, previous_key : Option>, transition_count : usize, usable_index : usize, language_size : usize, root : I, } impl Builder where I : Index, O : Output { fn register(&mut self, state : State) -> Result { let idx = &mut self.usable_index; let trans_r = &mut self.transition_count; let trans_s = state.transitions.len(); match self.registry.entry(state) { Entry::Occupied(e) => Ok(*e.get()), Entry::Vacant(e) => { let s_i = *idx; *idx += 1; *trans_r += trans_s; match s_i > I::bound() || *trans_r > I::bound() { true => Err(Error::OutOfBounds { reached : cmp::max(s_i, *trans_r), maximum : I::max_value().as_usize() }), false => Ok(*e.insert(I::as_index(s_i))) } } } } fn finalize_subpath(&mut self, path_start : usize) -> Result<()> { let mut idx = None; while path_start + 1 < self.dangling.len() { let state = match idx { Some(i) => self.dangling.finalize(i), None => self.dangling.pop_empty() }; idx = Some( self.register(state) ? ); } // By construction, the last state remaining has no last_arc if `idx` is None if let Some(i) = idx { self.dangling.finalize_last(i) } Ok(()) } fn finalize_root(&mut self) -> Result { let root = self.dangling.pop_root(); self.register(root) } fn validate_key<'a>(&mut self, key : &'a [u8]) -> Result<&'a [u8]> { match self.previous_key { Some(ref prev) if key == prev.as_slice() => Err(Error::Duplicate(key.to_vec())), Some(ref prev) if key < prev.as_slice() => Err(Error::OutOfOrder(key.to_vec(), prev.to_vec())), _ => { self.previous_key = key.to_vec().into(); Ok(key) } } } pub fn insert(&mut self, key : &[u8], value : O) -> Result<()> { let key = self.validate_key(key) ?; if key.is_empty() { self.dangling.set_root_output(value); self.language_size = 1; return Ok(()); } let (prefix_len, output) = self.dangling.redistribute_prefix(key, value); self.finalize_subpath(prefix_len) ?; let suffix = &key[prefix_len ..]; self.dangling.add_suffix(suffix, output); self.language_size += 1; Ok(()) } pub fn finish(&mut self) -> Result { self.finalize_subpath(0) .and_then(|_| self.finalize_root()) .map(|i| { self.root = i; i }) } pub fn from_iter(iter : T) -> Result> where K : AsRef<[u8]> , T : IntoIterator { let mut builder = Builder { dangling : DanglingPath::new(), ..Builder::default() }; for (k, v) in iter { builder.insert(k.as_ref(), v) ? } builder.finish() ?; Ok(builder) } pub fn root(&self) -> I { self.root } pub fn size(&self) -> usize { self.registry.len() } pub fn len(&self) -> usize { self.language_size } } atlatl-0.1.2/src/fst/error.rs010064400007650000024000000033401313636140700143000ustar0000000000000000use std::error; use std::fmt; use std::result; use std::str; pub type Result = result::Result; #[derive(Clone, Debug)] pub enum Error { /// A duplicate key was inserted in the FST builder. Duplicate(Vec), /// A key was inserted out of order in the FST builder. OutOfOrder(Vec, Vec), /// The length of the Dart exceeds its index size. OutOfBounds { reached : usize, maximum : usize } } impl error::Error for Error { fn description(&self) -> &str { match *self { Error::Duplicate(_) => "a duplicate key was inserted in the FST builder", Error::OutOfOrder(_, _) => "a key was inserted out of order in the FST builder", Error::OutOfBounds { .. } => "the Dart has grown too large for its index type", } } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Error::Duplicate(ref k) => write!(f, "\ FST construction error: the key {} was already present. All keys must be unique.", format_bytes(&k)), Error::OutOfOrder(ref k1, ref k2) => write!(f, "\ FST construction error: a key was inserted out of order. The lesser key {} was inserted after the greater key {} Keys must be inserted in lexicographic order.", format_bytes(&k2), format_bytes(&k1)), Error::OutOfBounds { reached, maximum } => write!(f, "\ FST construction error: the FST outgrew its index type. An FST with a maximum index of {} reached a state or transition that required an index of {}.", maximum, reached), } } } fn format_bytes(bytes: &[u8]) -> String { match str::from_utf8(bytes) { Ok(s) => s.to_owned(), Err(_) => format!("{:?}", bytes), } } atlatl-0.1.2/src/fst/intermediate.rs010064400007650000024000000104321314715105500156170ustar0000000000000000use fst::error::{Error, Result}; use fst::{FST, Output, Stipe, Terminal}; use fst::builder::{Builder, State}; use index::Index; use segment::IndexSegments; type BuilderState = usize; #[derive(Clone, Debug, Default)] pub struct Intermediary where I : Index, O : Output { stack : Vec, // Indexed by BuilderState registry : Vec>, segments : IndexSegments, fst : FST } impl Intermediary where I : Index, O : Output { pub fn into_dart(self) -> FST { self.fst } /// Build an intermediate representation pub fn from_builder(&mut self, fst : &Builder) -> Result<()> { self.reserve(fst.size()); self.registry.resize(fst.size(), None); let eph = &State::default(); let mut states = vec![eph; fst.size()]; for (state, &s_i) in fst.registry.iter() { states[s_i.as_usize()] = state } self.expand(); let root_idx = fst.root().as_usize(); let root_next = I::as_index(self.settle_root(states[root_idx]).unwrap()); self.fst.da.next[0] = root_next; self.registry[root_idx] = Some(root_next); match (states[root_idx].terminal, states[root_idx].final_output) { (false, _) => self.fst.da.stipe[0].terminal = Terminal::Not, (true, out) if out.is_zero() => self.fst.da.stipe[0].terminal = Terminal::Empty, (true, out) => { self.fst.da.stipe[0].terminal = Terminal::Inner; self.fst.state_output.insert(I::zero(), out); } } self.stack.push(root_idx); while let Some(s_i) = self.stack.pop() { for trans in &states[s_i].transitions { let t = trans.destination.as_usize(); let (is_final, final_output) = (states[t].terminal, states[t].final_output); let terminal = match (is_final, final_output.is_zero()) { (false, _) => Terminal::Not, (true, true) => Terminal::Empty, (true, false) => Terminal::Inner }; let label = trans.label; let e = self.registry[s_i].unwrap().as_usize() + (1 + label as usize); if e >= self.fst.len() { self.expand(); } self.fst.da.output[e] = trans.output; self.fst.da.stipe[e] = Stipe { check: label, terminal: terminal }; self.fst.da.next[e] = match self.registry[t] { Some(i) => i, None => { let next = I::as_index( self.settle(&states[t]) ?); self.registry[t] = Some(next); self.stack.push(t); if terminal.is_inner() { self.fst.state_output.insert(next, final_output); } next } }; } } Ok(()) } fn settle(&mut self, state : &State) -> Result { let inputs : Vec<_> = state.transitions.iter().map(|t| t.label).collect(); let base = self.first_available(&inputs); match base > I::bound() { true => Err(Error::OutOfBounds { reached : base, maximum : I::max_value().as_usize() }), false => Ok(base) } } fn settle_root(&mut self, state : &State) -> Option { let inputs : Vec<_> = state.transitions.iter().map(|t| t.label).collect(); self.expand(); self.segments.settle_index(&inputs, 0) } fn first_available(&mut self, symbols : &[u8]) -> usize { self.segments.settle(symbols).or_else(|| { self.expand(); self.segments.settle(symbols) }).unwrap() } fn expand(&mut self) { let old_length = self.len(); self.fst.resize(old_length + self.segments.block_size()); self.segments.expand(old_length); } fn reserve(&mut self, n : usize) { self.fst.reserve(n); self.segments.reserve(n / 64); self.registry.reserve(n); } pub fn len(&self) -> usize { self.fst.len() } pub fn unfixed_count(&self) -> usize { self.segments.unfixed_count() } } atlatl-0.1.2/src/fst/mod.rs010064400007650000024000000216631314715106100137310ustar0000000000000000pub mod builder; pub mod error; pub mod intermediate; pub mod output; pub use self::builder::Builder; pub use self::error::Error; pub use self::output::Output; use fnv::FnvHashMap; use std::slice; use fst::error::Result; use fst::intermediate::Intermediary; use index::Index; #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(Copy, Clone, Debug, Default, Eq, PartialEq)] pub struct Stipe { pub check : u8, pub terminal : Terminal } /// Finality of a transition's destination state. #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum Terminal { /// The transition is not final. Not, /// The transition is final and leads to a state with no inner output. Empty, /// The transition is final and leads to a state with inner output. Inner } impl Terminal { #[inline] pub fn is(self) -> bool { self != Terminal::Not } #[inline] pub fn is_inner(self) -> bool { self == Terminal::Inner } } impl Default for Terminal { fn default() -> Terminal { Terminal::Not } } /// Hybrid Dart representation for a finite subsequential transducer. #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct FST where I : Index, O : Output { pub da : Dart, pub state_output : FnvHashMap } /// The double-array trie, holding the core state machine for the FST. #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct Dart { pub stipe : Vec, pub next : Vec, pub output : Vec, } #[derive(Copy, Clone, Debug, Default, Eq, PartialEq)] pub struct State { pub index : I, pub terminal : Terminal } impl FST where I : Index, O : Output { pub fn from_builder(builder : &builder::Builder) -> Result { let mut repr = Intermediary::default(); repr.from_builder(builder) ?; Ok(repr.into_dart()) } /// Given a starting state and an input, returns the destination state, if any. pub fn transition(&self, state : I, input : u8) -> Option> { let e = state.as_usize() + (1 + input as usize); match self.da.stipe.get(e) { Some(&Stipe { check, terminal }) if check == input => Some(State { index: self.da.next[e], terminal: terminal }), _ => None } } /// Returns whether the key is present in the FST. pub fn contains(&self, key : K) -> bool where K : AsRef<[u8]> { let mut state = State::default(); for &label in key.as_ref() { let to = self.transition(state.index, label); match to { Some(s) => state = s, _ => return false } } state.terminal.is() } /// Get the value associated to the key, if any. pub fn get(&self, key : K) -> Option where K : AsRef<[u8]> { let mut out = O::zero(); let mut state = I::zero(); let mut terminal = self.da.stipe[0].terminal; for &label in key.as_ref() { let e = state.as_usize() + (1 + label as usize); let stipe = self.da.stipe.get(e); match stipe { Some(stipe) if stipe.check == label => { terminal = stipe.terminal; out.mappend_assign(self.da.output[e]); state = self.da.next[e]; }, _ => return None } } match terminal { Terminal::Not => None, Terminal::Empty => Some(out), Terminal::Inner => Some(out.mappend(self.state_output[&state])) } } /// Returns an iterator producing the values associated to all prefixes /// of the query, including the empty string and the query itself. pub fn reap<'a, 'q>(&'a self, query : &'q [u8]) -> Reaper<'a, 'q, I, O> { let root_output = match self.da.stipe[0].terminal { Terminal::Not => None, Terminal::Empty => Some((0, O::zero())), Terminal::Inner => Some((0, self.state_output[&I::zero()])) }; Reaper { query : query.into_iter(), position : 0, fst : &self, root_output : root_output, output : O::zero(), state : I::zero() } } /// Returns an iterator producing the values associated to all prefixes /// of the query, including the query itself but excluding the empty string. pub fn reap_past_root<'a, 'q>(&'a self, query : &'q [u8]) -> RootlessReaper<'a, 'q, I, O> { RootlessReaper { query : query.into_iter(), position : 0, fst : &self, output : O::zero(), state : I::zero() } } /// The number of nodes in the internal double array, including surplus. pub fn len(&self) -> usize { assert!(self.da.next.len() == self.da.stipe.len()); assert!(self.da.next.len() == self.da.output.len()); self.da.stipe.len() } fn resize(&mut self, length : usize) { self.da.stipe.resize(length, Stipe::default()); self.da.next.resize(length, I::zero()); self.da.output.resize(length, O::zero()); } fn reserve(&mut self, n : usize) { self.da.stipe.reserve(n); self.da.next.reserve(n); self.da.output.reserve(n); } } #[derive(Clone, Debug)] pub struct Reaper<'a, 'q, I, O> where I : Index + 'a , O : Output + 'a { query : slice::Iter<'q, u8>, position : usize, fst : &'a FST, root_output : Option<(usize, O)>, state : I, output : O } // FIXME: the root-skipping doppelgänger of `Reaper` exists solely because // downstream users of `atlatl` appear to suffer an inscrutable performance // penalty if they do not avail themselves to both. // // Surely something is amiss. #[derive(Clone, Debug)] pub struct RootlessReaper<'a, 'q, I, O> where I : Index + 'a , O : Output + 'a { query : slice::Iter<'q, u8>, position : usize, fst : &'a FST, state : I, output : O } impl<'a, 'q, I, O> Iterator for RootlessReaper<'a, 'q, I, O> where I : Index, O : Output { type Item = (usize, O); fn next(&mut self) -> Option { let mut terminal = Terminal::Not; let da = &self.fst.da; for &label in self.query.by_ref() { let e = self.state.as_usize() + (1 + label as usize); let stipe = da.stipe.get(e); match stipe { Some(stipe) if stipe.check == label => { self.output.mappend_assign(da.output[e]); self.state = da.next[e]; self.position += 1; terminal = stipe.terminal; if terminal.is() { break } }, _ => return None } } match terminal { Terminal::Not => None, Terminal::Empty => Some((self.position, self.output)), Terminal::Inner => Some((self.position, self.output.mappend(self.fst.state_output[&self.state]))) } } fn size_hint(&self) -> (usize, Option) { (0, Some(self.query.len())) } } impl<'a, 'q, I, O> Iterator for Reaper<'a, 'q, I, O> where I : Index, O : Output { type Item = (usize, O); fn next(&mut self) -> Option { // The root output representing the empty prefix, if present, is always // the first match of any query. self.root_output.take() .or_else(|| { let mut terminal = Terminal::Not; let da = &self.fst.da; for &label in self.query.by_ref() { let e = self.state.as_usize() + (1 + label as usize); let stipe = da.stipe.get(e); match stipe { Some(stipe) if stipe.check == label => { self.output.mappend_assign(da.output[e]); self.state = da.next[e]; self.position += 1; terminal = stipe.terminal; if terminal.is() { break } }, _ => return None } } match terminal { Terminal::Not => None, Terminal::Empty => Some((self.position, self.output)), Terminal::Inner => Some((self.position, self.output.mappend(self.fst.state_output[&self.state]))) } }) } fn size_hint(&self) -> (usize, Option) { let from_root = if self.root_output.is_some() { 1 } else { 0 }; (from_root, Some(self.query.len() + from_root)) } } atlatl-0.1.2/src/fst/output.rs010064400007650000024000000037541313636140700145200ustar0000000000000000use std::cmp; use std::fmt::Debug; use std::hash::Hash; /// An additive abelian group with a prefix operation. pub trait Output : Eq + Copy + Hash + Default + Debug { /// The identity element. fn zero() -> Self; /// The additive operation under which the output forms an abelian group. fn mappend(self, y : Self) -> Self; /// The additive operation applied to the inverse of `y`. fn inverse(self, y : Self) -> Self; /// The longest common prefix of the given values. fn prefix(self, y : Self) -> Self; #[inline] fn is_zero(self) -> bool { self == Self::zero() } #[inline] fn mappend_assign(&mut self, y : Self) { *self = self.mappend(y) } #[inline] fn inverse_assign(&mut self, y : Self) { *self = self.inverse(y) } } macro_rules! impl_output_unsigned { ($num:ty) => { impl Output for $num { #[inline] fn zero() -> Self { 0 } #[inline] fn mappend(self, y : Self) -> Self { self + y } #[inline] fn inverse(self, y : Self) -> Self { self - y } #[inline] fn prefix(self, y : Self) -> Self { cmp::min(self, y) } } } } macro_rules! impl_output_signed { ($num:ty) => { impl Output for $num { #[inline] fn zero() -> Self { 0 } #[inline] fn mappend(self, y : Self) -> Self { self + y } #[inline] fn inverse(self, y : Self) -> Self { self - y } #[inline] fn prefix(self, y : Self) -> Self { match (self > 0, y > 0) { (true, true) => cmp::min(self, y), (false, false) => cmp::max(self, y), (_, _) => 0 } } } } } impl_output_unsigned! { u8 } impl_output_unsigned! { u16 } impl_output_unsigned! { u32 } impl_output_unsigned! { u64 } impl_output_unsigned! { usize } impl_output_signed! { i8 } impl_output_signed! { i16 } impl_output_signed! { i32 } impl_output_signed! { i64 } impl_output_signed! { isize } atlatl-0.1.2/src/index.rs010064400007650000024000000017561313622617100134710ustar0000000000000000use std::fmt::{Debug, Display}; use std::hash::Hash; use std::ops::{AddAssign, SubAssign}; use num_traits::{Unsigned, Bounded}; /// A minimal trait for unchecked casting of unsigned integers to `usize`, /// for indexing purposes. pub trait Index : Unsigned + Bounded // An unsigned integer— + Eq + Copy + Hash // —with the properties we require— + Default + AddAssign + SubAssign // —and a bit of convenience. + Debug + Display { fn as_usize(self) -> usize; fn as_index(i : usize) -> Self; #[inline(always)] fn bound() -> usize { Self::max_value().as_usize() } } macro_rules! impl_index { ($idx:ty) => { impl Index for $idx { #[inline(always)] fn as_usize(self) -> usize { self as usize } #[inline(always)] fn as_index(i : usize) -> $idx { i as $idx } } } } impl_index! { usize } impl_index! { u16 } impl_index! { u32 } #[cfg(target_pointer_width = "64")] impl_index! { u64 } atlatl-0.1.2/src/lib.rs010064400007650000024000000003241314715106100131130ustar0000000000000000// Forsaken docs justly quibble the vexed programmer's waning zeal. extern crate fnv; extern crate num_traits; #[cfg(feature = "serde")] #[macro_use] extern crate serde; mod segment; pub mod fst; pub mod index; atlatl-0.1.2/src/segment.rs010064400007650000024000000042641314715105500140210ustar0000000000000000//! Paging structures for fast insertion in a Dart. use fnv::FnvHashSet; #[derive(Clone, Debug)] pub struct IndexSegments { as_state : FnvHashSet, as_trans : FnvHashSet, block_size : usize, } impl IndexSegments { /// Settle the transitions labelled with `symbols` in the segments, /// returning their base index. pub fn settle(&mut self, symbols : &[u8]) -> Option { self.usher(symbols).map(|base| { self.affix_state(base); for &s in symbols { self.affix_trans(base + (1 + s as usize)) } base }) } pub fn settle_index(&mut self, symbols : &[u8], i : usize) -> Option { self.as_state.get(&i).cloned() .map(|base| { self.affix_state(base); for &s in symbols { self.affix_trans(base + (1 + s as usize)) } base }) } /// Find the first index admitting all symbols. pub fn usher(&self, symbols : &[u8]) -> Option { self.as_state.iter() .find(|&&base| symbols.iter().all(|&s| self.as_trans.contains(&(base + (1 + s as usize))))) .cloned() } fn affix_state(&mut self, i : usize) { let r = self.as_state.remove(&i); assert!(r); } fn affix_trans(&mut self, i : usize) { let r = self.as_trans.remove(&i); assert!(r); } /// Add a new block to the segments. pub fn expand(&mut self, old_length : usize) { let new_length = old_length + self.block_size; self.as_state.extend(old_length .. new_length); self.as_trans.extend(old_length .. new_length); } pub fn block_size(&self) -> usize { self.block_size } pub fn unfixed_count(&self) -> usize { use std::cmp; cmp::min(self.as_trans.len(), self.as_state.len()) } pub fn reserve(&mut self, n : usize) { self.as_state.reserve(n); self.as_trans.reserve(n); } } impl Default for IndexSegments { fn default() -> Self { IndexSegments { as_state : FnvHashSet::default(), as_trans : FnvHashSet::default(), block_size : 257, } } } atlatl-0.1.2/tests/lib.rs010064400007650000024000000030341314715105500134720ustar0000000000000000extern crate atlatl; extern crate rand; extern crate quickcheck; use quickcheck::{quickcheck}; use std::collections::BTreeMap; use atlatl::*; use atlatl::fst::*; #[test] fn fst_output_matches_source_u32_u16() { fn property(btree: BTreeMap, u16>) -> bool { let b = fst::Builder::from_iter(btree.iter().map(|(k, &v)| (k, v))).unwrap(); let fst : FST = FST::from_builder(&b).unwrap(); btree.iter().all(|(k, &from_btree)| { let from_fst = fst.get(k).unwrap(); from_fst == from_btree }) } quickcheck(property as fn(BTreeMap, u16>) -> bool); } #[test] fn fst_output_matches_source_u32_i16() { fn property(btree: BTreeMap, i16>) -> bool { let b = fst::Builder::from_iter(btree.iter().map(|(k, &v)| (k, v))).unwrap(); let fst : FST = FST::from_builder(&b).unwrap(); btree.iter().all(|(k, &from_btree)| { let from_fst = fst.get(k).unwrap(); from_fst == from_btree }) } quickcheck(property as fn(BTreeMap, i16>) -> bool); } #[test] fn fst_reap() { let pairs = &[("", 3), ("a", 0), ("ab", 1), ("abc", 2)]; let b = fst::Builder::from_iter(pairs.iter().cloned()).unwrap(); let fst : FST = FST::from_builder(&b).unwrap(); let reaper = fst.reap("abcd".as_bytes()); assert!((1, Some(5)) == reaper.size_hint()); let reaped : Vec<_> = reaper.collect(); assert!(4 == reaped.len()); assert!(vec![(0, 3), (1, 0), (2, 1), (3, 2)] == reaped); } atlatl-0.1.2/.cargo_vcs_info.json0000644000000001120000000000000123460ustar00{ "git": { "sha1": "ccd22c182becd3d7669ddbc8ffbe00d90fa1a4b1" } }