1 // The Computer Language Benchmarks Game
2 // http://benchmarksgame.alioth.debian.org/
4 // contributed by the Rust Project Developers
6 // Copyright (c) 2014 The Rust Project Developers
8 // All rights reserved.
10 // Redistribution and use in source and binary forms, with or without
11 // modification, are permitted provided that the following conditions
14 // - Redistributions of source code must retain the above copyright
15 // notice, this list of conditions and the following disclaimer.
17 // - Redistributions in binary form must reproduce the above copyright
18 // notice, this list of conditions and the following disclaimer in
19 // the documentation and/or other materials provided with the
22 // - Neither the name of "The Computer Language Benchmarks Game" nor
23 // the name of "The Computer Language Shootout Benchmarks" nor the
24 // names of its contributors may be used to endorse or promote
25 // products derived from this software without specific prior
26 // written permission.
28 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
29 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
30 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
31 // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
32 // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
33 // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
34 // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
35 // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
36 // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
37 // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
38 // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
39 // OF THE POSSIBILITY OF SUCH DAMAGE.
41 // ignore-android: FIXME(#10393) hangs without output
43 use std::ascii::AsciiExt;
46 use std::io::prelude::*;
52 static TABLE: [u8;4] = [ 'A' as u8, 'C' as u8, 'G' as u8, 'T' as u8 ];
53 static TABLE_SIZE: usize = 2 << 16;
55 static OCCURRENCES: [&'static str;5] = [
63 // Code implementation
65 #[derive(Copy, Clone, PartialEq, PartialOrd, Ord, Eq)]
69 fn hash(&self) -> u64 {
70 let Code(ret) = *self;
74 fn push_char(&self, c: u8) -> Code {
75 Code((self.hash() << 2) + (pack_symbol(c) as u64))
78 fn rotate(&self, c: u8, frame: usize) -> Code {
79 Code(self.push_char(c).hash() & ((1 << (2 * frame)) - 1))
82 fn pack(string: &str) -> Code {
83 string.bytes().fold(Code(0), |a, b| a.push_char(b))
86 fn unpack(&self, frame: usize) -> String {
87 let mut key = self.hash();
88 let mut result = Vec::new();
90 result.push(unpack_symbol((key as u8) & 3));
95 String::from_utf8(result).unwrap()
99 // Hash table implementation
101 trait TableCallback {
102 fn f(&self, entry: &mut Entry);
107 impl TableCallback for BumpCallback {
108 fn f(&self, entry: &mut Entry) {
113 struct PrintCallback(&'static str);
115 impl TableCallback for PrintCallback {
116 fn f(&self, entry: &mut Entry) {
117 let PrintCallback(s) = *self;
118 println!("{}\t{}", entry.count, s);
125 next: Option<Box<Entry>>,
129 items: Vec<Option<Box<Entry>>>
133 cur: Option<&'a Entry>,
134 items: slice::Iter<'a, Option<Box<Entry>>>,
140 items: (0..TABLE_SIZE).map(|_| None).collect()
144 fn search_remainder<C:TableCallback>(item: &mut Entry, key: Code, c: C) {
147 let mut entry = Box::new(Entry {
153 item.next = Some(entry);
155 Some(ref mut entry) => {
156 if entry.code == key {
161 Table::search_remainder(&mut **entry, key, c)
166 fn lookup<C:TableCallback>(&mut self, key: Code, c: C) {
167 let index = key.hash() % (TABLE_SIZE as u64);
170 if self.items[index as usize].is_none() {
171 let mut entry = Box::new(Entry {
177 self.items[index as usize] = Some(entry);
183 let entry = self.items[index as usize].as_mut().unwrap();
184 if entry.code == key {
189 Table::search_remainder(&mut **entry, key, c)
193 fn iter(&self) -> Items {
194 Items { cur: None, items: self.items.iter() }
198 impl<'a> Iterator for Items<'a> {
199 type Item = &'a Entry;
201 fn next(&mut self) -> Option<&'a Entry> {
202 let ret = match self.cur {
206 match self.items.next() {
209 Some(&Some(ref a)) => { i = &**a; break }
212 self.cur = Some(&*i);
218 None => { self.cur = None; }
219 Some(ref next) => { self.cur = Some(&**next); }
227 fn pack_symbol(c: u8) -> u8 {
233 _ => panic!("{}", c as char),
237 fn unpack_symbol(c: u8) -> u8 {
241 fn generate_frequencies(mut input: &[u8], frame: usize) -> Table {
242 let mut frequencies = Table::new();
243 if input.len() < frame { return frequencies; }
244 let mut code = Code(0);
248 code = code.push_char(input[0]);
251 frequencies.lookup(code, BumpCallback);
253 while !input.is_empty() && input[0] != ('>' as u8) {
254 code = code.rotate(input[0], frame);
255 frequencies.lookup(code, BumpCallback);
261 fn print_frequencies(frequencies: &Table, frame: usize) {
262 let mut vector = Vec::new();
263 for entry in frequencies.iter() {
264 vector.push((entry.count, entry.code));
268 let mut total_count = 0;
269 for &(count, _) in &vector {
270 total_count += count;
273 for &(count, key) in vector.iter().rev() {
276 (count as f32 * 100.0) / (total_count as f32));
281 fn print_occurrences(frequencies: &mut Table, occurrence: &'static str) {
282 frequencies.lookup(Code::pack(occurrence), PrintCallback(occurrence))
285 fn get_sequence<R: BufRead>(r: &mut R, key: &str) -> Vec<u8> {
286 let mut res = Vec::<u8>::new();
287 for l in r.lines().map(|l| l.unwrap())
288 .skip_while(|l| key != &l[..key.len()]).skip(1)
290 res.extend(l.trim().as_bytes());
293 *s = s.to_ascii_uppercase();
299 let input = if env::var_os("RUST_BENCH").is_some() {
300 let f = File::open("shootout-k-nucleotide.data").unwrap();
301 get_sequence(&mut io::BufReader::new(f), ">THREE")
303 let stdin = io::stdin();
304 let mut stdin = stdin.lock();
305 get_sequence(&mut stdin, ">THREE")
307 let input = Arc::new(input);
309 let nb_freqs: Vec<_> = (1..3).map(|i| {
310 let input = input.clone();
311 (i, thread::spawn(move|| generate_frequencies(&input, i)))
313 let occ_freqs: Vec<_> = OCCURRENCES.iter().map(|&occ| {
314 let input = input.clone();
315 thread::spawn(move|| generate_frequencies(&input, occ.len()))
318 for (i, freq) in nb_freqs {
319 print_frequencies(&freq.join().unwrap(), i);
321 for (&occ, freq) in OCCURRENCES.iter().zip(occ_freqs) {
322 print_occurrences(&mut freq.join().unwrap(), occ);