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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
//! This project is a library for converting between different Ascii representations in the Rust language.
//! This is made for Rust programs that need to convert an ascii value.
//! This library has methods for converting any of the supported representations to any other.
//! 
//! ---
//! 
//! each supported ascii representation has it's type listed below:
//! 
//! - Binrary = `Vec<u32>`.
//! 
//! - Decimals = `Vec<u8>`.
//! 
//! - characters = `String`.
//! 
//! ---
//! 
//! Each method uses the `Result` enum for the return type so this will need to be unwrapped to get the actual value.
//! An example of how best to deal with the Results enum is below:
//! ```
//! use ascii_converter::*;
//! 
//! let input = vec![72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33];
//!
//! match decimals_to_string(&input){
//!     Ok(num) => println!("* Output: {}", num),
//!     Err(e) => println!("* Error: {}", e),
//! };
//! ```
//! 

/// This function returns a string's decimal values
/// 
/// takes a string and finds the decimal assciated with that character according to the Ascii table.
/// each decimal is pushed into a `Vec<u8>` .
/// 
/// charcters inside the string should only be in the ascii range  of `32 - 126` . any other
/// character will cause an error.
/// 
/// example of unsupported characters: `£` , `☢️` , `Æ`
/// 
/// # Example
/// ```
/// use ascii_converter::*;
/// 
/// let  expected = vec![72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33];
///    
/// assert_eq!(string_to_decimals("Hello world!").unwrap(), expected);
/// ```
pub fn  string_to_decimals(text: &str) -> Result<Vec<u8>, String>{   

    let mut vec = Vec::new();

    for c in text.chars(){

        if !c.is_ascii() {
            return Err("A character in the string isn't apart of the ascii table".to_string());
        }

        vec.push(c as u8);
    }

    Ok(vec)
}

/// This function returns a binary representations of decimal numbers
/// 
/// this function takes a `Vec<u8>` , it's elements should represent ascii characters. 
/// An error will be thrown if the a value is above `126` as this is the end of the ascii range. 
/// 
/// # Example
/// ```
/// use ascii_converter::*;
/// 
/// let  hello_world = vec![72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33];
/// let expected = vec![1001000, 1100101, 1101100, 1101100, 1101111, 100000, 1110111, 1101111, 1110010, 1101100, 1100100, 100001];
///    
/// assert_eq!(decimals_to_binary(&hello_world).unwrap(), expected);
/// ```
pub fn decimals_to_binary(dec_vec: &Vec<u8>) ->  Result<Vec<u32>, String>{
    
    let mut binary = Vec::new();

    for i in dec_vec.iter() {
        if i > &126 {
            return Err("this function doesn't support values over 126".to_string());
        }

        binary.push(dec_to_bit(*i));            
    }

    Ok(binary)
}

/// This function takes in binary numbers and will return the decimal version.
/// 
/// This function takes a `Vec<u8>`, it's elements should represent binary values.  
/// if a value passed in contains a digit that  isn't `1` or `0` an error will be thrown.
/// 
/// # Example
/// ```
/// use ascii_converter::*;
/// 
/// let hello_world = vec![1001000, 1100101, 1101100, 1101100, 1101111, 100000, 1110111, 1101111, 1110010, 1101100, 1100100, 100001];
/// let  expected = vec![72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33];
///    
/// assert_eq!(binary_to_decimal(&hello_world).unwrap(), expected);
/// ```
pub fn binary_to_decimal(bin_vec: &Vec<u32>) -> Result<Vec<u8>, String>{

    let mut decimals = Vec::new();

    for b in bin_vec.iter(){

        for c in b.to_string().chars() {
            if c != '0' && c != '1' {
                return Err("number passed in isn't binary".to_string());
            }
        }

        match bits_to_dec(b) {
            Ok(t) => (decimals.push(t)),
            Err(_) => return Err("FAIL".to_string()),
        };
    }

    Ok(decimals)
}

