fstool 0.0.3

Build disk images and filesystems (ext2/3/4, MBR, GPT) from a directory tree and TOML spec, in the spirit of genext2fs.
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
//! TOML image-specification schema and the `build` driver.
//!
//! A spec describes *what to put in an image* declaratively. Two shapes:
//!
//! 1. **Bare filesystem** — a top-level `[filesystem]` table. The whole
//!    image is one ext2/3/4 filesystem with no partition table. This is
//!    the `genext2fs` replacement.
//!
//!    ```toml
//!    [filesystem]
//!    type = "ext4"
//!    source = "./rootfs"
//!    block_size = 1024
//!    rootdevs = "minimal"
//!    ```
//!
//! 2. **Partitioned disk image** — an `[image]` table plus `[[partitions]]`
//!    entries. Partitions are laid out 1 MiB-aligned in declaration order;
//!    exactly one may use `size = "remaining"` (and it must be last). Each
//!    partition optionally carries a nested `[partitions.filesystem]` table
//!    whose ext filesystem is formatted to fill the partition.
//!
//! Sizes accept a human suffix: `512`, `4KiB`, `256MiB`, `1GiB`, `2GB`
//! (decimal `KB/MB/GB` and binary `KiB/MiB/GiB`; bare numbers are bytes).

use std::path::{Path, PathBuf};

use serde::Deserialize;

use crate::Result;
use crate::block::{BlockDevice, FileBackend};
use crate::fs::ext::{Ext, FsKind};
use crate::fs::rootdevs::RootDevs;

/// Top-level parsed spec. Exactly one of `filesystem` / `image` must be set.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Spec {
    /// Bare-filesystem mode: the entire image is this one filesystem.
    pub filesystem: Option<FilesystemSpec>,
    /// Partitioned-disk mode header. Requires `partitions` to be non-empty.
    pub image: Option<ImageSpec>,
    /// Partition entries (only meaningful alongside `image`).
    #[serde(default)]
    pub partitions: Vec<PartitionSpec>,
}

/// Disk-level options for a partitioned image.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ImageSpec {
    /// Total disk size, e.g. `"1GiB"`.
    pub size: String,
    /// `"gpt"` or `"mbr"`.
    pub partition_table: String,
}

/// One partition in a [`Spec::partitions`] list.
///
/// The optional filesystem goes in a nested `[partitions.filesystem]`
/// table (not flattened) so the partition's own `type` key doesn't collide
/// with the filesystem's `type` key:
///
/// ```toml
/// [[partitions]]
/// name = "root"
/// type = "linux"
/// size = "remaining"
///
/// [partitions.filesystem]
/// type = "ext4"
/// source = "./rootfs"
/// ```
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PartitionSpec {
    pub name: Option<String>,
    /// Partition type: `"esp"`, `"linux"`, `"linux-swap"`, `"bios-boot"`,
    /// `"fat"`, or a raw `"0x83"` / GPT UUID string.
    #[serde(rename = "type")]
    pub kind: String,
    /// Partition size, e.g. `"256MiB"` or `"remaining"`.
    pub size: String,
    /// Filesystem to create inside this partition (optional — a partition
    /// can be left raw).
    pub filesystem: Option<FilesystemSpec>,
}

/// Filesystem configuration. Used both as the top-level `[filesystem]`
/// table (bare-FS mode) and as the nested `[partitions.filesystem]` table.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct FilesystemSpec {
    /// `"ext2"`, `"ext3"`, `"ext4"`, or `"fat32"`.
    #[serde(rename = "type")]
    pub fs_type: String,
    /// Host directory whose contents become the filesystem's tree.
    /// Omitted → an empty filesystem (just `/` and `/lost+found`).
    pub source: Option<PathBuf>,
    /// FS block size in bytes (1024 / 2048 / 4096). Default 1024. (ext only.)
    pub block_size: Option<u32>,
    /// Journal size in blocks (ext3/ext4 only). Default 1024.
    pub journal_blocks: Option<u32>,
    /// `"none"`, `"minimal"`, or `"standard"` — pre-populate `/dev`. (ext only.)
    pub rootdevs: Option<String>,
    /// Volume label (≤ 16 bytes for ext, ≤ 11 bytes for FAT32).
    pub volume_label: Option<String>,
    /// Modification timestamp baked into every inode (seconds since epoch).
    /// Default 0 for reproducible output. (ext only.)
    pub mtime: Option<u32>,
    /// When true, regular files are written sparsely — all-zero blocks
    /// become holes instead of consuming data blocks. Default false. (ext only.)
    pub sparse: Option<bool>,
    /// Explicit filesystem size, e.g. `"64MiB"`. Required for FAT32 in
    /// bare-FS mode (FAT32 has a ~33 MiB minimum and no streaming auto-size).
    /// Ignored when the FS sits in a partition (the partition size wins).
    pub size: Option<String>,
    /// FAT32 volume ID / serial number. Default 0 for reproducible output.
    pub volume_id: Option<u32>,
}

