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
// Copyright (c) 2022 Nathaniel Bennett
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use crate::WireError;
use core::{cmp, mem, str};

#[cfg(feature = "ioslice")]
use std::io;

#[cfg(feature = "ioslice")]
pub type VectoredBufMut<'a> = &'a mut [io::IoSliceMut<'a>];
#[cfg(not(feature = "ioslice"))]
pub type VectoredBufMut<'a> = &'a mut [&'a mut [u8]];

/// Serialization from a data type to the wire.
///
/// A type that implements this trait guarantees that it can be serialized into a
/// number of bytes that will be written to the provided [`WireCursorMut`]. If the
/// bytes cannot be written to the wire, an error will be returned.
pub trait WireWrite {
    /// Serializes the data type into a number of bytes on the wire, or returns a [`WireError`] on failure.
    ///
    /// The generic boolean `E` designates the intended endianness of the data being written. If `E` is set to
    /// `true`, then the data will be serialized in big endian format; if `false`, it will be serialized
    /// in little endian.
    ///
    /// ## Errors
    ///
    /// [`WireError::InsufficientBytes`] - not enough bytes remained on the cursor to write the type to the wire.
    ///
    /// [`WireError::Internal`] - an internal error occurred in the `wire-rs` library
    fn write_wire<const E: bool>(&self, curs: &mut WireCursorMut<'_>) -> Result<(), WireError>;
}

/// Serialization from a data type to a portion of the wire smaller than the full size of the data type.
///
/// A type that implements this trait guarantees that at least a subset of its values can be serialized
/// into a specified number of bytes (greater than zero but less than the size of the type). The serialized
/// bytes are written to the supplied [`WireCursorMut`]. For values that cannot be serialized into the number
/// of bytes specified, the [`WireError::InvalidData`] error should be returned.
///
/// This trait is most useful for writing integer values to the wire that can be represented in fewer bytes
/// than what the data type is capable of storing, such as writing out a `u32` to 3 bytes. The caller must ensure
/// that the value stored in the data type can fit in the number of bytes specified for the operation to succeed.
///
/// Types implementing this trait should also implement [`WireWrite`] for the case where the specified number of bytes
/// is equal to the size of the type.
pub trait WireWritePart: Sized {
    /// Serializes the data type into exactly `L` bytes on the wire. If the data's value exceeds the bounds of
    /// what can be stored in `L` bytes, this function will return a [`WireError::InvalidData`] error.
    ///
    /// As an example, the following function would return an error because the value contained in the
    /// `u16` can't be represented by a single byte:
    ///
    /// ```rust
    /// use wire_rs::{WireError, WireWriter};
    ///
    /// fn decode_partial_out_of_range() -> Result<(), WireError> {
    ///     let mut buf = [0u8; 4];
    ///     let out_of_range = 0x0100u16;
    ///     let mut writer: WireWriter = WireWriter::new(buf.as_mut_slice());
    ///     writer.write_part::<u16, 1>(&out_of_range) // Returns Err(WireError::InvalidData)
    /// }
    /// ```
    ///
    /// If the `u16` were a value less than or equal to 0xFF, the above function would return an Ok() result.
    ///
    /// The generic boolean `E` designates the intended endianness of the data being written. If `E` is set to
    /// `true`, then the data will be serialized in big endian format; if `false`, it will be serialized in little endian.
    fn write_wire_part<const L: usize, const E: bool>(
        &self,
        curs: &mut WireCursorMut<'_>,
    ) -> Result<(), WireError>;
}

/// Serialization from a data type to the vectored wire.
///
/// A type that implements this trait guarantees that it can be serialized into a
/// number of bytes that will be written to the provided [`VectoredCursorMut`]. If the
/// bytes cannot be written to the vectored wire, an error will be returned.
pub trait VectoredWrite {
    /// Serializes the data type into a number of bytes on the vectored wire, or returns a [`WireError`] on failure.
    ///
    /// The generic boolean `E` designates the intended endianness of the data being written. If `E` is set to
    /// `true`, then the data will be serialized in big endian format; if `false`, it will be serialized
    /// in little endian.
    ///
    /// ## Errors
    ///
    /// [`WireError::InsufficientBytes`] - not enough bytes remained on the cursor to write the type to the wire.
    ///
    /// [`WireError::Internal`] - an internal error occurred in the `wire-rs` library
    fn write_vectored<const E: bool>(
        &self,
        curs: &mut VectoredCursorMut<'_>,
    ) -> Result<(), WireError>;
}

/// Serialization from an owned data type to a portion of the vectored wire smaller than what the data type would
/// normally produce.
///
/// This trait is most useful for writing integer values to the vectored wire that can be represented in fewer bytes
/// than what the data type is capable of storing, such as writing out a `u32` to 3 bytes. The caller must ensure
/// that the value stored in the data type can fit in the number of bytes specified.
///
/// A type implementing this trait must guarantee that any length `L` passed in that is greater than 0 and smaller
/// than the size of the type can be converted into the type. Types implementing this trait should also implement
/// [`WireWrite`] for the case where `L` is equal to the size of the type.
pub trait VectoredWritePart: Sized {
    /// Serializes the data type into `L` bytes on the vectored wire. If the data's value exceeds the bounds of
    /// what can be stored in `L` bytes, this function will return a WireError::InvalidData error.
    ///
    /// As an example, the following function would return an error because the value contained in the
    /// `u16` can't be represented by a single byte:
    ///
    /// ```rust
    /// use wire_rs::{WireWriter, WireError};
    ///
    /// fn decode_partial_out_of_range() -> Result<(), WireError> {
    ///     let mut buf = [0u8; 4];
    ///     let out_of_range = 0x0100u16;
    ///     let mut writer: WireWriter = WireWriter::new(buf.as_mut_slice());
    ///     writer.write_part::<u16, 1>(&out_of_range) // Returns Err(WireError::InvalidData)
    /// }
    /// ```
    ///
    /// If the value were <= 0xFF instead, the above function would return an Ok() result.
    ///
    /// The generic boolean `E` designates the intended endianness of the data being written. If `E` is set to
    /// `true`, then the data will be serialized in big endian format; if `false`, it will be serialized in little endian.
    fn write_vectored_part<const L: usize, const E: bool>(
        &self,
        curs: &mut VectoredCursorMut<'_>,
    ) -> Result<(), WireError>;
}

/// A cursor that acts as an index over a mutable slice and provides operations to sequentially
/// write data to it.
///
/// When implementing the [`WireWrite`] trait or one of its variants, this cursor provides an
/// interface for writing data to the wire. When an error is returned by the cursor, it
/// should be returned by the trait method being implemented. This can be easily accomplished
/// using the `?` operator.
///
/// NOTE: this is an internal structure, and is NOT meant to be used to write data from a wire
/// in the same manner as a [`WireWriter`]. A `WireWriter` is guaranteed to maintain the index
/// of its last succesful write if any of its methods return an error, while this cursor may move its
/// internal index forward by some unspecified amount when an error is encountered.
pub struct WireCursorMut<'a> {
    wire: &'a mut [u8],
    idx: usize,
}

impl<'a> WireCursorMut<'a> {
    /// Create a `WireCursorMut` that writes to the given slice `wire`.
    fn new(wire: &'a mut [u8]) -> Self {
        WireCursorMut { wire, idx: 0 }
    }

    /// Advance the cursor's index by the given amount, returning an error if
    /// there are insufficient bytes on the wire.
    pub fn advance(&mut self, amount: usize) -> Result<(), WireError> {
        self.idx = match self.idx.checked_add(amount) {
            Some(new_idx) if new_idx > self.wire.len() => return Err(WireError::InsufficientBytes),
            Some(new_idx) => new_idx,
            None => return Err(WireError::InsufficientBytes),
        };

        Ok(())
    }

    /// Advance the cursor's index by the given amount, or to the end of the wire if
    /// the amount exceeds the number of remaining bytes.
    pub fn advance_up_to(&mut self, amount: usize) {
        self.idx = match self.idx.checked_add(amount) {
            Some(new_idx) => cmp::min(new_idx, self.wire.len()),
            None => self.wire.len(),
        };
    }

    /// Check whether the vectored wire has any remaining bytes that can be written
    /// to by the cursor.
    pub fn is_empty(&self) -> bool {
        self.wire.is_empty()
    }

    /// Write a slice of bytes to the wire.
    pub fn put_slice(&mut self, slice: &[u8]) -> Result<(), WireError> {
        let tmp_slice = match self.wire.get_mut(self.idx..) {
            Some(s) => s,
            None => return Err(WireError::Internal), // Invariant: the index should never exceed the bound of the slice
        };

        if tmp_slice.len() < slice.len() {
            return Err(WireError::InsufficientBytes);
        }

        for (a, b) in tmp_slice.iter_mut().zip(slice.iter()) {
            *a = *b;
        }

        self.idx += slice.len(); // tmp_slice.len() >= slice.len, so self.idx + slice.len() <= self.wire.len()
        Ok(())
    }

    /// Serialize a given type `T` that implements the [`WireWrite`] trait to the wire.
    ///
    /// The generic boolean `E` designates the intended endianness of the data being written. If `E` is set to
    /// `true`, then the data will be serialized in big endian format; if `false`, it will be serialized
    /// in little endian.
    pub fn put_writable<T, const E: bool>(&mut self, writable: &T) -> Result<(), WireError>
    where
        T: WireWrite + ?Sized,
    {
        writable.write_wire::<E>(self)
    }

    /// Serialize `L` bytes to the wire from a given type `T` that implements the
    /// [`WireWritePart`] trait.
    ///
    /// The generic boolean `E` designates the intended endianness of the data being written. If `E` is set to
    /// `true`, then the data will be serialized in big endian format; if `false`, it will be serialized
    /// in little endian.
    pub fn put_writable_part<T, const L: usize, const E: bool>(
        &mut self,
        writable: &T,
    ) -> Result<(), WireError>
    where
        T: WireWritePart,
    {
        writable.write_wire_part::<L, E>(self)
    }

    /// Get the number of bytes remaining on the wire for the given cursor.
    pub fn remaining(&self) -> usize {
        self.wire.len().saturating_sub(self.idx)
    }
}

/// A cursor that acts as an index over a set of vectored mutable slices and provides
/// operations to sequentially write data to the slices.
///
/// When implementing the [`VectoredWrite`] trait or one of its variants, this cursor provides an
/// interface for writing data to the vectored wire. When an error is returned by the cursor, it
/// should be returned by the trait method being implemented. This can be easily accomplished
/// using the `?` operator.
///
/// NOTE: this is an internal structure, and is NOT meant to be used to write data from a wire
/// in the same manner as a [`WireWriter`]. A `WireWriter` is guaranteed to maintain the index
/// of its last succesful write if any of its methods return an error, while this cursor may move its
/// internal index forward by some unspecified amount when an error is encountered.
pub struct VectoredCursorMut<'a> {
    wire: VectoredBufMut<'a>,
    arr_idx: usize,
    idx: usize,
}

impl<'a> VectoredCursorMut<'a> {
    /// Create a `VectoredCursorMut` that writes to the given set of vectored slices `wire`.
    fn new(wire: VectoredBufMut<'a>) -> Self {
        VectoredCursorMut {
            wire,
            arr_idx: 0,
            idx: 0,
        }
    }

    /// Advance the cursor's index by the given amount, returning an error if there are insufficient bytes
    /// on the vectored wire.
    pub fn advance(&mut self, mut amount: usize) -> Result<(), WireError> {
        while let Some(curr_slice) = self.wire.get(self.arr_idx) {
            let remaining_slice_len = match curr_slice.len().checked_sub(self.idx) {
                None => return Err(WireError::Internal), // Invariant: the index should never exceed the bound of the slice
                Some(0) => {
                    if self.wire.get(self.arr_idx + 1).is_none() {
                        return Err(WireError::InsufficientBytes);
                    }

                    self.arr_idx += 1; // Checked above to ensure that self.wire[self.arr_idx + 1] exists
                    self.idx = 0;
                    continue;
                }
                Some(l) => l,
            };

            match amount.checked_sub(remaining_slice_len) {
                None | Some(0) => {
                    // Invariant: cannot overflow (as you cannot have a slice greater than `usize::MAX`)
                    self.idx += amount; // amount <= curr_slice.len() - self.idx -> self.idx + amount <= curr_slice.len()
                    return Ok(());
                }
                Some(new_amount) => {
                    self.arr_idx += 1;
                    self.idx = 0;
                    amount = new_amount;
                }
            }
        }

        Err(WireError::InsufficientBytes)
    }

    /// Advance the cursor's index by the given amount, or to the end of the vectored wire if the amount
    /// exceeds the number of remaining bytes.
    pub fn advance_up_to(&mut self, mut amount: usize) {
        while let Some(curr_slice) = self.wire.get(self.arr_idx) {
            let remaining_slice_len = match curr_slice.len().checked_sub(self.idx) {
                None | Some(0) => {
                    // Invariant: None should never occur, as the index should never exceed the bound of the first slice
                    if self.wire.get(self.arr_idx + 1).is_none() {
                        return;
                    }
                    self.arr_idx += 1; // Checked above to ensure that self.wire[self.arr_idx + 1] exists
                    self.idx = 0;
                    continue;
                }
                Some(l) => l,
            };

            match amount.checked_sub(remaining_slice_len) {
                Some(0) | None => {
                    // Invariant: cannot overflow (as you cannot have a slice greater than `usize::MAX`)
                    self.idx += amount; // amount < curr_slice.len() - self.idx -> self.idx + amount <= curr_slice.len()
                    return;
                }
                Some(new_amount) => {
                    if self.wire.get(self.arr_idx + 1).is_none() {
                        self.idx = curr_slice.len();
                        return;
                    }
                    self.arr_idx += 1; // Checked above to ensure that self.wire[self.arr_idx + 1] exists
                    self.idx = 0;
                    amount = new_amount;
                }
            }
        }
    }

    /// Check whether the vectored wire has any remaining bytes that can be written to by the cursor.
    pub fn is_empty(&self) -> bool {
        let mut tmp_arr_idx = self.arr_idx;
        let mut tmp_idx = self.idx;
        while let Some(tmp_slice) = self.wire.get(tmp_arr_idx) {
            if tmp_idx < tmp_slice.len() {
                return false;
            } else if self.wire.get(tmp_arr_idx).is_none() {
                // tmp_idx == first.len() and we're at the last slice
                return true;
            } else {
                tmp_idx = 0;
                tmp_arr_idx += 1;
            }
        }

        true
    }

    /// Write a slice of bytes to the wire.
    pub fn put_slice(&mut self, mut slice: &[u8]) -> Result<(), WireError> {
        while let Some(curr_slice) = self.wire.get_mut(self.arr_idx) {
            let wire_remaining = match curr_slice.get_mut(self.idx..) {
                Some(s) => s,
                None => return Err(WireError::Internal), // Invariant: the index can never exceed the bound of the slice
            };

            for (a, b) in wire_remaining.iter_mut().zip(slice.iter()) {
                *a = *b;
            }

            let num_read = cmp::min(wire_remaining.len(), slice.len());
            match slice.get(num_read..) {
                Some(&[]) => {
                    self.idx += num_read;
                    return Ok(());
                }
                Some(s) => {
                    if self.wire.get(self.arr_idx + 1).is_none() {
                        return Err(WireError::InsufficientBytes);
                    }
                    slice = s;
                    self.arr_idx += 1; // Checked above to ensure that self.wire[self.arr_idx + 1] exists
                    self.idx = 0;
                }
                None => return Err(WireError::Internal), // Invariant: num_read cannot exceed slice.len()
            }
        }

        Err(WireError::InsufficientBytes)
    }

    /// Serialize a given type `T` that implements the [`WireWrite`] trait to the wire.
    ///
    /// The generic boolean `E` designates the intended endianness of the data being written. If `E` is set to
    /// `true`, then the data will be serialized in big endian format; if `false`, it will be serialized
    /// in little endian.
    pub fn put_writable<T, const E: bool>(&mut self, writable: &T) -> Result<(), WireError>
    where
        T: VectoredWrite + ?Sized,
    {
        writable.write_vectored::<E>(self)
    }

    /// Serialize `L` bytes to the wire from a given type `T` that implements the [`WireWritePart`]
    /// trait.
    ///
    /// The generic boolean `E` designates the intended endianness of the data being written. If `E` is set to
    /// `true`, then the data will be serialized in big endian format; if `false`, it will be serialized
    /// in little endian.
    pub fn put_writable_part<T, const L: usize, const E: bool>(
        &mut self,
        writable: &T,
    ) -> Result<(), WireError>
    where
        T: VectoredWritePart,
    {
        writable.write_vectored_part::<L, E>(self)
    }

    /// Get the number of bytes remaining on the wire for the given cursor.
    pub fn remaining(&self) -> usize {
        self.wire
            .iter()
            .map(|s| s.len())
            .sum::<usize>()
            .saturating_sub(self.idx)
    }
}

pub struct WireWriter<'a, const E: bool = true> {
    curs: WireCursorMut<'a>,
    initial_len: usize,
}

