typst-pack 0.5.0

Portable single-file packs of Typst projects: sources, resources, packages, and fonts
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
//! Font Catalog reading for the reference filesystem Font Authority.

#[cfg(windows)]
use std::fs::File;
use std::io::Read;
use std::path::{Path, PathBuf};

use crate::error_display::format_error_list;
#[cfg(feature = "embedded-fonts")]
use crate::font_catalog::typst_embedded_font_containers;
use crate::font_catalog::{
    FontCatalog, FontCatalogEntry, FontContainer, FontContainerError, FontDisposition,
};
use crate::fs_traversal::{self, TraversalPolicy, UnsupportedEntry};
use crate::limits::{LimitError, Limits, ResourceKind};

/// A resource bounded during filesystem Font Catalog reading.
pub type FilesystemFontResource = ResourceKind<2>;

#[allow(non_upper_case_globals)]
impl ResourceKind<2> {
    pub const VisitedEntries: Self = Self::new(0);
    pub const AcceptedContainers: Self = Self::new(1);
    pub const ContainerBytes: Self = Self::new(2);
    pub const TotalAcceptedBytes: Self = Self::new(3);
}

/// A filesystem font source exceeded a mandatory reading ceiling.
pub type FilesystemFontLimitError = LimitError<FilesystemFontResource>;

/// Mandatory finite resource ceilings for filesystem Font Catalog reading.
pub type FilesystemFontLimits = Limits<FilesystemFontResource>;

impl Limits<FilesystemFontResource> {
    /// Constructs validated mandatory finite reading ceilings.
    #[track_caller]
    pub fn new(
        visited_entries: u64,
        accepted_containers: u64,
        container_bytes: u64,
        total_accepted_bytes: u64,
    ) -> Self {
        Self::from_ceilings([
            visited_entries,
            accepted_containers,
            container_bytes,
            total_accepted_bytes,
            0,
            0,
            0,
        ])
        .assert_probe_resources([
            FilesystemFontResource::VisitedEntries,
            FilesystemFontResource::AcceptedContainers,
            FilesystemFontResource::ContainerBytes,
            FilesystemFontResource::TotalAcceptedBytes,
        ])
    }

    /// The first-party limits for filesystem font sources.
    pub const fn reference_v1() -> Self {
        Self::from_ceilings([
            100_000,
            16_384,
            256 * 1024 * 1024,
            2 * 1024 * 1024 * 1024,
            0,
            0,
            0,
        ])
    }

    pub const fn visited_entries(&self) -> u64 {
        self.ceilings[0]
    }

    pub const fn accepted_containers(&self) -> u64 {
        self.ceilings[1]
    }

    pub const fn container_bytes(&self) -> u64 {
        self.ceilings[2]
    }

    pub const fn total_accepted_bytes(&self) -> u64 {
        self.ceilings[3]
    }
}

/// One explicitly configured source of Font Containers.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct FilesystemFontSource {
    kind: FilesystemFontSourceKind,
    disposition: FontDisposition,
}

#[derive(Clone, Debug, Eq, PartialEq)]
enum FilesystemFontSourceKind {
    System,
    #[cfg(feature = "embedded-fonts")]
    TypstEmbedded,
    Directory(PathBuf),
}

impl FilesystemFontSource {
    /// Selects the host's standard system font directories at this position.
    pub fn system(disposition: FontDisposition) -> Self {
        Self {
            kind: FilesystemFontSourceKind::System,
            disposition,
        }
    }

    /// Selects Typst's compiled-in Font Containers at this position.
    #[cfg(feature = "embedded-fonts")]
    pub fn typst_embedded(disposition: FontDisposition) -> Self {
        Self {
            kind: FilesystemFontSourceKind::TypstEmbedded,
            disposition,
        }
    }

    /// Selects every eligible Font Container beneath one directory.
    pub fn directory(path: impl Into<PathBuf>, disposition: FontDisposition) -> Self {
        Self {
            kind: FilesystemFontSourceKind::Directory(path.into()),
            disposition,
        }
    }

