bsn1 3.0.0

Rust BER and DER serializer/deserializer.
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
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
// Copyright 2021-2024 Shin Yoshida
//
// "GPL-3.0-only"
//
// This is part of BSN1
//
// BSN1 is free software: you can redistribute it and/or modify it under the terms of the
// GNU General Public License as published by the Free Software Foundation, version 3.
//
// BSN1 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
// even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License along with this program. If
// not, see <https://www.gnu.org/licenses/>.

use crate::{BerRef, Buffer, ContentsRef, Der, DerRef, Error, IdRef, Length};
use std::borrow::Borrow;
use std::io::Read;
use std::ops::{Deref, DerefMut};

/// `Ber` owns [`BerRef`] and represents a BER.
///
/// The structure of `Ber` is similar to that of `Vec<u8>`.
///
/// Users can access the inner [`BerRef`] via the `Deref` and `DerefMut` implementation.
///
/// # Warnings
///
/// ASN.1 allows BER both 'definite' and 'indefinite' length octets.
/// In case of 'indefinite', the contents must be a sequence of BERs,
/// and must be terminated by 'EOC BER'.
/// (Single 'EOC BER' is allowed.)
///
/// `Ber` instance works fine even if the user violates the rule,
/// however, the holding octets will be invalid as a BER then.
/// Such octets can not be parsed as a BER again.
#[derive(Debug, Clone, Eq, Hash)]
pub struct Ber {
    buffer: Buffer,
}

impl Ber {
    /// Creates a new instance with definite length from `id` and `contents`.
    ///
    /// Note that BER allows both definite length and indefinite length,
    /// however, this function always returns a definite length value.
    /// Use [`new_indefinite`] to build an indefinite length value.
    ///
    /// Warnings
    ///
    /// ASN.1 reserves some universal identifiers and they should not be used,
    /// however, this function ignores the rule.
    /// For example, the number 15 (0x0f) is reserved for now, but this function creates such
    /// an instance with the number 15 identifier.
    ///
    /// # Panics
    ///
    /// Panics if the total length exceeds `isize::MAX`.
    ///
    /// [`new_indefinite`]: Self::new_indefinite
    ///
    /// # Examples
    ///
    /// ```
    /// use bsn1::{Ber, ContentsRef, IdRef};
    ///
    /// let id = IdRef::octet_string();
    /// let contents: &ContentsRef = "Foo".into();
    /// let ber = Ber::new(id, contents);
    ///
    /// assert_eq!(ber.id(), id);
    /// assert!(ber.length().is_definite());
    /// assert_eq!(ber.contents().as_ref(), "Foo".as_bytes());
    /// ```
    pub fn new(id: &IdRef, contents: &ContentsRef) -> Self {
        Der::new(id, contents).into()
    }

    /// Creates a new instance from `id` and `contents` with indefinite length.
    ///
    /// Note that BER allows both definite length and indefinite length,
    /// however, this function always returns an indefinite length value.
    /// Use [`new`] to build a definite length value.
    ///
    /// Warnings
    ///
    /// ASN.1 reserves some universal identifiers and they should not be used,
    /// however, this function ignores the rule.
    /// For example, the number 15 (0x0f) is reserved for now, but this function creates such
    /// an instance with the number 15 identifier.
    ///
    /// # Safety
    ///
    /// ASN.1 defined that the contents of indefinite length BER must be a sequence of BERs,
    /// and must be terminated by 'EOC BER'.
    ///
    /// The methods of `Ber` works fine even if the user violates the rule, however, such instance
    /// may not be parsed again once after serialized.
    ///
    /// # Panics
    ///
    /// Panics if the total length exceeds `isize::MAX`.
    ///
    /// [`new`]: Self::new
    ///
    /// # Examples
    ///
    /// ```
    /// use bsn1::{Ber, BerRef, Contents, IdRef, Length};
    ///
    /// let id = IdRef::sequence();
    ///
    /// let contents0 = Ber::new(IdRef::utf8_string(), "Foo".as_bytes().into());
    /// let contents1 = Ber::new(IdRef::integer(), &Contents::from(29_i32));
    /// let contents2 = BerRef::eoc();
    ///
    /// let mut contents: Vec<u8> = Vec::new();
    /// contents.extend_from_slice(contents0.as_ref() as &[u8]);
    /// contents.extend_from_slice(contents1.as_ref() as &[u8]);
    /// contents.extend_from_slice(contents2.as_ref() as &[u8]);
    ///
    /// let ber = unsafe { Ber::new_indefinite(id, contents.as_slice().into()) };
    ///
    /// assert_eq!(ber.id(), id);
    /// assert!(ber.length().is_indefinite());
    ///
    /// let mut contents_: &[u8] = ber.contents().as_ref();
    ///
    /// let contents0_ = BerRef::parse(&mut contents_).unwrap();
    /// assert_eq!(contents0, contents0_);
    ///
    /// let contents1_ = BerRef::parse(&mut contents_).unwrap();
    /// assert_eq!(contents1, contents1_);
    ///
    /// let contents2_ = BerRef::parse(&mut contents_).unwrap();
    /// assert_eq!(contents2, contents2_);
    ///
    /// assert_eq!(contents_.is_empty(), true);
    /// ```
    pub unsafe fn new_indefinite(id: &IdRef, contents: &ContentsRef) -> Self {
        let mut ret = Self::with_id_length_indefinite(id, contents.len());
        ret.mut_contents()
            .as_mut()
            .copy_from_slice(contents.as_ref());

        ret
    }

    /// Creates a new instance with `id` and 'definite `length`'.
    ///
    /// The 'contents octets' of the return value holds `length` bytes,
    /// but they are not initialized.
    /// Use [`mut_contents`] via `DerefMut` implementation to initialize them.
    ///
    /// # Warnings
    ///
    /// ASN.1 reserves some universal identifiers and they should not be used, however, this
    /// function ignores the rule. For example, the number 15 (0x0f) is reserved for now,
    /// but this function creates such an instance with the number 15 identifier.
    ///
    /// # Panics
    ///
    /// Panics if the total bytes exceeds `isize::MAX`.
    ///
    /// [`mut_contents`]: BerRef::mut_contents
    ///
    /// # Examples
    ///
    /// ```
    /// use bsn1::{Ber, IdRef, Length};
    ///
    /// let mut ber = Ber::with_id_length(IdRef::utf8_string(), "Hello".len());
    ///
    /// assert_eq!(ber.id(), IdRef::utf8_string());
    /// assert_eq!(ber.length(), Length::Definite("Hello".len()));
    /// assert_eq!(ber.contents().len(), "Hello".len());
    ///
    /// ber.mut_contents().as_mut().copy_from_slice("Hello".as_bytes());
    /// assert_eq!(ber.contents().as_ref(), "Hello".as_bytes());
    /// ```
    pub fn with_id_length(id: &IdRef, length: usize) -> Self {
        Der::with_id_length(id, length).into()
    }

    /// Creates a new instance with `id` and 'indefinite length'.
    ///
    /// The 'contents octets' of the return value holds `length` bytes,
    /// but they are not initialized.
    /// Use [`mut_contents`] via `DerefMut` implementation to initialize them.
    ///
    /// # Warnings
    ///
    /// ASN.1 reserves some universal identifiers and they should not be used, however, this
    /// function accepts such identifiers. For example, the number 15 (0x0f) is reserved for now,
    /// but this function creates such an instance with the number 15 identifier.
    ///
    /// # Safety
    ///
    /// ASN.1 defined that the contents of indefinite length BER must be a sequence of BERs,
    /// and must be terminated by 'EOC BER'.
    ///
    /// The methods of `Ber` works fine even if the user violates the rule, however, such instance
    /// may not be parsed again once after serialized.
    ///
    /// # Panics
    ///
    /// Panics if the total bytes exceeds `isize::MAX`.
    ///
    /// [`mut_contents`]: BerRef::mut_contents
    ///
    /// # Examples
    ///
    /// ```
    /// use bsn1::{Ber, BerRef, Contents, IdRef};
    ///
    /// let contents0 = Ber::new(IdRef::utf8_string(), "Foo".as_bytes().into());
    /// let contents1 = Ber::new(IdRef::integer(), &Contents::from(29_i32));
    /// let contents2 = BerRef::eoc();
    ///
    /// let mut contents: Vec<u8> = Vec::new();
    /// contents.extend_from_slice(contents0.as_ref() as &[u8]);
    /// contents.extend_from_slice(contents1.as_ref() as &[u8]);
    /// contents.extend_from_slice(contents2.as_ref() as &[u8]);
    ///
    /// let mut ber
    ///     = unsafe { Ber::with_id_length_indefinite(IdRef::sequence(), contents.len()) };
    /// ber.mut_contents().as_mut().copy_from_slice(contents.as_slice());
    ///
    /// assert_eq!(ber.id(), IdRef::sequence());
    /// assert!(ber.length().is_indefinite());
    /// assert_eq!(ber.contents().as_ref(), contents.as_slice());
    /// ```
    pub unsafe fn with_id_length_indefinite(id: &IdRef, length: usize) -> Self {
        let length_ = Length::Indefinite.to_bytes();
        let total_len = id.len() + length_.len() + length;

        let mut buffer = Buffer::with_capacity(total_len);

        let dst = buffer.as_mut_ptr();
        dst.copy_from_nonoverlapping(id.as_ref().as_ptr(), id.len());

        let dst = dst.add(id.len());
        dst.copy_from_nonoverlapping(length_.as_ptr(), length_.len());

        buffer.set_len(total_len);

        Self { buffer }
    }

    /// Parses `readable` starting with BER octets and returns a new instance.
    ///
    /// This function ignores extra octet(s) at the end of `bytes` if any.
    ///
    /// On error, the state of `readable` is unspecified;
    /// otherwise, `readable` is advanced to the end of BER octets.
    ///
    /// # Performance
    ///
    /// This function is not so efficient compared with [`Ber::parse`].
    /// If you have a slice of serialized BER, use [`BerRef::parse`]
    /// and then call `Ber::from` instead.
    ///
    /// # Warnings
    ///
    /// ASN.1 reserves some universal identifiers and they should not be used, however, this
    /// function ignores the rule. For example, the number 15 (0x0f) is reserved for now,
    /// but this function returns `Ok`.
    ///
    /// # Examples
    ///
    /// ```
    /// use bsn1::{Ber, BerRef};
    ///
    /// // Serialize DER of '10' as Integer.
    /// let ber = Ber::from(10_i32);
    /// let mut serialized = Vec::from(ber.as_ref() as &[u8]);
    ///
    /// // Deserialize.
    /// {
    ///     let serialized = &mut &serialized[..];
    ///     let deserialized = Ber::parse(serialized).unwrap();
    ///     assert_eq!(ber, deserialized);
    ///     assert!(serialized.is_empty());
    /// }
    ///
    /// // Extra octets at the end does not affect the result.
    /// serialized.push(0x00);
    /// serialized.push(0x01);
    /// {
    ///     let serialized = &mut &serialized[..];
    ///     let deserialized = Ber::parse(serialized).unwrap();
    ///     assert_eq!(ber, deserialized);
    ///     assert_eq!(serialized, &[0x00, 0x01]);
    /// }
    ///
    /// // We can access to the inner slice of `serialized`.
    /// // We can use `BerRef::parse` instead of this function.
    /// // (`BerRef::parse` is more efficient than this function.)
    /// let deserialized: Ber = BerRef::parse(&mut &serialized[..]).unwrap().into();
    /// assert_eq!(ber, deserialized);
    /// ```
    pub fn parse<R>(readable: &mut R) -> Result<Self, Error>
    where
        R: ?Sized + Read,
    {
        let mut buffer = Buffer::new();
        let mut stack_depth: isize = 0;

        while {
            stack_depth += Self::do_parse(readable, &mut buffer)? as isize;
            stack_depth > 0
        } {}

        Ok(Self { buffer })
    }

    fn do_parse<R>(readable: &mut R, writeable: &mut Buffer) -> Result<i8, Error>
    where
        R: ?Sized + Read,
    {
        let init_len = writeable.len();

        match unsafe { crate::misc::parse_id_length(readable, writeable)? } {
            Length::Definite(length) => {
                writeable.reserve(length);
                let current_len = writeable.len();
                unsafe { writeable.set_len(current_len + length) };

                let buffer = &mut writeable.as_mut_slice()[current_len..];
                readable.read_exact(buffer).map_err(Error::from)?;

                let read = &(writeable.as_slice()[init_len..]);
                if read == BerRef::eoc().as_ref() {
                    Ok(-1)
                } else {
                    Ok(0)
                }
            }
            Length::Indefinite => Ok(1),
        }
    }

    /// Returns a new instance holding `bytes` without any check.
    ///
    /// `bytes` must not include any extra octet.
    ///
    /// If it is not sure whether `bytes` are valid octets as a 'BER', use [`parse`] instead.
    ///
    /// [`parse`]: Self::parse
    ///
    /// # Safety
    ///
    /// The behaviour is undefined if `bytes` is not formatted as a BER.
    ///
    /// # Examples
    ///
    /// ```
    /// use bsn1::Ber;
    ///
    /// let ber = Ber::from(5_i32);
    /// let serialized: &[u8] = ber.as_ref();
    /// let deserialized = unsafe { Ber::from_bytes_unchecked(serialized) };
    /// assert_eq!(ber, deserialized);
    /// ```
    pub unsafe fn from_bytes_unchecked(bytes: &[u8]) -> Self {
        Self {
            buffer: Buffer::from(bytes),
        }
    }

    /// Builds a new instance holding `bytes` without any check.
    ///
    /// `bytes` must not includ any extra octet.
    ///
    /// If it is not sure whether `bytes` are valid octets as an 'DER', use [`parse`] instead.
    ///
    /// [`parse`]: Self::parse
    ///
    /// # Safety
    ///
    /// The behavior is undefined if `bytes` is not formatted as a BER.
    ///
    /// # Examples
    ///
    /// ```
    /// use bsn1::Ber;
    ///
    /// let ber = Ber::from(5_i32);
    /// let serialized = ber.clone().into_vec();
    /// let from_vec = unsafe { Ber::from_vec_unchecked(serialized) };
    ///
    /// assert_eq!(ber, from_vec);
    /// ```
    pub unsafe fn from_vec_unchecked(bytes: Vec<u8>) -> Self {
        Self {
            buffer: Buffer::from(bytes),
        }
    }

    /// Creates a new instance containing concatnated `contents`.
    ///
    /// The length octets will be `definite`.
    ///
    /// # Panics
    ///
    /// Panics if the total length exceeds `isize::MAX`.
    ///
    /// # Examples
    ///
    /// ```
    /// use bsn1::{Ber, ContentsRef, IdRef};
    ///
    /// // Build an sequence DER containing 2 other DERs.
    /// let contents0 = vec![Ber::from("foo"), Ber::from(29_i32)];
    /// let ber0 = Ber::from_id_iterator(IdRef::sequence(), contents0.iter());
    ///
    /// let mut contents1: Vec<u8> = Ber::from("foo").into_vec();
    /// contents1.extend_from_slice(&Ber::from(29_i32).into_vec());
    /// let ber1 = Ber::new(IdRef::sequence(), <&ContentsRef>::from(&contents1[..]));
    ///
    /// assert_eq!(ber0, ber1);
    ///
    /// // Build an utf8-string DER using function `from_id_iterator()`.
    /// let contents = vec!["Foo", "Bar"];
    /// let ber = Ber::from_id_iterator(
    ///             IdRef::utf8_string(), contents.iter().map(|s| s.as_bytes()));
    /// assert_eq!(ber, Ber::from("FooBar"));
    /// ```
    pub fn from_id_iterator<I>(id: &IdRef, contents: I) -> Self
    where
        I: Iterator + Clone,
        I::Item: AsRef<[u8]>,
    {
        let der = Der::from_id_iterator(id, contents);
        Self::from(der)
    }

    /// Creates a new instance containing concatnated `contents` with indefinite length.
    ///
    /// # Safety
    ///
    /// ASN.1 defined that the contents of indefinite length BER must be a sequence of BERs,
    /// and must be terminated by 'EOC BER'.
    ///
    /// The methods of `Ber` works fine even if the user violates the rule, however, such instance
    /// may not be parsed again once after serialized.
    ///
    /// # Panics
    ///
    /// Panics if the total length exceeds `isize::MAX`.
    ///
    /// # Examples
    ///
    /// ```
    /// use bsn1::{Ber, BerRef, IdRef};
    ///
    /// // Build an sequence DER containing 2 other DERs.
    /// let contents0 = vec![Ber::from("foo"), Ber::from(29_i32), BerRef::eoc().into()];
    /// let ber0
    ///     = unsafe { Ber::from_id_iterator_indefinite(IdRef::sequence(), contents0.iter()) };
    ///
    /// let mut contents1: Vec<u8> = Ber::from("foo").into_vec();
    /// contents1.extend_from_slice(&Ber::from(29_i32).as_ref());
    /// contents1.extend_from_slice(BerRef::eoc().as_ref());
    /// let ber1 = unsafe { Ber::new_indefinite(IdRef::sequence(), contents1.as_slice().into()) };
    ///
    /// assert_eq!(ber0, ber1);
    /// ```
    pub unsafe fn from_id_iterator_indefinite<I>(id: &IdRef, contents: I) -> Self
    where
        I: Iterator + Clone,
        I::Item: AsRef<[u8]>,
    {
        let length = contents
            .clone()
            .fold(0, |acc, item| acc + item.as_ref().len());
        let length_bytes = Length::Indefinite.to_bytes();
        let total_len = id.len() + length_bytes.len() + length;

        let mut buffer = Buffer::with_capacity(total_len);
        unsafe {
            buffer.extend_from_slice(id.as_ref());
            buffer.extend_from_slice(&length_bytes);
            contents.for_each(|c| buffer.extend_from_slice(c.as_ref()));
        }

        Self { buffer }
    }

    /// Consumes `self`, returning `Vec`.
    ///
    /// # Examples
    ///
    /// ```
    /// use bsn1::{Ber, Contents, IdRef};
    ///
    /// let id = IdRef::octet_string();
    /// let contents = Contents::from(&[0, 1, 2, 3, 4]);
    ///
    /// let ber = Ber::new(id, &contents);
    /// let v = ber.clone().into_vec();
    ///
    /// assert_eq!(ber.as_ref() as &[u8], &v);
    /// ```
    pub fn into_vec(self) -> Vec<u8> {
        self.buffer.into_vec()
    }

    /// Appends `byte` to the end of the 'contents octets'.
    ///
    /// If `self` had indefinite length, the length octets will not be changed;
    /// otherwise, the length octets will be `Length::Definite(new_length)`
    /// where `new_length` is the current byte count of the 'contents octets' plus 1.
    ///
    /// Note that this method may shift the 'contents octets',
    /// and the performance is `O(n)` where `n` is the byte count of 'contents octets'
    /// in the worst-case,
    /// because the byte count of 'length octets' may change.
    /// (BER is composed of 'identifier octets', 'length octets' and 'contents octets'
    /// in this order.)
    ///
    /// # Examples
    ///
    /// ```
    /// use bsn1::{Ber, BerRef, IdRef, Length};
    ///
    /// let bytes: Vec<u8> = (0..10).collect();
    ///
    /// // Push to BER with definite length.
    /// let mut ber = Ber::from(&bytes[..9]);
    /// ber.push(bytes[9]);
    ///
    /// assert_eq!(ber.id(), IdRef::octet_string());
    /// assert_eq!(ber.length(), Length::Definite(bytes.len()));
    /// assert_eq!(ber.contents().as_ref(), &bytes[..]);
    ///
    /// // Push to BER with indefinite length.
    /// let contents = [Ber::from("Foo"), Ber::from(-5_i32)];
    /// let mut ber
    ///         = unsafe { Ber::from_id_iterator_indefinite(IdRef::sequence(), contents.iter()) };
    ///
    /// // Add 'EOC BER' to the end of 'contents octets'.
    /// for byte in BerRef::eoc().as_ref() {
    ///    ber.push(*byte);
    /// }
    ///
    /// assert_eq!(ber.id(), IdRef::sequence());
    /// assert!(ber.length().is_indefinite());
    ///
    /// let mut contents_: &[u8] = ber.contents().as_ref();
    /// let contents0_ = BerRef::parse(&mut contents_).unwrap();
    /// let contents1_ = BerRef::parse(&mut contents_).unwrap();
    /// let contents2_ = BerRef::parse(&mut contents_).unwrap();
    /// assert_eq!(contents_.is_empty(), true);
    ///
    /// assert_eq!(contents0_, &contents[0]);
    /// assert_eq!(contents1_, &contents[1]);
    /// assert_eq!(contents2_, BerRef::eoc());
    /// ```
    pub fn push(&mut self, byte: u8) {
        self.extend_from_slice(&[byte]);
    }

    /// Appends `bytes` to the end of the 'contents octets'.
    ///
    /// If `self` had indefinite length, the length octets will not be changed;
    /// otherwise, the length octets will be `Length::Definite(new_length)`
    /// where `new_length` is the current byte count of the 'contents octets' plus `bytes.len()`.
    ///
    /// Note that this method may shift the 'contents octets',
    /// and the performance is `O(n)` where `n` is the byte count of 'contents octets'
    /// in the worst-case,
    /// because the byte count of 'length octets' may change.
    /// (BER is composed of 'identifier octets', 'length octets' and 'contents octets'
    /// in this order.)
    ///
    /// # Examples
    ///
    /// ```
    /// use bsn1::{Ber, IdRef, Length};
    ///
    /// let bytes: Vec<u8> = (0..10).collect();
    ///
    /// // Extends BER with definite length.
    /// let mut ber = Ber::from(&bytes[..5]);
    /// ber.extend_from_slice(&bytes[5..]);
    ///
    /// assert_eq!(ber.id(), IdRef::octet_string());
    /// assert_eq!(ber.length(), Length::Definite(bytes.len()));
    /// assert_eq!(ber.contents().as_ref(), &bytes[..]);
    ///
    /// // Extends BER with indefinite length.
    /// let mut ber = unsafe { Ber::new_indefinite(IdRef::octet_string(), (&bytes[..5]).into()) };
    /// ber.extend_from_slice(&bytes[5..]);
    ///
    /// assert_eq!(ber.id(), IdRef::octet_string());
    /// assert!(ber.length().is_indefinite());
    /// assert_eq!(ber.contents().as_ref(), &bytes[..]);
    /// ```
    pub fn extend_from_slice<T>(&mut self, bytes: &T)
    where
        T: ?Sized + AsRef<[u8]>,
    {
        let bytes = bytes.as_ref();

        match self.length() {
            Length::Definite(_) => unsafe {
                let this = std::mem::transmute::<&mut Self, &mut Der>(self);
                this.extend_from_slice(bytes);
            },
            Length::Indefinite => {
                self.buffer.reserve(bytes.len());

                let src = bytes.as_ptr();
                let dst = unsafe { self.buffer.as_mut_ptr().add(self.buffer.len()) };
                unsafe {
                    src.copy_to_nonoverlapping(dst, bytes.len());
                    self.buffer.set_len(self.buffer.len() + bytes.len());
                }
            }
        }
    }

    /// Enshorten the `contents`, keeping the first `new_length` and discarding the rest
    /// if `new_length` is less than the length of the current 'contents octets';
    /// otherwise, does nothing.
    ///
    /// If `self` had indefinite length, the length octets will not be changed;
    /// otherwise, the length octets will be `Length::Definite(new_length)`
    /// if `new_length` is less than the current byte count of the 'contents octets'.
    ///
    /// Note that this method may shift the 'contents octets',
    /// and the performance is `O(n)` where `n` is the byte count of 'contents octets'
    /// in the worst-case,
    /// because the byte count of 'length octets' may change.
    /// (BER is composed of 'identifier octets', 'length octets' and 'contents octets'
    /// in this order.)
    ///
    /// # Warnings
    ///
    /// `new_length` specifies the length of the 'contents octets' after this method returns.
    /// The total length of `self` will be greater than `new_length`.
    ///
    /// # Examples
    ///
    /// ```
    /// use bsn1::{Ber, IdRef, Length};
    ///
    /// let bytes: Vec<u8> = (0..=255).collect();
    ///
    /// // Truncate BER with definite length.
    /// let mut ber = Ber::from(&bytes[..]);
    /// ber.truncate(100);
    ///
    /// assert_eq!(ber.id(), IdRef::octet_string());
    /// assert_eq!(ber.length(), Length::Definite(100));
    /// assert_eq!(ber.contents().as_ref(), &bytes[..100]);
    ///
    /// // Truncate BER with indefinite length.
    /// let mut ber = unsafe { Ber::new_indefinite(IdRef::octet_string(), (&bytes[..]).into()) };
    /// ber.truncate(100);
    ///
    /// assert_eq!(ber.id(), IdRef::octet_string());
    /// assert!(ber.length().is_indefinite());
    /// assert_eq!(ber.contents().as_ref(), &bytes[..100]);
    /// ```
    pub fn truncate(&mut self, new_length: usize) {
        match self.length() {
            Length::Definite(_) => unsafe {
                let this = std::mem::transmute::<&mut Self, &mut Der>(self);
                this.truncate(new_length);
            },
            Length::Indefinite => {
                let old_length = self.contents().len();
                if old_length <= new_length {
                    return;
                } else {
                    let new_total_len = self.buffer.len() + new_length - old_length;
                    unsafe { self.buffer.set_len(new_total_len) };
                }
            }
        }
    }
}

#[doc(hidden)]
impl From<Buffer> for Ber {
    fn from(buffer: Buffer) -> Self {
        Self { buffer }
    }
}

impl From<&DerRef> for Ber {
    fn from(der: &DerRef) -> Self {
        <&BerRef>::from(der).to_owned()
    }
}

impl From<Der> for Ber {
    fn from(der: Der) -> Self {
        Self {
            buffer: crate::der::disassemble_der(der),
        }
    }
}

impl From<&BerRef> for Ber {
    fn from(ber_ref: &BerRef) -> Self {
        ber_ref.to_owned()
    }
}

impl From<bool> for Ber {
    /// Creates a new instance representing a boolean containing `contents`.
    fn from(contents: bool) -> Self {
        Der::from(contents).into()
    }
}

impl From<i8> for Ber {
    /// Creates a new instance representing a integer containing `contents`.
    fn from(contents: i8) -> Self {
        Der::from(contents).into()
    }
}

impl From<u8> for Ber {
    /// Creates a new instance representing a integer containing `contents`.
    fn from(contents: u8) -> Self {
        Der::from(contents).into()
    }
}

impl From<i16> for Ber {
    /// Creates a new instance representing a integer containing `contents`.
    fn from(contents: i16) -> Self {
        Der::from(contents).into()
    }
}

impl From<u16> for Ber {
    /// Creates a new instance representing a integer containing `contents`.
    fn from(contents: u16) -> Self {
        Der::from(contents).into()
    }
}

impl From<i32> for Ber {
    /// Creates a new instance representing a integer containing `contents`.
    fn from(contents: i32) -> Self {
        Der::from(contents).into()
    }
}

impl From<u32> for Ber {
    /// Creates a new instance representing a integer containing `contents`.
    fn from(contents: u32) -> Self {
        Der::from(contents).into()
    }
}

impl From<i64> for Ber {
    /// Creates a new instance representing a integer containing `contents`.
    fn from(contents: i64) -> Self {
        Der::from(contents).into()
    }
}

impl From<u64> for Ber {
    /// Creates a new instance representing a integer containing `contents`.
    fn from(contents: u64) -> Self {
        Der::from(contents).into()
    }
}

impl From<i128> for Ber {
    /// Creates a new instance representing a integer containing `contents`.
    fn from(contents: i128) -> Self {
        Der::from(contents).into()
    }
}

impl From<u128> for Ber {
    /// Creates a new instance representing a integer containing `contents`.
    fn from(contents: u128) -> Self {
        Der::from(contents).into()
    }
}

impl From<isize> for Ber {
    /// Creates a new instance representing a integer containing `contents`.
    fn from(contents: isize) -> Self {
        Der::from(contents).into()
    }
}

impl From<usize> for Ber {
    /// Creates a new instance representing a integer containing `contents`.
    fn from(contents: usize) -> Self {
        Der::from(contents).into()
    }
}

impl From<&str> for Ber {
    /// Creates a new instance representing a utf8-string containing `contents`.
    fn from(contents: &str) -> Self {
        Der::from(contents).into()
    }
}

impl From<&[u8]> for Ber {
    /// Creates a new instance representing an octet-string containing `contents`.
    fn from(contents: &[u8]) -> Self {
        Der::from(contents).into()
    }
}

impl AsRef<[u8]> for Ber {
    fn as_ref(&self) -> &[u8] {
        self.buffer.as_slice()
    }
}

impl AsRef<BerRef> for Ber {
    fn as_ref(&self) -> &BerRef {
        self.deref()
    }
}

impl AsMut<BerRef> for Ber {
    fn as_mut(&mut self) -> &mut BerRef {
        self.deref_mut()
    }
}

impl Borrow<BerRef> for Ber {
    fn borrow(&self) -> &BerRef {
        self.deref()
    }
}

impl Deref for Ber {
    type Target = BerRef;

    fn deref(&self) -> &Self::Target {
        unsafe { BerRef::from_bytes_unchecked(self.buffer.as_slice()) }
    }
}

impl DerefMut for Ber {
    fn deref_mut(&mut self) -> &mut Self::Target {
        unsafe { BerRef::from_mut_bytes_unchecked(self.buffer.as_mut_slice()) }
    }
}

impl<T> PartialEq<T> for Ber
where
    T: Borrow<BerRef>,
{
    fn eq(&self, other: &T) -> bool {
        self.deref() == other.borrow()
    }
}

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

    #[test]
    fn parse_deinite() {
        let bytes: Vec<u8> = (0..=u8::MAX).collect();
        for i in 0..bytes.len() {
            let ber = Ber::from(&bytes[..i]);
            let mut bytes: &[u8] = ber.as_ref();
            let parsed = Ber::parse(&mut bytes).unwrap();

            assert_eq!(ber, parsed);
            assert_eq!(bytes.len(), 0);
        }
    }

    #[test]
    fn parse_indefinite() {
        let bers: Vec<Ber> = (0..10).map(Ber::from).collect();

        for i in 0..10 {
            let contents: Vec<u8> = bers[..i]
                .iter()
                .map(|ber| ber.as_ref() as &[u8])
                .flatten()
                .copied()
                .collect();
            let mut ber =
                unsafe { Ber::new_indefinite(IdRef::sequence(), contents.as_slice().into()) };
            ber.extend_from_slice(BerRef::eoc());

            let mut bytes: &[u8] = ber.as_ref();
            let parsed = Ber::parse(&mut bytes).unwrap();

            assert_eq!(ber, parsed);
            assert_eq!(bytes.len(), 0);
        }
    }

    #[test]
    fn parse_deinite_in_definite() {
        let bytes: Vec<u8> = (0..=u8::MAX).collect();
        for i in 0..bytes.len() {
            let inner = Ber::from(&bytes[..i]);

            let ber = Ber::new(IdRef::sequence(), (inner.as_ref() as &[u8]).into());
            let mut bytes: &[u8] = ber.as_ref();

            let parsed = Ber::parse(&mut bytes).unwrap();
            assert_eq!(ber, parsed);
            assert_eq!(bytes.len(), 0);
        }
    }

    #[test]
    fn parse_indeinite_in_definite() {
        let bers: Vec<Ber> = (0..10).map(Ber::from).collect();
        for i in 0..bers.len() {
            let contents: Vec<u8> = bers[..i]
                .iter()
                .map(|ber| ber.as_ref() as &[u8])
                .flatten()
                .copied()
                .collect();
            let mut inner =
                unsafe { Ber::new_indefinite(IdRef::octet_string(), contents.as_slice().into()) };
            inner.extend_from_slice(BerRef::eoc());

            let ber = Ber::new(IdRef::sequence(), (inner.as_ref() as &[u8]).into());
            let mut bytes: &[u8] = ber.as_ref();

            let parsed = Ber::parse(&mut bytes).unwrap();
            assert_eq!(ber, parsed);
            assert_eq!(bytes.len(), 0);
        }
    }

    #[test]
    fn parse_deinite_in_indefinite() {
        let bytes: Vec<u8> = (0..=u8::MAX).collect();
        for i in 0..bytes.len() {
            let inner = Ber::from(&bytes[..i]);

            let mut ber =
                unsafe { Ber::new_indefinite(IdRef::sequence(), (inner.as_ref() as &[u8]).into()) };
            ber.extend_from_slice(BerRef::eoc());

            let mut bytes: &[u8] = ber.as_ref();
            let parsed = Ber::parse(&mut bytes).unwrap();

            assert_eq!(ber, parsed);
            assert_eq!(bytes.len(), 0);
        }
    }

    #[test]
    fn parse_indeinite_in_indefinite() {
        let bers: Vec<Ber> = (0..10).map(Ber::from).collect();
        for i in 0..bers.len() {
            let contents: Vec<u8> = bers[..i]
                .iter()
                .map(|ber| ber.as_ref() as &[u8])
                .flatten()
                .copied()
                .collect();
            let mut inner =
                unsafe { Ber::new_indefinite(IdRef::octet_string(), contents.as_slice().into()) };
            inner.extend_from_slice(BerRef::eoc());

            let mut ber =
                unsafe { Ber::new_indefinite(IdRef::sequence(), (inner.as_ref() as &[u8]).into()) };
            ber.extend_from_slice(BerRef::eoc());

            let mut bytes: &[u8] = ber.as_ref();
            let parsed = Ber::parse(&mut bytes).unwrap();

            assert_eq!(ber, parsed);
            assert_eq!(bytes.len(), 0);
        }
    }

    #[test]
    fn truncate_definite() {
        let contents: Vec<u8> = (0..=u8::MAX).collect();
        for i in 0..contents.len() {
            let mut ber = Ber::from(&contents[..]);

            ber.truncate(i as usize);
            assert_eq!(ber.id(), IdRef::octet_string());
            assert_eq!(ber.length(), Length::Definite(i as usize));
            assert_eq!(ber.contents().as_ref(), &contents[..i as usize]);
        }

        for &i in &[contents.len(), contents.len() + 1] {
            let mut ber = Ber::from(&contents[..]);
            ber.truncate(i);

            ber.truncate((ber.as_ref() as &[u8]).len() + 1);
            assert_eq!(ber.id(), IdRef::octet_string());
            assert_eq!(ber.length(), Length::Definite(contents.len()));
            assert_eq!(ber.contents().as_ref(), &contents[..]);
        }
    }

    #[test]
    fn truncate_indefinite() {
        let contents: Vec<u8> = (0..=u8::MAX).collect();
        for i in 0..contents.len() {
            let mut ber =
                unsafe { Ber::new_indefinite(IdRef::octet_string(), (&contents[..]).into()) };

            ber.truncate(i as usize);
            assert_eq!(ber.id(), IdRef::octet_string());
            assert!(ber.length().is_indefinite());
            assert_eq!(ber.contents().as_ref(), &contents[..i as usize]);
        }

        for &i in &[contents.len(), contents.len() + 1] {
            let mut ber =
                unsafe { Ber::new_indefinite(IdRef::octet_string(), (&contents[..]).into()) };
            ber.truncate(i);

            ber.truncate((ber.as_ref() as &[u8]).len() + 1);
            assert_eq!(ber.id(), IdRef::octet_string());
            assert!(ber.length().is_indefinite());
            assert_eq!(ber.contents().as_ref(), &contents[..]);
        }
    }

    #[test]
    fn extend_definite_from_slice() {
        let bytes: Vec<u8> = (0..=u8::MAX).collect();

        for i in 0..bytes.len() {
            for j in 0..bytes.len() {
                let mut ber = Ber::from(&bytes[..i]);
                ber.extend_from_slice(&bytes[..j]);

                assert_eq!(ber.id(), IdRef::octet_string());
                assert_eq!(ber.length(), Length::Definite(i + j));
                assert_eq!(&ber.contents().as_ref()[..i], &bytes[..i]);
                assert_eq!(&ber.contents().as_ref()[i..], &bytes[..j]);
            }
        }
    }

    #[test]
    fn extend_indefinite_from_slice() {
        let bytes: Vec<u8> = (0..=u8::MAX).collect();

        for i in 0..bytes.len() {
            for j in 0..bytes.len() {
                let mut ber =
                    unsafe { Ber::new_indefinite(IdRef::octet_string(), (&bytes[..i]).into()) };
                ber.extend_from_slice(&bytes[..j]);

                assert_eq!(ber.id(), IdRef::octet_string());
                assert!(ber.length().is_indefinite());
                assert_eq!(&ber.contents().as_ref()[..i], &bytes[..i]);
                assert_eq!(&ber.contents().as_ref()[i..], &bytes[..j]);
            }
        }
    }
}