morse_lib/
lib.rs

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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
//! # Morse Library
//!
//! Morse Library is a library parsing text and binary data
//! to Morse Code and vice versa.
//!
//! By default Morse Library support only International rules and codes for Morse
//! Code, but if needed it support extend metods to convert any language-specific
//! Morse Code implementations. The library provides **Lines**, **Dots** and **Whitespace**
//! aliasing. That means output Morse Code could be not only lines, dots and whitespaces,
//! but also any UTF-8 emoji or even text! Also the library support playing Morse Code by sound
//! if needed, and customization of speed, frequency of playing.
//!
//! ## Extend multimultilingualism
//!
//! To provide custom language conversion the library accept two functions:
//! - first that match conversion from character to Morse Code
//! - second that match conversion from Morse Code to Character
//!
//! ## Data formats
//!
//! The following is a list of data formats that have been implemented
//! for Morse Library.
//!
//! ### Input
//!
//! - [String], the casual String or &str that contains text
//! - [Binary String], the casual String or &str that contains Morse Code represented by byte code.
//!
//! ### Output
//!
//! - [String], the casual String that contains Morse Code. By default **lines** and **dots**, but could be
//!   any UTF-8 character or even string
//! - [Binary String], the casual String that contains Morse Code represented by byte code.
//! - [Sound], sound representation of Morse Code

use std::{cell::RefCell, thread, time};

// Private modules
mod morse_char;
use morse_char::*;

mod morse_processors;
use morse_processors::*;

mod display_chars;
use display_chars::DisplayChars;

mod sound;
use sound::Sound;

mod iterator;
use iterator::*;
// Public modules
mod morse_unit;
pub use morse_unit::MorseUnit;

mod error;
pub use error::*;

/// ## Main library struct.
///
/// All magic going here
#[derive(Debug, PartialEq, Clone)]
pub struct Morse {
    morse_str: Vec<MorseChar>,
    language: String,
    display_as: DisplayChars,
    sound: Sound,
    from_char_converter: fn(char) -> MorseResult<Vec<MorseUnit>>,
    into_char_converter: fn(Vec<MorseUnit>) -> MorseResult<char>,
}

impl Morse {
    /// Creates extended Morse Code struct.
    /// # Examples
    ///
    /// ```
    /// use morse_lib::{Morse, MorseUnit, MorseError, MorseResult};
    /// use MorseUnit::{Dot, Line, Whitespace};
    ///
    /// fn from_char(letter: char) -> MorseResult<Vec<MorseUnit>>{
    ///     match letter {
    ///         'a' => Ok(vec![Dot, Line]),
    ///         'б' => Ok(vec![Line, Dot, Dot, Dot]),
    ///         'в' => Ok(vec![Dot, Line, Line]),
    ///         'г' => Ok(vec![Dot, Dot, Dot, Dot]),
    ///         ' ' => Ok(vec![Whitespace]),
    ///           _ => Err(MorseError::InvalidChar)
    ///     }
    /// }
    ///
    /// fn into_char(letter: Vec<MorseUnit>) -> MorseResult<char> {
    ///     if letter.len() == 1 && letter[0] == Whitespace {
    ///         return Ok(' ');
    ///     } else if letter.len() == 2 && letter[0] == Dot && letter[1] == Line {
    ///         return Ok('а')
    ///     } else if letter.len() == 3 && letter[0] == Dot && letter[1] == Line && letter[2] == Line {
    ///         return Ok('в');
    ///     } else if letter.len() == 4 {
    ///         if letter[0] == Line && letter[1] == Dot && letter[2] == Dot && letter[3] == Dot {
    ///             return Ok('б');
    ///         } else {
    ///             return Ok('г');
    ///         }
    ///     } else {
    ///         Err(MorseError::InvalidMorseSequence)
    ///     }
    /// }
    ///
    /// let morse = Morse::new("Ukrainian".to_string(), from_char, into_char);
    /// ```
    pub fn new(
        language: String,
        from_char: fn(char) -> MorseResult<Vec<MorseUnit>>,
        into_char: fn(Vec<MorseUnit>) -> MorseResult<char>,
    ) -> Morse {
        Morse {
            morse_str: Vec::new(),
            language,
            display_as: DisplayChars::default(),
            sound: Sound::default(),
            from_char_converter: from_char,
            into_char_converter: into_char,
        }
    }
    /// Creates International Morse Code struct from text.
    /// # Examples
    ///
    /// ```
    /// use morse_lib::Morse;
    ///
    /// let morse = Morse::from_int_text("sos").unwrap();
    ///
    /// assert_eq!(
    ///        morse.to_string(),
    ///        ". . .   ⚊ ⚊ ⚊   . . ."
    ///    );
    /// ```
    pub fn from_int_text(text: &str) -> MorseResult<Morse> {
        let mut morse_str: Vec<MorseChar> = Vec::new();

        for letter in text.chars() {
            morse_str.push(MorseChar::from_char(
                letter,
                "International",
                from_int_char,
            )?);
        }

        Ok(Morse {
            morse_str,
            ..Morse::default()
        })
    }
    /// Parse text into Morse Code.
    pub fn parse_text(&mut self, text: &str) -> MorseResult<()> {
        let mut morse: Vec<MorseChar> = Vec::new();

        for letter in text.chars() {
            morse.push(MorseChar::from_char(
                letter,
                &self.language,
                self.from_char_converter,
            )?);
        }

        Ok(())
    }

