fzpart 0.2.2

A Rust library to interact with GPT / MBR partition tables.
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
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
//! This module provides tools for working with GUID Partition Tables (GPT), a modern
//! partitioning system used in UEFI-based systems. GPT replaces the older Master Boot Record (MBR)
//! format and is designed to support larger disks, more partitions, and better data reliability.
//!
//! A **GUID Partition Table (GPT)** is a partitioning scheme that stores metadata at both the start
//! and end of a disk. It supports:
//!
//! - Disks larger than 2TB.
//! - Up to 128 partitions (by default) with flexible sizes and boundaries.
//! - Metadata integrity through CRC32 checksums for headers and partition entries.
//! - Unique partition identification using GUIDs.
//! - Redundant metadata for recovery in case of corruption.
//!
//! ## Features
//!
//! This module provides a clean interface for reading, writing, and managing GPT structures.
//! It abstracts the low-level details of the GPT format, making it easier to build tools and utilities
//! for partition management. It provides:
//!
//! - Parsing, validation, and modification of GPT headers.
//! - **Partition Operations:**
//!   - Iterate over partitions, skipping unused or invalid entries.
//!   - Retrieve partitions by index.
//!   - Add, update, or delete partitions.
//! - **Backup Support:** Work with alternate (backup) GPT headers and partition tables.
//! - **Integrity Checks:** Detect overlapping partitions, validate checksums, and ensure table correctness.
//!
//! ## Compatibility
//!
//! This module works with any structure providing a storage device API through the implementation
//! of the [`DiskRead`] and [`DiskSeek`] traits, allowing it to interact with a wide variety of
//! storage backends, including raw block devices and virtual disks.
//!
//! If the `std` crate feature is enabled, [`DiskSeek`] and [`DiskRead`] are aliases to
//! [`std::io::Seek`] and [`std::io::Read`]. In a `no-std` environment, you need to provide your
//! own implementation of those two traits to provide a simple API to interact with the storage
//! devices.
//!
//! To access all of the functionalities of this module, the device-like structure should also
//! implement [`DiskWrite`], an alias to [`std::io::Write`] if the `std` feature is enabled.
//!
//! ## Example
//!
//! ```rust
//! use fzpart::{Gpt, GptPartition};
//! use std::io::Cursor;
//!
//! let mut device: Cursor<Vec<u8>> = Cursor::new(vec![0u8; 0x200 * 1024]);
//!
//! let mut gpt: Gpt<Cursor<Vec<u8>>, 0x200> = Gpt::new_on_device(device, 0, 1023).unwrap();
//!
//! gpt.header.set_first_usable_lba(400);
//!
//! assert_eq!(gpt.header.first_usable_lba(), 400);
//! assert_eq!(gpt.header.compute_checksum(), gpt.header.checksum());
//!
//! let mut part = GptPartition::default();
//! part.set_start_lba(400);
//! part.set_last_lba(800);
//! part.set_type_guid(1);
//!
//! gpt.append_partition(part).unwrap();
//!
//! assert_eq!(gpt.iter_partitions().count(), 1);
//! assert_eq!(gpt.get_partition(0).unwrap().start_lba(), 400);
//! ```

use core::{
    cell::RefCell,
    mem::{offset_of, MaybeUninit},
    slice,
};

#[cfg(feature = "alloc")]
use alloc::{string::String, vec::Vec};
use crc32fast::Hasher;
use zerocopy::{FromBytes, Immutable, IntoBytes};
use zerocopy_derive::{FromBytes, Immutable, IntoBytes};

use crate::{DiskRead, DiskSeek, DiskWrite, SeekFrom};

const GPT_HEADER_OFFSET: u64 = 0x200;
const GPT_SIG: &[u8; 8] = b"EFI PART";
const GPT_REVISION: u32 = 0x0001_0000;
const GPT_TABLE_SIZE: u32 = 1 << 17;

macro_rules! packed_field_accessors {
    ($field:ident, $type:ty) => {
        #[must_use]
        pub fn $field(&self) -> $type {
            unsafe { core::ptr::read_unaligned(core::ptr::addr_of!(self.$field)) }
        }
    };
    ($field:ident, $type:ty, $accq:vis) => {
        $accq fn $field(&self) -> $type {
            unsafe { core::ptr::read_unaligned(core::ptr::addr_of!(self.$field)) }
        }
    };
    ($field:ident, $field_setter:ident, $type:ty) => {
        #[must_use]
        pub fn $field(&self) -> $type {
            unsafe { core::ptr::read_unaligned(core::ptr::addr_of!(self.$field)) }
        }

        pub fn $field_setter(&mut self, value: $type) {
            unsafe { core::ptr::write_unaligned(core::ptr::addr_of_mut!(self.$field), value) }
        }
    };
    ($field:ident, $field_setter:ident, $type:ty, $post_call:expr) => {
        #[must_use]
        pub fn $field(&self) -> $type {
            unsafe { core::ptr::read_unaligned(core::ptr::addr_of!(self.$field)) }
        }

        pub fn $field_setter(&mut self, value: $type) {
            unsafe { core::ptr::write_unaligned(core::ptr::addr_of_mut!(self.$field), value) }
            $post_call(self);
        }
    };
    ($field:ident, $field_setter:ident, $type:ty, $accq:vis) => {
        $accq fn $field(&self) -> $type {
            unsafe { core::ptr::read_unaligned(core::ptr::addr_of!(self.$field)) }
        }

        $accq fn $field_setter(&mut self, value: $type) {
            unsafe { core::ptr::write_unaligned(core::ptr::addr_of_mut!(self.$field), value) }
        }
    };
}

/// Represents any error that can occur when working with a [`Gpt`].
#[derive(Clone, Copy, Debug)]
pub enum GptError {
    /// A specific partition in the [`Gpt`] is invalid, or an invalid operation on a partition was
    /// attempted.
    ///
    /// Tuple containing the index of the partition which caused the error, as well as a
    /// description of the error using a [`GptPartitionError`] variant.
    InvalidPartition(u32, GptPartitionError),

    /// An I/O operation to the underlying device failed.
    IoError,

    /// The [`GptHeader`] checksum value is invalid.
    InvalidHeaderChecksum {
        /// Checksum value stored in the [`GptHeader`].
        expected: u32,

        /// Checksum value computed from the [`GptHeader`].
        actual: u32,
    },