    /// The disposition every catalog position from this source carries.
    pub fn disposition(&self) -> FontDisposition {
        self.disposition
    }
}

/// The kind of an eligible filesystem entry that cannot become a Font Container.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
#[non_exhaustive]
pub enum FilesystemFontEntryKind {
    Socket,
    Fifo,
    BlockDevice,
    CharacterDevice,
    Unknown,
}

/// The filesystem operation that failed while reading a Font Catalog.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
#[non_exhaustive]
pub enum FilesystemFontOperation {
    InspectRoot,
    SurveyEntry,
    InspectContainer,
    ReadContainer,
}

impl std::fmt::Display for FilesystemFontOperation {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(match self {
            Self::InspectRoot => "inspect font source root",
            Self::SurveyEntry => "survey font source entry",
            Self::InspectContainer => "inspect selected Font Container",
            Self::ReadContainer => "read selected Font Container",
        })
    }
}

/// One independently detectable filesystem font survey issue.
#[derive(Debug, Clone, Eq, PartialEq, thiserror::Error)]
#[non_exhaustive]
pub enum FilesystemFontIssue {
    #[error("unsupported filesystem entry {path:?}: aliases cannot become Font Containers")]
    Alias { path: PathBuf },
    #[error("unsupported eligible font entry {path:?}")]
    UnsupportedEntry {
        path: PathBuf,
        kind: FilesystemFontEntryKind,
    },
    #[error("filesystem font source root {path:?} is not a directory")]
    RootNotDirectory { path: PathBuf },
}

impl FilesystemFontIssue {
    fn path(&self) -> &Path {
        match self {
            Self::Alias { path }
            | Self::UnsupportedEntry { path, .. }
            | Self::RootNotDirectory { path } => path,
        }
    }

    fn rank(&self) -> u8 {
        match self {
            Self::Alias { .. } => 0,
            Self::UnsupportedEntry { .. } => 1,
            Self::RootNotDirectory { .. } => 2,
        }
    }
}

/// All safely detectable issues found by one filesystem font survey.
#[derive(Debug, Clone, Eq, PartialEq, thiserror::Error)]
#[error(
    "filesystem font survey found {} issue(s){}",
    .issues.len(),
    format_error_list(.issues.as_slice())
)]
pub struct FilesystemFontSurveyError {
    issues: Vec<FilesystemFontIssue>,
}

impl FilesystemFontSurveyError {
    pub fn issues(&self) -> &[FilesystemFontIssue] {
        &self.issues
    }
}

/// One selected filesystem entry whose bytes are not a valid Font Container.
#[derive(Debug, Clone, Eq, PartialEq, thiserror::Error)]
#[error("invalid Font Container at {path:?}: {source}")]
pub struct FilesystemFontContainerIssue {
    path: PathBuf,
    source: FontContainerError,
}

impl FilesystemFontContainerIssue {
    /// The selected filesystem path whose exact bytes failed validation.
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// The authoritative Font Container validation failure.
    pub fn source(&self) -> FontContainerError {
        self.source
    }
}

/// Every invalid Font Container found while validating selected entries.
#[derive(Debug, Clone, Eq, PartialEq, thiserror::Error)]
#[error(
    "filesystem font validation found {} invalid container(s){}",
    .issues.len(),
    format_error_list(.issues.as_slice())
)]
pub struct FilesystemFontValidationError {
    issues: Vec<FilesystemFontContainerIssue>,
}

impl FilesystemFontValidationError {
    pub fn issues(&self) -> &[FilesystemFontContainerIssue] {
        &self.issues
    }
}

/// A failure while reading a Font Catalog from configured filesystem sources.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum FilesystemFontReadError {
    #[error("failed to {operation} {path:?}: {source}")]
    Io {
        operation: FilesystemFontOperation,
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },
    #[error(transparent)]
    Survey(FilesystemFontSurveyError),
    #[error("filesystem font resource limit at {path:?}: {source}")]
    Limit {
        path: PathBuf,
        source: FilesystemFontLimitError,
    },
    #[error(transparent)]
    InvalidContainers(FilesystemFontValidationError),
}