impl<'a, const E: bool> WireWriter<'a, E> {
    /// Create a `WireWriter` that can write data types sequentially to the `bytes` slice.
    pub fn new(bytes: &'a mut [u8]) -> Self {
        let initial_len = bytes.len();
        WireWriter {
            curs: WireCursorMut::new(bytes),
            initial_len,
        }
    }

    /// Advance the writer's index forward by the given amount of bytes, returning an error if there are insufficient
    /// bytes on the wire to do so.
    pub fn advance(&mut self, amount: usize) -> Result<(), WireError> {
        let prev_idx = self.curs.idx;
        let res = self.curs.advance(amount);
        if res.is_err() {
            self.curs.idx = prev_idx;
        }
        res
    }

    /// Advance the writer's index forward by the given number of bytes, or to the end of the wire if the amount
    /// exceeds the number of remaining bytes.
    pub fn advance_up_to(&mut self, amount: usize) {
        self.curs.advance_up_to(amount);
    }

    /// Check if the writer has no more bytes left on the wire that can be written to. If any
    /// bytes remain, return [`WireError::ExtraBytes`]; otherwise, return Ok().
    pub fn finalize(&self) -> Result<(), WireError> {
        if !self.is_empty() {
            Err(WireError::ExtraBytes)
        } else {
            Ok(())
        }
    }