    /// The partition table checksum is invalid.
    InvalidPartitionsChecksum {
        /// Partition table checksum value stored in the [`GptHeader`].
        expected: u32,

        /// Checksum value computed from the partition table entries.
        actual: u32,
    },

    /// The [`GptHeader`] signature is invalid.
    InvalidSignature,

    /// Attempted to access a partition entry that does not exist.
    NoSuchPartition,

    /// Attempted to access a partition entry outside of the bounds defined in the [`GptHeader`].
    OutOfBounds,

    /// The partition table is full and cannot accommodate more partitions.
    TableFull,

    /// Partitions in the table overlap with each other.
    OverlappingPartitions,
}

/// Represents any error than can occur when working with a [`GptPartition`].
#[derive(Clone, Copy, Debug)]
pub enum GptPartitionError {
    /// The *LBA* (_logical block address_) range for this partition is invalid.
    InvalidLbaRange,

    /// The partition name is invalid (should be at most 35 characters of valid UTF-16).
    InvalidName,
}

/// Represents the header of a [`Gpt`] (_GUID Partition Table_).
///
/// This header contains metadata about the partition table, and is replicated once on the storage
/// device (alternate header, located in the last sector).
///
/// # Examples
///
/// ```
/// use fzpart::Gpt;
/// use std::io::Cursor;
///
/// // Create a new device with 1024 512bytes sectors.
/// let mut device: Cursor<Vec<u8>> = Cursor::new(vec![0u8; 0x200 * 1024]);
///
/// let mut gpt: Gpt<Cursor<Vec<u8>>, 0x200> = Gpt::new_on_device(device, 0, 1023).unwrap();
///
/// gpt.header.set_first_usable_lba(400);
///
/// assert_eq!(gpt.header.first_usable_lba(), 400);
/// assert_eq!(gpt.header.compute_checksum(), gpt.header.checksum());
/// ```
#[derive(Clone, Debug, PartialEq, Eq, FromBytes, IntoBytes, Immutable)]
#[repr(packed(1), C)]
pub struct GptHeader {
    /// Identifies EFI-compatible partition table header.
    /// Should contain the string "EFI PART".
    signature: [u8; 8],

    /// Revision number for this header.
    revision: u32,

    /// Size of the header in bytes.
    size: u32,

    /// CRC32 checksum for the header.
    checksum: u32,

    reserved: [u8; 4],

    /// The LBA that contains this structure.
    lba: u64,

    /// The LBA of the alternate `GPT` header.
    alternate_lba: u64,

    /// First logical block that may be used by a partition.
    first_usable_lba: u64,

    /// Last logical block that may be used by a partition.
    last_usable_lba: u64,

    /// GUID used to identify the disk.
    guid: u128,

    /// Starting LBA of the GUID Partition Entry array.
    partition_start_lba: u64,

    /// Number of partitions entries in the GUID Partition Entry array.
    partition_entries_count: u32,

    /// Size in bytes of each entry in the GUID Partition Entry array.
    partition_entry_size: u32,

    /// CRC32 of the GUID Partition Entry array.
    partition_entries_checksum: u32,
}

assert_eq_size!(GptHeader, [u8; 0x5C]);
assert_eq_align!(GptHeader, u8);

impl GptHeader {
    /// Returns the checksum of the [`Gpt`] header part (_CRC32_).
    ///
    /// # Examples
    ///
    /// ```
    /// use fzpart::Gpt;
    /// use std::io::Cursor;
    ///
    /// // Create a new device with 1024 512bytes sectors.
    /// let mut device: Cursor<Vec<u8>> = Cursor::new(vec![0u8; 0x200 * 1024]);
    ///
    /// let mut gpt: Gpt<Cursor<Vec<u8>>, 0x200> = Gpt::new_on_device(device, 0, 1023).unwrap();
    ///
    /// assert_eq!(gpt.header.compute_checksum(), gpt.header.checksum());
    /// ```
    #[must_use]
    pub fn compute_checksum(&self) -> u32 {
        let chksum_offset = offset_of!(GptHeader, checksum);
        let bytes = self.as_bytes();

        let mut crc32_hasher = Hasher::new();

        crc32_hasher.update(&bytes[..chksum_offset]);
        crc32_hasher.update(&[0u8; size_of::<u32>()]);
        crc32_hasher.update(&bytes[chksum_offset + size_of::<u32>()..]);

        crc32_hasher.finalize()
    }

    fn update_checksum(&mut self) {
        self.checksum = self.compute_checksum();
    }

    fn is_valid(&self) -> Result<(), GptError> {
        if &self.signature != GPT_SIG {
            return Err(GptError::InvalidSignature);
        }

        let computed_checksum = self.compute_checksum();

        if computed_checksum != self.checksum {
            return Err(GptError::InvalidHeaderChecksum {
                expected: self.checksum,
                actual: computed_checksum,
            });
        }

        Ok(())
    }

    packed_field_accessors!(
        signature,
        set_signature,
        [u8; 8],
        GptHeader::update_checksum
    );
    packed_field_accessors!(revision, set_revision, u32, GptHeader::update_checksum);
    packed_field_accessors!(lba, set_lba, u64, GptHeader::update_checksum);
    packed_field_accessors!(
        alternate_lba,
        set_alternate_lba,
        u64,
        GptHeader::update_checksum
    );
    packed_field_accessors!(
        first_usable_lba,
        set_first_usable_lba,
        u64,
        GptHeader::update_checksum
    );
    packed_field_accessors!(
        last_usable_lba,
        set_last_usable_lba,
        u64,
        GptHeader::update_checksum
    );
    packed_field_accessors!(guid, set_guid, u128, GptHeader::update_checksum);
    packed_field_accessors!(checksum, u32);
    packed_field_accessors!(partition_start_lba, u64);
    packed_field_accessors!(partition_entries_count, u32);
    packed_field_accessors!(partition_entry_size, u32);
    packed_field_accessors!(partition_entries_checksum, u32, pub(self));
}

/// Represents an individual partition entry in a [`Gpt`] (_GUID Partition Table_).
///
/// Each entry describes a partition type, location, attributes and a human-readable name (UTF-16
/// encoded).
///
/// This structure directly maps the layout of a _GPT_ partition, as defined in the UEFI
/// specification, ensuring compatibility.
///
/// # Examples
///
/// ```
/// use fzpart::GptPartition;
///
/// let mut part = GptPartition::default();
///
/// part.set_start_lba(1024);
/// part.set_last_lba(4096);
/// part.set_name("my_part");
///
/// assert_eq!(part.name().unwrap(), "my_part");
/// assert_eq!(part.size(), 3072);
/// ```
#[derive(Clone, Copy, Debug, FromBytes, IntoBytes, Immutable)]
#[repr(packed(1), C)]
pub struct GptPartition {
    /// Defines the purpose and type of this partition.
    type_guid: u128,