impl FilesystemFontReadError {
    fn io(
        operation: FilesystemFontOperation,
        path: impl Into<PathBuf>,
        source: std::io::Error,
    ) -> Self {
        Self::Io {
            operation,
            path: path.into(),
            source,
        }
    }

    fn limit(path: &Path, source: FilesystemFontLimitError) -> Self {
        Self::Limit {
            path: path.to_owned(),
            source,
        }
    }
}

struct SelectedFont {
    root: PathBuf,
    boundary: PathBuf,
    path: PathBuf,
}

enum PlannedSource {
    Filesystem {
        selected: Vec<SelectedFont>,
        disposition: FontDisposition,
    },
    #[cfg(feature = "embedded-fonts")]
    TypstEmbedded {
        containers: Vec<FontContainer>,
        disposition: FontDisposition,
    },
}

#[derive(Default)]
struct SurveyState {
    visited_entries: u64,
    accepted_containers: u64,
    declared_total: u64,
    issues: Vec<FilesystemFontIssue>,
    deferred_limit: Option<FilesystemFontReadError>,
}

/// Reads one ordered Font Catalog from explicitly configured sources.
///
/// Sources compose in iterator order. Paths within one scanned root compose in
/// lexical order, and no system or embedded source is added implicitly.
pub fn read_filesystem_fonts(
    sources: impl IntoIterator<Item = FilesystemFontSource>,
    limits: FilesystemFontLimits,
) -> Result<FontCatalog, FilesystemFontReadError> {
    let mut state = SurveyState::default();
    let mut plans = Vec::new();

    for source in sources {
        match source.kind {
            FilesystemFontSourceKind::System => {
                let selected = survey_system_fonts(limits, &mut state)?;
                plans.push(PlannedSource::Filesystem {
                    selected,
                    disposition: source.disposition,
                });
            }
            #[cfg(feature = "embedded-fonts")]
            FilesystemFontSourceKind::TypstEmbedded => {
                let mut containers = Vec::new();
                for container in typst_embedded_font_containers() {
                    containers.push(container);
                }
                plans.push(PlannedSource::TypstEmbedded {
                    containers,
                    disposition: source.disposition,
                });
            }
            FilesystemFontSourceKind::Directory(root) => {
                let selected = survey_root(&root, true, limits, &mut state)?;
                plans.push(PlannedSource::Filesystem {
                    selected,
                    disposition: source.disposition,
                });
            }
        }
    }

    if !state.issues.is_empty() {
        state.issues.sort_by(|left, right| {
            left.path()
                .cmp(right.path())
                .then_with(|| left.rank().cmp(&right.rank()))
        });
        return Err(FilesystemFontReadError::Survey(FilesystemFontSurveyError {
            issues: state.issues,
        }));
    }
    if let Some(error) = state.deferred_limit {
        return Err(error);
    }

    let mut catalog = FontCatalog::new();
    let mut actual_total = 0u64;
    let mut invalid_containers = Vec::new();
    for plan in plans {
        match plan {
            PlannedSource::Filesystem {
                selected,
                disposition,
            } => {
                for selected in selected {
                    let bytes = read_bounded(
                        &selected.root,
                        &selected.boundary,
                        &selected.path,
                        actual_total,
                        limits,
                    )?;
                    actual_total = checked_add(
                        actual_total,
                        bytes.len() as u64,
                        FilesystemFontResource::TotalAcceptedBytes,
                    )
                    .map_err(|source| FilesystemFontReadError::limit(&selected.path, source))?;
                    match FontContainer::new(bytes) {
                        Ok(container) => {
                            catalog.push(FontCatalogEntry::new(container, disposition));
                        }
                        Err(source) => invalid_containers.push(FilesystemFontContainerIssue {
                            path: selected.path,
                            source,
                        }),
                    }
                }
            }
            #[cfg(feature = "embedded-fonts")]
            PlannedSource::TypstEmbedded {
                containers,
                disposition,
            } => {
                for container in containers {
                    catalog.push(FontCatalogEntry::new(container, disposition));
                }
            }
        }
    }
    if !invalid_containers.is_empty() {
        invalid_containers.sort_by(|left, right| left.path.cmp(&right.path));
        return Err(FilesystemFontReadError::InvalidContainers(
            FilesystemFontValidationError {
                issues: invalid_containers,
            },
        ));
    }
    Ok(catalog)
}