impl Spec {
    /// Parse a spec from TOML text.
    pub fn parse(toml_text: &str) -> Result<Self> {
        let spec: Spec = toml::from_str(toml_text)
            .map_err(|e| crate::Error::InvalidArgument(format!("spec: invalid TOML: {e}")))?;
        spec.validate()?;
        Ok(spec)
    }

    /// Parse a spec from a file on disk.
    pub fn parse_file(path: &Path) -> Result<Self> {
        let text = std::fs::read_to_string(path)?;
        Self::parse(&text)
    }

    fn validate(&self) -> Result<()> {
        match (&self.filesystem, &self.image) {
            (Some(_), Some(_)) => Err(crate::Error::InvalidArgument(
                "spec: cannot set both [filesystem] and [image] — pick bare-FS or partitioned"
                    .into(),
            )),
            (None, None) => Err(crate::Error::InvalidArgument(
                "spec: must set either [filesystem] (bare FS) or [image] + [[partitions]]".into(),
            )),
            (Some(_), None) => {
                if !self.partitions.is_empty() {
                    return Err(crate::Error::InvalidArgument(
                        "spec: [[partitions]] is meaningless without [image]".into(),
                    ));
                }
                Ok(())
            }
            (None, Some(_)) => {
                if self.partitions.is_empty() {
                    return Err(crate::Error::InvalidArgument(
                        "spec: [image] requires at least one [[partitions]] entry".into(),
                    ));
                }
                Ok(())
            }
        }
    }
}

/// Build the image described by `spec` into the file at `output`.
pub fn build(spec: &Spec, output: &Path) -> Result<()> {
    if let Some(fs) = &spec.filesystem {
        build_bare_fs(fs, output)
    } else if let Some(image) = &spec.image {
        build_partitioned(image, &spec.partitions, output)
    } else {
        // validate() guarantees one of the two is set.
        unreachable!("Spec::validate ensures filesystem xor image")
    }
}

fn build_bare_fs(fs: &FilesystemSpec, output: &Path) -> Result<()> {
    match fs.fs_type.to_ascii_lowercase().as_str() {
        "ext2" | "ext3" | "ext4" => build_bare_ext(fs, output),
        "fat32" | "vfat" => build_bare_fat32(fs, output),
        other => Err(crate::Error::InvalidArgument(format!(
            "spec: unknown filesystem type {other:?}"
        ))),
    }
}

fn build_bare_ext(fs: &FilesystemSpec, output: &Path) -> Result<()> {
    let kind = parse_fs_kind(&fs.fs_type)?;
    let block_size = fs.block_size.unwrap_or(1024);
    let opts = ext_format_opts(fs, kind, block_size, None)?;
    let size = opts.blocks_count as u64 * opts.block_size as u64;
    let mut dev = FileBackend::create(output, size)?;
    format_ext_into(&mut dev, fs, &opts)?;
    dev.sync()?;
    Ok(())
}

fn build_bare_fat32(fs: &FilesystemSpec, output: &Path) -> Result<()> {
    let size_str = fs.size.as_deref().ok_or_else(|| {
        crate::Error::InvalidArgument(
            "spec: FAT32 requires an explicit `size` (no streaming auto-size; minimum ~33 MiB)"
                .into(),
        )
    })?;
    let bytes = parse_size(size_str)?;
    let total_sectors: u32 = (bytes / SECTOR).try_into().map_err(|_| {
        crate::Error::InvalidArgument(
            "spec: FAT32 image size doesn't fit in a u32 sector count".into(),
        )
    })?;
    let label = fat32_volume_label(fs.volume_label.as_deref());
    let volume_id = fs.volume_id.unwrap_or(0);
    let mut dev = FileBackend::create(output, bytes)?;
    format_fat32_into(&mut dev, fs, total_sectors, volume_id, label)?;
    dev.sync()?;
    Ok(())
}