    /// GUID unique for every partition entry.
    partition_guid: u128,

    /// Starting LBA of this partition.
    start_lba: u64,

    /// Last LBA of this partition.
    last_lba: u64,

    /// Partition's attributes bits.
    attributes: u64,

    /// Null-terminated string containing a human-readable name of this partition.
    partition_name: [u16; 36],
}

assert_eq_size!(GptPartition, [u8; 0x80]);
assert_eq_align!(GptPartition, u8);

impl GptPartition {
    /// Returns the size of this partition, in sectors.
    ///
    /// # Examples
    ///
    /// ```
    /// use fzpart::GptPartition;
    ///
    /// let mut part = GptPartition::default();
    ///
    /// part.set_start_lba(1024);
    /// part.set_last_lba(4096);
    ///
    /// assert_eq!(part.size(), 3072);
    /// ```
    pub fn size(&self) -> u64 {
        self.last_lba - self.start_lba
    }

    /// Returns `true` if this partition is being used.
    ///
    /// # Examples
    ///
    /// ```
    /// use fzpart::GptPartition;
    ///
    /// let mut part = GptPartition::default();
    ///
    /// assert!(!part.is_used());
    /// part.set_type_guid(1);
    /// assert!(part.is_used());
    /// ```
    pub fn is_used(&self) -> bool {
        self.type_guid != 0
    }

    /// Checks if this partition's structure is valid.
    ///
    /// If this partition cannot be used in a [`Gpt`] (invalid start / end LBAs, ...), returns an `Err`
    /// describing the issue.
    ///
    /// # Examples
    ///
    /// ```
    /// use fzpart::{GptPartition, gpt::GptPartitionError};
    ///
    /// let mut part = GptPartition::default();
    ///
    /// part.set_start_lba(4096);
    /// part.set_last_lba(1024);
    ///
    /// assert!(matches!(part.check_correctness(), Err(GptPartitionError::InvalidLbaRange)));
    ///
    /// part.set_start_lba(1024);
    /// part.set_last_lba(4096);
    ///
    /// assert!(part.check_correctness().is_ok());
    /// ```
    pub fn check_correctness(&self) -> Result<(), GptPartitionError> {
        if self.start_lba() > self.last_lba() {
            return Err(GptPartitionError::InvalidLbaRange);
        }

        Ok(())
    }

    /// Sets the partition name as a UTF-16 encoded string.
    ///
    /// This converts the provided UTF-8 string into UTF-16 encoding, required by the _UEFI_
    /// standards.
    ///
    /// # Errors
    ///
    /// Returns an `Err` if the provided name is too long (more than 35 characters).
    ///
    /// # Examples
    ///
    /// ```
    /// use fzpart::GptPartition;
    ///
    /// let mut part = GptPartition::default();
    ///
    /// part.set_name("my_part").unwrap();
    ///
    /// assert_eq!(part.name().unwrap(), "my_part");
    /// ```
    #[cfg(feature = "alloc")]
    pub fn set_name(&mut self, name: &str) -> Result<(), GptPartitionError> {
        let mut utf16_encoding = name.encode_utf16().collect::<Vec<_>>();

        if utf16_encoding.len() >= 36 {
            return Err(GptPartitionError::InvalidName);
        }

        utf16_encoding.resize(36, 0);

        self.set_partition_name(utf16_encoding.try_into().unwrap());

        Ok(())
    }

    /// Returns the partition name as a UTF-8 encoded string.
    ///
    /// This converts the UTF-16 encoded partition name to UTF-8, after removing the trailing zero
    /// bytes.
    ///
    /// # Errors
    ///
    /// Returns an `Err` if the partition name is an invalid UTF-16 sequence.
    ///
    /// # Examples
    ///
    /// ```
    /// use fzpart::GptPartition;
    ///
    /// let mut part = GptPartition::default();
    ///
    /// part.set_name("my_part").unwrap();
    ///
    /// assert_eq!(part.name().unwrap(), "my_part");
    /// ```
    #[cfg(feature = "alloc")]
    pub fn name(&self) -> Result<String, GptPartitionError> {
        let name_buf = self.partition_name();
        let filtered_buf: Vec<u16> = name_buf.into_iter().take_while(|&c| c != 0).collect();

        String::from_utf16(&filtered_buf).map_err(|_| GptPartitionError::InvalidName)
    }

    packed_field_accessors!(type_guid, set_type_guid, u128);
    packed_field_accessors!(start_lba, set_start_lba, u64);
    packed_field_accessors!(last_lba, set_last_lba, u64);
    packed_field_accessors!(partition_name, set_partition_name, [u16; 36], pub(self));
}

impl Default for GptPartition {
    fn default() -> Self {
        Self {
            type_guid: Default::default(),
            partition_guid: Default::default(),
            start_lba: Default::default(),
            last_lba: Default::default(),
            attributes: Default::default(),
            partition_name: [0u16; 36],
        }
    }
}

/// Represents a **GUID Partition Table** (_GPT_).
///
/// The _GPT_ is a partitioning standard defined by the UEFI specifications, improving the
/// legacy _Master Boot Record_ ([`Mbr`](crate::Mbr)).
///
/// This provides a convenient way to interact with a GPT partitioned disk, and handles internaly
/// all raw reads / writes to and from the disk device, as well as ensuring consistenty inside of
/// the partition table.
///
/// It uses two generic parameters:
///
/// - `D` : A type representing a disk device API. It should implement at least [`DiskRead`] and
///         [`DiskSeek`], and [`DiskWrite`] is required to access all of the methods (especially those
///         requiring an update of the partition scheme).
///
/// - `S` : The size of a sector on the disk, in bytes. This supports any type of disk device, as
///         long as they can be accessed using standard APIs, and as such it cannot dynamically retrieve
///         the sector size. Therefore, it must be known at compile time (but the default value of `0x200`
///         should be correct in almost all usual cases).
///
/// # Examples
///
/// ```
/// use fzpart::{Gpt, GptPartition};
/// use std::io::Cursor;
///
/// let mut device: Cursor<Vec<u8>> = Cursor::new(vec![0u8; 0x200 * 1024]);
///
/// let mut gpt: Gpt<Cursor<Vec<u8>>, 0x200> = Gpt::new_on_device(device, 0, 1023).unwrap();
///
/// gpt.header.set_first_usable_lba(400);
///
/// assert_eq!(gpt.header.first_usable_lba(), 400);
/// assert_eq!(gpt.header.compute_checksum(), gpt.header.checksum());
///
/// let mut part = GptPartition::default();
/// part.set_start_lba(400);
/// part.set_last_lba(800);
/// part.set_type_guid(1);
///
/// gpt.append_partition(part).unwrap();
///
/// assert_eq!(gpt.iter_partitions().count(), 1);
/// assert_eq!(gpt.get_partition(0).unwrap().start_lba(), 400);
/// ```
pub struct Gpt<D, const S: u64 = 0x200>
where
    D: DiskRead + DiskSeek,
{
    pub header: GptHeader,
    device_mapping: RefCell<D>,
}