fn survey_system_fonts(
    limits: FilesystemFontLimits,
    state: &mut SurveyState,
) -> Result<Vec<SelectedFont>, FilesystemFontReadError> {
    let mut selected = Vec::new();
    for root in system_font_roots() {
        selected.extend(survey_root(&root, false, limits, state)?);
    }

    #[cfg(target_os = "macos")]
    {
        selected.extend(survey_macos_downloadable_fonts(limits, state)?);
        for root in macos_system_font_roots_after_downloadable() {
            selected.extend(survey_root(&root, false, limits, state)?);
        }
    }

    Ok(selected)
}

#[cfg(target_os = "macos")]
fn survey_macos_downloadable_fonts(
    limits: FilesystemFontLimits,
    state: &mut SurveyState,
) -> Result<Vec<SelectedFont>, FilesystemFontReadError> {
    let root = Path::new("/System/Library/AssetsV2");
    let entries = match std::fs::read_dir(root) {
        Ok(entries) => entries,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
        Err(error) => {
            return Err(FilesystemFontReadError::io(
                FilesystemFontOperation::SurveyEntry,
                root,
                error,
            ));
        }
    };
    let mut roots = Vec::new();
    for entry in entries {
        let entry = entry.map_err(|error| {
            FilesystemFontReadError::io(FilesystemFontOperation::SurveyEntry, root, error)
        })?;
        state.visited_entries = checked_add(
            state.visited_entries,
            1,
            FilesystemFontResource::VisitedEntries,
        )
        .map_err(|source| FilesystemFontReadError::limit(&entry.path(), source))?;
        check_limit(
            FilesystemFontResource::VisitedEntries,
            limits.visited_entries(),
            state.visited_entries,
        )
        .map_err(|source| FilesystemFontReadError::limit(&entry.path(), source))?;
        if entry
            .file_name()
            .to_string_lossy()
            .starts_with("com_apple_MobileAsset_Font")
        {
            roots.push(entry.path());
        }
    }
    roots.sort();

    let mut selected = Vec::new();
    for root in roots {
        selected.extend(survey_root(&root, false, limits, state)?);
    }
    Ok(selected)
}