fn format_fat32_into(
    dev: &mut dyn BlockDevice,
    fs: &FilesystemSpec,
    total_sectors: u32,
    volume_id: u32,
    label: [u8; 11],
) -> Result<()> {
    use crate::fs::fat::Fat32;
    if let Some(src) = &fs.source {
        Fat32::build_from_host_dir(dev, total_sectors, src, volume_id, label)?;
    } else {
        let opts = crate::fs::fat::FatFormatOpts {
            total_sectors,
            volume_id,
            volume_label: label,
        };
        Fat32::format(dev, &opts)?;
    }
    Ok(())
}

/// Space-pad and truncate `label` to exactly 11 bytes for FAT32. ASCII only;
/// non-ASCII bytes are replaced with `_` (FAT32 short labels are OEM-encoded;
/// we don't try to translate code pages).
fn fat32_volume_label(label: Option<&str>) -> [u8; 11] {
    let mut out = [b' '; 11];
    let Some(s) = label else {
        return *b"NO NAME    ";
    };
    let upper = s.to_ascii_uppercase();
    let bytes = upper.as_bytes();
    for (i, &b) in bytes.iter().take(11).enumerate() {
        out[i] = if b.is_ascii() && b >= 0x20 && b != 0x7F {
            b
        } else {
            b'_'
        };
    }
    out
}

/// Build the [`crate::fs::ext::FormatOpts`] for a [`FilesystemSpec`].
/// `blocks_count_override` forces a specific block count (used to make a
/// partition's filesystem fill the partition exactly); `None` auto-sizes
/// from the source tree.
fn ext_format_opts(
    fs: &FilesystemSpec,
    kind: FsKind,
    block_size: u32,
    blocks_count_override: Option<u32>,
) -> Result<crate::fs::ext::FormatOpts> {
    let rootdevs = parse_rootdevs(fs.rootdevs.as_deref())?;
    let mtime = fs.mtime.unwrap_or(0);

    let mut plan = crate::fs::ext::BuildPlan::new(block_size, kind);
    if let Some(j) = fs.journal_blocks {
        plan.journal_blocks = j;
    }
    if let Some(src) = &fs.source {
        plan.scan_host_path(src)?;
    }
    for _ in 0..rootdevs_entry_count(rootdevs) {
        plan.add_device();
    }
    if rootdevs != RootDevs::None {
        plan.add_dir(); // the /dev directory itself
    }

    let mut opts = plan.to_format_opts();
    opts.mtime = mtime;
    opts.sparse = fs.sparse.unwrap_or(false);
    if let Some(label) = &fs.volume_label {
        let bytes = label.as_bytes();
        let n = bytes.len().min(16);
        opts.volume_label[..n].copy_from_slice(&bytes[..n]);
    }
    if let Some(bc) = blocks_count_override {
        if bc < opts.blocks_count {
            return Err(crate::Error::InvalidArgument(format!(
                "spec: partition holds {bc} blocks but its contents need at least {}",
                opts.blocks_count
            )));
        }
        opts.blocks_count = bc;
        // The auto-sized inode count was computed for the source tree only.
        // When filling a (potentially much larger) partition, scale up to
        // mke2fs's default density of one inode per 16 KiB so the partition
        // isn't inode-starved.
        let by_density = (bc as u64 * block_size as u64 / 16_384) as u32;
        opts.inodes_count = opts.inodes_count.max(by_density);
    }
    Ok(opts)
}

/// Format + populate an ext filesystem into `dev` from `fs`.
fn format_ext_into(
    dev: &mut dyn BlockDevice,
    fs: &FilesystemSpec,
    opts: &crate::fs::ext::FormatOpts,
) -> Result<()> {
    let rootdevs = parse_rootdevs(fs.rootdevs.as_deref())?;
    let mut ext = Ext::format_with(dev, opts)?;
    if let Some(src) = &fs.source {
        ext.populate_from_host_dir(dev, 2, src)?;
    }
    if rootdevs != RootDevs::None {
        ext.populate_rootdevs(dev, rootdevs, 0, 0, opts.mtime)?;
    }
    ext.flush(dev)?;
    Ok(())
}

/// Logical sector size for partition-table geometry. Both MBR and our v1
/// GPT writer assume 512-byte sectors.
const SECTOR: u64 = 512;
/// Partition-start alignment: 1 MiB, the modern convention.
const ALIGN_LBA: u64 = 2048;