impl<D, const S: u64> Gpt<D, S>
where
    D: DiskRead + DiskSeek,
{
    /// Parses a `Gpt` structure from a disk device.
    ///
    /// The provided `device_mapping` must implement [`DiskRead`] and [`DiskSeek`], as this
    /// function will handle all reads from the device to properly load the `Gpt`.
    ///
    /// # Errors
    ///
    /// - [`GptError::IoError`]: if any error occured during an I/O operation to the disk.
    /// - [`GptError::InvalidHeaderChecksum`]: the _CRC32C_ header checksum is invalid (corrupted
    ///                                        `Gpt`)..
    /// - [`GptError::InvalidSignature`]: the [`GptHeader`] signature is invalid. The device might
    ///                                   not be partitioned using _GPT_, or the table is corrupted.
    ///
    /// # Examples
    ///
    /// ```
    /// use fzpart::Gpt;
    /// use std::io::Cursor;
    ///
    /// let mut buf = [0u8; 0x200 * 1024];
    /// let mut device: Cursor<&mut [u8]> = Cursor::new(&mut buf);
    ///
    /// Gpt::<Cursor<&mut [u8]>, 0x200>::new_on_device(device, 1, 1023).unwrap();
    /// let gpt = Gpt::<Cursor<&mut [u8]>, 0x200>::parse_from_device(Cursor::new(&mut
    /// buf)).unwrap();
    ///
    /// assert!(gpt.check_table_correctness().is_ok());
    /// ```
    pub fn parse_from_device(mut device_mapping: D) -> Result<Self, GptError> {
        device_mapping
            .seek(SeekFrom::Start(GPT_HEADER_OFFSET))
            .map_err(|_| GptError::IoError)?;

        let mut buf = [0u8; size_of::<GptHeader>()];
        device_mapping
            .read(&mut buf)
            .map_err(|_| GptError::IoError)?;
        let header = GptHeader::read_from_bytes(&buf).map_err(|_| GptError::IoError)?;

        header.is_valid()?;

        let table = Gpt {
            header,
            device_mapping: RefCell::new(device_mapping),
        };

        Ok(table)
    }

    /// Returns an iterator over the valid partitions in the `Gpt`.
    ///
    /// The iterator goes through the partition entry array, skipping any unused or invalid
    /// partition. The indices in this iterator are consistent with the partitions
    /// returned by the [`Gpt::get_partition`] method.
    ///
    /// # Examples:
    ///
    /// ```
    /// use fzpart::{Gpt, GptPartition};
    /// use fzpart::gpt::GptError;
    /// use std::io::Cursor;
    ///
    /// let mut device: Cursor<Vec<u8>> = Cursor::new(vec![0u8; 0x200 * 1024]);
    /// let mut gpt: Gpt<Cursor<Vec<u8>>, 0x200> = Gpt::new_on_device(device, 0, 1023).unwrap();
    ///
    /// let mut part_a = GptPartition::default();
    /// part_a.set_start_lba(400);
    /// part_a.set_last_lba(800);
    /// part_a.set_type_guid(1);
    /// part_a.set_name("part_a");
    ///
    /// let mut part_b = GptPartition::default();
    /// part_b.set_start_lba(801);
    /// part_b.set_last_lba(920);
    /// part_b.set_type_guid(1);
    /// part_b.set_name("part_b");
    ///
    /// gpt.append_partition(part_a).unwrap();
    /// gpt.append_partition(part_b).unwrap();
    ///
    /// assert_eq!(gpt.iter_partitions().count(), 2);
    /// assert_eq!(gpt.iter_partitions().map(|part| part.name().unwrap()).collect::<Vec<_>>(),
    /// ["part_a", "part_b"]);
    /// ```
    pub fn iter_partitions(&self) -> GptPartitionsIterator<'_, D, S> {
        GptPartitionsIterator {
            table: self,
            cursor: 0,
            skip_empty: true,
        }
    }

    /// Retrieves a partition from the `Gpt` from its index in the partition array.
    ///
    /// Partitions are 0-indexed, and unused ones are skipped. This index matches the position of
    /// the partition in the iterator returned by the [`Gpt::iter_partitions`] method.
    ///
    /// # Examples
    ///
    /// ```
    /// use fzpart::{Gpt, GptPartition};
    /// use fzpart::gpt::GptError;
    /// use std::io::Cursor;
    ///
    /// let mut device: Cursor<Vec<u8>> = Cursor::new(vec![0u8; 0x200 * 1024]);
    /// let mut gpt: Gpt<Cursor<Vec<u8>>, 0x200> = Gpt::new_on_device(device, 0, 1023).unwrap();
    ///
    /// let mut part = GptPartition::default();
    /// part.set_start_lba(400);
    /// part.set_last_lba(800);
    /// part.set_type_guid(1);
    ///
    /// gpt.append_partition(part).unwrap();
    ///
    /// assert_eq!(gpt.get_partition(0).unwrap().start_lba(), 400);
    /// assert!(matches!(gpt.get_partition(1), None));
    /// ```
    pub fn get_partition(&self, part_id: u32) -> Option<GptPartition> {
        self.iter_partitions().nth(usize::try_from(part_id).ok()?)
    }

    /// Returns `Ok` if this _Gpt_ is correct (according to the _UEFI_ specifications).
    ///
    /// # Errors
    ///
    /// Returns an `Err` if this _Gpt_ is not usable, with:
    ///
    /// - [`GptError::InvalidHeaderChecksum`]: the _CRC32C_ header checksum is invalid (corrupted
    ///                                        `Gpt`).
    /// - [`GptError::InvalidPartitionsChecksum`]: the _CRC32C_ checksum of the partition entries array
    ///                                            is invalid (corrupted `Gpt`).
    /// - [`GptError::InvalidSignature`]: the [`GptHeader`] signature is invalid. The device might
    ///                                   not be partitioned using _GPT_, or the table is corrupted.
    /// - [`GptError::OverlappingPartitions`] : if two partitions range overlap (this check requires the
    ///                                         `alloc` crate feature).
    /// - [`GptError::InvalidPartition`]: if any individual partition has an issue (described by a
    ///                                   [`GptPartitionError`] variant).
    ///
    /// # Examples
    ///
    /// ```    
    /// use fzpart::Gpt;
    /// use std::io::Cursor;
    ///
    /// let mut buf = [0u8; 0x200 * 1024];
    /// let mut device: Cursor<&mut [u8]> = Cursor::new(&mut buf);
    ///
    /// let mut gpt = Gpt::<Cursor<&mut [u8]>, 0x200>::new_on_device(device, 1, 1023).unwrap();
    ///
    /// assert!(gpt.check_table_correctness().is_ok());
    /// ```
    pub fn check_table_correctness(&self) -> Result<(), GptError> {
        self.header.is_valid()?;

        let computed_checksum = self.compute_partitions_checksum();

        if computed_checksum != self.header.partition_entries_checksum {
            return Err(GptError::InvalidPartitionsChecksum {
                expected: self.header.partition_entries_checksum(),
                actual: computed_checksum,
            });
        }

        #[cfg(feature = "alloc")]
        {
            let overlappings =
                find_overlapping_partitions(self.iter_partitions().collect::<Vec<_>>());

            if !overlappings.is_empty() {
                return Err(GptError::OverlappingPartitions);
            }
        }

        for (part, idx) in self.iter_partitions().zip(0u32..) {
            part.check_correctness()
                .map_err(|err| GptError::InvalidPartition(idx, err))?;
        }

        Ok(())
    }

    fn update_checksums(&mut self) {
        let partitions_chksum = self.compute_partitions_checksum();
        self.header.partition_entries_checksum = partitions_chksum;

        let header_chksum = self.header.compute_checksum();
        self.header.checksum = header_chksum;
    }

    fn compute_partitions_checksum(&self) -> u32 {
        let mut crc32_hasher = Hasher::new();

        self.iter_entries()
            .for_each(|part| crc32_hasher.update(part.as_bytes()));

        crc32_hasher.finalize()
    }

    fn read_from_device<T>(&self, offset: u64) -> Result<T, GptError>
    where
        T: FromBytes,
    {
        let mut device = self.device_mapping.borrow_mut();
        device
            .seek(SeekFrom::Start(offset))
            .map_err(|_| GptError::IoError)?;

        if cfg!(feature = "alloc") {
            let mut buf = alloc::vec![0u8; size_of::<T>()];

            let read = device.read(&mut buf).map_err(|_| GptError::IoError)?;

            if read != size_of::<T>() {
                return Err(GptError::IoError);
            }

            T::read_from_bytes(&buf).map_err(|_| GptError::IoError)
        } else {
            unsafe {
                let mut uninit_data: MaybeUninit<T> = MaybeUninit::uninit();

                let read = device
                    .read(slice::from_raw_parts_mut(
                        uninit_data.as_mut_ptr().cast(),
                        size_of::<T>(),
                    ))
                    .map_err(|_| GptError::IoError)?;

                if read != size_of::<T>() {
                    return Err(GptError::IoError);
                }

                Ok(uninit_data.assume_init())
            }
        }
    }

    fn read_alternate(&self) -> Result<GptHeader, GptError> {
        self.read_from_device(S * self.header.alternate_lba())
    }

    #[cfg(feature = "alloc")]
    fn would_new_partitions_overlap(&self, new_part: Vec<GptPartition>) -> bool {
        let mut partitions = self.iter_partitions().collect::<Vec<_>>();
        partitions.extend(new_part);

        let overlappings = find_overlapping_partitions(partitions);

        !overlappings.is_empty()
    }

    fn read_partition_entry(&self, part_id: u32) -> Result<GptPartition, GptError> {
        if part_id >= self.header.partition_entry_size() {
            return Err(GptError::OutOfBounds);
        }

        let (primary, _) = self.partition_offset(part_id);

        self.read_from_device::<GptPartition>(primary)
    }

    fn iter_entries(&self) -> GptPartitionsIterator<'_, D, S> {
        GptPartitionsIterator {
            table: self,
            cursor: 0,
            skip_empty: false,
        }
    }

    fn partition_offset(&self, part_id: u32) -> (u64, u64) {
        let offset_in_table = u64::from(part_id * self.header.partition_entry_size());
        let primary_offset = self.header.partition_start_lba() * S + offset_in_table;

        let alternate_offset = S * self.header.alternate_lba()
            - u64::from(self.header.partition_entries_count() * self.header.partition_entry_size())
            + offset_in_table;

        (primary_offset, alternate_offset)
    }

    fn find_first_empty_slot(&self) -> Option<u32> {
        self.iter_entries()
            .position(|part| part.type_guid == 0)
            .map(|idx| u32::try_from(idx).ok())?
    }
}