/// This function takes in Decimal numbers and will return the string they represent 
/// 
/// this function will takes a `Vec<u8>` and changes each element to a `char` then pushs it into a string.
/// if a element of the vec passed in is below 32 or above 126 it will cause an error to be thrown.
/// 
/// # Example
/// ```
/// use ascii_converter::*;
/// 
/// let hello_world = vec![72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33];
///    
/// assert_eq!(decimals_to_string(&hello_world).unwrap(), "Hello world!".to_string());
/// ```
pub fn decimals_to_string(dec_vec: &Vec<u8>) -> Result<String, String>{

    let mut text = String::new();

    for d in dec_vec.iter(){

        if !(d >=  &32 && d <= &126) {
            return Err("the number is outside the ascii range".to_string());
        }

        text.push(*d as char);
    }

    Ok(text)
}

/// This function returns the binary numbers of each letter passed in. 
/// 
/// This function takes each `char` of the `&str` passed in and converts it to a binary number which is represented
/// as a `u32`. These are then pushed into a `Vec<u32>`. 
/// 
/// # Example
/// ```
/// use ascii_converter::*;
/// 
/// let expected = vec![1001000, 1100101, 1101100, 1101100, 1101111, 100000, 1110111, 1101111, 1110010, 1101100, 1100100, 100001];
/// 
/// assert_eq!(string_to_binary("Hello world!").unwrap(), expected);
/// ```
pub fn string_to_binary(text: &str) -> Result<Vec<u32>, String>{

    let dec = string_to_decimals(text);

    let dec = match dec {
        Ok(new_dec_vec) => new_dec_vec,
        Err(error) => return Err(error.to_string()), 
    };

    let bin = decimals_to_binary(&dec);

    match bin {
        Ok(ref bin_vec) => bin_vec,
        Err(error) => return Err(error),
    };

    return bin;

}

/// This function returns a string made from the binary values passed to it.
/// 
/// This function will take a `Vec<u32>`, each `u32` element will be converted to
/// its a `char` value and then return as a `string`.
/// 
/// # Example
/// ```
/// use ascii_converter::*;
/// 
/// let input = vec! [1001000, 1100101, 1101100, 1101100, 1101111, 100000, 1110111, 1101111, 1110010, 1101100, 1100100, 100001];
/// 
/// assert_eq!(binary_to_string(&input).unwrap(), "Hello world!".to_string());
/// ```
 pub fn binary_to_string(bin: &Vec<u32>) -> Result<String, String>{
    
     let dec = binary_to_decimal(&bin);

     let dec = match dec {
         Ok(new_dec_vec) => new_dec_vec, 
         Err(error) => return Err(error.to_string()),
     };

     let string = decimals_to_string(&dec);

      match string {
          Ok(ref dec_string) => dec_string,
          Err(error) => return Err(error.to_string()),
      };

      return string;
 }


 fn dec_to_bit(dec: u8) -> u32 {
    let n = &format!("{:b}", dec);
    let n: u32  = n.trim().parse().unwrap();
    n
}

 fn bits_to_dec(bit: &u32) -> Result<u8, String> {

    match u8::from_str_radix(&bit.to_string(), 2) {
        Ok(dec) => Ok(dec),
        Err(_) => Err("error".to_string()),
    }

}

#[cfg(test)]
mod tests{
    
    mod string_to_decimal_tests{

        use super::super::*;

        
        #[test]
        fn string_to_decimals_test_happy_path(){
    
            let  expected = vec![104, 101, 108, 108, 111];
    
            assert_eq!(string_to_decimals("hello"), Ok(expected));
        }

        #[test]
        fn string_to_decimals_test_happy_none_alphabetical(){
    
            let  expected = vec![49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 32, 33, 36, 37, 94, 38, 42,
             40, 41, 45, 95, 61, 43, 123, 125, 91, 93, 59, 58, 64, 39, 126, 35, 60, 44, 46, 62, 47, 63];
         
            
            assert_eq!(string_to_decimals("1234567890 !$%^&*()-_=+{}[];:@'~#<,.>/?"), Ok(expected));
        }
        
        #[test]
        fn string_to_decimals_test_happy_alphabetical(){
    
            let  expected = vec![113, 119, 101, 114, 116, 121, 117, 105, 111, 112, 97, 115, 100, 102, 103,
             104, 106, 107, 108, 122, 120, 99, 118, 98, 110, 109, 81, 87, 69, 82, 84, 89, 85, 73, 79, 80,
              65, 83, 68, 70, 71, 72, 74, 75, 76, 90, 88, 67, 86, 66, 78, 77];
         
            
            assert_eq!(string_to_decimals("qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM"), Ok(expected));
        }
    
        #[test]
        fn string_to_decimals_test_unhappy_path(){
            
            assert_eq!(string_to_decimals("☢️"), Err("A character in the string isn't apart of the ascii table".to_string()));
        }

    }

    mod decimals_to_binary_tests{

        use super::super::*;

        #[test]
        fn decimals_to_binary_test_happy_path(){
    
            let  input = vec![104, 101, 108, 108, 111];
            let  expected = vec![1101000, 1100101, 1101100, 1101100, 1101111];
            
            assert_eq!(decimals_to_binary(&input), Ok(expected));
        }

        #[test]
        fn decimals_to_binary_test_unhappy_path(){
    
            let  input = vec![127];
            
            assert_eq!(decimals_to_binary(&input), Err("this function doesn't support values over 126".to_string()));
        }

        
        #[test]
        fn decimals_to_binary_test_max_num(){
    
            let  input = vec![126];
            let  expected = vec![01111110];
            
            assert_eq!(decimals_to_binary(&input), Ok(expected));
        }

        #[test]
        fn decimals_to_binary_test_min_num(){
    
            let  input = vec![0];
            let  expected = vec![0];
            
            assert_eq!(decimals_to_binary(&input), Ok(expected));
        }

    }

    mod binary_to_decimal_tests{

        use super::super::*;

        #[test]
        fn binary_to_decimal_test_happy_path(){
    
            let  input = vec![1101000, 1100101, 1101100, 1101100, 1101111];
            let  expected = vec![104, 101, 108, 108, 111];
            
            assert_eq!(binary_to_decimal(&input), Ok(expected));
        }

        #[test]
        fn binary_to_decimal_test_unhappy_path(){
    
            let  input = vec![30340];
            
            assert_eq!(binary_to_decimal(&input), Err("number passed in isn't binary".to_string()));
        }
        
    }

    mod decimals_to_string_tests{

        use super::super::*;

        #[test]
        fn decimals_to_string_test_happy_path(){
            
            let  input = vec![104, 101, 108, 108, 111];
            
            assert_eq!(decimals_to_string(&input), Ok("hello".to_string()));
        }
        
        #[test]
        fn decimals_to_string_test_unhappy_path(){
            
            let  input = vec![168];
            
            assert_eq!(decimals_to_string(&input), Err("the number is outside the ascii range".to_string()));
        }

    }
    
    mod binary_to_string_tests{
        
        use super::super::*;
        
        #[test]
        fn binary_to_string_test_happy_path(){
            
            let  input = vec![1101000, 1100101, 1101100, 1101100, 1101111];
            
            assert_eq!(binary_to_string(&input), Ok("hello".to_string()));
        }
        
        #[test]
        fn binary_to_string_test_unhappy_path_none_binary(){
            
            let  input = vec![104];
            
            assert_eq!(binary_to_string(&input), Err("number passed in isn't binary".to_string()));
        }
        
        #[test]
        fn binary_to_string_test_unhappy_path_out_of_range(){
            
            let  input = vec![1];
            
            assert_eq!(binary_to_string(&input), Err("the number is outside the ascii range".to_string()));
        }
    }

    mod string_to_binary_tests{
        
        use super::super::*;
        
        #[test]
        fn string_to_binary_test_happy_path(){
            
            let  expected = vec![1101000, 1100101, 1101100, 1101100, 1101111];
            
            assert_eq!(string_to_binary("hello"), Ok(expected));
        }

        #[test]
        fn string_to_binary_test_unhappy_path(){
                        
            assert_eq!(string_to_binary("☢️"), Err("A character in the string isn't apart of the ascii table".to_string()));
        }

    }

}