fn build_partitioned(image: &ImageSpec, partitions: &[PartitionSpec], output: &Path) -> Result<()> {
    use crate::part::{Gpt, Mbr, Partition, PartitionTable, slice_partition};

    let total_bytes = parse_size(&image.size)?;
    let total_lba = total_bytes / SECTOR;
    let table = image.partition_table.to_ascii_lowercase();

    // Reserve space for the partition table's own metadata.
    //   GPT: LBA 0 protective MBR + 1..33 primary + last 33 backup.
    //   MBR: just LBA 0.
    let (first_free, last_usable) = match table.as_str() {
        "gpt" => (ALIGN_LBA, total_lba.saturating_sub(34)),
        "mbr" => (ALIGN_LBA, total_lba.saturating_sub(1)),
        other => {
            return Err(crate::Error::InvalidArgument(format!(
                "spec: unknown partition_table {other:?} (want gpt or mbr)"
            )));
        }
    };
    if table == "mbr" && partitions.len() > 4 {
        return Err(crate::Error::InvalidArgument(
            "spec: MBR supports at most 4 partitions".into(),
        ));
    }

    // Lay out partitions sequentially. Exactly one may use size
    // "remaining", and it must be the last entry.
    let remaining_idx = partitions
        .iter()
        .position(|p| p.size.eq_ignore_ascii_case("remaining"));
    if let Some(idx) = remaining_idx
        && idx != partitions.len() - 1
    {
        return Err(crate::Error::InvalidArgument(
            "spec: size = \"remaining\" is only allowed on the last partition".into(),
        ));
    }

    let mut placed: Vec<Partition> = Vec::with_capacity(partitions.len());
    let mut cursor = first_free;
    for p in partitions {
        let start = cursor.div_ceil(ALIGN_LBA) * ALIGN_LBA;
        let size_lba = if p.size.eq_ignore_ascii_case("remaining") {
            if last_usable < start {
                return Err(crate::Error::InvalidArgument(
                    "spec: no space left for the \"remaining\" partition".into(),
                ));
            }
            last_usable + 1 - start
        } else {
            let bytes = parse_size(&p.size)?;
            bytes / SECTOR
        };
        if size_lba == 0 {
            return Err(crate::Error::InvalidArgument(format!(
                "spec: partition {:?} has zero size",
                p.name.as_deref().unwrap_or("?")
            )));
        }
        if start + size_lba - 1 > last_usable {
            return Err(crate::Error::InvalidArgument(format!(
                "spec: partition {:?} (LBA {}..{}) overflows the {}-LBA disk",
                p.name.as_deref().unwrap_or("?"),
                start,
                start + size_lba - 1,
                total_lba
            )));
        }
        let kind = parse_partition_kind(&p.kind)?;
        let mut part = Partition::new(start, size_lba, kind);
        part.name = p.name.clone();
        placed.push(part);
        cursor = start + size_lba;
    }

    // Create the backing file and write the partition table.
    let mut dev = FileBackend::create(output, total_bytes)?;
    match table.as_str() {
        "gpt" => {
            let gpt = Gpt::build(placed.clone())?;
            gpt.write(&mut dev)?;
        }
        "mbr" => {
            let mbr = Mbr::new(placed.clone())?;
            mbr.write(&mut dev)?;
        }
        _ => unreachable!(),
    }

    // Rebuild a PartitionTable trait object once so slice_partition can
    // compute each partition's byte range. (The Gpt/Mbr built above were
    // consumed by write(); rebuilding from `placed` is cheap.)
    let table_obj: Box<dyn PartitionTable> = match table.as_str() {
        "gpt" => Box::new(Gpt::build(placed.clone())?),
        "mbr" => Box::new(Mbr::new(placed.clone())?),
        _ => unreachable!(),
    };

    // Format + populate each partition that carries a filesystem.
    for (i, p) in partitions.iter().enumerate() {
        let Some(fs) = &p.filesystem else {
            continue;
        };
        let part_bytes = placed[i].size_lba * SECTOR;
        let mut slice = slice_partition(table_obj.as_ref(), &mut dev, i)?;
        match fs.fs_type.to_ascii_lowercase().as_str() {
            "ext2" | "ext3" | "ext4" => {
                let kind = parse_fs_kind(&fs.fs_type)?;
                let block_size = fs.block_size.unwrap_or(1024);
                // Fill the partition: blocks_count = partition_bytes / fs_block_size,
                // rounded DOWN to a multiple of 8 (the byte-aligned-group invariant).
                let blocks = ((part_bytes / block_size as u64) / 8 * 8) as u32;
                let opts = ext_format_opts(fs, kind, block_size, Some(blocks))?;
                format_ext_into(&mut slice, fs, &opts)?;
            }
            "fat32" | "vfat" => {
                let total_sectors: u32 = (part_bytes / SECTOR).try_into().map_err(|_| {
                    crate::Error::InvalidArgument(
                        "spec: FAT32 partition size doesn't fit in a u32 sector count".into(),
                    )
                })?;
                let label = fat32_volume_label(fs.volume_label.as_deref());
                let volume_id = fs.volume_id.unwrap_or(0);
                format_fat32_into(&mut slice, fs, total_sectors, volume_id, label)?;
            }
            other => {
                return Err(crate::Error::InvalidArgument(format!(
                    "spec: unknown filesystem type {other:?}"
                )));
            }
        }
    }

    dev.sync()?;
    Ok(())
}