    /// Check if the writer has no more bytes left on the wire that can be written to after
    /// the given action. If any bytes remain, return [`WireError::ExtraBytes`]; otherwise,
    /// return Ok().
    pub fn finalize_after<T>(
        action: Result<(), WireError>,
        reader: &Self,
    ) -> Result<(), WireError> {
        if action.is_ok() {
            reader.finalize()?;
        }
        action
    }

    /// Check whether the writer has any remaining bytes that can be written to.
    pub fn is_empty(&self) -> bool {
        self.curs.is_empty()
    }

    /// Write the given data type `writable` to the wire.
    pub fn write<T>(&mut self, writable: &T) -> Result<(), WireError>
    where
        T: WireWrite + ?Sized,
    {
        let temp_idx = self.curs.idx;
        let res = writable.write_wire::<E>(&mut self.curs);
        if res.is_err() {
            self.curs.idx = temp_idx;
        }
        res
    }

    /// Write the given data type `writable` to `L` bytes on the wire.
    pub fn write_part<T, const L: usize>(&mut self, writable: &T) -> Result<(), WireError>
    where
        T: WireWritePart,
    {
        let temp_idx = self.curs.idx;
        let res = writable.write_wire_part::<L, E>(&mut self.curs);
        if res.is_err() {
            self.curs.idx = temp_idx;
        }
        res
    }
}

