1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
// Copyright 2017 Daniel P. Clark & base_custom Developers
// 
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://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.
#![deny(missing_docs,trivial_casts,trivial_numeric_casts,
        missing_debug_implementations, missing_copy_implementations,
        unsafe_code,unstable_features,unused_import_braces,unused_qualifications)
]
//! # base_custom
//!
//! allows you to use any set of characters as your own numeric base and convert
//! to and from decimal.  This can be taken advantage of in various ways:
//!
//! * Mathematics: number conversion
//!
//! * Brute force sequencing
//!
//! * Rolling ciphers
//!
//! * Moderate information concealment
//!
//! * Other potential uses such as deriving music or art from numbers
//!
//! ## To Include It
//!
//! Add `base_custom` to your dependencies section of your `Cargo.toml` file.
//!
//! ```text
//! [dependencies]
//! base_custom = "^0.1"
//! ```
//!
//! In your rust files where you plan to use it put this at the top
//!
//! ```text
//! extern crate base_custom;
//! use base_custom::BaseCustom;
//! ```
//!
//! This is licensed under MIT or APACHE 2.0 at your option.

use std::collections::HashMap;
use std::string::String;
use std::fmt;
use std::ops::Range;

/// The BaseCustom struct holds the information to perform number conversions
/// via the `gen` and `decimal` methods.
///
/// A new instance of BaseCustom can be created with either
///
/// * `BaseCustom::<char>::new(Vec<char>)`
/// * `BaseCustom::<char>::from_ordinal_range(Range)`
/// * `BaseCustom::<String>::new(String, Option<char>)`
///
/// _If you are going to provide a delimiter you need to use the `<String>` implementation.
/// A delimiter is optional._
///
/// The primitives for BaseCustom get built from the provides characters or string groups
/// and conversion methods are available to use then.  String groupings will be single character
/// strings if no delimiter is given, otherwise they may be strings of any length split only
/// by the delimiter provided.
pub struct BaseCustom<T> {
  primitives: Vec<T>,
  primitives_hash: HashMap<T, u8>,
  /// The size of the base
  pub base: u64,
  delim: Option<char>,
}

impl fmt::Debug for BaseCustom<char> {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    write!(f,
      "BaseCustom\n\tprimitives: {:?}\n\tprimitives_hash: {:?}\n\tbase: {}\n\tdelim: {:?}",
      self.primitives, self.primitives_hash, self.base, self.delim
    )
  }
}

impl fmt::Debug for BaseCustom<String> {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    write!(f,
      "BaseCustom\n\tprimitives: {:?}\n\tprimitives_hash: {:?}\n\tbase: {}\n\tdelim: {:?}",
      self.primitives, self.primitives_hash, self.base, self.delim
    )
  }
}

fn unique(chars: Vec<char>) -> Vec<char> {
  let mut a = chars.clone();
  for x in (0..a.len()).rev() {
    for y in (x+1..a.len()).rev() {
      if a[x] == a[y] {
        a.remove(y);
      }
    }
  }
  a
}

impl BaseCustom<char> {

  /// 'new' creates a new BaseCustom instance and propogates the values for converting
  /// numeric bases.
  ///
  /// `new` for `BaseCustom<char>` requires a `Vec<char>` as its parameters and units
  /// for measuring the custom numeric base will only be one character long each.
  pub fn new(chars: Vec<char>) -> BaseCustom<char> {
    if chars.iter().count() < 2 { panic!("Too few numeric units! Provide two or more.") }
    if chars.iter().count() > 255 { panic!("Too many numeric units!") }

    let chars = unique(chars);

    let mut mapped = HashMap::with_capacity(chars.iter().count());
    for (i,c) in chars.iter().enumerate() {
      mapped.insert(c.clone(), i as u8);
    }
    BaseCustom::<char> {
      primitives: chars.clone(),
      primitives_hash: mapped,
      base: chars.iter().count() as u64,
      delim: None,
    }
  }

