Skip to content

Commit

Permalink
Merge 920b650 into a66df48
Browse files Browse the repository at this point in the history
  • Loading branch information
ia0 committed Dec 31, 2018
2 parents a66df48 + 920b650 commit 9adbb42
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 53 deletions.
36 changes: 18 additions & 18 deletions bin/src/main.rs
Expand Up @@ -32,14 +32,14 @@ impl ::std::fmt::Display for Error {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
use self::Error::*;
match self {
&ParseOpts(ref e) => e.fmt(f),
&ExtraArgs(ref a) => write!(f, "Unexpected arguments {:?}", a),
&Cmdline(ref m) => write!(f, "{}", m),
&Decode(ref e) => e.fmt(f),
&Builder(ref e) => e.fmt(f),
&IO(ref p, ref e) => write!(f, "{}: {}", p, e),
&Read(ref e) => write!(f, "Read error: {}", e),
&Write(ref e) => write!(f, "Write error: {}", e),
ParseOpts(ref e) => e.fmt(f),
ExtraArgs(ref a) => write!(f, "Unexpected arguments {:?}", a),
Cmdline(ref m) => write!(f, "{}", m),
Decode(ref e) => e.fmt(f),
Builder(ref e) => e.fmt(f),
IO(ref p, ref e) => write!(f, "{}: {}", p, e),
Read(ref e) => write!(f, "Read error: {}", e),
Write(ref e) => write!(f, "Write error: {}", e),
}
}
}
Expand All @@ -48,14 +48,14 @@ impl ::std::error::Error for Error {
fn description(&self) -> &str {
use self::Error::*;
match self {
&ParseOpts(ref e) => e.description(),
&ExtraArgs(_) => "unexpected argument",
&Cmdline(_) => "invalid command-line",
&Decode(ref e) => e.description(),
&Builder(ref e) => e.description(),
&IO(_, ref e) => e.description(),
&Read(ref e) => e.description(),
&Write(ref e) => e.description(),
ParseOpts(ref e) => e.description(),
ExtraArgs(_) => "unexpected argument",
Cmdline(_) => "invalid command-line",
Decode(ref e) => e.description(),
Builder(ref e) => e.description(),
IO(_, ref e) => e.description(),
Read(ref e) => e.description(),
Write(ref e) => e.description(),
}
}
}
Expand Down Expand Up @@ -234,7 +234,7 @@ Examples:
let mut spec = ::data_encoding::Specification::new();
spec.symbols = matches
.opt_str("symbols")
.ok_or(Error::Cmdline("Base or symbols must be provided".into()))?;
.ok_or_else(|| Error::Cmdline("Base or symbols must be provided".into()))?;
spec
}
Some(base) => {
Expand Down Expand Up @@ -314,7 +314,7 @@ Examples:

let size = matches
.opt_str("block")
.unwrap_or("15360".to_owned())
.unwrap_or_else(|| "15360".to_owned())
.parse()
.map_err(|_| Error::Cmdline("Invalid block value".into()))?;
check!(Error::Cmdline("Block value must be greater or equal than 8".into()), size >= 8);
Expand Down
28 changes: 11 additions & 17 deletions lib/macro/internal/src/lib.rs
Expand Up @@ -65,14 +65,8 @@ fn parse_map(mut tokens: IntoIter) -> HashMap<String, TokenTree> {
#[cfg(feature = "stable")]
fn parse_map(mut input: &str) -> HashMap<String, Token> {
let mut map = HashMap::new();
loop {
let key = match syn::parse::tt(input) {
IResult::Done(rest, key) => {
input = rest;
key
}
IResult::Error => break,
};
while let IResult::Done(rest, key) = syn::parse::tt(input) {
input = rest;
let key = match key {
TokenTree::Token(Token::Ident(key)) => key,
_ => panic!("expected key got {:?}", key),
Expand Down Expand Up @@ -109,7 +103,7 @@ fn get_string(map: &mut HashMap<String, TokenTree>, key: &str) -> String {
#[cfg(feature = "stable")]
fn get_string(map: &mut HashMap<String, Token>, key: &str) -> String {
match map.remove(key) {
None => return String::new(),
None => String::new(),
Some(Token::Literal(Lit::Str(value, _))) => value,
Some(_) => panic!("expected string literal for {}", key),
}
Expand All @@ -133,7 +127,7 @@ fn get_usize(map: &mut HashMap<String, TokenTree>, key: &str) -> usize {
#[cfg(feature = "stable")]
fn get_usize(map: &mut HashMap<String, Token>, key: &str) -> usize {
match map.remove(key) {
None => return 0,
None => 0,
Some(Token::Literal(Lit::Int(value, _))) => value as usize,
Some(_) => panic!("expected usize for {}", key),
}
Expand All @@ -155,7 +149,7 @@ fn get_padding(map: &mut HashMap<String, TokenTree>) -> Option<char> {
#[cfg(feature = "stable")]
fn get_padding(map: &mut HashMap<String, Token>) -> Option<char> {
match map.remove("padding") {
None => return None,
None => None,
Some(Token::Ident(ref ident)) if ident.as_ref() == "None" => None,
Some(Token::Literal(Lit::Char(value))) => Some(value),
Some(_) => panic!("expected char for padding"),
Expand All @@ -177,7 +171,7 @@ fn get_bool(map: &mut HashMap<String, TokenTree>, key: &str) -> Option<bool> {
#[cfg(feature = "stable")]
fn get_bool(map: &mut HashMap<String, Token>, key: &str) -> Option<bool> {
match map.remove(key) {
None => return None,
None => None,
Some(Token::Literal(Lit::Bool(value))) => Some(value),
Some(_) => panic!("expected bool for {}", key),
}
Expand Down Expand Up @@ -206,7 +200,7 @@ fn get_bit_order(map: &mut HashMap<String, Token>) -> BitOrder {
let msb = "MostSignificantFirst";
let lsb = "LeastSignificantFirst";
match map.remove("bit_order") {
None => return BitOrder::MostSignificantFirst,
None => BitOrder::MostSignificantFirst,
Some(Token::Ident(ref ident)) if ident.as_ref() == msb => BitOrder::MostSignificantFirst,
Some(Token::Ident(ref ident)) if ident.as_ref() == lsb => BitOrder::LeastSignificantFirst,
Some(_) => panic!("expected {} or {} for bit_order", msb, lsb),
Expand Down Expand Up @@ -292,9 +286,9 @@ proc_macro_expr_impl! {
pub fn internal_decode_array(input: TokenStream) -> TokenStream {
let mut hash_map = parse_map(input.into_iter());
let encoding = get_encoding(&mut hash_map);
check_present(&mut hash_map, "name");
check_present(&hash_map, "name");
let name = get_string(&mut hash_map, "name");
check_present(&mut hash_map, "input");
check_present(&hash_map, "input");
let input = get_string(&mut hash_map, "input");
check_empty(hash_map);
let output = encoding.decode(input.as_bytes()).unwrap();
Expand All @@ -306,7 +300,7 @@ pub fn internal_decode_array(input: TokenStream) -> TokenStream {
pub fn internal_decode_slice(input: TokenStream) -> TokenStream {
let mut hash_map = parse_map(input.into_iter());
let encoding = get_encoding(&mut hash_map);
check_present(&mut hash_map, "input");
check_present(&hash_map, "input");
let input = get_string(&mut hash_map, "input");
check_empty(hash_map);
format!("{:?}", encoding.decode(input.as_bytes()).unwrap()).parse().unwrap()
Expand All @@ -317,7 +311,7 @@ proc_macro_expr_impl! {
pub fn internal_decode_slice_impl(input: &str) -> String {
let mut hash_map = parse_map(input);
let encoding = get_encoding(&mut hash_map);
check_present(&mut hash_map, "input");
check_present(&hash_map, "input");
let input = get_string(&mut hash_map, "input");
check_empty(hash_map);
format!("{:?}", encoding.decode(input.as_bytes()).unwrap())
Expand Down
47 changes: 29 additions & 18 deletions lib/src/lib.rs
Expand Up @@ -221,9 +221,10 @@ impl<T: Copy> Static<Option<T>> for Os<T> {

macro_rules! dispatch {
(let $var: ident: bool = $val: expr; $($body: tt)*) => {
match $val {
false => { let $var = Bf; dispatch!($($body)*) },
true => { let $var = Bt; dispatch!($($body)*) },
if $val {
let $var = Bt; dispatch!($($body)*)
} else {
let $var = Bf; dispatch!($($body)*)
}
};
(let $var: ident: usize = $val: expr; $($body: tt)*) => {
Expand All @@ -248,12 +249,12 @@ macro_rules! dispatch {

unsafe fn chunk_unchecked(x: &[u8], n: usize, i: usize) -> &[u8] {
debug_assert!((i + 1) * n <= x.len());
let ptr = x.as_ptr().offset((n * i) as isize);
let ptr = x.as_ptr().add(n * i);
std::slice::from_raw_parts(ptr, n)
}
unsafe fn chunk_mut_unchecked(x: &mut [u8], n: usize, i: usize) -> &mut [u8] {
debug_assert!((i + 1) * n <= x.len());
let ptr = x.as_mut_ptr().offset((n * i) as isize);
let ptr = x.as_mut_ptr().add(n * i);
std::slice::from_raw_parts_mut(ptr, n)
}
unsafe fn as_array(x: &[u8]) -> &[u8; 256] {
Expand Down Expand Up @@ -373,12 +374,12 @@ fn encode_block<B: Static<usize>, M: Static<bool>>(
let bit = bit.val();
let msb = msb.val();
let mut x = 0u64;
for i in 0 .. input.len() {
x |= (input[i] as u64) << 8 * order(msb, enc(bit), i);
for (i, input) in input.iter().enumerate() {
x |= u64::from(*input) << (8 * order(msb, enc(bit), i));
}
for i in 0 .. output.len() {
let y = x >> bit * order(msb, dec(bit), i);
output[i] = symbols[y as usize % 256];
for (i, output) in output.iter_mut().enumerate() {
let y = x >> (bit * order(msb, dec(bit), i));
*output = symbols[y as usize % 256];
}
}
fn encode_mut<B: Static<usize>, M: Static<bool>>(
Expand Down Expand Up @@ -414,10 +415,10 @@ fn decode_block<B: Static<usize>, M: Static<bool>>(
for j in 0 .. input.len() {
let y = values[input[j] as usize];
check!(j, y < 1 << bit);
x |= (y as u64) << bit * order(msb, dec(bit), j);
x |= u64::from(y) << (bit * order(msb, dec(bit), j));
}
for j in 0 .. output.len() {
output[j] = (x >> 8 * order(msb, enc(bit), j)) as u8;
for (j, output) in output.iter_mut().enumerate() {
*output = (x >> (8 * order(msb, enc(bit), j))) as u8;
}
Ok(())
}
Expand Down Expand Up @@ -495,8 +496,8 @@ fn encode_pad<B: Static<usize>, M: Static<bool>, P: Static<Option<u8>>>(
debug_assert_eq!(output.len(), encode_pad_len(bit, spad, input.len()));
let olen = encode_base_len(bit, input.len());
encode_base(bit, msb, symbols, input, &mut output[.. olen]);
for i in olen .. output.len() {
output[i] = pad;
for output in output.iter_mut().skip(olen) {
*output = pad;
}
}

Expand Down Expand Up @@ -716,6 +717,7 @@ fn decode_wrap_block<B: Static<usize>, M: Static<bool>, P: Static<bool>>(
// of the first padding character of the invalid padding.
// Fails with Trailing if there are non-zero trailing bits.
// Fails with Length if input length (without ignored characters) is invalid.
#[allow(clippy::too_many_arguments)]
fn decode_wrap_mut<B: Static<usize>, M: Static<bool>, P: Static<bool>, I: Static<bool>>(
bit: B, msb: M, ctb: bool, values: &[u8; 256], pad: P, has_ignore: I, input: &[u8],
output: &mut [u8],
Expand Down Expand Up @@ -1204,6 +1206,12 @@ impl Specification {
}
}

impl Default for Specification {
fn default() -> Self {
Self::new()
}
}

impl Encoding {
fn sym(&self) -> &[u8; 256] {
unsafe { as_array(&self.0[0 .. 256]) }
Expand Down Expand Up @@ -1270,6 +1278,7 @@ impl Encoding {
/// ```
///
/// [`encode_len`]: struct.Encoding.html#method.encode_len
#[allow(clippy::cyclomatic_complexity)]
pub fn encode_mut(&self, input: &[u8], output: &mut [u8]) {
assert_eq!(output.len(), self.encode_len(input.len()));
dispatch! {
Expand Down Expand Up @@ -1359,6 +1368,7 @@ impl Encoding {
/// [`Length`]: enum.DecodeKind.html#variant.Length
/// [`read`]: struct.DecodePartial.html#structfield.read
/// [`written`]: struct.DecodePartial.html#structfield.written
#[allow(clippy::cyclomatic_complexity)]
pub fn decode_mut(&self, input: &[u8], output: &mut [u8]) -> Result<usize, DecodePartial> {
assert_eq!(Ok(output.len()), self.decode_len(input.len()));
dispatch! {
Expand Down Expand Up @@ -1562,10 +1572,11 @@ impl Specification {
return Ok(());
}
check!(SpecificationError(Duplicate(i)), v[i as usize] == INVALID);
Ok(v[i as usize] = x)
v[i as usize] = x;
Ok(())
};
for v in 0 .. symbols.len() {
set(&mut values, symbols[v], v as u8)?;
for (v, symbols) in symbols.iter().enumerate() {
set(&mut values, *symbols, v as u8)?;
}
let msb = self.bit_order == MostSignificantFirst;
let ctb = self.check_trailing_bits || 8 % bit == 0;
Expand Down

0 comments on commit 9adbb42

Please sign in to comment.