stegtext 0.1.2

Text steganography command-line tool and library.
Documentation
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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
//! Text [steganography][] tool.
//!
//! Hide secret value in [UTF-8][] text using [homoglyphs][].
//!
//! See also: [IDN homograph attack][].
//!
//! # Examples
//!
//! Hide secret in text:
//!
//! ```
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // secret
//! const SECRET: [u8; 5] = *b"hello";
//!
//! // input text
//! const TEXT: &str = "\
//! Тhe Нitсhhikеr's Guіdе to thе Galaxy is a 1979 ѕcіеncе fiсtion соmedy
//! novеl bу Englіѕh author Douglаѕ Adаmѕ, adарtеd frоm the fіrѕt four parts
//! of hiѕ radiо соmedу ѕеriеѕ оf thе sаmе name.";
//!
//! // expected output
//! const EXP: &str = "\
//! Тhe Нitсhhikеr's Guide to the Galaxy is a 1979 ѕcіеncе fiсtion соmedy
//! novеl bу Englіѕh author Douglаѕ Adаmѕ, adарtеd frоm the fіrѕt four parts
//! of hiѕ radiо соmedу ѕеriеѕ оf thе sаmе name.";
//!
//! // encode secret, check result
//! assert_eq!(stegtext::encode(&SECRET, TEXT)?, EXP);
//! # Ok(())
//! # }
//! ```
//!
//! Get secret from text:
//!
//! ```
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // text with embedded secret
//! const TEXT: &str = "\
//! Тhe Нitсhhikеr's Guide to the Galaxy is a 1979 ѕcіеncе fiсtion соmedy
//! novеl bу Englіѕh author Douglаѕ Adаmѕ, adарtеd frоm the fіrѕt four parts
//! of hiѕ radiо соmedу ѕеriеѕ оf thе sаmе name.";
//!
//! // decode secret, check result
//! assert_eq!(stegtext::decode(TEXT)?, "hello");
//! # Ok(())
//! # }
//! ```
//!
//! Get text embedding capacity:
//!
//! ```
//! # fn main() {
//! // input text
//! const TEXT: &str = "\
//! Тhe Нitсhhikеr's Guіdе to thе Galaxy is a 1979 ѕcіеncе fiсtion соmedy
//! novеl bу Englіѕh author Douglаѕ Adаmѕ, adарtеd frоm the fіrѕt four parts
//! of hiѕ radiо соmedу ѕеriеѕ оf thе sаmе name. Іt centrеѕ оn the
//! misаdvеntureѕ оf Arthur Dent, the оnly man tо ѕurvive the destruction of
//! Earth, as he roams the cosmos and learns the truth behind his very
//! existence. The novel's namesake is an in-universe electronic travel
//! guide written in the form of an encyclopaedia, through which the story
//! is framed.";
//!
//! // calculate capacity, check result
//! assert_eq!(stegtext::capacity(TEXT), 23);
//! # }
//! ```
//!
//! # Technical Details
//!
//! Encoding process:
//!
//! 1. The first prefix byte is constructed.  The lower 4 bits of the
//!    first prefix byte are the are a constant tag (`0x5`) and the
//!    upper 4 bits of the first prefix byte are bits `0..4` of the
//!    length of the secret.
//! 2. The second prefix byte is constructed from bits `4..12` of the
//!    length of the secret.
//! 3. The secret bytes are appended to the prefix bytes to create a
//!    payload.
//! 4. The total number of payload bits are calculated.
//! 5. The input text is scanned for characters that can be replaced
//!    by [homoglyphs][].
//! 6. Non-matching characters are passed through to the output
//!    unaltered.
//! 7. When a matching character is encountered it is modified
//!    based on the value of the current payload bit:
//!    - if the current payload bit is **set**, then the character
//!      is replaced with a non-Latin [homoglyph][] character.  For
//!      example, [`'A'` (`U+0041`)][a-l] is replaced with [`'А'` (`U+0410`)][a-c],
//!      [`'B'` (`U+0042`)][b-l] is replaced by [`'В'` (`U+0412`)][b-c],
//!      and so on.
//!    - if the current payload bit is **not set**, then the character
//!      is replaced with a Latin character.
//! 8. The current payload bit position is incremented.
//! 9. Steps 5-8 are repeated until the current payload bit position
//!    equals the total number of payload bits.
//! 10. If payload bits remain when the end of the input text is
//!     reached, then [`Err::Capacity`] is returned.
//! 11. Once all the payload bits have been encoded, the remaining
//!     characters from the input text are passed through to the output
//!     unaltered.
//!
//! [steganography]: https://en.wikipedia.org/wiki/Steganography
//!   "Steganography (Wikipedia)"
//! [utf-8]: https://en.wikipedia.org/wiki/UTF-8
//!   "UTF-8 (Wikipedia)"
//! [homoglyph]: https://en.wikipedia.org/wiki/Homoglyph
//!   "Homoglyph (Wikipedia)"
//! [homoglyphs]: https://en.wikipedia.org/wiki/Homoglyph
//!   "Homoglyph (Wikipedia)"
//! [idn homograph attack]: https://en.wikipedia.org/wiki/IDN_homograph_attack#Cyrillic
//!   "IDN homograph attack (Wikipedia)"
//! [a-l]: https://en.wikipedia.org/wiki/A
//!   "A (Latin)"
//! [a-c]: https://en.wikipedia.org/wiki/A_(Cyrillic)
//!   "A (Cyrillic)"
//! [b-l]: https://en.wikipedia.org/wiki/B
//!   "B (Latin)"
//! [b-c]: https://en.wikipedia.org/wiki/B_(Cyrillic)
//!   "B (Cyrillic)"