/// Map a partition-type string to a [`crate::part::PartitionKind`].
fn parse_partition_kind(s: &str) -> Result<crate::part::PartitionKind> {
    use crate::part::PartitionKind;
    let lower = s.to_ascii_lowercase();
    Ok(match lower.as_str() {
        "esp" | "efi" | "efi-system" => PartitionKind::EfiSystem,
        "linux" | "linux-filesystem" => PartitionKind::LinuxFilesystem,
        "linux-swap" | "swap" => PartitionKind::LinuxSwap,
        "bios-boot" | "bios" => PartitionKind::BiosBoot,
        "fat" | "fat32" => PartitionKind::Fat32,
        "msdata" | "microsoft-basic-data" | "basic-data" => PartitionKind::MicrosoftBasicData,
        "empty" => PartitionKind::Empty,
        other => {
            // Accept a raw MBR byte ("0x83") or a GPT type UUID.
            if let Some(hex) = other.strip_prefix("0x") {
                let b = u8::from_str_radix(hex, 16).map_err(|_| {
                    crate::Error::InvalidArgument(format!("spec: bad MBR type byte {other:?}"))
                })?;
                PartitionKind::from_mbr_byte(b)
            } else if let Ok(uuid) = uuid::Uuid::parse_str(other) {
                PartitionKind::from_gpt_uuid(uuid)
            } else {
                return Err(crate::Error::InvalidArgument(format!(
                    "spec: unknown partition type {s:?}"
                )));
            }
        }
    })
}

fn parse_fs_kind(s: &str) -> Result<FsKind> {
    match s.to_ascii_lowercase().as_str() {
        "ext2" => Ok(FsKind::Ext2),
        "ext3" => Ok(FsKind::Ext3),
        "ext4" => Ok(FsKind::Ext4),
        other => Err(crate::Error::InvalidArgument(format!(
            "spec: parse_fs_kind only handles ext2/3/4 (got {other:?})"
        ))),
    }
}

fn parse_rootdevs(s: Option<&str>) -> Result<RootDevs> {
    match s.map(|x| x.to_ascii_lowercase()) {
        None => Ok(RootDevs::None),
        Some(x) => match x.as_str() {
            "none" => Ok(RootDevs::None),
            "minimal" => Ok(RootDevs::Minimal),
            "standard" => Ok(RootDevs::Standard),
            other => Err(crate::Error::InvalidArgument(format!(
                "spec: unknown rootdevs value {other:?} (want none/minimal/standard)"
            ))),
        },
    }
}

fn rootdevs_entry_count(kind: RootDevs) -> usize {
    crate::fs::rootdevs::device_table(kind).len()
}