impl<D, const S: u64> Gpt<D, S>
where
    D: DiskRead + DiskWrite + DiskSeek,
{
    /// Partitions the given device using a `GPT`, using the provided `header_lba` and `alternate_lba`
    /// locations to store the headers.
    ///
    /// The `alternate_lba` must be located in the last LBA of the device.
    ///
    /// # Errors
    ///
    /// Returns `Err` if the `GPT` creation went wrong, with:
    ///
    /// - [`GptError::IoError`]: if any error occured during an I/O operation to the disk, or if
    ///                          the **[**`header_lba`, `alternate_lba`**]** bounds provided are
    ///                          invalid for this device.
    ///
    /// # Examples
    ///
    /// ```
    /// use fzpart::{Gpt, GptPartition};
    /// use std::io::Cursor;
    ///
    /// let mut device: Cursor<Vec<u8>> = Cursor::new(vec![0u8; 0x200 * 1024]);
    ///
    /// let mut gpt: Gpt<Cursor<Vec<u8>>, 0x200> = Gpt::new_on_device(device, 0, 1023).unwrap();
    ///
    /// assert!(gpt.check_table_correctness().is_ok());
    /// ```
    #[cfg(feature = "std")]
    pub fn new_on_device(device: D, header_lba: u64, alternate_lba: u64) -> Result<Self, GptError> {
        // TODO: create another function that takes the uuud as an argument to remove dependency on
        // std
        use uuid::Uuid;

        let first_usable_lba = 1 + header_lba + u64::from(GPT_TABLE_SIZE) / S;

        let last_usable_lba = alternate_lba - u64::from(GPT_TABLE_SIZE) / S - 1;

        if alternate_lba < 1 + u64::from(GPT_TABLE_SIZE) / S || first_usable_lba > last_usable_lba {
            return Err(GptError::IoError);
        }

        let header = GptHeader {
            signature: *GPT_SIG,
            revision: GPT_REVISION,
            size: u32::try_from(size_of::<GptHeader>()).expect("invalid gpt header size"),
            checksum: 0,
            reserved: [0u8; 4],
            lba: header_lba,
            alternate_lba,
            first_usable_lba,
            last_usable_lba,
            guid: Uuid::new_v4().to_u128_le(),
            partition_start_lba: header_lba + 1,
            partition_entries_count: GPT_TABLE_SIZE
                / u32::try_from(size_of::<GptPartition>()).expect("invalid gpt partition size"),
            partition_entry_size: u32::try_from(size_of::<GptPartition>())
                .expect("invalid gpt partition size"),
            partition_entries_checksum: 0,
        };

        let mut gpt = Self {
            header,
            device_mapping: RefCell::new(device),
        };

        gpt.update_checksums();
        gpt.write_header()?;
        gpt.write_alternate()?;

        Ok(gpt)
    }

    /// Restores the primary _GPT_ header and partition array from the backup.
    ///
    /// This can be attempted when the _GPT_ is corrupted, a backup of the entire structure is
    /// kept at the end of the device.
    ///
    /// # Errors
    ///
    /// Returns `Err` if the `GPT` restoration went wrong, or if the alternate structure is
    /// corrupted as well with:
    ///
    /// - [`GptError::IoError`]: if any error occured during an I/O operation to the disk
    /// - [`GptError::InvalidHeaderChecksum`]: the _CRC32C_ header checksum is invalid (corrupted
    ///                                        `Gpt`)..
    /// - [`GptError::InvalidSignature`]: the [`GptHeader`] signature is invalid. The device might
    ///                                   not be partitioned using _GPT_, or the table is corrupted.
    ///
    /// # Examples
    ///
    /// ```
    /// use fzpart::Gpt;
    /// use std::io::Cursor;
    ///
    /// let mut device: Cursor<Vec<u8>> = Cursor::new(vec![0u8; 0x200 * 1024]);
    ///
    /// let mut gpt: Gpt<Cursor<Vec<u8>>, 0x200> = Gpt::new_on_device(device, 0, 1023).unwrap();
    ///
    /// assert!(gpt.restore_from_alternate().is_ok());
    /// ```
    pub fn restore_from_alternate(&mut self) -> Result<(), GptError> {
        self.restore_main_header_from_alternate()?;
        self.restore_partitions_from_alternate()?;

        Ok(())
    }

    /// Removes a partition from the table.
    ///
    /// The `part_id` must match the indices used by the [`Gpt::iter_partitions`] iterator, same as
    /// with the [`Gpt::get_partition`] method.
    ///
    /// # Errors
    ///
    /// - [`GptError::IoError`]: if any error occured during an I/O operation to the disk.
    /// - [`GptError::OutOfBounds`]: if the provided `part_id` is bigger than the number of used
    ///                              partitions.
    /// - [`GptError::NoSuchPartition`]: there is no partition with the provided `part_id`.
    ///
    /// # Examples
    ///
    /// ```
    /// use fzpart::{Gpt, GptPartition};
    /// use fzpart::gpt::GptError;
    /// use std::io::Cursor;
    ///
    /// let mut device: Cursor<Vec<u8>> = Cursor::new(vec![0u8; 0x200 * 1024]);
    /// let mut gpt: Gpt<Cursor<Vec<u8>>, 0x200> = Gpt::new_on_device(device, 0, 1023).unwrap();
    ///
    /// let mut part = GptPartition::default();
    /// part.set_start_lba(400);
    /// part.set_last_lba(800);
    /// part.set_type_guid(1);
    /// gpt.append_partition(part).unwrap();
    ///
    /// assert!(gpt.remove_partition(0).is_ok());
    ///
    /// assert!(matches!(gpt.remove_partition(0), Err(GptError::NoSuchPartition)));
    /// ```
    pub fn remove_partition(&mut self, part_id: u32) -> Result<(), GptError> {
        self.get_partition(part_id)
            .ok_or(GptError::NoSuchPartition)?;

        let (primary, alternate) = self.partition_offset(part_id);

        self.write_to_device(primary, &[0u8; size_of::<GptPartition>()])?;
        self.write_to_device(alternate, &[0u8; size_of::<GptPartition>()])?;

        self.update_checksums();

        Ok(())
    }

    /// Appends a partition to the table.
    ///
    /// Uses the next available slot in the _GPT_ partition array.
    ///
    /// # Errors
    ///
    /// - [`GptError::IoError`]: if any error occured during an I/O operation to the disk.
    /// - [`GptError::TableFull`]: if the _GPT_ partition array is full. We do not support dynamic
    ///                            resizing of the _GPT_ to fit additional partitions.
    /// - [`GptError::OverlappingPartitions`]: The new partition range would overlap with an existing partition.
    ///
    /// # Examples
    ///
    /// ```
    /// use fzpart::{Gpt, GptPartition};
    /// use fzpart::gpt::GptError;
    /// use std::io::Cursor;
    ///
    /// let mut device: Cursor<Vec<u8>> = Cursor::new(vec![0u8; 0x200 * 1024]);
    /// let mut gpt: Gpt<Cursor<Vec<u8>>, 0x200> = Gpt::new_on_device(device, 0, 1023).unwrap();
    ///
    /// let mut part = GptPartition::default();
    /// part.set_start_lba(400);
    /// part.set_last_lba(800);
    /// part.set_type_guid(1);
    ///
    /// gpt.append_partition(part).unwrap();
    ///
    /// assert!(gpt.get_partition(0).is_some())
    /// ```
    pub fn append_partition(&mut self, new_part: GptPartition) -> Result<(), GptError> {
        let empty_idx = self.find_first_empty_slot().ok_or(GptError::TableFull)?;

        #[cfg(feature = "alloc")]
        {
            if self.would_new_partitions_overlap(alloc::vec![new_part]) {
                return Err(GptError::OverlappingPartitions);
            }
        }

        self.write_partition_entry(empty_idx, &new_part)
    }

    /// Updates a partion entry in the _GPT_.
    ///
    /// The `part_id` must match the indices used by the [`Gpt::iter_partitions`] iterator, same as
    /// with the [`Gpt::get_partition`] method.
    ///
    /// # Errors
    ///
    /// - [`GptError::IoError`]: if any error occured during an I/O operation to the disk.
    /// - [`GptError::NoSuchPartition`]: there is no partition with the provided `part_id`.
    /// - [`GptError::OverlappingPartitions`]: The new partition range would overlap with an existing
    ///                                        partition (this check requires the `alloc` crate feature
    ///                                        to be enabled).
    ///
    /// # Examples
    ///
    /// ```
    /// use fzpart::{Gpt, GptPartition};
    /// use fzpart::gpt::GptError;
    /// use std::io::Cursor;
    ///
    /// let mut device: Cursor<Vec<u8>> = Cursor::new(vec![0u8; 0x200 * 1024]);
    /// let mut gpt: Gpt<Cursor<Vec<u8>>, 0x200> = Gpt::new_on_device(device, 0, 1023).unwrap();
    ///
    /// let mut part = GptPartition::default();
    /// part.set_start_lba(400);
    /// part.set_last_lba(800);
    /// part.set_type_guid(1);
    /// gpt.append_partition(part).unwrap();
    ///
    /// let mut part = gpt.get_partition(0).unwrap();
    /// part.set_start_lba(500);
    ///
    /// gpt.update_partition(0, part);
    ///
    /// assert_eq!(gpt.get_partition(0).unwrap().start_lba(), 500);
    /// ```
    pub fn update_partition(
        &mut self,
        part_id: u32,
        new_part: GptPartition,
    ) -> Result<(), GptError> {
        let (_, idx) = self
            .iter_entries()
            .zip(0u32..)
            .filter(|(part, _)| part.is_used())
            .nth(usize::try_from(part_id).map_err(|_| GptError::OutOfBounds)?)
            .ok_or(GptError::NoSuchPartition)?;
        new_part
            .check_correctness()
            .map_err(|err| GptError::InvalidPartition(part_id, err))?;

        #[cfg(feature = "alloc")]
        {
            let mut partitions = self
                .iter_partitions()
                .enumerate()
                .filter_map(|(idx, part)| {
                    if idx == usize::try_from(part_id).unwrap_or(0) {
                        None
                    } else {
                        Some(part)
                    }
                })
                .collect::<Vec<_>>();
            partitions.push(new_part);

            if !find_overlapping_partitions(partitions).is_empty() {
                return Err(GptError::OverlappingPartitions);
            }
        }
        self.write_partition_entry(idx, &new_part)
    }

    fn restore_partitions_from_alternate(&mut self) -> Result<(), GptError> {
        let (_, alternate_start) = self.partition_offset(0);

        for part_idx in 0..self.header.partition_entries_count() {
            self.write_partition_entry(
                part_idx,
                &self.read_from_device::<GptPartition>(
                    alternate_start
                        + u64::try_from(
                            size_of::<GptPartition>()
                                * usize::try_from(part_idx).map_err(|_| GptError::IoError)?,
                        )
                        .map_err(|_| GptError::IoError)?,
                )?,
            )?;
        }

        Ok(())
    }

    fn restore_main_header_from_alternate(&mut self) -> Result<(), GptError> {
        let alternate = self.read_alternate()?;
        alternate.is_valid()?;
        self.header = alternate;

        self.write_header()?;

        Ok(())
    }

    fn write_header(&mut self) -> Result<(), GptError> {
        self.write_to_device::<GptHeader>(S * self.header.lba(), &self.header.clone())
    }

    fn write_alternate(&mut self) -> Result<(), GptError> {
        self.write_to_device(S * self.header.alternate_lba(), &self.header.clone())
    }

    fn write_partition_entry(
        &mut self,
        entry_id: u32,
        new_part: &GptPartition,
    ) -> Result<(), GptError> {
        let (primary, alternate) = self.partition_offset(entry_id);
        self.write_to_device::<GptPartition>(primary, new_part)?;
        self.write_to_device::<GptPartition>(alternate, new_part)?;

        self.update_checksums();
        self.write_alternate()?;

        Ok(())
    }

    fn write_to_device<T>(&mut self, offset: u64, obj: &T) -> Result<(), GptError>
    where
        T: IntoBytes + Immutable,
    {
        self.device_mapping
            .borrow_mut()
            .seek(SeekFrom::Start(offset))
            .map_err(|_| GptError::IoError)?;

        let bytes_written = self
            .device_mapping
            .borrow_mut()
            .write(obj.as_bytes())
            .map_err(|_| GptError::IoError)?;

        if bytes_written != size_of::<T>() {
            return Err(GptError::IoError);
        }

        Ok(())
    }
}