#![deny(missing_docs)]
#![deny(unsafe_code)]

// TODO:
// - ci/cd
// - doc: tests
// - doc: linting
// - doc: coverage
// - doc: fuzzing

use std::io::Write;

/// Prefix tag.
///
/// Lower 4 bits of first decoded byte.  Used to identify text with
/// embedded steganographic data.
const TAG: u8 = 0x5;

/// Maximum secret length.
///
/// Note: encoded in prefix bytes as a 12-bit integer.
const MAX_SECRET_LEN: usize = 4095;

/// Encode/decode error.
#[derive(Clone, Debug, PartialEq)]
pub enum Err {
  /// Secret length is greater than 4095 bytes.
  ///
  /// # Example
  ///
  /// ```
  /// # fn main() {
  /// use stegtext::{Err, encode};
  /// let secret: [u8; 4096] = [0; 4096];
  /// assert_eq!(encode(&secret, ""), Err(Err::SecretLen(4096)));
  /// # }
  /// ```
  SecretLen(usize),

  /// Not enough text capacity to encode secret.
  ///
  /// # Example
  ///
  /// ```
  /// # fn main() {
  /// use stegtext::{Err, encode};
  /// let secret: [u8; 1] = [0; 1];
  /// assert_eq!(encode(&secret, "aa"), Err(Err::Capacity));
  /// # }
  /// ```
  Capacity,

  /// Write to output buffer failed.
  Write,

  /// UTF-8 encoding error.
  Encoding(std::string::FromUtf8Error),

  /// Invalid tag in encoded text.
  ///
  /// # Example
  ///
  /// ```
  /// # fn main() {
  /// use stegtext::{Err, decode};
  /// assert_eq!(decode("aaaaaaaa aaaaaaaa"), Err(Err::BadTag(0)));
  /// # }
  /// ```
  BadTag(u8),

  /// Truncated secret.
  ///
  /// # Example
  ///
  /// ```
  /// # fn main() {
  /// use stegtext::{Err, decode};
  /// let s = "\u{0430}a\u{0430}a\u{0430}aaa aaaaaaaa";
  /// assert_eq!(decode(s), Err(Err::TruncatedSecret(0, 1)));
  /// # }
  /// ```
  TruncatedSecret(usize, usize),
}

impl std::error::Error for Err {}

impl std::fmt::Display for Err {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    match self {
      Err::SecretLen(len) => write!(f, "secret length greater than {MAX_SECRET_LEN} bytes: {len}"),
      Err::Capacity => write!(f, "not enough text capacity to encode secret"),
      Err::Write => write!(f, "buffer write failed"),
      Err::Encoding(err) => write!(f, "encode error: {err}"),
      Err::BadTag(val) => write!(f, "invalid tag: got 0x{val:x}, expected 0x{TAG:x}"),
      Err::TruncatedSecret(got, exp) => write!(f, "truncated secret: got {got} bytes, expected {exp} bytes"),
    }
  }
}

/// Does this character have a homoglyph?
fn is_encodable(c: char) -> bool {
  matches!(c, 'A' | 'B' | 'C' | 'E' | 'H' | 'I' | 'J' | 'K' | 'M' | 'O' | 'P' | 'S' | 'T' | 'X' | 'a' | 'c' | 'e' | 'i' | 'j' | 'o' | 'p' | 'q' | 's' | 'w' | 'x' | 'y' | 'А' | 'В' | 'С' | 'Е' | 'Н' | 'І' | 'Ј' | 'К' | 'М' | 'О' | 'Р' | 'Ѕ' | 'Т' | 'Х' | 'а' | 'с' | 'е' | 'і' | 'ј' | 'о' | 'р' | 'ԛ' | 'ѕ' | 'ԝ' | 'х' | 'у')
}