pub fn _internal_wirewriter_consumed(writer: &WireWriter<'_>) -> usize {
    writer.initial_len - writer.curs.remaining()
}

pub struct VectoredWriter<'a, const E: bool = true> {
    curs: VectoredCursorMut<'a>,
}

impl<'a, const E: bool> VectoredWriter<'a, E> {
    /// Create a `VectoredWriter` that can write data types sequentially to the vectored `bytes` slice.
    pub fn new(bytes: VectoredBufMut<'a>) -> Self {
        VectoredWriter {
            curs: VectoredCursorMut::new(bytes),
        }
    }

    /// Advance the writer's index forward by the given amount of bytes, returning an error if there are insufficient
    /// bytes on the wire to do so.
    pub fn advance(&mut self, amount: usize) -> Result<(), WireError> {
        let temp_arr_idx = self.curs.arr_idx;
        let temp_idx = self.curs.idx;
        let res = self.curs.advance(amount);
        if res.is_err() {
            self.curs.arr_idx = temp_arr_idx;
            self.curs.idx = temp_idx;
        }
        res
    }

    /// Advance the writer's index forward by the given number of bytes, or to the end of the vectored
    /// wire if the amount exceeds the number of remaining bytes.
    pub fn advance_up_to(&mut self, index: usize) {
        self.curs.advance_up_to(index);
    }