/// Parse a human-readable size string into bytes. Accepts a bare integer
/// (bytes), or a number followed by a unit: `KB`/`MB`/`GB`/`TB` (decimal,
/// ×1000) or `KiB`/`MiB`/`GiB`/`TiB` (binary, ×1024). Case-insensitive.
pub fn parse_size(s: &str) -> Result<u64> {
    let s = s.trim();
    let split = s.find(|c: char| !c.is_ascii_digit()).unwrap_or(s.len());
    let (num, unit) = s.split_at(split);
    let value: u64 = num
        .parse()
        .map_err(|_| crate::Error::InvalidArgument(format!("spec: bad size {s:?}")))?;
    let mult: u64 = match unit.trim().to_ascii_lowercase().as_str() {
        "" | "b" => 1,
        "kb" => 1_000,
        "mb" => 1_000_000,
        "gb" => 1_000_000_000,
        "tb" => 1_000_000_000_000,
        "kib" | "k" => 1 << 10,
        "mib" | "m" => 1 << 20,
        "gib" | "g" => 1 << 30,
        "tib" | "t" => 1 << 40,
        other => {
            return Err(crate::Error::InvalidArgument(format!(
                "spec: unknown size unit {other:?}"
            )));
        }
    };
    value
        .checked_mul(mult)
        .ok_or_else(|| crate::Error::InvalidArgument(format!("spec: size {s:?} overflows u64")))
}

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

    #[test]
    fn size_parsing() {
        assert_eq!(parse_size("0").unwrap(), 0);
        assert_eq!(parse_size("512").unwrap(), 512);
        assert_eq!(parse_size("1KiB").unwrap(), 1024);
        assert_eq!(parse_size("4 KiB").unwrap(), 4096);
        assert_eq!(parse_size("256MiB").unwrap(), 256 * 1024 * 1024);
        assert_eq!(parse_size("1GiB").unwrap(), 1 << 30);
        assert_eq!(parse_size("2GB").unwrap(), 2_000_000_000);
        assert_eq!(parse_size("1m").unwrap(), 1 << 20);
        assert!(parse_size("12parsecs").is_err());
        assert!(parse_size("").is_err());
    }

    #[test]
    fn bare_fs_spec_parses() {
        let toml = r#"
            [filesystem]
            type = "ext4"
            source = "./rootfs"
            block_size = 4096
            rootdevs = "minimal"
        "#;
        let spec = Spec::parse(toml).unwrap();
        let fs = spec.filesystem.unwrap();
        assert_eq!(fs.fs_type, "ext4");
        assert_eq!(fs.block_size, Some(4096));
        assert_eq!(fs.rootdevs.as_deref(), Some("minimal"));
        assert!(spec.image.is_none());
    }

    #[test]
    fn rejects_both_filesystem_and_image() {
        let toml = r#"
            [filesystem]
            type = "ext2"

            [image]
            size = "1GiB"
            partition_table = "gpt"
        "#;
        assert!(Spec::parse(toml).is_err());
    }

    #[test]
    fn rejects_empty_spec() {
        assert!(Spec::parse("").is_err());
    }

    #[test]
    fn image_requires_partitions() {
        let toml = r#"
            [image]
            size = "1GiB"
            partition_table = "gpt"
        "#;
        assert!(Spec::parse(toml).is_err());
    }

    #[test]
    fn partitioned_spec_with_nested_filesystem_parses() {
        let toml = r#"
            [image]
            size = "64MiB"
            partition_table = "gpt"

            [[partitions]]
            name = "EFI"
            type = "esp"
            size = "16MiB"

            [[partitions]]
            name = "root"
            type = "linux"
            size = "remaining"

            [partitions.filesystem]
            type = "ext4"
            source = "./rootfs"
            block_size = 4096
        "#;
        let spec = Spec::parse(toml).unwrap();
        assert_eq!(spec.partitions.len(), 2);
        assert_eq!(spec.partitions[0].kind, "esp");
        assert!(spec.partitions[0].filesystem.is_none());
        let root_fs = spec.partitions[1].filesystem.as_ref().unwrap();
        assert_eq!(root_fs.fs_type, "ext4");
        assert_eq!(root_fs.block_size, Some(4096));
    }

    #[test]
    fn remaining_must_be_last_partition() {
        let toml = r#"
            [image]
            size = "64MiB"
            partition_table = "gpt"

            [[partitions]]
            name = "a"
            type = "linux"
            size = "remaining"

            [[partitions]]
            name = "b"
            type = "linux"
            size = "16MiB"
        "#;
        let spec = Spec::parse(toml).unwrap();
        let err = build(&spec, std::path::Path::new("/tmp/fstool-test-unused.img")).unwrap_err();
        assert!(matches!(err, crate::Error::InvalidArgument(_)));
    }

    #[test]
    fn partition_kind_strings() {
        use crate::part::PartitionKind;
        assert_eq!(
            parse_partition_kind("esp").unwrap(),
            PartitionKind::EfiSystem
        );
        assert_eq!(
            parse_partition_kind("linux").unwrap(),
            PartitionKind::LinuxFilesystem
        );
        assert_eq!(
            parse_partition_kind("0x83").unwrap(),
            PartitionKind::LinuxFilesystem
        );
        assert!(parse_partition_kind("nonsense").is_err());
    }
}