/// Encode bit value in character.
fn encode_char(c: char, bit: bool) -> char {
  match (c, bit) {
    ('A' | 'А', true) => 'А',
    ('A' | 'А', false) => 'A',
    ('B' | 'В', true) => 'В',
    ('B' | 'В', false) => 'B',
    ('C' | 'С', true) => 'С',
    ('C' | 'С', false) => 'C',
    ('E' | 'Е', true) => 'Е',
    ('E' | 'Е', false) => 'E',
    ('H' | 'Н', true) => 'Н',
    ('H' | 'Н', false) => 'H',
    ('I' | 'І', true) => 'І',
    ('I' | 'І', false) => 'I',
    ('J' | 'Ј', true) => 'Ј',
    ('J' | 'Ј', false) => 'J',
    ('K' | 'К', true) => 'К',
    ('K' | 'К', false) => 'K',
    ('M' | 'М', true) => 'М',
    ('M' | 'М', false) => 'M',
    ('O' | 'О', true) => 'О',
    ('O' | 'О', false) => 'O',
    ('P' | 'Р', true) => 'Р',
    ('P' | 'Р', false) => 'P',
    ('S' | 'Ѕ', true) => 'Ѕ',
    ('S' | 'Ѕ', false) => 'S',
    ('T' | 'Т', true) => 'Т',
    ('T' | 'Т', false) => 'T',
    ('X' | 'Х', true) => 'Х',
    ('X' | 'Х', false) => 'X',
    ('a' | 'а', true) => 'а',
    ('a' | 'а', false) => 'a',
    ('c' | 'с', true) => 'с',
    ('c' | 'с', false) => 'c',
    ('e' | 'е', true) => 'е',
    ('e' | 'е', false) => 'e',
    ('i' | 'і', true) => 'і',
    ('i' | 'і', false) => 'i',
    ('j' | 'ј', true) => 'ј',
    ('j' | 'ј', false) => 'j',
    ('o' | 'о', true) => 'о',
    ('o' | 'о', false) => 'o',
    ('p' | 'р', true) => 'р',
    ('p' | 'р', false) => 'p',
    ('q' | 'ԛ', true) => 'ԛ',
    ('q' | 'ԛ', false) => 'q',
    ('s' | 'ѕ', true) => 'ѕ',
    ('s' | 'ѕ', false) => 's',
    ('w' | 'ԝ', true) => 'ԝ',
    ('w' | 'ԝ', false) => 'w',
    ('x' | 'х', true) => 'х',
    ('x' | 'х', false) => 'x',
    ('y' | 'у', true) => 'у',
    ('y' | 'у', false) => 'y',
    _ => c,
  }
}

/// Hide secret in text and return result as byte vector.
///
/// # Example
///
/// ```
/// # fn main() {
/// let secret = b"hi"; // secret
/// let text = "aaaaaaaa aaaaaaaa aaaaaaaa aaaaaaaa"; // text
/// let exp = vec![
///   0xd0, 0xb0, 0x61, 0xd0, 0xb0, 0x61, 0x61, 0xd0,
///   0xb0, 0x61, 0x61, 0x20, 0x61, 0x61, 0x61, 0x61,
///   0x61, 0x61, 0x61, 0x61, 0x20, 0x61, 0x61, 0x61,
///   0xd0, 0xb0, 0x61, 0xd0, 0xb0, 0xd0, 0xb0, 0x61,
///   0x20, 0xd0, 0xb0, 0x61, 0x61, 0xd0, 0xb0, 0x61,
///   0xd0, 0xb0, 0xd0, 0xb0, 0x61,
/// ];
///
/// // encode secret in text, check result
/// assert_eq!(stegtext::encode_vec(secret, text), Ok(exp));
/// # }
/// ```
pub fn encode_vec(secret: &[u8], text: &str) -> Result<Vec<u8>, Err> {
  // check secret length
  if secret.len() > MAX_SECRET_LEN {
    return Err(Err::SecretLen(secret.len()));
  }

  // build tag byte and encoded secret
  let tag_byte = (((secret.len() & 0xf) << 4) as u8) | TAG;
  let mut src = vec![tag_byte, (secret.len() >> 4) as u8];
  src.extend(secret);

  let mut src_pos: usize = 0; // bit position
  let src_bit_len = src.len() << 3; // src len, in bits

  // build output
  let mut dst = Vec::new();
  for c in text.chars() {
    let c = if src_pos < src_bit_len && is_encodable(c) {
      let bit = ((src[src_pos >> 3] >> (src_pos & 7)) & 1) == 1; // get bit
      src_pos += 1; // advance position
      encode_char(c, bit) // encode character
    } else {
      c // pass character through
    };

    // write character to output buffer
    match write!(dst, "{c}") {
      Ok(_) => {},
      Err(_) => return Err(Err::Write),
    }
  }

  // were all secret bits encoded?
  if src_pos != src_bit_len {
    return Err(Err::Capacity)
  }

  Ok(dst)
}