    /// Check if the writer has no more bytes left on the vectored wire that can be written
    /// to. If any bytes remain, return [`WireError::ExtraBytes`]; otherwise, return Ok().
    pub fn finalize(&self) -> Result<(), WireError> {
        if self.is_empty() {
            Ok(())
        } else {
            Err(WireError::ExtraBytes)
        }
    }

    /// Check if the writer has no more bytes left on the vectored wire that can be written
    /// to after the given action. If any bytes remain, return [`WireError::ExtraBytes`];
    /// otherwise, return Ok().
    pub fn finalize_after<T>(
        action: Result<(), WireError>,
        reader: &Self,
    ) -> Result<(), WireError> {
        if action.is_ok() {
            reader.finalize()?;
        }
        action
    }

    /// Check whether the writer has any remaining bytes that can be written to.
    pub fn is_empty(&self) -> bool {
        self.curs.is_empty()
    }

    /// Write the given data type `writable` to the vectored wire.
    pub fn write<T>(&mut self, writable: &T) -> Result<(), WireError>
    where
        T: VectoredWrite + ?Sized,
    {
        let temp_arr_idx = self.curs.arr_idx;
        let temp_idx = self.curs.idx;
        let res = writable.write_vectored::<E>(&mut self.curs);
        if res.is_err() {
            self.curs.arr_idx = temp_arr_idx;
            self.curs.idx = temp_idx;
        }
        res
    }

    /// Write the given data type `writable` to `L` bytes on the vectored wire.
    pub fn write_part<T, const L: usize>(&mut self, writable: &T) -> Result<(), WireError>
    where
        T: VectoredWritePart,
    {
        let temp_arr_idx = self.curs.arr_idx;
        let temp_idx = self.curs.idx;
        let res = writable.write_vectored_part::<L, E>(&mut self.curs);
        if res.is_err() {
            self.curs.arr_idx = temp_arr_idx;
            self.curs.idx = temp_idx;
        }
        res
    }
}

pub fn _internal_vectoredwriter_vec_index(writer: &VectoredWriter) -> usize {
    writer.curs.wire.len().saturating_sub(writer.curs.arr_idx)
}

pub fn _internal_vectoredwriter_slice_index(writer: &VectoredWriter) -> usize {
    writer.curs.idx
}

impl WireWrite for str {
    fn write_wire<'a, const E: bool>(&self, curs: &mut WireCursorMut<'a>) -> Result<(), WireError> {
        curs.put_slice(self.as_bytes())
    }
}

impl VectoredWrite for str {
    fn write_vectored<'a, const E: bool>(
        &self,
        curs: &mut VectoredCursorMut<'a>,
    ) -> Result<(), WireError> {
        curs.put_slice(self.as_bytes())
    }
}