fn survey_root(
    root: &Path,
    required: bool,
    limits: FilesystemFontLimits,
    state: &mut SurveyState,
) -> Result<Vec<SelectedFont>, FilesystemFontReadError> {
    let metadata = match std::fs::symlink_metadata(root) {
        Ok(metadata) => metadata,
        Err(error) if !required && error.kind() == std::io::ErrorKind::NotFound => {
            return Ok(Vec::new());
        }
        Err(error) => {
            return Err(FilesystemFontReadError::io(
                FilesystemFontOperation::InspectRoot,
                root,
                error,
            ));
        }
    };
    if metadata.file_type().is_symlink() {
        state.issues.push(FilesystemFontIssue::Alias {
            path: root.to_owned(),
        });
        return Ok(Vec::new());
    }
    if !metadata.is_dir() {
        state.issues.push(FilesystemFontIssue::RootNotDirectory {
            path: root.to_owned(),
        });
        return Ok(Vec::new());
    }
    let boundary = std::fs::canonicalize(root).map_err(|source| {
        FilesystemFontReadError::io(FilesystemFontOperation::InspectRoot, root, source)
    })?;

    let mut selected = Vec::new();
    for entry in walkdir::WalkDir::new(root).follow_links(false) {
        let entry = entry.map_err(|error| {
            let path = error.path().unwrap_or(root).to_owned();
            let source = error
                .into_io_error()
                .unwrap_or_else(|| std::io::Error::other("filesystem traversal failed"));
            FilesystemFontReadError::io(FilesystemFontOperation::SurveyEntry, path, source)
        })?;
        if entry.depth() == 0 {
            continue;
        }

        state.visited_entries = checked_add(
            state.visited_entries,
            1,
            FilesystemFontResource::VisitedEntries,
        )
        .map_err(|source| FilesystemFontReadError::limit(entry.path(), source))?;
        check_limit(
            FilesystemFontResource::VisitedEntries,
            limits.visited_entries(),
            state.visited_entries,
        )
        .map_err(|source| FilesystemFontReadError::limit(entry.path(), source))?;

        let file_type = entry.file_type();
        if file_type.is_dir() {
            continue;
        }
        if file_type.is_symlink() {
            state.issues.push(FilesystemFontIssue::Alias {
                path: entry.path().to_owned(),
            });
            continue;
        }
        if !font_eligible(entry.path()) {
            continue;
        }
        if !file_type.is_file() {
            state.issues.push(FilesystemFontIssue::UnsupportedEntry {
                path: entry.path().to_owned(),
                kind: UnsupportedEntry::of(&file_type).into(),
            });
            continue;
        }

        let metadata = entry.metadata().map_err(|error| {
            let path = error.path().unwrap_or(entry.path()).to_owned();
            let source = error
                .into_io_error()
                .unwrap_or_else(|| std::io::Error::other("failed to inspect Font Container"));
            FilesystemFontReadError::io(FilesystemFontOperation::InspectContainer, path, source)
        })?;
        let accepted = account_container(entry.path(), metadata.len(), limits, state)?;
        if accepted {
            selected.push(SelectedFont {
                root: root.to_owned(),
                boundary: boundary.clone(),
                path: entry.path().to_owned(),
            });
        }
    }
    selected.sort_by(|left, right| left.path.cmp(&right.path));
    Ok(selected)
}

fn account_container(
    path: &Path,
    declared: u64,
    limits: FilesystemFontLimits,
    state: &mut SurveyState,
) -> Result<bool, FilesystemFontReadError> {
    state.accepted_containers = checked_add(
        state.accepted_containers,
        1,
        FilesystemFontResource::AcceptedContainers,
    )
    .map_err(|source| FilesystemFontReadError::limit(path, source))?;
    if let Err(source) = check_limit(
        FilesystemFontResource::AcceptedContainers,
        limits.accepted_containers(),
        state.accepted_containers,
    ) {
        if state.deferred_limit.is_none() {
            state.deferred_limit = Some(FilesystemFontReadError::limit(path, source));
        }
        return Ok(false);
    }
    if let Err(source) = check_limit(
        FilesystemFontResource::ContainerBytes,
        limits.container_bytes(),
        declared,
    ) {
        if state.deferred_limit.is_none() {
            state.deferred_limit = Some(FilesystemFontReadError::limit(path, source));
        }
        return Ok(false);
    }
    state.declared_total = checked_add(
        state.declared_total,
        declared,
        FilesystemFontResource::TotalAcceptedBytes,
    )
    .map_err(|source| FilesystemFontReadError::limit(path, source))?;
    if let Err(source) = check_limit(
        FilesystemFontResource::TotalAcceptedBytes,
        limits.total_accepted_bytes(),
        state.declared_total,
    ) {
        if state.deferred_limit.is_none() {
            state.deferred_limit = Some(FilesystemFontReadError::limit(path, source));
        }
        return Ok(false);
    }
    Ok(true)
}