/// Hide secret in text and return result as string.
///
/// # Example
///
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// // secret
/// const SECRET: [u8; 5] = *b"hello";
///
/// // input text
/// const TEXT: &str = "\
/// Тhe Нitсhhikеr's Guіdе to thе Galaxy is a 1979 ѕcіеncе fiсtion соmedy
/// novеl bу Englіѕh author Douglаѕ Adаmѕ, adарtеd frоm the fіrѕt four parts
/// of hiѕ radiо соmedу ѕеriеѕ оf thе sаmе name.";
///
/// // expected output
/// const EXP: &str = "\
/// Тhe Нitсhhikеr's Guide to the Galaxy is a 1979 ѕcіеncе fiсtion соmedy
/// novеl bу Englіѕh author Douglаѕ Adаmѕ, adарtеd frоm the fіrѕt four parts
/// of hiѕ radiо соmedу ѕеriеѕ оf thе sаmе name.";
///
/// // encode secret, check result
/// assert_eq!(stegtext::encode(&SECRET, TEXT)?, EXP);
/// # Ok(())
/// # }
/// ```
pub fn encode(secret: &[u8], text: &str) -> Result<String, Err> {
  match String::from_utf8(encode_vec(secret, text)?) {
    Ok(s) => Ok(s),
    Err(err) => Err(Err::Encoding(err)),
  }
}

/// Get embedding capacity, in bytes.
///
/// # Example
///
/// ```
/// # fn main() {
/// // input text
/// const TEXT: &str = "\
/// Тhe Нitсhhikеr's Guіdе to thе Galaxy is a 1979 ѕcіеncе fiсtion соmedy
/// novеl bу Englіѕh author Douglаѕ Adаmѕ, adарtеd frоm the fіrѕt four parts
/// of hiѕ radiо соmedу ѕеriеѕ оf thе sаmе name. Іt centrеѕ оn the
/// misаdvеntureѕ оf Arthur Dent, the оnly man tо ѕurvive the destruction of
/// Earth, as he roams the cosmos and learns the truth behind his very
/// existence. The novel's namesake is an in-universe electronic travel
/// guide written in the form of an encyclopaedia, through which the story
/// is framed.";
///
/// // get capacity, check result
/// assert_eq!(stegtext::capacity(TEXT), 23);
/// # }
/// ```
pub fn capacity(text: &str) -> usize {
  let len = text.chars().filter(|c| is_encodable(*c)).count();
  if len > 16 {
    // truncate to multiple of 8, subtract two bytes for tag and length
    (len / 8) - 2
  } else {
    0
  }
}

/// Maybe decode bit from character.
fn decode_char(c: char) -> Option<bool> {
  match c {
    'A' | 'B' | 'C' | 'E' | 'H' | 'I' | 'J' | 'K' | 'M' | 'O' | 'P' | 'S' | 'T' | 'X' | 'a' | 'c' | 'e' | 'i' | 'j' | 'o' | 'p' | 'q' | 's' | 'w' | 'x' | 'y' => Some(false), // latin
    'А' | 'В' | 'С' | 'Е' | 'Н' | 'І' | 'Ј' | 'К' | 'М' | 'О' | 'Р' | 'Ѕ' | 'Т' | 'Х' | 'а' | 'с' | 'е' | 'і' | 'ј' | 'о' | 'р' | 'ԛ' | 'ѕ' | 'ԝ' | 'х' | 'у' => Some(true), // cyrillic
    _ => None,
  }
}

/// Extract secret from text and return result as byte vector.
///
/// # Example
///
/// ```
/// # fn main() {
/// // text and expected value
/// let text = "\u{0430}a\u{0430}a\u{0430}\u{0430}aa aaaaaaaa \u{0430}aaaaaaa a\u{0430}aaaaaa \u{0430}\u{0430}aaaaaa";
/// let exp = vec![1u8, 2, 3];
///
/// // decode vector, check result
/// assert_eq!(stegtext::decode_vec(text), Ok(exp));
/// # }
pub fn decode_vec(text: &str) -> Result<Vec<u8>, Err> {
  let mut pos: usize = 0; // current bit
  let mut byte: u8 = 0; // current byte
  let mut exp_len: usize = 0; // expected output length

  let mut dst = Vec::new(); // output vector
  for c in text.chars() {
    if let Some(bit) = decode_char(c) {
      byte |= u8::from(bit) << pos;
      pos += 1; // advance

      if pos == 8 {
        dst.push(byte); // add byte to output
        byte = 0; // clear byte
        pos = 0; // clear position

        match (exp_len, dst.len()) {
          (0, 2) => {
            // get tag and expected length
            let tag = dst[0] & 0xf;
            exp_len = ((dst[0] >> 4) as usize) | ((dst[1] as usize) << 8);

            // check tag and length
            if tag != TAG {
              return Err(Err::BadTag(tag));
            }

            dst.clear(); // clear vector
            if exp_len == 0 {
              return Ok(dst);
            }
          },
          (_, dst_len) if dst_len == exp_len => break,
          (_, _) => {},
        };
      }
    }
  }

  // check decoded secret length
  if dst.len() == exp_len {
    Ok(dst)
  } else {
    Err(Err::TruncatedSecret(dst.len(), exp_len))
  }
}