impl WireWrite for [u8] {
    fn write_wire<'a, const E: bool>(&self, curs: &mut WireCursorMut<'a>) -> Result<(), WireError> {
        curs.put_slice(self)
    }
}

impl VectoredWrite for [u8] {
    fn write_vectored<'a, const E: bool>(
        &self,
        curs: &mut VectoredCursorMut<'a>,
    ) -> Result<(), WireError> {
        curs.put_slice(self)
    }
}

macro_rules! derive_wire_writable {
    ($int:ty)=> {
        impl WireWrite for $int {
            fn write_wire<const E: bool>(&self, curs: &mut WireCursorMut<'_>) -> Result<(), WireError> {
                if E {
                    curs.put_slice(self.to_be_bytes().as_slice())
                } else {
                    curs.put_slice(self.to_le_bytes().as_slice())
                }
            }
        }
    };

    ($i1:ty, $($i2:ty),+) => {
        derive_wire_writable! { $i1 }
        derive_wire_writable! { $($i2),+ }
    };
}

macro_rules! derive_wire_partwritable {
    ($int:ty)=> {
        impl WireWritePart for $int {
            fn write_wire_part<const L: usize, const E: bool>(&self, curs: &mut WireCursorMut<'_>) -> Result<(), WireError> {
                assert!(L < mem::size_of::<$int>()); // TODO: once more powerful const generic expressions are in rust, use them
                if E {
                    curs.put_slice(&self.to_be_bytes().get(..L).unwrap_or(&[])) // TODO: downcast larger array to smaller one here for safety guarantees
                } else {
                    curs.put_slice(&self.to_le_bytes().get(..L).unwrap_or(&[]))
                }
            }
        }
    };

    ($i1:ty, $($i2:ty),+) => {
        derive_wire_partwritable! { $i1 }
        derive_wire_partwritable! { $($i2),+ }
    };
}

macro_rules! derive_vectored_writable {
    ($int:ty)=> {
        impl VectoredWrite for $int {
            fn write_vectored<const E: bool>(&self, curs: &mut VectoredCursorMut<'_>) -> Result<(), WireError> {
                if E {
                    curs.put_slice(self.to_be_bytes().as_slice())
                } else {
                    curs.put_slice(self.to_le_bytes().as_slice())
                }
            }
        }
    };

    ($i1:ty, $($i2:ty),+) => {
        derive_vectored_writable! { $i1 }
        derive_vectored_writable! { $($i2),+ }
    };
}

macro_rules! derive_vectored_partwritable {
    ($int:ty)=> {
        impl VectoredWritePart for $int {
            fn write_vectored_part<const L: usize, const E: bool>(&self, curs: &mut VectoredCursorMut<'_>) -> Result<(), WireError> {
                assert!(L < mem::size_of::<$int>()); // TODO: once more powerful const generic expressions are in rust, use them
                if E {
                    curs.put_slice(&self.to_be_bytes().get(..L).unwrap_or(&[])) // TODO: downcast larger array to smaller one here for safety guarantees
                } else {
                    curs.put_slice(&self.to_le_bytes().get(..L).unwrap_or(&[]))
                }
            }
        }
    };

    ($i1:ty, $($i2:ty),+) => {
        derive_vectored_partwritable! { $i1 }
        derive_vectored_partwritable! { $($i2),+ }
    };
}

derive_wire_writable!(i8, u8, i16, u16, i32, u32, i64, u64, i128, u128, f32, f64, isize, usize);
derive_vectored_writable!(i8, u8, i16, u16, i32, u32, i64, u64, i128, u128, f32, f64, isize, usize);

// No floats or signed integers--their implementations aren't conducive to chopping off bytes at will
derive_wire_partwritable!(u16, u32, u64, u128, usize);
derive_vectored_partwritable!(u16, u32, u64, u128, usize);