/// An iterator over the partition entries in a [`Gpt`].
pub struct GptPartitionsIterator<'a, D, const S: u64>
where
    D: DiskRead + DiskSeek,
{
    table: &'a Gpt<D, S>,
    cursor: u32,
    skip_empty: bool,
}

impl<D, const S: u64> Iterator for GptPartitionsIterator<'_, D, S>
where
    D: DiskRead + DiskSeek,
{
    type Item = GptPartition;

    fn next(&mut self) -> Option<Self::Item> {
        let part = self.table.read_partition_entry(self.cursor).ok()?;
        self.cursor += 1;

        if self.skip_empty && part.type_guid == 0 {
            return self.next();
        }

        Some(part)
    }
}

#[cfg(feature = "alloc")]
fn find_overlapping_partitions(mut partitions: Vec<GptPartition>) -> Vec<Vec<GptPartition>> {
    partitions.sort_by_key(GptPartition::start_lba);

    let mut partitions_groups: Vec<Vec<GptPartition>> = Vec::with_capacity(partitions.len());
    let mut curr_group_end = 0;

    for part in partitions {
        if part.start_lba() > curr_group_end {
            curr_group_end = part.last_lba();
            partitions_groups.push(alloc::vec![part]);
            continue;
        }

        curr_group_end = core::cmp::max(part.last_lba(), curr_group_end);
        partitions_groups.last_mut().unwrap().push(part);
    }

    partitions_groups.retain(|grp| grp.len() > 1);

    partitions_groups
}