/// Extract secret from text and return result as string.
///
/// # Example
///
/// ```
/// // Text with hidden secret.
/// const TEXT: &str = "\
/// Тhe Нitсhhikеr's Guide to the Galaxy is a 1979 ѕcіеncе fiсtion соmedy
/// novеl bу Englіѕh author Douglаѕ Adаmѕ, adарtеd frоm the fіrѕt four parts
/// of hiѕ radiо соmedу ѕеriеѕ оf thе sаmе name.";
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// // decode secret, check result
/// assert_eq!(stegtext::decode(TEXT)?, "hello");
/// # Ok(())
/// # }
/// ```
pub fn decode(text: &str) -> Result<String, Err> {
  match String::from_utf8(decode_vec(text)?) {
    Ok(s) => Ok(s),
    Err(err) => Err(Err::Encoding(err)),
  }
}

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

  #[test]
  fn test_err_fmt() {
    let bad_utf8 = vec![0x80u8];
    let from_err = String::from_utf8(bad_utf8).unwrap_err();
    let tests = vec![
      (Err::SecretLen(4096), "secret length greater than 4095 bytes: 4096"),
      (Err::Capacity, "not enough text capacity to encode secret"),
      (Err::Write, "buffer write failed"),
      (Err::Encoding(from_err), "encode error: invalid utf-8 sequence of 1 bytes from index 0"),
      (Err::BadTag(0), "invalid tag: got 0x0, expected 0x5"),
      (Err::TruncatedSecret(0, 1), "truncated secret: got 0 bytes, expected 1 bytes"),
    ];

    for (err, exp) in tests {
      assert_eq!(err.to_string(), exp, "{err:?}");
    }
  }

  #[test]
  fn test_encode_char() {
    let tests = vec![
      ('A', true, 'А'),
      ('А', true, 'А'),
      ('A', false, 'A'),
      ('А', false, 'A'),
      ('B', true, 'В'),
      ('В', true, 'В'),
      ('B', false, 'B'),
      ('В', false, 'B'),
      ('C', true, 'С'),
      ('С', true, 'С'),
      ('C', false, 'C'),
      ('С', false, 'C'),
      ('E', true, 'Е'),
      ('Е', true, 'Е'),
      ('E', false, 'E'),
      ('Е', false, 'E'),
      ('H', true, 'Н'),
      ('Н', true, 'Н'),
      ('H', false, 'H'),
      ('Н', false, 'H'),
      ('I', true, 'І'),
      ('І', true, 'І'),
      ('I', false, 'I'),
      ('І', false, 'I'),
      ('J', true, 'Ј'),
      ('Ј', true, 'Ј'),
      ('J', false, 'J'),
      ('Ј', false, 'J'),
      ('K', true, 'К'),
      ('К', true, 'К'),
      ('K', false, 'K'),
      ('К', false, 'K'),
      ('M', true, 'М'),
      ('М', true, 'М'),
      ('M', false, 'M'),
      ('М', false, 'M'),
      ('O', true, 'О'),
      ('О', true, 'О'),
      ('O', false, 'O'),
      ('О', false, 'O'),
      ('P', true, 'Р'),
      ('Р', true, 'Р'),
      ('P', false, 'P'),
      ('Р', false, 'P'),
      ('S', true, 'Ѕ'),
      ('Ѕ', true, 'Ѕ'),
      ('S', false, 'S'),
      ('Ѕ', false, 'S'),
      ('T', true, 'Т'),
      ('Т', true, 'Т'),
      ('T', false, 'T'),
      ('Т', false, 'T'),
      ('X', true, 'Х'),
      ('Х', true, 'Х'),
      ('X', false, 'X'),
      ('Х', false, 'X'),
      ('a', true, 'а'),
      ('а', true, 'а'),
      ('a', false, 'a'),
      ('а', false, 'a'),
      ('c', true, 'с'),
      ('с', true, 'с'),
      ('c', false, 'c'),
      ('с', false, 'c'),
      ('e', true, 'е'),
      ('е', true, 'е'),
      ('e', false, 'e'),
      ('е', false, 'e'),
      ('i', true, 'і'),
      ('і', true, 'і'),
      ('i', false, 'i'),
      ('і', false, 'i'),
      ('j', true, 'ј'),
      ('ј', true, 'ј'),
      ('j', false, 'j'),
      ('ј', false, 'j'),
      ('o', true, 'о'),
      ('о', true, 'о'),
      ('o', false, 'o'),
      ('о', false, 'o'),
      ('p', true, 'р'),
      ('р', true, 'р'),
      ('p', false, 'p'),
      ('р', false, 'p'),
      ('q', true, 'ԛ'),
      ('ԛ', true, 'ԛ'),
      ('q', false, 'q'),
      ('ԛ', false, 'q'),
      ('s', true, 'ѕ'),
      ('ѕ', true, 'ѕ'),
      ('s', false, 's'),
      ('ѕ', false, 's'),
      ('w', true, 'ԝ'),
      ('ԝ', true, 'ԝ'),
      ('w', false, 'w'),
      ('ԝ', false, 'w'),
      ('x', true, 'х'),
      ('х', true, 'х'),
      ('x', false, 'x'),
      ('х', false, 'x'),
      ('y', true, 'у'),
      ('у', true, 'у'),
      ('y', false, 'y'),
      ('у', false, 'y'),

      ('z', false, 'z'),
    ];

    for (c, bit, exp) in tests {
      assert_eq!(encode_char(c, bit), exp, "{} (U+{:04x})", c, u32::from(c));
    }
  }

  #[test]
  fn test_encode_vec_fail() {
    let tests = vec![(
      "long secret", // name
      [0u8; MAX_SECRET_LEN+1].to_vec(), // secret
      "aaaaaaaa aaaaaaaa aaaaaaaa", // text
      Err(Err::SecretLen(MAX_SECRET_LEN+1)),
    ), (
      "short text", // name
      vec![0u8], // secret
      "aaaaaaaa aaaaaaaa", // text
      Err(Err::Capacity),
    )];

    for (name, msg, text, exp) in tests {
      assert_eq!(encode_vec(&msg, text), exp, "{name}");
    }
  }

  #[test]
  fn test_encode_vec_pass() {
    let tests = vec![(
      "aaa", // name
      vec![1], // secret
      "aaaaaaaa aaaaaaaa aaaaaaaa", // text
      vec![ // exp
        0xd0, 0xb0, 0x61, 0xd0, 0xb0, 0x61, 0xd0, 0xb0, 0x61, 0x61, 0x61,
        0x20,
        0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61,
        0x20,
        0xd0, 0xb0, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61,
      ],
    ), (
      "acc", // name
      vec![1], // secret
      "aaaaaaaa cccccccc cccccccc", // text
      vec![ // exp
        0xd0, 0xb0, 0x61, 0xd0, 0xb0, 0x61, 0xd0, 0xb0, 0x61, 0x61, 0x61,
        0x20,
        0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63,
        0x20,
        0xd1, 0x81, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63,
      ],
    ), (
      "ace", // name
      vec![1], // secret
      "aaaaaaaa cccccccc eeeeeeee", // text
      vec![ // exp
        0xd0, 0xb0, 0x61, 0xd0, 0xb0, 0x61, 0xd0, 0xb0, 0x61, 0x61, 0x61,
        0x20,
        0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63,
        0x20,
        0xd0, 0xb5, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65,
      ],
    ), (
      "aop", // name
      vec![1], // secret
      "aaaaaaaa oooooooo pppppppp", // text
      vec![ // exp
        0xd0, 0xb0, 0x61, 0xd0, 0xb0, 0x61, 0xd0, 0xb0, 0x61, 0x61, 0x61,
        0x20,
        0x6f, 0x6f, 0x6f, 0x6f, 0x6f, 0x6f, 0x6f, 0x6f,
        0x20,
        0xd1, 0x80, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70,
      ],
    ), (
      "pxy", // name
      vec![1], // secret
      "pppppppp xxxxxxxx yyyyyyyy", // text
      vec![ // exp
        0xd1, 0x80, 0x70, 0xd1, 0x80, 0x70, 0xd1, 0x80, 0x70, 0x70, 0x70,
        0x20,
        0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78,
        0x20,
        0xd1, 0x83, 0x79, 0x79, 0x79, 0x79, 0x79, 0x79, 0x79,
      ],
    ), (
      "ijqs", // name
      vec![1, 1], // secret
      "iiiiiiii jjjjjjjj qqqqqqqq ssssssss", // text
      vec![ // exp
        0xd1, 0x96, 0x69, 0xd1, 0x96, 0x69, 0x69, 0xd1, 0x96, 0x69, 0x69,
        0x20,
        0x6a, 0x6a, 0x6a, 0x6a, 0x6a, 0x6a, 0x6a, 0x6a,
        0x20,
        0xd4, 0x9b, 0x71, 0x71, 0x71, 0x71, 0x71, 0x71, 0x71,
        0x20,
        0xd1, 0x95, 0x73, 0x73, 0x73, 0x73, 0x73, 0x73, 0x73,
      ],
    ), (
      "wwww", // name
      vec![1, 1], // secret
      "wwwwwwww wwwwwwww wwwwwwww wwwwwwww", // text
      vec![ // exp
        0xd4, 0x9d, 0x77, 0xd4, 0x9d, 0x77, 0x77, 0xd4, 0x9d, 0x77, 0x77,
        0x20,
        0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77,
        0x20,
        0xd4, 0x9d, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77,
        0x20,
        0xd4, 0x9d, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77,
      ],
    ), (
      "ABCE", // name
      vec![1, 1], // secret
      "AAAAAAAA BBBBBBBB CCCCCCCC EEEEEEEE", // text
      vec![ // exp
        0xd0, 0x90, 0x41, 0xd0, 0x90, 0x41, 0x41, 0xd0, 0x90, 0x41, 0x41,
        0x20,
        0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42,
        0x20,
        0xd0, 0xa1, 0x43, 0x43, 0x43, 0x43, 0x43, 0x43, 0x43,
        0x20,
        0xd0, 0x95, 0x45, 0x45, 0x45, 0x45, 0x45, 0x45, 0x45,
      ],
    ), (
      "HIJKM", // name
      vec![1, 1, 1], // secret
      "HHHHHHHH IIIIIIII JJJJJJJJ KKKKKKKK MMMMMMMM", // text
      vec![ // exp
        0xd0, 0x9d, 0x48, 0xd0, 0x9d, 0x48, 0xd0, 0x9d, 0xd0, 0x9d, 0x48, 0x48,
        0x20,
        0x49, 0x49, 0x49, 0x49, 0x49, 0x49, 0x49, 0x49,
        0x20,
        0xd0, 0x88, 0x4a, 0x4a, 0x4a, 0x4a, 0x4a, 0x4a, 0x4a,
        0x20,
        0xd0, 0x9a, 0x4b, 0x4b, 0x4b, 0x4b, 0x4b, 0x4b, 0x4b,
        0x20,
        0xd0, 0x9c, 0x4d, 0x4d, 0x4d, 0x4d, 0x4d, 0x4d, 0x4d,
      ],
    ), (
      "OPSTX", // name
      vec![1, 1, 1], // secret
      "OOOOOOOO PPPPPPPP SSSSSSSS TTTTTTTT XXXXXXXX", // text
      vec![ // exp
        0xd0, 0x9e, 0x4f, 0xd0, 0x9e, 0x4f, 0xd0, 0x9e, 0xd0, 0x9e, 0x4f, 0x4f,
        0x20,
        0x50, 0x50, 0x50, 0x50, 0x50, 0x50, 0x50, 0x50,
        0x20,
        0xd0, 0x85, 0x53, 0x53, 0x53, 0x53, 0x53, 0x53, 0x53,
        0x20,
        0xd0, 0xa2, 0x54, 0x54, 0x54, 0x54, 0x54, 0x54, 0x54,
        0x20,
        0xd0, 0xa5, 0x58, 0x58, 0x58, 0x58, 0x58, 0x58, 0x58,
      ],
    )];

    for (name, secret, text, exp) in tests {
      assert_eq!(encode_vec(&secret, text), Ok(exp), "{name}");
    }
  }

  #[test]
  fn test_encode_fail() {
    let tests = vec![(
      "long secret", // name
      [0u8; MAX_SECRET_LEN+1].to_vec(), // secret
      "aaaaaaaa aaaaaaaa aaaaaaaa", // text
      Err(Err::SecretLen(MAX_SECRET_LEN+1)),
    ), (
      "short text", // name
      vec![0u8], // secret
      "aaaaaaaa aaaaaaaa", // text
      Err(Err::Capacity),
    )];

    for (name, msg, text, exp) in tests {
      assert_eq!(encode(&msg, text), exp, "{name}");
    }
  }

  #[test]
  fn test_encode_pass() {
    let tests = vec![(
      "aaa", // name
      b"A".to_vec(), // secret
      "aaaaaaaa aaaaaaaa aaaaaaaa", // text
      "аaаaаaaa aaaaaaaa аaaaaaаa".to_string(), // expected value
    )];

    for (name, secret, text, exp) in tests {
      assert_eq!(encode(&secret, text), Ok(exp), "{name}");
    }
  }

  #[test]
  fn test_capacity() {
    let tests = vec![
      ("", 0),
      ("aaaa", 0),
      ("aaaaaaaa aaaaaaaa", 0),
      ("aaaaaaaa aaaaaaaa aaaaaaa", 0),
      ("aaaaaaaa aaaaaaaa aaaaaaaa", 1),
      ("aaaaaaaa aaaaaaaa aaaaaaaa aa", 1),
      ("aaaaaaaa aaaaaaaa aaaaaaaa a", 1),
      ("aaaaaaaa aaaaaaaa aaaaaaaa aaaaaaaa", 2),
      ("aaaaaaaa aaaaaaaa aaaaaaaa aaaaaaaa ", 2),
    ];

    for (s, exp) in tests {
      assert_eq!(capacity(s), exp, "s = {s}");
    }
  }

  #[test]
  fn test_decode_vec_fail() {
    let invalid_len_str = String::from_utf8(vec![ // text
      0xd0, 0x9e, 0x4f, 0xd0, 0x9e, 0x4f, 0xd0, 0x9e, 0xd0, 0x9e, 0x4f, 0x4f,
      0x20,
      0x50, 0x50, 0x50, 0x50, 0x50, 0x50, 0x50, 0x50,
      0x20,
      0xd0, 0x85, 0x53, 0x53, 0x53, 0x53, 0x53, 0x53, 0x53,
      0x20,
      0xd0, 0xa2, 0x54, 0x54, 0x54, 0x54, 0x54, 0x54, 0x54,
      0x20,
    ]).unwrap();

    let tests = vec![(
      "invalid tag", // name
      "aaaaaaaa aaaaaaaa aaaaaaaa", // text
      Err(Err::BadTag(0)),
    ), (
      "invalid length", // name
      invalid_len_str.as_str(),
      Err(Err::TruncatedSecret(2, 3)),
    )];

    for (name, text, exp) in tests {
      assert_eq!(decode_vec(text), exp, "{name}");
    }
  }

  #[test]
  fn test_decode_vec_pass() {
    let trips_str = String::from_utf8(vec![
      0xd0, 0x9e, 0x4f, 0xd0, 0x9e, 0x4f, 0xd0, 0x9e, 0xd0, 0x9e, 0x4f, 0x4f,
      0x20,
      0x50, 0x50, 0x50, 0x50, 0x50, 0x50, 0x50, 0x50,
      0x20,
      0xd0, 0x85, 0x53, 0x53, 0x53, 0x53, 0x53, 0x53, 0x53,
      0x20,
      0xd0, 0xa2, 0x54, 0x54, 0x54, 0x54, 0x54, 0x54, 0x54,
      0x20,
      0xd0, 0xa5, 0x58, 0x58, 0x58, 0x58, 0x58, 0x58, 0x58,
    ]).unwrap();

    let tests = vec![(
      "none", // name
      "", // text
      Ok(Vec::<u8>::new()), // exp
    ), (
      "trips", // name
      trips_str.as_str(), // text
      Ok(vec![1, 1, 1]),
    )];

    for (name, text, exp) in tests {
      assert_eq!(decode_vec(text), exp, "{name}");
    }
  }

  #[test]
  fn test_decode_fail() {
    let invalid_len_str = String::from_utf8(vec![ // text
      0xd0, 0x9e, 0x4f, 0xd0, 0x9e, 0x4f, 0xd0, 0x9e, 0xd0, 0x9e, 0x4f, 0x4f,
      0x20,
      0x50, 0x50, 0x50, 0x50, 0x50, 0x50, 0x50, 0x50,
      0x20,
      0xd0, 0x85, 0x53, 0x53, 0x53, 0x53, 0x53, 0x53, 0x53,
      0x20,
      0xd0, 0xa2, 0x54, 0x54, 0x54, 0x54, 0x54, 0x54, 0x54,
      0x20,
    ]).unwrap();

    let tests = vec![(
      "invalid tag", // name
      "aaaaaaaa aaaaaaaa aaaaaaaa", // text
      Err(Err::BadTag(0)),
    ), (
      "invalid length", // name
      invalid_len_str.as_str(),
      Err(Err::TruncatedSecret(2, 3)),
    )];

    for (name, text, exp) in tests {
      assert_eq!(decode(text), exp, "{name}");
    }
  }


  #[test]
  fn test_decode_pass() {
    let tests = vec![(
      "empty", // name
      "аaаaaaaa aaaaaaaa".to_string(), // text
      "".to_string(), // exp
    ), (
      "A", // name
      "аaаaаaaa aaaaaaaa аaaaaaаa".to_string(), // text
      "A".to_string(), // exp
    )];

    for (name, text, exp) in tests {
      assert_eq!(decode(&text), Ok(exp), "{name}");
    }
  }

}