  /// `gen` returns a String computed from the character mapping and 
  /// positional values the given u64 parameter evalutes to for your
  /// custom base
  ///
  /// # Example
  /// ```
  /// use base_custom::BaseCustom;
  ///
  /// let base2 = BaseCustom::<char>::new(vec!['0','1']);
  /// assert_eq!(base2.gen(3), "11");
  /// ```
  ///
  /// # Output
  /// ```text
  /// "11"
  /// ```
  pub fn gen(&self, input_val: u64) -> String {
    if input_val == 0 {
      return format!("{}", self.primitives[0]);
    }
    let mut number = input_val;
    let mut result = String::new();
    loop {
      if number == 0 { break };
      result.insert(0, self.primitives[(number % self.base) as usize]);
      number = number/self.base;
    };
    format!("{}", result)
  }

  /// `char` returns a char straight from the character mapping.
  /// decimal value must be within character range for a Some result.
  ///
  /// # Example
  /// ```
  /// use base_custom::BaseCustom;
  ///
  /// let base10 = BaseCustom::<char>::new("0123456789".chars().collect());
  /// assert_eq!(base10.char(9), Some('9'));
  /// ```
  ///
  /// # Output
  /// ```text
  /// '9'
  /// ```
  pub fn char(&self, input_val: usize) -> Option<char> {
    if input_val > self.primitives.len() { return None }
    Some(self.primitives[input_val])
  }


  /// `decimal` returns a u64 value on computed from the units that form
  /// the custom base.
  ///
  /// # Example
  /// ```
  /// use base_custom::BaseCustom;
  ///
  /// let base2 = BaseCustom::<char>::new(vec!['0','1']);
  /// assert_eq!(base2.decimal("00011"), 3);
  /// ```
  ///
  /// # Output
  /// ```text
  /// 3
  /// ```
  pub fn decimal<S>(&self, input_val: S) -> u64
    where S: Into<String> {
    let input_val = input_val.into();

    input_val.chars().rev().enumerate().fold(0, |sum, (i, chr)|
      sum + (self.primitives_hash[&chr] as u64) * self.base.pow(i as u32)
    )
  }

  /// Returns the zero value of your custom base
  pub fn zero(&self) -> &char {
    &self.primitives[0]
  }

  /// Returns the one value of your custom base
  pub fn one(&self) -> &char {
    &self.primitives[1]
  }

  /// Returns the nth value of your custom base
  /// 
  /// Like most indexing operations, the count starts from zero, so nth(0) returns the first value,
  /// nth(1) the second, and so on.
  pub fn nth(&self, pos: usize) -> Option<&char> {
    if pos > 0 && pos < self.base as usize {
      Some(&self.primitives[pos])
    } else {
      None
    }
  }

  /// Create a custom numeric base from an ascii range of ordinal values
  ///
  /// This method currently restricts the ascii character range of the
  /// 95 typical characters starting from 32 and ending with 127.  If you'd
  /// like to use characters outside of this range please use the `new` method.
  pub fn from_ordinal_range(range: Range<u32>) -> BaseCustom<char> {
    let min = std::cmp::max(32, range.start);
    let max = std::cmp::min(127, range.end);
    let mut chars: Vec<char> = Vec::with_capacity(std::cmp::min(range.len(), 95));
    for chr in min..max {
      chars.push(std::char::from_u32(chr).unwrap());
    }
    BaseCustom::<char>::new(chars)
  }
}

impl BaseCustom<String> {

