Skip to content

Instantly share code, notes, and snippets.

@SiegeLord
Created September 1, 2014 12:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SiegeLord/6db81b1b8d918b44b15e to your computer and use it in GitHub Desktop.
Save SiegeLord/6db81b1b8d918b44b15e to your computer and use it in GitHub Desktop.
Escaped string
test count_bench ... bench: 16566 ns/iter (+/- 307)
test lower_bench ... bench: 16149 ns/iter (+/- 581)
extern crate test;
use test::Bencher;
fn convert_count(s: &str) -> String
{
let mut count = 0;
let mut take_next = false;
for c in s.chars()
{
if c == '\\' && !take_next
{
take_next = true;
continue;
}
take_next = false;
count += 1;
}
let mut ret = String::with_capacity(count);
take_next = false;
for c in s.chars()
{
if c == '\\' && !take_next
{
take_next = true;
continue;
}
take_next = false;
ret.push_char(c);
}
ret
}
fn convert_lower(s: &str) -> String
{
let lb = s.len() - s.chars().filter(|&c| c == '\\').count();
let mut ret = String::with_capacity(lb);
let mut take_next = false;
for c in s.chars()
{
if c == '\\' && !take_next
{
take_next = true;
continue;
}
take_next = false;
ret.push_char(c);
}
ret
}
fn load_strings() -> Vec<String>
{
use std::io::{BufferedReader, File};
let mut ret = vec![];
for word in BufferedReader::new(File::open(&Path::new("words")).unwrap()).lines()
{
ret.push(word.unwrap());
}
ret
}
#[bench]
fn lower_bench(bench: &mut Bencher)
{
let strings = load_strings();
let mut count = 0;
bench.iter(||
{
for s in strings.iter()
{
count += convert_lower(s.as_slice()).len();
}
});
assert!(count != 23);
}
#[bench]
fn count_bench(bench: &mut Bencher)
{
let strings = load_strings();
let mut count = 0;
bench.iter(||
{
for s in strings.iter()
{
count += convert_count(s.as_slice()).len();
}
});
assert!(count != 23);
}
aboard
accurate
actual
adventure
apartment
applied
appropriate
arrive
atom
Bay
behavior
bend
bet
birth
brass
breathe
brief
buried
camera
captured
chamber
command
crack
Daniel
David
dawn
declared
diameter
difficulty
dirty
dull
duty
eager
eleven
engineer
equally
equator
fierce
firm
fix
flame
former
forty
fox
Fred
frog
fully
goose
gravity
Greece
guard
gulf
handsome
harbor
hay
hello
horn
hospital
ill
interior
Jeff
jungle
labor
limited
lo\cation
m\ainly
managed
Maria
mental
mixture
movie
nearer
nervous
noted
October
officer
Ohio
opinion
opportunity
organization
package
pale
plastic
Pole
port
pour
private
properly
protection
pupil
rear
refused
roar
Rome
Russia
Russian
saddle
settle
shelf
shelter
shine
sink
slabs
slave
somehow
split
st\ems
stock
swept
thy
tide
torn
troops
tropical
typical
unh\appy
vertical
victory
voyage
welcome
weren't
whistle
widely
worried
wrapped
writer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment