internet 0.0.3

Network library for rust
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
//! TLS 1.3 Extensions encoding following [RFC 8446].
//!
//! Encoding is supported for the following structures:
//!
//!  - [`ExtensionType`]
//!  - [`Extension`]
//!  - [`NamedGroup`]
//!  - [`KeyShareEntry`]
//!  - [`SignatureScheme`]
//!  - [`ServerName`]
//!  - [`ServerNameEntry`]
//!  - [`MaxFragmentLength`]
//!  - [`StatusRequest`]
//!  - [`SupportedGroups`]
//!  - [`SignatureAlgorithms`]
//!  - [`UseSrtp`]
//!  - [`Heartbeat`]
//!  - [`ApplicationLayerProtocolNegotiation`]
//!  - [`SignedCertificateTimestamp`]
//!  - [`ClientCertificateType`]
//!  - [`ServerCertificateType`]
//!  - [`Padding`]
//!  - [`KeyShare`]
//!  - [`PreSharedKey`]
//!  - [`PskIdentity`]
//!  - [`PskKeyExchangeModes`]
//!  - [`EarlyData`]
//!  - [`Cookie`]
//!  - [`SupportedVersions`]
//!  - [`CertificateAuthorities`]
//!  - [`OidFilters`]
//!  - [`OidFilter`]
//!  - [`PostHandshakeAuth`]
//!  - [`SignatureAlgorithmsCert`]
//!
//! [RFC 8446]: https://datatracker.ietf.org/doc/html/rfc8446

use crate::{
    Buf, BufMut, BufResult, Codec, Cursor,
    tls::{ProtocolVersion, TlsVec},
    tls1_3::SignatureScheme,
};

/// An Extension Type following [Section 4.2].
///
/// According to RFC 8446, unknown extensions MUST be ignored, not treated as errors.
/// Therefore, this is implemented as a newtype struct with constants rather than an enum.
///
/// [Section 4.2]: https://datatracker.ietf.org/doc/html/rfc8446#section-4.2
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ExtensionType(pub u16);

impl ExtensionType {
    /// server_name(0)
    pub const SERVER_NAME: Self = Self(0);
    /// status_request(5)
    pub const STATUS_REQUEST: Self = Self(5);
    /// supported_groups(10)
    pub const SUPPORTED_GROUPS: Self = Self(10);
    /// signature_algorithms(13)
    pub const SIGNATURE_ALGORITHMS: Self = Self(13);
    /// use_srtp(14)
    pub const USE_SRTP: Self = Self(14);
    /// heartbeat(15)
    pub const HEARTBEAT: Self = Self(15);
    /// application_layer_protocol_negotiation(16)
    pub const APPLICATION_LAYER_PROTOCOL_NEGOTIATION: Self = Self(16);
    /// client_certificate_type(19)
    pub const CLIENT_CERTIFICATE_TYPE: Self = Self(19);
    /// server_certificate_type(20)
    pub const SERVER_CERTIFICATE_TYPE: Self = Self(20);
    /// padding(21)
    pub const PADDING: Self = Self(21);
    /// compress_certificate(27)
    pub const COMPRESS_CERTIFICATE: Self = Self(27);
    /// record_size_limit(28)
    pub const RECORD_SIZE_LIMIT: Self = Self(28);
    /// delegated_credential(34)
    pub const DELEGATED_CREDENTIAL: Self = Self(34);
    /// supported_ekt_ciphers(39)
    pub const SUPPORTED_EKT_CIPHERS: Self = Self(39);
    /// pre_shared_key(41)
    pub const PRE_SHARED_KEY: Self = Self(41);
    /// early_data(42)
    pub const EARLY_DATA: Self = Self(42);
    /// supported_versions(43)
    pub const SUPPORTED_VERSIONS: Self = Self(43);
    /// cookie(44)
    pub const COOKIE: Self = Self(44);
    /// psk_key_exchange_modes(45)
    pub const PSK_KEY_EXCHANGE_MODES: Self = Self(45);
    /// certificate_authorities(47)
    pub const CERTIFICATE_AUTHORITIES: Self = Self(47);
    /// oid_filters(48)
    pub const OID_FILTERS: Self = Self(48);
    /// post_handshake_auth(49)
    pub const POST_HANDSHAKE_AUTH: Self = Self(49);
    /// signature_algorithms_cert(50)
    pub const SIGNATURE_ALGORITHMS_CERT: Self = Self(50);
    /// key_share(51)
    pub const KEY_SHARE: Self = Self(51);
    /// transparency_info(52)
    pub const TRANSPARENCY_INFO: Self = Self(52);
    /// external_id_hash(55)
    pub const EXTERNAL_ID_HASH: Self = Self(55);
    /// external_session_id(56)
    pub const EXTERNAL_SESSION_ID: Self = Self(56);
    /// quic_transport_parameters(57)
    pub const QUIC_TRANSPORT_PARAMETERS: Self = Self(57);
    /// ticket_request(58)
    pub const TICKET_REQUEST: Self = Self(58);
    /// ech_outer_extensions(64768)
    pub const ECH_OUTER_EXTENSIONS: Self = Self(64768);
    /// encrypted_client_hello(65037)
    pub const ENCRYPTED_CLIENT_HELLO: Self = Self(65037);
}

impl Codec for ExtensionType {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        self.0.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        Ok(Self(u16::decode(reader, ())?))
    }
}

/// An Extension following [Section 4.2].
///
/// [Section 4.2]: https://datatracker.ietf.org/doc/html/rfc8446#section-4.2
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Extension {
    /// The type of the extension.
    pub extension_type: ExtensionType,
    /// The opaque extension data.
    pub extension_data: TlsVec<u8, u16>,
}

impl Codec for Extension {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        self.extension_type.encode(writer, ())?;
        self.extension_data.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        Ok(Self {
            extension_type: ExtensionType::decode(reader, ())?,
            extension_data: TlsVec::<u8, u16>::decode(reader, ())?,
        })
    }
}

/// A Named Group following [Section 4.2.7].
///
/// Unknown groups are ignored per RFC, so this is a struct with constants.
///
/// [Section 4.2.7]: https://datatracker.ietf.org/doc/html/rfc8446#section-4.2.7
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct NamedGroup(pub u16);

impl NamedGroup {
    /// secp256r1(0x0017)
    pub const SECP256R1: Self = Self(0x0017);
    /// secp384r1(0x0018)
    pub const SECP384R1: Self = Self(0x0018);
    /// x25519(0x001D)
    pub const X25519: Self = Self(0x001D);
    /// x448(0x001E)
    pub const X448: Self = Self(0x001E);
}

impl Codec for NamedGroup {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        self.0.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        Ok(Self(u16::decode(reader, ())?))
    }
}

/// A Key Share Entry following [Section 4.2.8].
///
/// [Section 4.2.8]: https://datatracker.ietf.org/doc/html/rfc8446#section-4.2.8
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct KeyShareEntry {
    /// The named group.
    pub group: NamedGroup,
    /// The key exchange data.
    pub key_exchange: TlsVec<u8, u16>,
}

impl Codec for KeyShareEntry {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        self.group.encode(writer, ())?;
        self.key_exchange.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        Ok(Self {
            group: NamedGroup::decode(reader, ())?,
            key_exchange: TlsVec::<u8, u16>::decode(reader, ())?,
        })
    }
}

/// Server Name extension data following [RFC 6066].
///
/// [RFC 6066]: https://datatracker.ietf.org/doc/html/rfc6066#section-3
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ServerName(pub TlsVec<ServerNameEntry, u16>);

impl Codec for ServerName {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        self.0.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        Ok(Self(TlsVec::<ServerNameEntry, u16>::decode(reader, ())?))
    }
}

/// A Server Name Entry following [RFC 6066].
///
/// [RFC 6066]: https://datatracker.ietf.org/doc/html/rfc6066#section-3
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ServerNameEntry {
    /// The name type (0 = host_name).
    pub name_type: u8,
    /// The name data.
    pub name: TlsVec<u8, u16>,
}

impl Codec for ServerNameEntry {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        self.name_type.encode(writer, ())?;
        self.name.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        Ok(Self {
            name_type: u8::decode(reader, ())?,
            name: TlsVec::<u8, u16>::decode(reader, ())?,
        })
    }
}

/// Max Fragment Length extension data following [RFC 6066].
///
/// [RFC 6066]: https://datatracker.ietf.org/doc/html/rfc6066#section-4
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct MaxFragmentLength(pub u8);

impl Codec for MaxFragmentLength {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        self.0.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        Ok(Self(u8::decode(reader, ())?))
    }
}

/// Status Request extension data following [RFC 6066].
///
/// [RFC 6066]: https://datatracker.ietf.org/doc/html/rfc6066#section-8
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct StatusRequest {
    /// The status type (1 = ocsp).
    pub status_type: u8,
    /// The responder ID list.
    pub responder_id_list: TlsVec<TlsVec<u8, u16>, u16>,
    /// The request extensions.
    pub request_extensions: TlsVec<u8, u16>,
}

impl Codec for StatusRequest {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        self.status_type.encode(writer, ())?;
        self.responder_id_list.encode(writer, ())?;
        self.request_extensions.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        Ok(Self {
            status_type: u8::decode(reader, ())?,
            responder_id_list: TlsVec::<TlsVec<u8, u16>, u16>::decode(reader, ())?,
            request_extensions: TlsVec::<u8, u16>::decode(reader, ())?,
        })
    }
}

/// Supported Groups extension data following [Section 4.2.7].
///
/// [Section 4.2.7]: https://datatracker.ietf.org/doc/html/rfc8446#section-4.2.7
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct SupportedGroups(pub TlsVec<NamedGroup, u16>);

impl Codec for SupportedGroups {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        self.0.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        Ok(Self(TlsVec::<NamedGroup, u16>::decode(reader, ())?))
    }
}

/// Signature Algorithms extension data following [Section 4.2.3].
///
/// [Section 4.2.3]: https://datatracker.ietf.org/doc/html/rfc8446#section-4.2.3
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct SignatureAlgorithms(pub TlsVec<SignatureScheme, u16>);

impl Codec for SignatureAlgorithms {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        self.0.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        Ok(Self(TlsVec::<SignatureScheme, u16>::decode(reader, ())?))
    }
}

/// Use SRTP extension data following [RFC 5764].
///
/// [RFC 5764]: https://datatracker.ietf.org/doc/html/rfc5764
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct UseSrtp {
    /// The SRTP protection profiles.
    pub profiles: TlsVec<u16, u16>,
    /// The SRTP master key identifier.
    pub mki: TlsVec<u8, u8>,
}

impl Codec for UseSrtp {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        self.profiles.encode(writer, ())?;
        self.mki.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        Ok(Self {
            profiles: TlsVec::<u16, u16>::decode(reader, ())?,
            mki: TlsVec::<u8, u8>::decode(reader, ())?,
        })
    }
}

/// Heartbeat extension data following [RFC 6520].
///
/// [RFC 6520]: https://datatracker.ietf.org/doc/html/rfc6520
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Heartbeat(pub u8);

impl Codec for Heartbeat {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        self.0.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        Ok(Self(u8::decode(reader, ())?))
    }
}

/// Application Layer Protocol Negotiation (ALPN) extension data following [RFC 7301].
///
/// [RFC 7301]: https://datatracker.ietf.org/doc/html/rfc7301
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ApplicationLayerProtocolNegotiation(pub TlsVec<TlsVec<u8, u8>, u16>);

impl Codec for ApplicationLayerProtocolNegotiation {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        self.0.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        Ok(Self(TlsVec::<TlsVec<u8, u8>, u16>::decode(reader, ())?))
    }
}

/// Signed Certificate Timestamp extension data following [RFC 6962].
///
/// [RFC 6962]: https://datatracker.ietf.org/doc/html/rfc6962
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct SignedCertificateTimestamp(pub TlsVec<u8, u16>);

impl Codec for SignedCertificateTimestamp {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        self.0.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        Ok(Self(TlsVec::<u8, u16>::decode(reader, ())?))
    }
}

/// Client Certificate Type extension data.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ClientCertificateType(pub u8);

impl Codec for ClientCertificateType {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        self.0.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        Ok(Self(u8::decode(reader, ())?))
    }
}

/// Server Certificate Type extension data.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ServerCertificateType(pub u8);

impl Codec for ServerCertificateType {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        self.0.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        Ok(Self(u8::decode(reader, ())?))
    }
}

/// Padding extension data following [RFC 7685].
///
/// [RFC 7685]: https://datatracker.ietf.org/doc/html/rfc7685
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Padding(pub TlsVec<u8, u16>);

impl Codec for Padding {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        self.0.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        Ok(Self(TlsVec::<u8, u16>::decode(reader, ())?))
    }
}

/// Key Share extension data for ClientHello following [Section 4.2.8].
///
/// [Section 4.2.8]: https://datatracker.ietf.org/doc/html/rfc8446#section-4.2.8
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct KeyShare(pub TlsVec<KeyShareEntry, u16>);

impl Codec for KeyShare {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        self.0.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        Ok(Self(TlsVec::<KeyShareEntry, u16>::decode(reader, ())?))
    }
}

/// Pre-Shared Key extension data for ClientHello following [Section 4.2.9].
///
/// [Section 4.2.9]: https://datatracker.ietf.org/doc/html/rfc8446#section-4.2.9
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct PreSharedKey {
    /// The PSK identities.
    pub identities: TlsVec<PskIdentity, u16>,
    /// The PSK binders.
    pub binders: TlsVec<TlsVec<u8, u8>, u16>,
}

impl Codec for PreSharedKey {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        self.identities.encode(writer, ())?;
        self.binders.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        Ok(Self {
            identities: TlsVec::<PskIdentity, u16>::decode(reader, ())?,
            binders: TlsVec::<TlsVec<u8, u8>, u16>::decode(reader, ())?,
        })
    }
}

/// A PSK Identity following [Section 4.2.9].
///
/// [Section 4.2.9]: https://datatracker.ietf.org/doc/html/rfc8446#section-4.2.9
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct PskIdentity {
    /// The identity label.
    pub identity: TlsVec<u8, u16>,
    /// The obfuscated ticket age.
    pub obfuscated_ticket_age: u32,
}

impl Codec for PskIdentity {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        self.identity.encode(writer, ())?;
        self.obfuscated_ticket_age.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        Ok(Self {
            identity: TlsVec::<u8, u16>::decode(reader, ())?,
            obfuscated_ticket_age: u32::decode(reader, ())?,
        })
    }
}

/// PSK Key Exchange Modes extension data following [Section 4.2.9].
///
/// [Section 4.2.9]: https://datatracker.ietf.org/doc/html/rfc8446#section-4.2.9
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct PskKeyExchangeModes(pub TlsVec<u8, u8>);

impl Codec for PskKeyExchangeModes {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        self.0.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        Ok(Self(TlsVec::<u8, u8>::decode(reader, ())?))
    }
}

/// Early Data extension data following [Section 4.2.10].
///
/// [Section 4.2.10]: https://datatracker.ietf.org/doc/html/rfc8446#section-4.2.10
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct EarlyData {
    /// The maximum early data size (present in NewSessionTicket, absent in ClientHello).
    pub max_early_data_size: Option<u32>,
}

impl Codec for EarlyData {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        match self.max_early_data_size {
            Some(size) => size.encode(writer, ()),
            None => Ok(()),
        }
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        let max_early_data_size = if reader.remaining() >= 4 {
            Some(u32::decode(reader, ())?)
        } else {
            None
        };
        Ok(Self {
            max_early_data_size,
        })
    }
}

/// Cookie extension data following [Section 4.2.2].
///
/// [Section 4.2.2]: https://datatracker.ietf.org/doc/html/rfc8446#section-4.2.2
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Cookie(pub TlsVec<u8, u16>);

impl Codec for Cookie {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        self.0.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        Ok(Self(TlsVec::<u8, u16>::decode(reader, ())?))
    }
}

/// Supported Versions extension data for ClientHello following [Section 4.2.1].
///
/// [Section 4.2.1]: https://datatracker.ietf.org/doc/html/rfc8446#section-4.2.1
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct SupportedVersions(pub TlsVec<ProtocolVersion, u8>);

impl Codec for SupportedVersions {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        self.0.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        Ok(Self(TlsVec::<ProtocolVersion, u8>::decode(reader, ())?))
    }
}

/// Certificate Authorities extension data following [Section 4.2.4].
///
/// [Section 4.2.4]: https://datatracker.ietf.org/doc/html/rfc8446#section-4.2.4
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CertificateAuthorities(pub TlsVec<TlsVec<u8, u16>, u16>);

impl Codec for CertificateAuthorities {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        self.0.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        Ok(Self(TlsVec::<TlsVec<u8, u16>, u16>::decode(reader, ())?))
    }
}

/// OID Filters extension data following [Section 4.2.5].
///
/// [Section 4.2.5]: https://datatracker.ietf.org/doc/html/rfc8446#section-4.2.5
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct OidFilters(pub TlsVec<OidFilter, u16>);

impl Codec for OidFilters {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        self.0.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        Ok(Self(TlsVec::<OidFilter, u16>::decode(reader, ())?))
    }
}

/// An OID Filter following [Section 4.2.5].
///
/// [Section 4.2.5]: https://datatracker.ietf.org/doc/html/rfc8446#section-4.2.5
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct OidFilter {
    /// The certificate extension OID.
    pub certificate_extension_oid: TlsVec<u8, u8>,
    /// The certificate extension value.
    pub certificate_extension_value: TlsVec<u8, u8>,
}

impl Codec for OidFilter {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        self.certificate_extension_oid.encode(writer, ())?;
        self.certificate_extension_value.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        Ok(Self {
            certificate_extension_oid: TlsVec::<u8, u8>::decode(reader, ())?,
            certificate_extension_value: TlsVec::<u8, u8>::decode(reader, ())?,
        })
    }
}

/// Post Handshake Auth extension data following [Section 4.2.6].
///
/// [Section 4.2.6]: https://datatracker.ietf.org/doc/html/rfc8446#section-4.2.6
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct PostHandshakeAuth;

impl Codec for PostHandshakeAuth {
    fn encode<W: BufMut>(&self, _writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        Ok(())
    }

    fn decode<R: Buf>(_reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        Ok(Self)
    }
}

/// Signature Algorithms Cert extension data following [Section 4.2.3].
///
/// [Section 4.2.3]: https://datatracker.ietf.org/doc/html/rfc8446#section-4.2.3
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct SignatureAlgorithmsCert(pub TlsVec<SignatureScheme, u16>);

impl Codec for SignatureAlgorithmsCert {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        self.0.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        Ok(Self(TlsVec::<SignatureScheme, u16>::decode(reader, ())?))
    }
}

#[cfg(test)]
mod tests {
    use core::fmt::Debug;

    use super::{Extension, ExtensionType, NamedGroup};
    use crate::tls::TlsVec;
    use crate::{Codec, Cursor};

    fn codec_roundtrip<T: Codec<C> + Debug + Eq, C: Copy>(
        etalon_struct: T,
        etalon_bytes: &[u8],
        context: C,
    ) {
        let mut encoded_bytes = vec![];
        {
            let writer = &mut Cursor::new(&mut encoded_bytes);
            etalon_struct.encode(writer, context).unwrap();
        }
        assert_eq!(etalon_bytes, &encoded_bytes);

        let decoded_struct = {
            let reader = &mut Cursor::new(&mut encoded_bytes);
            T::decode(reader, context).unwrap()
        };
        assert_eq!(etalon_struct, decoded_struct);

        encoded_bytes.fill(0x00);
        {
            let writer = &mut Cursor::new(&mut encoded_bytes);
            decoded_struct.encode(writer, context).unwrap();
        }
        assert_eq!(etalon_bytes, &encoded_bytes);
    }

    #[test]
    fn extension_type() {
        let etalon_bytes = &[0x00, 0x00];
        let etalon_struct = ExtensionType::SERVER_NAME;

        codec_roundtrip(etalon_struct, etalon_bytes, ());
    }

    #[test]
    fn named_group() {
        let etalon_bytes = &[0x00, 0x1D];
        let etalon_struct = NamedGroup::X25519;

        codec_roundtrip(etalon_struct, etalon_bytes, ());
    }

    #[test]
    fn extension() {
        let etalon_bytes = &[0x00, 0x00, 0x00, 0x00]; // empty server_name extension
        let etalon_struct = Extension {
            extension_type: ExtensionType::SERVER_NAME,
            extension_data: TlsVec::new(vec![]),
        };

        codec_roundtrip(etalon_struct, etalon_bytes, ());
    }
}