    /// Creates International Morse Code struct from binary.
    /// # Examples
    ///
    /// ```
    /// use morse_lib::Morse;
    ///
    /// let morse = Morse::from_int_bin("101010001110111011100010101").unwrap();
    ///
    /// assert_eq!(
    ///        morse.to_string(),
    ///        ". . .   ⚊ ⚊ ⚊   . . ."
    ///    );
    /// ```
    pub fn from_int_bin(bin: &str) -> MorseResult<Morse> {
        let words: Vec<&str> = bin.split("0000000").collect();
        let mut morse_str: Vec<MorseChar> = Vec::new();

        for word in words {
            let letters: Vec<&str> = word.split("000").collect();

            for letter in letters {
                morse_str.push(MorseChar::from_bin(letter, "International", into_int_char)?);
            }
        }

        Ok(Morse {
            morse_str,
            ..Morse::default()
        })
    }
    /// Parse binary into Morse Code.
    pub fn parse_bin(&mut self, bin: &str) -> MorseResult<()> {
        let words: Vec<&str> = bin.split("0000000").collect();

        for word in words {
            let letters: Vec<&str> = word.split("000").collect();

            for letter in letters {
                self.morse_str.push(MorseChar::from_bin(
                    letter,
                    &self.language,
                    self.into_char_converter,
                )?);
            }
        }

        Ok(())
    }

    /// Play sound that represent Morse Code.
    pub fn to_beep(&self) {
        let morse_str = RefCell::new(self.morse_str.clone());
        for (idx, m_char) in morse_str.borrow_mut().iter_mut().enumerate() {
            m_char.frequency(self.sound.frequency);
            m_char.play_speed(self.sound.speed);

            m_char.to_beep();

            // The space between letters is three units
            if idx < self.morse_str.len() - 1 {
                thread::sleep(time::Duration::from_secs(3));
            }
        }
    }
    /// Return String value that contains stored language label.
    pub fn get_language(&self) -> String {
        self.language.clone()
    }
    /// Creates alias for dot in output string.
    /// # Examples
    ///
    /// ```
    /// use morse_lib::Morse;
    ///
    /// let mut morse = Morse::from_int_text("sos").unwrap();
    /// morse.dot_as("🔥");
    ///
    /// assert_eq!(
    ///        morse.to_string(),
    ///        "🔥 🔥 🔥   ⚊ ⚊ ⚊   🔥 🔥 🔥"
    ///    );
    /// ```
    pub fn dot_as(&mut self, alias: &str) {
        self.display_as.dot = alias.to_string();
    }
    /// Creates alias for line in output string.
    /// # Examples
    ///
    /// ```
    /// use morse_lib::Morse;
    ///
    /// let mut morse = Morse::from_int_text("sos").unwrap();
    /// morse.line_as("➖");
    ///
    /// assert_eq!(
    ///        morse.to_string(),
    ///        ". . .   ➖ ➖ ➖   . . ."
    ///    );
    /// ```
    pub fn line_as(&mut self, alias: &str) {
        self.display_as.line = alias.to_string();
    }
    /// Creates alias for whitespace in output string.
    /// # Examples
    ///
    /// ```
    /// use morse_lib::Morse;
    ///
    /// let mut morse = Morse::from_int_text("s o").unwrap();
    /// morse.whitespace_as("🚧");
    ///
    /// assert_eq!(
    ///        morse.to_string(),
    ///        ". . .   🚧   ⚊ ⚊ ⚊"
    ///    );
    /// ```
    pub fn whitespace_as(&mut self, alias: &str) {
        self.display_as.whitespace = alias.to_string();
    }
    /// Set sound frequency in MHz.
    /// # Examples
    ///
    /// ```
    /// use morse_lib::Morse;
    ///
    /// let mut morse = Morse::from_int_text("s o").unwrap();
    /// morse.frequency(643.0);
    /// ```
    pub fn frequency(&mut self, frequency: f32) {
        self.sound.frequency = frequency;
    }
    /// Set sound speed.
    /// 1 - normal speed
    /// > 1 - faster
    /// < 1 - slower
    /// # Examples
    ///
    /// ```
    /// use morse_lib::Morse;
    ///
    /// let mut morse = Morse::from_int_text("s o").unwrap();
    /// morse.play_speed(2.0);
    /// ```
    pub fn play_speed(&mut self, speed: f32) {
        self.sound.speed = speed;
    }
    /// Creates binary-formatted Morse Code.
    /// # Examples
    ///
    /// ```
    /// use morse_lib::Morse;
    ///
    /// let morse = Morse::from_int_text("sos").unwrap();
    ///
    /// assert_eq!(
    ///        morse.to_bin_str(),
    ///        "101010001110111011100010101"
    ///    );
    /// ```
    pub fn to_bin_str(&self) -> String {
        let mut string = String::new();

        for (idx, m_char) in self.morse_str.iter().enumerate() {
            string.push_str(&m_char.to_bin_str());

            // The space between letters is three units
            if idx < self.morse_str.len() - 1 {
                string.push_str("000");
            }
        }

        string
    }
    /// Convert Morse Code back to text.
    /// # Examples
    ///
    /// ```
    /// use morse_lib::Morse;
    ///
    /// let morse = Morse::from_int_bin("101010001110111011100010101").unwrap();
    /// let text = morse.to_text();
    ///
    /// assert_eq!(
    ///        text,
    ///        "sos"
    ///    );
    /// ```
    pub fn to_text(&self) -> String {
        let mut text = String::new();

        for m_char in &self.morse_str {
            text.push(m_char.get_letter());
        }

        text
    }