fn read_bounded(
    root: &Path,
    boundary: &Path,
    path: &Path,
    total_before: u64,
    limits: FilesystemFontLimits,
) -> Result<Vec<u8>, FilesystemFontReadError> {
    let total_allowance = limits.total_accepted_bytes().saturating_sub(total_before);
    let allowance = limits.container_bytes().min(total_allowance);
    let mut file = open_without_following(root, boundary, path)?;
    let mut bytes = Vec::new();
    file.by_ref()
        .take(allowance + 1)
        .read_to_end(&mut bytes)
        .map_err(|error| {
            FilesystemFontReadError::io(FilesystemFontOperation::ReadContainer, path, error)
        })?;
    let observed = u64::try_from(bytes.len()).map_err(|_| {
        FilesystemFontReadError::limit(
            path,
            FilesystemFontLimitError::AccountingOverflow {
                resource: FilesystemFontResource::ContainerBytes,
            },
        )
    })?;
    check_limit(
        FilesystemFontResource::ContainerBytes,
        limits.container_bytes(),
        observed,
    )
    .map_err(|source| FilesystemFontReadError::limit(path, source))?;
    let total = checked_add(
        total_before,
        observed,
        FilesystemFontResource::TotalAcceptedBytes,
    )
    .map_err(|source| FilesystemFontReadError::limit(path, source))?;
    check_limit(
        FilesystemFontResource::TotalAcceptedBytes,
        limits.total_accepted_bytes(),
        total,
    )
    .map_err(|source| FilesystemFontReadError::limit(path, source))?;
    Ok(bytes)
}

#[cfg(windows)]
fn validate_windows_boundary(
    file: &File,
    boundary: &Path,
    path: &Path,
) -> Result<(), FilesystemFontReadError> {
    use std::os::windows::ffi::OsStringExt;
    use std::os::windows::io::AsRawHandle;
    use windows_sys::Win32::Storage::FileSystem::GetFinalPathNameByHandleW;

    let handle = file.as_raw_handle();
    // SAFETY: `handle` remains owned by `file`; a null output buffer requests
    // the required UTF-16 length and writes no bytes.
    let required = unsafe { GetFinalPathNameByHandleW(handle, std::ptr::null_mut(), 0, 0) };
    if required == 0 {
        return Err(FilesystemFontReadError::io(
            FilesystemFontOperation::ReadContainer,
            path,
            std::io::Error::last_os_error(),
        ));
    }
    let mut buffer = vec![0u16; required as usize + 1];
    // SAFETY: `buffer` has the size reported by the first call and `handle`
    // remains valid for the duration of this call.
    let written =
        unsafe { GetFinalPathNameByHandleW(handle, buffer.as_mut_ptr(), buffer.len() as u32, 0) };
    if written == 0 || written as usize >= buffer.len() {
        return Err(FilesystemFontReadError::io(
            FilesystemFontOperation::ReadContainer,
            path,
            std::io::Error::last_os_error(),
        ));
    }
    let opened = PathBuf::from(std::ffi::OsString::from_wide(&buffer[..written as usize]));
    if !opened.starts_with(boundary) {
        return Err(alias_error(path));
    }
    Ok(())
}

/// The font reader's vocabulary for the shared symlink-refusing open.
///
/// Font roots come from host configuration rather than from an already
/// established project or package root, so an aliased root is refused here.
struct FontTraversal;

impl TraversalPolicy for FontTraversal {
    type Error = FilesystemFontReadError;

    const ROOT_INVARIANT: &'static str = "a selected font path remains beneath its root";
    const ALIASED_ROOT_IS_REFUSED: bool = true;

    fn io(&self, path: &Path, source: std::io::Error) -> Self::Error {
        FilesystemFontReadError::io(FilesystemFontOperation::ReadContainer, path, source)
    }

    fn alias(&self, path: &Path) -> Self::Error {
        alias_error(path)
    }

    fn unsupported_entry(&self, path: &Path, entry: UnsupportedEntry) -> Self::Error {
        FilesystemFontReadError::Survey(FilesystemFontSurveyError {
            issues: vec![FilesystemFontIssue::UnsupportedEntry {
                path: path.to_owned(),
                kind: entry.into(),
            }],
        })
    }
}