#[cfg(test)]
#[cfg(feature = "std")]
mod tests {
    use std::{io::Cursor, vec::Vec};

    use super::Gpt;

    const GPT_DUMP: &[u8] = include_bytes!("../tests/dummy_gpt.bin");

    #[test]
    pub fn parse_gpt_from_buf() {
        let gpt_dump = Cursor::new(GPT_DUMP);
        let gpt: Gpt<Cursor<&[u8]>> = Gpt::parse_from_device(gpt_dump).unwrap();

        assert_eq!(gpt.header.partition_entries_count(), 128);
        assert_eq!(gpt.header.lba(), 1);
        assert_eq!(gpt.header.last_usable_lba(), 264158);
    }

    #[test]
    pub fn gpt_update_header() {
        let gpt_dump = Cursor::new(GPT_DUMP);
        let mut gpt: Gpt<Cursor<&[u8]>> = Gpt::parse_from_device(gpt_dump).unwrap();

        gpt.header.set_last_usable_lba(27278);

        assert_eq!(gpt.header.last_usable_lba(), 27278);
        assert!(gpt.check_table_correctness().is_ok());
    }

    #[test]
    pub fn new_gpt_in_buf() {
        let mut buf = [0u8; 0x200 * 1024];
        let device: Cursor<&mut [u8]> = Cursor::new(&mut buf);

        let gpt_in_dev = Gpt::<Cursor<&mut [u8]>, 0x200>::new_on_device(device, 1, 1023).unwrap();
        assert!(gpt_in_dev.check_table_correctness().is_ok());
        let gpt =
            Gpt::<Cursor<&mut [u8]>, 0x200>::parse_from_device(Cursor::new(&mut buf)).unwrap();

        assert!(gpt.check_table_correctness().is_ok());
    }