    /// Now we can iterate:
    /// ```
    /// use morse_lib::Morse;
    ///
    /// let morse = Morse::from_int_text("sos").unwrap();
    /// for char in morse.iter() {
    ///     println!("{}", char);
    /// }
    /// ```
    pub fn iter(&self) -> MorseIterator {
        MorseIterator::init(self)
    }
}

impl IntoIterator for Morse {
    type Item = MorseChar;
    type IntoIter = MorseIntoIterator;

    /// ```
    /// use morse_lib::Morse;
    ///
    /// let morse = Morse::from_int_text("sos").unwrap();
    /// for char in morse {
    /// println!("{}", char);
    /// }
    /// ```
    fn into_iter(self) -> MorseIntoIterator {
        MorseIntoIterator { morse: self }
    }
}

impl Default for Morse {
    fn default() -> Self {
        Self {
            morse_str: Vec::new(),
            language: "International".to_string(),
            display_as: DisplayChars::default(),
            sound: Sound::default(),
            from_char_converter: from_int_char,
            into_char_converter: into_int_char,
        }
    }
}

impl ToString for Morse {
    /// Return String value of Morse Code.
    fn to_string(&self) -> String {
        let mut string = String::new();
        let morse = RefCell::new(self.morse_str.clone());

        for (idx, m_char) in morse.borrow_mut().iter_mut().enumerate() {
            m_char.dot_as(&self.display_as.dot);
            m_char.line_as(&self.display_as.line);
            m_char.whitespace_as(&self.display_as.whitespace);
            string.push_str(&m_char.to_string());

            // The space between letters is three units
            if idx < self.morse_str.len() - 1 {
                string.push_str("   ");
            }
        }

        string
    }
}

#[cfg(test)]
mod morse_tests {
    use super::*;

    #[test]
    fn create_from_text_str() {
        assert_eq!(
            Morse::from_int_text("Hello").unwrap().to_bin_str(),
            "1010101000100010111010100010111010100011101110111"
        );
    }

    #[test]
    fn create_from_binary_str() {
        const HELLO_BIN: &str = "1010101000100010111010100010111010100011101110111";
        assert_eq!(
            Morse::from_int_bin(HELLO_BIN).unwrap().to_bin_str(),
            HELLO_BIN
        );
    }

    #[test]
    fn get_language() {
        assert_eq!(
            Morse::from_int_text("hello").unwrap().get_language(),
            "International".to_string()
        );
        assert_eq!(
            Morse::from_int_bin("1").unwrap().get_language(),
            "International".to_string()
        );
    }

    #[test]
    fn to_string() {
        assert_eq!(
            Morse::from_int_text("hi u").unwrap().to_string(),
            ". . . .   . .       . . ⚊"
        );
    }

    #[test]
    fn to_bin_str() {
        assert_eq!(
            Morse::from_int_text("hi u").unwrap().to_bin_str(),
            "101010100010100000001010111"
        );
    }
    #[test]
    fn set_aliases_for_whitespace_lines_and_dots() {
        let mut morse = Morse::from_int_text("hi u").unwrap();

        morse.dot_as("🔥");
        morse.line_as("➖");
        morse.whitespace_as("🚧");

        assert_eq!(morse.to_string(), "🔥 🔥 🔥 🔥   🔥 🔥   🚧   🔥 🔥 ➖");
    }
}