impl From<UnsupportedEntry> for FilesystemFontEntryKind {
    fn from(entry: UnsupportedEntry) -> Self {
        match entry {
            UnsupportedEntry::Socket => Self::Socket,
            UnsupportedEntry::Fifo => Self::Fifo,
            UnsupportedEntry::BlockDevice => Self::BlockDevice,
            UnsupportedEntry::CharacterDevice => Self::CharacterDevice,
            UnsupportedEntry::Unknown => Self::Unknown,
        }
    }
}

/// Opens one selected font container beneath `root`.
///
/// Windows exposes no open-time no-follow flag, so the opened handle is
/// additionally confirmed to resolve inside `boundary`.
fn open_without_following(
    root: &Path,
    boundary: &Path,
    path: &Path,
) -> Result<std::fs::File, FilesystemFontReadError> {
    #[cfg(not(windows))]
    let _ = boundary;

    let file = fs_traversal::open_without_following(&FontTraversal, root, path)?;
    #[cfg(windows)]
    validate_windows_boundary(&file, boundary, path)?;
    Ok(file)
}

fn alias_error(path: &Path) -> FilesystemFontReadError {
    FilesystemFontReadError::Survey(FilesystemFontSurveyError {
        issues: vec![FilesystemFontIssue::Alias {
            path: path.to_owned(),
        }],
    })
}

fn font_eligible(path: &Path) -> bool {
    path.extension()
        .and_then(|extension| extension.to_str())
        .is_some_and(crate::read_layout::is_font_container_extension)
}

fn checked_add(
    total: u64,
    value: u64,
    resource: FilesystemFontResource,
) -> Result<u64, FilesystemFontLimitError> {
    total
        .checked_add(value)
        .ok_or(FilesystemFontLimitError::AccountingOverflow { resource })
}

fn check_limit(
    resource: FilesystemFontResource,
    ceiling: u64,
    observed: u64,
) -> Result<(), FilesystemFontLimitError> {
    if observed > ceiling {
        return Err(FilesystemFontLimitError::exceeded(resource, ceiling));
    }
    Ok(())
}

fn system_font_roots() -> Vec<PathBuf> {
    let mut roots = Vec::new();

    #[cfg(target_os = "windows")]
    {
        let system_root = std::env::var_os("SYSTEMROOT")
            .map(PathBuf::from)
            .unwrap_or_else(|| PathBuf::from(r"C:\Windows"));
        roots.push(system_root.join("Fonts"));
        if let Some(home) = std::env::var_os("USERPROFILE").map(PathBuf::from) {
            roots.push(home.join(r"AppData\Local\Microsoft\Windows\Fonts"));
            roots.push(home.join(r"AppData\Roaming\Microsoft\Windows\Fonts"));
        }
        if let Some(data) = std::env::var_os("APPDATA").map(PathBuf::from) {
            roots.push(data.join("Adobe/CoreSync/plugins/livetype/r"));
            roots.push(data.join("Adobe/User Owned Fonts"));
        }
    }

    #[cfg(target_os = "macos")]
    {
        roots.extend([
            PathBuf::from("/Library/Fonts"),
            PathBuf::from("/System/Library/Fonts"),
        ]);
    }

    #[cfg(target_os = "redox")]
    roots.push(PathBuf::from("/ui/fonts"));

    #[cfg(all(unix, not(any(target_os = "macos", target_os = "android"))))]
    roots.extend(fontconfig_roots());

    roots
}

#[cfg(target_os = "macos")]
fn macos_system_font_roots_after_downloadable() -> Vec<PathBuf> {
    let mut roots = vec![PathBuf::from("/Network/Library/Fonts")];
    if let Some(home) = std::env::var_os("HOME").map(PathBuf::from) {
        roots.push(home.join("Library/Fonts"));
        let data = home.join("Library/Application Support/Adobe");
        roots.push(data.join("CoreSync/plugins/livetype/.r"));
        roots.push(data.join(".User Owned Fonts"));
    }
    roots
}