    #[test]
    pub fn parse_gpt_partitions() {
        let gpt_dump = Cursor::new(GPT_DUMP);
        let gpt: Gpt<Cursor<&[u8]>> = Gpt::parse_from_device(gpt_dump).unwrap();

        for part in gpt.iter_partitions() {
            assert!(part.is_used());
        }

        let partitions = gpt.iter_partitions().collect::<Vec<_>>();

        assert_eq!(partitions[0].name().unwrap(), "part_a");
        assert_eq!(partitions[1].name().unwrap(), "part_b");

        assert_eq!(partitions[0].start_lba(), 40);
        assert_eq!(partitions[1].start_lba(), 131112);
        assert!(gpt.check_table_correctness().is_ok());
    }

    #[test]
    pub fn gpt_partitions_checksum() {
        let gpt_dump = Cursor::new(GPT_DUMP);
        let gpt: Gpt<Cursor<&[u8]>> = Gpt::parse_from_device(gpt_dump).unwrap();

        assert_eq!(
            gpt.compute_partitions_checksum(),
            gpt.header.partition_entries_checksum()
        );
        assert!(gpt.check_table_correctness().is_ok());
    }

    #[test]
    pub fn gpt_partition_overlapping_check() {
        let gpt_dump = Cursor::new(GPT_DUMP.iter().cloned().collect::<Vec<_>>());
        let mut gpt: Gpt<Cursor<Vec<u8>>> = Gpt::parse_from_device(gpt_dump).unwrap();

        let mut part_a = gpt.get_partition(0).unwrap();
        part_a.set_start_lba(2727);

        gpt.update_partition(0, part_a).unwrap();
        assert!(gpt.check_table_correctness().is_ok());
    }

    #[test]
    pub fn gpt_append_partition() {
        let gpt_dump = Cursor::new(GPT_DUMP.iter().cloned().collect::<Vec<_>>());
        let mut gpt: Gpt<Cursor<Vec<u8>>> = Gpt::parse_from_device(gpt_dump).unwrap();

        let mut part_a = gpt.get_partition(0).unwrap();
        part_a.set_start_lba(27272727);
        part_a.set_last_lba(27272728);

        gpt.append_partition(part_a).unwrap();

        assert_eq!(gpt.iter_partitions().count(), 3);

        let partitions = gpt.iter_partitions().collect::<Vec<_>>();

        assert_eq!(partitions[2].name().unwrap(), "part_a");

        assert_eq!(partitions[2].start_lba(), 27272727);

        assert_eq!(gpt.read_alternate().unwrap(), gpt.header);
        assert!(gpt.check_table_correctness().is_ok());
    }

    #[test]
    pub fn gpt_update_partition() {
        let gpt_dump = Cursor::new(GPT_DUMP.iter().cloned().collect::<Vec<_>>());
        let mut gpt: Gpt<Cursor<Vec<u8>>> = Gpt::parse_from_device(gpt_dump).unwrap();

        let mut part_a = gpt.get_partition(0).unwrap();
        part_a.set_start_lba(2727);
        part_a.set_name("frost").unwrap();

        gpt.update_partition(0, part_a).unwrap();

        let partitions = gpt.iter_partitions().collect::<Vec<_>>();

        assert_eq!(partitions[0].name().unwrap(), "frost");

        assert_eq!(partitions[0].start_lba(), 2727);

        assert_eq!(gpt.read_alternate().unwrap(), gpt.header);
        assert!(gpt.check_table_correctness().is_ok());
    }

    #[test]
    pub fn gpt_remove_partition() {
        let gpt_dump = Cursor::new(GPT_DUMP.iter().cloned().collect::<Vec<_>>());
        let mut gpt: Gpt<Cursor<Vec<u8>>> = Gpt::parse_from_device(gpt_dump).unwrap();

        gpt.remove_partition(0).unwrap();

        let partitions = gpt.iter_partitions().collect::<Vec<_>>();

        assert_eq!(partitions.len(), 1);

        assert_eq!(partitions[0].name().unwrap(), "part_b");
        assert!(gpt.check_table_correctness().is_ok());
    }

    #[test]
    pub fn gpt_alternate_partition_offset() {
        let gpt_dump = Cursor::new(GPT_DUMP);
        let gpt: Gpt<Cursor<&[u8]>> = Gpt::parse_from_device(gpt_dump).unwrap();

        let (primary, alternate) = gpt.partition_offset(0);

        assert_eq!(
            alternate - gpt.header.last_usable_lba() * 0x200,
            primary - 0x200
        );

        let (primary, alternate) = gpt.partition_offset(1);

        assert_eq!(
            alternate - gpt.header.last_usable_lba() * 0x200,
            primary - 0x200
        );
    }
}