  /// 'new' creates a new BaseCustom instance and propogates the values for converting
  /// numeric bases.
  /// 
  /// `new` for `BaseCustom<String>` requires a `String` as its first parameter and units
  /// for measuring the custom numeric base can be one character long, or many in length.
  /// The second parameter is of `Option<char>` is a delimiter option for determining whether
  /// to split the string into single character length strings or possibly multiple length
  /// if the delimiter is partitioning the string in such a way.
  pub fn new<S>(chars: S, delim: Option<char>) -> BaseCustom<String> 
    where S: Into<String> {
    let chars = chars.into();
    let mut mapped = HashMap::with_capacity(chars.len());
    let strings: Vec<String> = match delim {
      Some(c) => chars.split(c).map(|c| format!("{}", c)).filter(|s| !s.is_empty()).collect(),
      None => unique(chars.chars().collect()).iter().map(|c| format!("{}", c)).filter(|s| !s.is_empty()).collect(),
    };
    if strings.iter().count() < 2 { panic!("Too few numeric units! Provide two or more.") }
    if strings.iter().count() > 255 { panic!("Too many numeric units!") }
    let mut enumerator = strings.iter().enumerate();
    loop {
      match enumerator.next() {
        Some((i,c)) => mapped.insert(format!("{}", c), i as u8),
        None => break,
      };
    }
    BaseCustom::<String> {
      primitives: strings.iter().map(|s| format!("{}", s)).collect(),
      primitives_hash: mapped,
      base: strings.len() as u64,
      delim: delim,
    }
  }

  /// `gen` returns a String computed from the character mapping and 
  /// positional values the given u64 parameter evalutes to for your
  /// custom base
  ///
  /// # Example
  /// ```
  /// use base_custom::BaseCustom;
  ///
  /// let base2 = BaseCustom::<String>::new("01", None);
  /// assert_eq!(base2.gen(3), "11");
  /// ```
  ///
  /// # Output
  /// ```text
  /// "11"
  /// ```
  pub fn gen(&self, input_val: u64) -> String {
    if input_val == 0 {
      return format!("{}", self.primitives[0]);
    }
    let mut number = input_val;
    let mut result = String::new();
    loop {
      if number == 0 { break };
      if self.delim != None { result.insert(0, self.delim.unwrap()) };
      result.insert_str(0, &self.primitives[(number % self.base) as usize][..]);
      number = number/self.base;
    };
    format!("{}", result)
  }

  /// `decimal` returns a u64 value on computed from the units that form
  /// the custom base.
  ///
  /// # Example
  /// ```
  /// use base_custom::BaseCustom;
  ///
  /// let base2 = BaseCustom::<String>::new("01", None);
  /// assert_eq!(base2.decimal("00011"), 3);
  /// ```
  ///
  /// # Output
  /// ```text
  /// 3
  /// ```
  pub fn decimal<S>(&self, input_val: S) -> u64
    where S: Into<String> {
    let input_val = input_val.into();
    let strings: Vec<String> = match self.delim {
      Some(c) => input_val.split(c).filter(|c| !c.is_empty()).map(|c| format!("{}", c)).collect(),
      None => input_val.chars().map(|c| format!("{}", c)).collect(),
    };

    strings.iter().rev().enumerate().fold(0, |sum, (i, chr)|
      sum + (self.primitives_hash[&chr[..]] as u64) * self.base.pow(i as u32)
    )
  }

  /// Returns the zero value of your custom base
  pub fn zero(&self) -> &str {
    &self.primitives[0]
  }

  /// Returns the one value of your custom base
  pub fn one(&self) -> &str {
    &self.primitives[1]
  }

  /// Returns the nth value of your custom base
  /// 
  /// Like most indexing operations, the count starts from zero, so nth(0) returns the first value,
  /// nth(1) the second, and so on.
  pub fn nth(&self, pos: usize) -> Option<&str> {
    if pos > 0 && pos < self.base as usize {
      Some(&self.primitives[pos])
    } else {
      None
    }
  }
}

impl PartialEq for BaseCustom<char> {
  fn eq(&self, other: &BaseCustom<char>) -> bool {
    self.primitives == other.primitives &&
      self.base == other.base &&
      self.delim == other.delim
  }
}

impl PartialEq for BaseCustom<String> {
  fn eq(&self, other: &BaseCustom<String>) -> bool {
    self.primitives == other.primitives &&
      self.base == other.base &&
      self.delim == other.delim
  }
}