#[cfg(all(unix, not(any(target_os = "macos", target_os = "android"))))]
fn fontconfig_roots() -> Vec<PathBuf> {
    let mut config = fontconfig_parser::FontConfig::default();
    let home = std::env::var_os("HOME").map(PathBuf::from);
    if let Some(config_file) = std::env::var_os("FONTCONFIG_FILE") {
        let _ = config.merge_config(Path::new(&config_file));
    } else {
        let user_config = std::env::var_os("XDG_CONFIG_HOME")
            .map(PathBuf::from)
            .or_else(|| home.as_ref().map(|home| home.join(".config")));
        let read_global = user_config.is_none_or(|path| {
            config
                .merge_config(&path.join("fontconfig/fonts.conf"))
                .is_err()
        });
        if read_global {
            let _ = config.merge_config(Path::new("/etc/fonts/local.conf"));
        }
        let _ = config.merge_config(Path::new("/etc/fonts/fonts.conf"));
    }

    let mut roots = config
        .dirs
        .into_iter()
        .filter_map(|directory| {
            if directory.path.starts_with("~") {
                home.as_ref()
                    .map(|home| home.join(directory.path.strip_prefix("~").unwrap()))
            } else {
                Some(directory.path)
            }
        })
        .collect::<Vec<_>>();
    if roots.is_empty() {
        roots.extend([
            PathBuf::from("/usr/share/fonts"),
            PathBuf::from("/usr/local/share/fonts"),
        ]);
        if let Some(home) = home {
            roots.push(home.join(".fonts"));
            roots.push(home.join(".local/share/fonts"));
        }
    }
    roots
}

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

    #[test]
    fn accepted_container_accounting_overflow_is_typed() {
        assert_eq!(
            checked_add(u64::MAX, 1, FilesystemFontResource::AcceptedContainers),
            Err(FilesystemFontLimitError::AccountingOverflow {
                resource: FilesystemFontResource::AcceptedContainers,
            })
        );
    }

    #[cfg(unix)]
    #[test]
    fn bounded_reads_do_not_follow_an_alias_created_after_survey() {
        use std::os::unix::fs::symlink;

        let directory = tempfile::tempdir().unwrap();
        let outside = directory.path().join("outside.ttf");
        let selected = directory.path().join("selected.ttf");
        let boundary = directory.path().canonicalize().unwrap();
        std::fs::write(&outside, b"outside").unwrap();
        symlink(&outside, &selected).unwrap();

        let error = read_bounded(
            directory.path(),
            &boundary,
            &selected,
            0,
            FilesystemFontLimits::new(1, 1, 16, 16),
        )
        .unwrap_err();

        assert!(matches!(
            error,
            FilesystemFontReadError::Survey(ref survey)
                if matches!(survey.issues(), [FilesystemFontIssue::Alias { path }] if path == &selected)
        ));
    }

    #[cfg(unix)]
    #[test]
    fn bounded_reads_do_not_follow_a_root_alias_created_after_survey() {
        use std::os::unix::fs::symlink;

        let directory = tempfile::tempdir().unwrap();
        let root = directory.path().join("fonts");
        let outside = directory.path().join("outside");
        let selected = root.join("selected.ttf");
        std::fs::create_dir(&root).unwrap();
        std::fs::create_dir(&outside).unwrap();
        std::fs::write(&selected, b"surveyed").unwrap();
        std::fs::write(outside.join("selected.ttf"), b"outside").unwrap();
        let boundary = root.canonicalize().unwrap();
        std::fs::remove_dir_all(&root).unwrap();
        symlink(&outside, &root).unwrap();

        let error = read_bounded(
            &root,
            &boundary,
            &selected,
            0,
            FilesystemFontLimits::new(1, 1, 16, 16),
        )
        .unwrap_err();

        assert!(matches!(
            error,
            FilesystemFontReadError::Survey(ref survey)
                if matches!(survey.issues(), [FilesystemFontIssue::Alias { path }] if path == &root)
        ));
    }
}