1
//! File system operations module for C API
2
//!
3
//! Provides C-compatible wrappers around Rust's std::fs API.
4
//! This allows C code to use Rust's file operations without importing stdio.h.
5

            
6
use alloc::{string::String, vec::Vec};
7
use core::fmt;
8
#[cfg(feature = "std")]
9
use std::path::Path;
10

            
11
use azul_css::{
12
    impl_option, impl_option_inner, impl_result, impl_result_inner, impl_vec, impl_vec_clone,
13
    impl_vec_debug, impl_vec_mut, impl_vec_partialeq, AzString, EmptyStruct, U8Vec,
14
};
15

            
16
#[cfg(feature = "std")]
17
278
fn path_to_azstring(p: impl AsRef<Path>) -> AzString {
18
278
    AzString::from(p.as_ref().to_string_lossy().into_owned())
19
278
}
20

            
21
// ============================================================================
22
// Error types
23
// ============================================================================
24

            
25
/// Error when performing file operations
26
#[derive(Debug, Clone, PartialEq, Eq)]
27
#[repr(C)]
28
pub struct FileError {
29
    /// Error message
30
    pub message: AzString,
31
    /// Error kind
32
    pub kind: FileErrorKind,
33
}
34

            
35
/// Kind of file error
36
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37
#[repr(C)]
38
pub enum FileErrorKind {
39
    /// File or directory not found
40
    NotFound,
41
    /// Permission denied
42
    PermissionDenied,
43
    /// File already exists
44
    AlreadyExists,
45
    /// Invalid path
46
    InvalidPath,
47
    /// I/O error
48
    IoError,
49
    /// Directory not empty
50
    DirectoryNotEmpty,
51
    /// Is a directory (expected file)
52
    IsDirectory,
53
    /// Is a file (expected directory)
54
    IsFile,
55
    /// Other error
56
    Other,
57
    /// The operation needs a user gesture and was requested outside one
58
    /// (browser pickers and permission prompts only open from a transient
59
    /// activation; a request issued from a timer gets this kind).
60
    NeedsUserGesture,
61
    /// No implementation exists on this engine / target. Distinct from
62
    /// `PermissionDenied`, which is a decision, not an absence.
63
    Unsupported,
64
}
65

            
66
impl FileError {
67
5
    pub fn new(kind: FileErrorKind, message: impl Into<String>) -> Self {
68
5
        Self {
69
5
            message: AzString::from(message.into()),
70
5
            kind,
71
5
        }
72
5
    }
73

            
74
    #[cfg(feature = "std")]
75
    // taken by value so it can be used directly as `.map_err(FileError::from_io_error)`
76
    // (map_err yields an owned io::Error); a &-param would break every such call site.
77
    #[allow(clippy::needless_pass_by_value)]
78
    #[must_use]
79
152
    pub fn from_io_error(e: std::io::Error) -> Self {
80
        use std::io::ErrorKind;
81

            
82
152
        let kind = match e.kind() {
83
112
            ErrorKind::NotFound => FileErrorKind::NotFound,
84
1
            ErrorKind::PermissionDenied => FileErrorKind::PermissionDenied,
85
2
            ErrorKind::AlreadyExists => FileErrorKind::AlreadyExists,
86
3
            ErrorKind::IsADirectory => FileErrorKind::IsDirectory,
87
2
            ErrorKind::DirectoryNotEmpty => FileErrorKind::DirectoryNotEmpty,
88
32
            _ => FileErrorKind::IoError,
89
        };
90

            
91
152
        Self {
92
152
            message: AzString::from(e.to_string()),
93
152
            kind,
94
152
        }
95
152
    }
96
}
97

            
98
impl fmt::Display for FileError {
99
3
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
100
3
        write!(f, "{}", self.message.as_str())
101
3
    }
102
}
103

            
104
#[cfg(feature = "std")]
105
impl std::error::Error for FileError {}
106

            
107
// FFI-safe Result types for file operations
108
impl_result!(
109
    EmptyStruct,
110
    FileError,
111
    ResultEmptyStructFileError,
112
    copy = false,
113
    [Debug, Clone, PartialEq, Eq]
114
);
115

            
116
impl_result!(
117
    U8Vec,
118
    FileError,
119
    ResultU8VecFileError,
120
    copy = false,
121
    [Debug, Clone, PartialEq, Eq]
122
);
123

            
124
impl_result!(
125
    AzString,
126
    FileError,
127
    ResultStringFileError,
128
    copy = false,
129
    [Debug, Clone, PartialEq, Eq]
130
);
131

            
132
impl_result!(
133
    u64,
134
    FileError,
135
    Resultu64FileError,
136
    copy = false,
137
    [Debug, Clone, PartialEq, Eq]
138
);
139

            
140
// Forward declarations for result types that need later-defined types
141
// (FilePath, FileMetadata, DirEntryVec are defined below)
142

            
143
// ============================================================================
144
// File metadata
145
// ============================================================================
146

            
147
/// File type (file, directory, symlink)
148
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
149
#[repr(C)]
150
pub enum FileType {
151
    /// Regular file
152
    File,
153
    /// Directory
154
    Directory,
155
    /// Symbolic link
156
    Symlink,
157
    /// Other (device, socket, etc.)
158
    Other,
159
}
160

            
161
/// Metadata about a file
162
#[derive(Copy, Debug, Clone, PartialEq, Eq)]
163
#[repr(C)]
164
pub struct FileMetadata {
165
    /// File size in bytes
166
    pub size: u64,
167
    /// File type
168
    pub file_type: FileType,
169
    /// Is read-only
170
    pub is_readonly: bool,
171
    /// Last modification time (Unix timestamp in seconds)
172
    pub modified_secs: u64,
173
    /// Creation time (Unix timestamp in seconds, 0 if unavailable)
174
    pub created_secs: u64,
175
}
176

            
177
/// A directory entry
178
#[derive(Debug, Clone)]
179
#[repr(C)]
180
pub struct DirEntry {
181
    /// File name (not full path)
182
    pub name: AzString,
183
    /// Full path
184
    pub path: AzString,
185
    /// File type
186
    pub file_type: FileType,
187
}
188

            
189
/// Vec of DirEntry
190
impl_option!(DirEntry, OptionDirEntry, copy = false, [Debug, Clone]);
191
impl_vec!(
192
    DirEntry,
193
    DirEntryVec,
194
    DirEntryVecDestructor,
195
    DirEntryVecDestructorType,
196
    DirEntryVecSlice,
197
    OptionDirEntry
198
);
199
impl_vec_clone!(DirEntry, DirEntryVec, DirEntryVecDestructor);
200
impl_vec_debug!(DirEntry, DirEntryVec);
201
impl_vec_mut!(DirEntry, DirEntryVec);
202

            
203
// Additional FFI-safe Result types for complex types
204
impl_result!(
205
    FileMetadata,
206
    FileError,
207
    ResultFileMetadataFileError,
208
    copy = false,
209
    [Debug, Clone, PartialEq, Eq]
210
);
211

            
212
impl_result!(
213
    DirEntryVec,
214
    FileError,
215
    ResultDirEntryVecFileError,
216
    copy = false,
217
    clone = false,
218
    [Debug, Clone]
219
);
220

            
221
// ============================================================================
222
// File operations
223
// ============================================================================
224

            
225
/// Read a file to bytes
226
#[cfg(feature = "std")]
227
/// # Errors
228
///
229
/// Returns a `FileError` if the filesystem operation fails (e.g. path not found, permission denied,
230
/// or an I/O error).
231
28
pub fn file_read(path: &str) -> Result<U8Vec, FileError> {
232
28
    let data = std::fs::read(path).map_err(FileError::from_io_error)?;
233
7
    Ok(U8Vec::from(data))
234
28
}
235

            
236
/// Read a file to string (UTF-8)
237
#[cfg(feature = "std")]
238
/// # Errors
239
///
240
/// Returns a `FileError` if the filesystem operation fails (e.g. path not found, permission denied,
241
/// or an I/O error).
242
25
pub fn file_read_string(path: &str) -> Result<AzString, FileError> {
243
25
    let data = std::fs::read_to_string(path).map_err(FileError::from_io_error)?;
244
6
    Ok(AzString::from(data))
245
25
}
246

            
247
/// Write bytes to a file (creates or overwrites)
248
#[cfg(feature = "std")]
249
/// # Errors
250
///
251
/// Returns a `FileError` if the filesystem operation fails (e.g. path not found, permission denied,
252
/// or an I/O error).
253
8
pub fn file_write(path: &str, data: &[u8]) -> Result<EmptyStruct, FileError> {
254
8
    std::fs::write(path, data)
255
8
        .map(|()| EmptyStruct::default())
256
8
        .map_err(FileError::from_io_error)
257
8
}
258

            
259
/// Write string to a file (creates or overwrites)
260
#[cfg(feature = "std")]
261
/// # Errors
262
///
263
/// Returns a `FileError` if the filesystem operation fails (e.g. path not found, permission denied,
264
/// or an I/O error).
265
14
pub fn file_write_string(path: &str, data: &str) -> Result<EmptyStruct, FileError> {
266
14
    std::fs::write(path, data.as_bytes())
267
14
        .map(|()| EmptyStruct::default())
268
14
        .map_err(FileError::from_io_error)
269
14
}
270

            
271
/// Append bytes to a file
272
#[cfg(feature = "std")]
273
/// # Errors
274
///
275
/// Returns a `FileError` if the filesystem operation fails (e.g. path not found, permission denied,
276
/// or an I/O error).
277
3
pub fn file_append(path: &str, data: &[u8]) -> Result<EmptyStruct, FileError> {
278
    use std::{fs::OpenOptions, io::Write};
279

            
280
3
    let mut file = OpenOptions::new()
281
3
        .create(true)
282
3
        .append(true)
283
3
        .open(path)
284
3
        .map_err(FileError::from_io_error)?;
285

            
286
3
    file.write_all(data)
287
3
        .map(|()| EmptyStruct::default())
288
3
        .map_err(FileError::from_io_error)
289
3
}
290

            
291
/// Copy a file
292
#[cfg(feature = "std")]
293
/// # Errors
294
///
295
/// Returns a `FileError` if the filesystem operation fails (e.g. path not found, permission denied,
296
/// or an I/O error).
297
5
pub fn file_copy(from: &str, to: &str) -> Result<u64, FileError> {
298
5
    std::fs::copy(from, to).map_err(FileError::from_io_error)
299
5
}
300

            
301
/// Rename/move a file
302
#[cfg(feature = "std")]
303
/// # Errors
304
///
305
/// Returns a `FileError` if the filesystem operation fails (e.g. path not found, permission denied,
306
/// or an I/O error).
307
4
pub fn file_rename(from: &str, to: &str) -> Result<EmptyStruct, FileError> {
308
4
    std::fs::rename(from, to)
309
4
        .map(|()| EmptyStruct::default())
310
4
        .map_err(FileError::from_io_error)
311
4
}
312

            
313
/// Delete a file
314
#[cfg(feature = "std")]
315
/// # Errors
316
///
317
/// Returns a `FileError` if the filesystem operation fails (e.g. path not found, permission denied,
318
/// or an I/O error).
319
6
pub fn file_delete(path: &str) -> Result<EmptyStruct, FileError> {
320
6
    std::fs::remove_file(path)
321
6
        .map(|()| EmptyStruct::default())
322
6
        .map_err(FileError::from_io_error)
323
6
}
324

            
325
/// Check if a file or directory exists
326
#[cfg(feature = "std")]
327
#[must_use]
328
57
pub fn path_exists(path: &str) -> bool {
329
57
    Path::new(path).exists()
330
57
}
331

            
332
/// Check if path is a file
333
#[cfg(feature = "std")]
334
#[must_use]
335
49
pub fn path_is_file(path: &str) -> bool {
336
49
    Path::new(path).is_file()
337
49
}
338

            
339
/// Check if path is a directory
340
#[cfg(feature = "std")]
341
#[must_use]
342
50
pub fn path_is_dir(path: &str) -> bool {
343
50
    Path::new(path).is_dir()
344
50
}
345

            
346
/// Get file metadata
347
#[cfg(feature = "std")]
348
/// # Errors
349
///
350
/// Returns a `FileError` if the filesystem operation fails (e.g. path not found, permission denied,
351
/// or an I/O error).
352
26
pub fn file_metadata(path: &str) -> Result<FileMetadata, FileError> {
353
26
    let meta = std::fs::symlink_metadata(path).map_err(FileError::from_io_error)?;
354

            
355
8
    let file_type = if meta.is_file() {
356
5
        FileType::File
357
3
    } else if meta.is_dir() {
358
1
        FileType::Directory
359
2
    } else if meta.is_symlink() {
360
2
        FileType::Symlink
361
    } else {
362
        FileType::Other
363
    };
364

            
365
8
    let modified_secs = meta
366
8
        .modified()
367
8
        .ok()
368
8
        .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
369
8
        .map_or(0, |d| d.as_secs());
370

            
371
8
    let created_secs = meta
372
8
        .created()
373
8
        .ok()
374
8
        .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
375
8
        .map_or(0, |d| d.as_secs());
376

            
377
8
    Ok(FileMetadata {
378
8
        size: meta.len(),
379
8
        file_type,
380
8
        is_readonly: meta.permissions().readonly(),
381
8
        modified_secs,
382
8
        created_secs,
383
8
    })
384
26
}
385

            
386
// ----------------------------------------------------------------------------
387
// no_std stubs: keep the file API surface present without std::fs.
388
// ----------------------------------------------------------------------------
389

            
390
/// Error returned by file stubs when the `std` feature is disabled.
391
#[cfg(not(feature = "std"))]
392
fn no_std_file_error() -> FileError {
393
    FileError::new(FileErrorKind::Other, "file IO requires the `std` feature")
394
}
395

            
396
/// Stub: `std` feature disabled.
397
#[cfg(not(feature = "std"))]
398
pub fn file_read(_path: &str) -> Result<U8Vec, FileError> {
399
    Err(no_std_file_error())
400
}
401

            
402
/// Stub: `std` feature disabled.
403
#[cfg(not(feature = "std"))]
404
pub fn file_read_string(_path: &str) -> Result<AzString, FileError> {
405
    Err(no_std_file_error())
406
}
407

            
408
/// Stub: `std` feature disabled.
409
#[cfg(not(feature = "std"))]
410
pub fn file_write(_path: &str, _data: &[u8]) -> Result<EmptyStruct, FileError> {
411
    Err(no_std_file_error())
412
}
413

            
414
/// Stub: `std` feature disabled.
415
#[cfg(not(feature = "std"))]
416
pub fn file_write_string(_path: &str, _data: &str) -> Result<EmptyStruct, FileError> {
417
    Err(no_std_file_error())
418
}
419

            
420
/// Stub: `std` feature disabled.
421
#[cfg(not(feature = "std"))]
422
pub fn file_append(_path: &str, _data: &[u8]) -> Result<EmptyStruct, FileError> {
423
    Err(no_std_file_error())
424
}
425

            
426
/// Stub: `std` feature disabled.
427
#[cfg(not(feature = "std"))]
428
pub fn file_copy(_from: &str, _to: &str) -> Result<u64, FileError> {
429
    Err(no_std_file_error())
430
}
431

            
432
/// Stub: `std` feature disabled.
433
#[cfg(not(feature = "std"))]
434
pub fn file_rename(_from: &str, _to: &str) -> Result<EmptyStruct, FileError> {
435
    Err(no_std_file_error())
436
}
437

            
438
/// Stub: `std` feature disabled.
439
#[cfg(not(feature = "std"))]
440
pub fn file_delete(_path: &str) -> Result<EmptyStruct, FileError> {
441
    Err(no_std_file_error())
442
}
443

            
444
/// Stub: `std` feature disabled.
445
#[cfg(not(feature = "std"))]
446
pub fn path_exists(_path: &str) -> bool {
447
    false
448
}
449

            
450
/// Stub: `std` feature disabled.
451
#[cfg(not(feature = "std"))]
452
pub fn path_is_file(_path: &str) -> bool {
453
    false
454
}
455

            
456
/// Stub: `std` feature disabled.
457
#[cfg(not(feature = "std"))]
458
pub fn path_is_dir(_path: &str) -> bool {
459
    false
460
}
461

            
462
/// Stub: `std` feature disabled.
463
#[cfg(not(feature = "std"))]
464
pub fn file_metadata(_path: &str) -> Result<FileMetadata, FileError> {
465
    Err(no_std_file_error())
466
}
467

            
468
// ============================================================================
469
// Directory operations
470
// ============================================================================
471

            
472
/// Create a directory
473
#[cfg(feature = "std")]
474
/// # Errors
475
///
476
/// Returns a `FileError` if the filesystem operation fails (e.g. path not found, permission denied,
477
/// or an I/O error).
478
7
pub fn dir_create(path: &str) -> Result<EmptyStruct, FileError> {
479
7
    std::fs::create_dir(path)
480
7
        .map(|()| EmptyStruct::default())
481
7
        .map_err(FileError::from_io_error)
482
7
}
483

            
484
/// Create a directory and all parent directories
485
#[cfg(feature = "std")]
486
/// # Errors
487
///
488
/// Returns a `FileError` if the filesystem operation fails (e.g. path not found, permission denied,
489
/// or an I/O error).
490
30
pub fn dir_create_all(path: &str) -> Result<EmptyStruct, FileError> {
491
30
    std::fs::create_dir_all(path)
492
30
        .map(|()| EmptyStruct::default())
493
30
        .map_err(FileError::from_io_error)
494
30
}
495

            
496
/// Delete an empty directory
497
#[cfg(feature = "std")]
498
/// # Errors
499
///
500
/// Returns a `FileError` if the filesystem operation fails (e.g. path not found, permission denied,
501
/// or an I/O error).
502
4
pub fn dir_delete(path: &str) -> Result<EmptyStruct, FileError> {
503
4
    std::fs::remove_dir(path)
504
4
        .map(|()| EmptyStruct::default())
505
4
        .map_err(FileError::from_io_error)
506
4
}
507

            
508
/// Delete a directory and all its contents
509
#[cfg(feature = "std")]
510
/// # Errors
511
///
512
/// Returns a `FileError` if the filesystem operation fails (e.g. path not found, permission denied,
513
/// or an I/O error).
514
52
pub fn dir_delete_all(path: &str) -> Result<EmptyStruct, FileError> {
515
52
    std::fs::remove_dir_all(path)
516
52
        .map(|()| EmptyStruct::default())
517
52
        .map_err(FileError::from_io_error)
518
52
}
519

            
520
/// List directory contents
521
#[cfg(feature = "std")]
522
/// # Errors
523
///
524
/// Returns a `FileError` if the filesystem operation fails (e.g. path not found, permission denied,
525
/// or an I/O error).
526
22
pub fn dir_list(path: &str) -> Result<DirEntryVec, FileError> {
527
22
    let entries = std::fs::read_dir(path).map_err(FileError::from_io_error)?;
528

            
529
4
    let mut result = Vec::new();
530

            
531
10
    for entry in entries {
532
6
        let entry = entry.map_err(FileError::from_io_error)?;
533
6
        let file_type = entry
534
6
            .file_type()
535
6
            .map(|ft| {
536
6
                if ft.is_file() {
537
4
                    FileType::File
538
2
                } else if ft.is_dir() {
539
1
                    FileType::Directory
540
1
                } else if ft.is_symlink() {
541
1
                    FileType::Symlink
542
                } else {
543
                    FileType::Other
544
                }
545
6
            })
546
6
            .unwrap_or(FileType::Other);
547

            
548
6
        result.push(DirEntry {
549
6
            name: path_to_azstring(entry.file_name()),
550
6
            path: path_to_azstring(entry.path()),
551
6
            file_type,
552
6
        });
553
    }
554

            
555
4
    Ok(DirEntryVec::from_vec(result))
556
22
}
557

            
558
/// Stub: `std` feature disabled.
559
#[cfg(not(feature = "std"))]
560
pub fn dir_create(_path: &str) -> Result<EmptyStruct, FileError> {
561
    Err(no_std_file_error())
562
}
563

            
564
/// Stub: `std` feature disabled.
565
#[cfg(not(feature = "std"))]
566
pub fn dir_create_all(_path: &str) -> Result<EmptyStruct, FileError> {
567
    Err(no_std_file_error())
568
}
569

            
570
/// Stub: `std` feature disabled.
571
#[cfg(not(feature = "std"))]
572
pub fn dir_delete(_path: &str) -> Result<EmptyStruct, FileError> {
573
    Err(no_std_file_error())
574
}
575

            
576
/// Stub: `std` feature disabled.
577
#[cfg(not(feature = "std"))]
578
pub fn dir_delete_all(_path: &str) -> Result<EmptyStruct, FileError> {
579
    Err(no_std_file_error())
580
}
581

            
582
/// Stub: `std` feature disabled.
583
#[cfg(not(feature = "std"))]
584
pub fn dir_list(_path: &str) -> Result<DirEntryVec, FileError> {
585
    Err(no_std_file_error())
586
}
587

            
588
// ============================================================================
589
// Path operations
590
// ============================================================================
591

            
592
/// Join two paths
593
#[cfg(feature = "std")]
594
#[must_use]
595
170
pub fn path_join(base: &str, path: &str) -> AzString {
596
170
    let joined = Path::new(base).join(path);
597
170
    path_to_azstring(joined)
598
170
}
599

            
600
/// Get the parent directory of a path
601
#[cfg(feature = "std")]
602
28
pub fn path_parent(path: &str) -> Option<AzString> {
603
28
    Path::new(path).parent().map(path_to_azstring)
604
28
}
605

            
606
/// Get the file name from a path
607
#[cfg(feature = "std")]
608
27
pub fn path_file_name(path: &str) -> Option<AzString> {
609
27
    Path::new(path).file_name().map(path_to_azstring)
610
27
}
611

            
612
/// Get the file extension from a path
613
#[cfg(feature = "std")]
614
27
pub fn path_extension(path: &str) -> Option<AzString> {
615
27
    Path::new(path).extension().map(path_to_azstring)
616
27
}
617

            
618
/// Canonicalize a path (resolve symlinks, make absolute)
619
#[cfg(feature = "std")]
620
/// # Errors
621
///
622
/// Returns a `FileError` if the filesystem operation fails (e.g. path not found, permission denied,
623
/// or an I/O error).
624
26
pub fn path_canonicalize(path: &str) -> Result<AzString, FileError> {
625
26
    let canonical = std::fs::canonicalize(path).map_err(FileError::from_io_error)?;
626
6
    Ok(path_to_azstring(canonical))
627
26
}
628

            
629
// ============================================================================
630
// Temporary files
631
// ============================================================================
632

            
633
/// Get the system temporary directory
634
#[cfg(feature = "std")]
635
#[must_use]
636
28
pub fn temp_dir() -> AzString {
637
28
    path_to_azstring(std::env::temp_dir())
638
28
}
639

            
640
/// Stub: `std` feature disabled.
641
#[cfg(not(feature = "std"))]
642
pub fn path_join(_base: &str, _path: &str) -> AzString {
643
    AzString::from_const_str("")
644
}
645

            
646
/// Stub: `std` feature disabled.
647
#[cfg(not(feature = "std"))]
648
pub fn path_parent(_path: &str) -> Option<AzString> {
649
    None
650
}
651

            
652
/// Stub: `std` feature disabled.
653
#[cfg(not(feature = "std"))]
654
pub fn path_file_name(_path: &str) -> Option<AzString> {
655
    None
656
}
657

            
658
/// Stub: `std` feature disabled.
659
#[cfg(not(feature = "std"))]
660
pub fn path_extension(_path: &str) -> Option<AzString> {
661
    None
662
}
663

            
664
/// Stub: `std` feature disabled.
665
#[cfg(not(feature = "std"))]
666
pub fn path_canonicalize(_path: &str) -> Result<AzString, FileError> {
667
    Err(no_std_file_error())
668
}
669

            
670
/// Stub: `std` feature disabled.
671
#[cfg(not(feature = "std"))]
672
pub fn temp_dir() -> AzString {
673
    AzString::from_const_str("")
674
}
675

            
676
// ============================================================================
677
// OOP-style Path wrapper
678
// ============================================================================
679

            
680
/// FFI-safe path type with OOP-style methods
681
///
682
/// This wraps a string path and provides method-based access to file operations.
683
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
684
#[repr(C)]
685
pub struct FilePath {
686
    pub inner: AzString,
687
}
688

            
689
// Result type for FilePath operations (must be after FilePath definition)
690
impl_result!(
691
    FilePath,
692
    FileError,
693
    ResultFilePathFileError,
694
    copy = false,
695
    [Debug, Clone, PartialEq, Eq]
696
);
697

            
698
// Option type for FilePath
699
impl_option!(
700
    FilePath,
701
    OptionFilePath,
702
    copy = false,
703
    [Clone, Debug, PartialEq, Eq]
704
);
705

            
706
impl_vec!(
707
    FilePath,
708
    FilePathVec,
709
    FilePathVecDestructor,
710
    FilePathVecDestructorType,
711
    FilePathVecSlice,
712
    OptionFilePath
713
);
714
impl_vec_clone!(FilePath, FilePathVec, FilePathVecDestructor);
715
impl_vec_debug!(FilePath, FilePathVec);
716
impl_vec_partialeq!(FilePath, FilePathVec);
717
impl_vec_mut!(FilePath, FilePathVec);
718

            
719
// ============================================================================
720
// Resumable read results
721
// ============================================================================
722
//
723
// `FilePath::read_bytes` / `read_string` / `read_dir` are request functions
724
// (see `crate::request`): they return a `RequestId` and resume the caller's
725
// `ResumeCallback` with one of these structs, type-erased into a `RefAny`.
726
// Each struct has exactly one static `downcast(result)` accessor, which is
727
// the binding-portable way to get the typed value back out.
728

            
729
/// Result of [`FilePath::read_bytes`].
730
#[derive(Debug, Clone)]
731
#[repr(C)]
732
pub struct FileReadBytesResult {
733
    pub result: ResultU8VecFileError,
734
}
735

            
736
impl_option!(
737
    FileReadBytesResult,
738
    OptionFileReadBytesResult,
739
    copy = false,
740
    [Debug, Clone]
741
);
742

            
743
impl FileReadBytesResult {
744
    /// Downcast the `result` `RefAny` delivered to a `ResumeCallback`.
745
    #[must_use]
746
    pub fn downcast(mut result: azul_core::refany::RefAny) -> OptionFileReadBytesResult {
747
        result.downcast_ref::<Self>().map(|r| r.clone()).into()
748
    }
749
}
750

            
751
/// Result of [`FilePath::read_string`].
752
#[derive(Debug, Clone)]
753
#[repr(C)]
754
pub struct FileReadStringResult {
755
    pub result: ResultStringFileError,
756
}
757

            
758
impl_option!(
759
    FileReadStringResult,
760
    OptionFileReadStringResult,
761
    copy = false,
762
    [Debug, Clone]
763
);
764

            
765
impl FileReadStringResult {
766
    /// Downcast the `result` `RefAny` delivered to a `ResumeCallback`.
767
    #[must_use]
768
    pub fn downcast(mut result: azul_core::refany::RefAny) -> OptionFileReadStringResult {
769
        result.downcast_ref::<Self>().map(|r| r.clone()).into()
770
    }
771
}
772

            
773
/// Result of [`FilePath::read_dir`].
774
#[derive(Debug, Clone)]
775
#[repr(C)]
776
pub struct FileDirListResult {
777
    pub result: ResultDirEntryVecFileError,
778
}
779

            
780
impl_option!(
781
    FileDirListResult,
782
    OptionFileDirListResult,
783
    copy = false,
784
    [Debug, Clone]
785
);
786

            
787
impl FileDirListResult {
788
    /// Downcast the `result` `RefAny` delivered to a `ResumeCallback`.
789
    #[must_use]
790
    pub fn downcast(mut result: azul_core::refany::RefAny) -> OptionFileDirListResult {
791
        result.downcast_ref::<Self>().map(|r| r.clone()).into()
792
    }
793
}
794

            
795
impl Default for FilePath {
796
5
    fn default() -> Self {
797
5
        Self {
798
5
            inner: AzString::from_const_str(""),
799
5
        }
800
5
    }
801
}
802

            
803
impl FilePath {
804
    /// Creates a new path from a string
805
    #[must_use]
806
7
    pub const fn new(path: AzString) -> Self {
807
7
        Self { inner: path }
808
7
    }
809

            
810
    /// Creates an empty path
811
    #[must_use]
812
4
    pub fn empty() -> Self {
813
4
        Self::default()
814
4
    }
815

            
816
    /// Creates a path from a string slice
817
    #[must_use]
818
46
    pub fn from_str(s: &str) -> Self {
819
46
        Self {
820
46
            inner: AzString::from(String::from(s)),
821
46
        }
822
46
    }
823

            
824
    /// Returns the system temporary directory
825
    #[cfg(feature = "std")]
826
    #[must_use]
827
1
    pub fn get_temp_dir() -> Self {
828
1
        Self { inner: temp_dir() }
829
1
    }
830

            
831
    /// Returns the current working directory
832
    #[cfg(feature = "std")]
833
    /// # Errors
834
    ///
835
    /// Returns a `FileError` if the filesystem operation fails (e.g. path not found, permission
836
    /// denied, or an I/O error).
837
1
    pub fn get_current_dir() -> Result<Self, FileError> {
838
1
        match std::env::current_dir() {
839
1
            Ok(p) => Ok(Self {
840
1
                inner: path_to_azstring(p),
841
1
            }),
842
            Err(e) => Err(FileError::from_io_error(e)),
843
        }
844
1
    }
845

            
846
    /// Returns the user's home directory (e.g., /home/username on Linux, C:\Users\username on
847
    /// Windows)
848
    #[cfg(all(feature = "std", feature = "extra"))]
849
    #[must_use]
850
1
    pub fn get_home_dir() -> Option<Self> {
851
1
        dirs::home_dir().map(|p| Self {
852
1
            inner: path_to_azstring(p),
853
1
        })
854
1
    }
855

            
856
    /// Returns the user's cache directory (e.g., ~/.cache on Linux, ~/Library/Caches on macOS)
857
    #[cfg(all(feature = "std", feature = "extra"))]
858
    #[must_use]
859
1
    pub fn get_cache_dir() -> Option<Self> {
860
1
        dirs::cache_dir().map(|p| Self {
861
1
            inner: path_to_azstring(p),
862
1
        })
863
1
    }
864

            
865
    /// Returns the user's config directory (e.g., ~/.config on Linux, ~/Library/Application Support
866
    /// on macOS)
867
    #[cfg(all(feature = "std", feature = "extra"))]
868
    #[must_use]
869
1
    pub fn get_config_dir() -> Option<Self> {
870
1
        dirs::config_dir().map(|p| Self {
871
1
            inner: path_to_azstring(p),
872
1
        })
873
1
    }
874

            
875
    /// Returns the user's local config directory (e.g., ~/.config on Linux, ~/Library/Application
876
    /// Support on macOS)
877
    #[cfg(all(feature = "std", feature = "extra"))]
878
    #[must_use]
879
1
    pub fn get_config_local_dir() -> Option<Self> {
880
1
        dirs::config_local_dir().map(|p| Self {
881
1
            inner: path_to_azstring(p),
882
1
        })
883
1
    }
884

            
885
    /// Returns the user's data directory (e.g., ~/.local/share on Linux, ~/Library/Application
886
    /// Support on macOS)
887
    #[cfg(all(feature = "std", feature = "extra"))]
888
    #[must_use]
889
1
    pub fn get_data_dir() -> Option<Self> {
890
1
        dirs::data_dir().map(|p| Self {
891
1
            inner: path_to_azstring(p),
892
1
        })
893
1
    }
894

            
895
    /// Returns the user's local data directory (e.g., ~/.local/share on Linux,
896
    /// ~/Library/Application Support on macOS)
897
    #[cfg(all(feature = "std", feature = "extra"))]
898
    #[must_use]
899
1
    pub fn get_data_local_dir() -> Option<Self> {
900
1
        dirs::data_local_dir().map(|p| Self {
901
1
            inner: path_to_azstring(p),
902
1
        })
903
1
    }
904

            
905
    /// Returns the user's desktop directory (e.g., ~/Desktop)
906
    #[cfg(all(feature = "std", feature = "extra"))]
907
    #[must_use]
908
1
    pub fn get_desktop_dir() -> Option<Self> {
909
1
        dirs::desktop_dir().map(|p| Self {
910
            inner: path_to_azstring(p),
911
        })
912
1
    }
913

            
914
    /// Returns the user's documents directory (e.g., ~/Documents)
915
    #[cfg(all(feature = "std", feature = "extra"))]
916
    #[must_use]
917
1
    pub fn get_document_dir() -> Option<Self> {
918
1
        dirs::document_dir().map(|p| Self {
919
            inner: path_to_azstring(p),
920
        })
921
1
    }
922

            
923
    /// Returns the user's downloads directory (e.g., ~/Downloads)
924
    #[cfg(all(feature = "std", feature = "extra"))]
925
    #[must_use]
926
1
    pub fn get_download_dir() -> Option<Self> {
927
1
        dirs::download_dir().map(|p| Self {
928
            inner: path_to_azstring(p),
929
        })
930
1
    }
931

            
932
    /// Returns the user's executable directory (e.g., ~/.local/bin on Linux)
933
    #[cfg(all(feature = "std", feature = "extra"))]
934
    #[must_use]
935
1
    pub fn get_executable_dir() -> Option<Self> {
936
1
        dirs::executable_dir().map(|p| Self {
937
1
            inner: path_to_azstring(p),
938
1
        })
939
1
    }
940

            
941
    /// Returns the user's font directory (e.g., ~/.local/share/fonts on Linux, ~/Library/Fonts on
942
    /// macOS)
943
    #[cfg(all(feature = "std", feature = "extra"))]
944
    #[must_use]
945
1
    pub fn get_font_dir() -> Option<Self> {
946
1
        dirs::font_dir().map(|p| Self {
947
1
            inner: path_to_azstring(p),
948
1
        })
949
1
    }
950

            
951
    /// Returns the user's pictures directory (e.g., ~/Pictures)
952
    #[cfg(all(feature = "std", feature = "extra"))]
953
    #[must_use]
954
1
    pub fn get_picture_dir() -> Option<Self> {
955
1
        dirs::picture_dir().map(|p| Self {
956
            inner: path_to_azstring(p),
957
        })
958
1
    }
959

            
960
    /// Returns the user's preference directory (e.g., ~/.config on Linux, ~/Library/Preferences on
961
    /// macOS)
962
    #[cfg(all(feature = "std", feature = "extra"))]
963
    #[must_use]
964
1
    pub fn get_preference_dir() -> Option<Self> {
965
1
        dirs::preference_dir().map(|p| Self {
966
1
            inner: path_to_azstring(p),
967
1
        })
968
1
    }
969

            
970
    /// Returns the user's public directory (e.g., ~/Public)
971
    #[cfg(all(feature = "std", feature = "extra"))]
972
    #[must_use]
973
1
    pub fn get_public_dir() -> Option<Self> {
974
1
        dirs::public_dir().map(|p| Self {
975
            inner: path_to_azstring(p),
976
        })
977
1
    }
978

            
979
    /// Returns the user's runtime directory (e.g., /run/user/1000 on Linux)
980
    #[cfg(all(feature = "std", feature = "extra"))]
981
    #[must_use]
982
1
    pub fn get_runtime_dir() -> Option<Self> {
983
1
        dirs::runtime_dir().map(|p| Self {
984
1
            inner: path_to_azstring(p),
985
1
        })
986
1
    }
987

            
988
    /// Returns the user's state directory (e.g., ~/.local/state on Linux)
989
    #[cfg(all(feature = "std", feature = "extra"))]
990
    #[must_use]
991
1
    pub fn get_state_dir() -> Option<Self> {
992
1
        dirs::state_dir().map(|p| Self {
993
1
            inner: path_to_azstring(p),
994
1
        })
995
1
    }
996

            
997
    /// Returns the user's audio directory (e.g., ~/Music)
998
    #[cfg(all(feature = "std", feature = "extra"))]
999
    #[must_use]
1
    pub fn get_audio_dir() -> Option<Self> {
1
        dirs::audio_dir().map(|p| Self {
            inner: path_to_azstring(p),
        })
1
    }
    /// Returns the user's video directory (e.g., ~/Videos)
    #[cfg(all(feature = "std", feature = "extra"))]
    #[must_use]
1
    pub fn get_video_dir() -> Option<Self> {
1
        dirs::video_dir().map(|p| Self {
            inner: path_to_azstring(p),
        })
1
    }
    /// Returns the user's templates directory
    #[cfg(all(feature = "std", feature = "extra"))]
    #[must_use]
1
    pub fn get_template_dir() -> Option<Self> {
1
        dirs::template_dir().map(|p| Self {
            inner: path_to_azstring(p),
        })
1
    }
    /// Joins this path with another path component
    #[cfg(feature = "std")]
    #[must_use]
15
    pub fn join(&self, other: &Self) -> Self {
15
        Self {
15
            inner: path_join(self.inner.as_str(), other.inner.as_str()),
15
        }
15
    }
    /// Joins this path with a string component
    #[cfg(feature = "std")]
    #[must_use]
10
    pub fn join_str(&self, component: &AzString) -> Self {
10
        Self {
10
            inner: path_join(self.inner.as_str(), component.as_str()),
10
        }
10
    }
    /// Returns the parent directory of this path
    #[cfg(feature = "std")]
    #[must_use]
11
    pub fn parent(&self) -> Option<Self> {
11
        path_parent(self.inner.as_str()).map(|p| Self { inner: p })
11
    }
    /// Returns the file name component of this path
    #[cfg(feature = "std")]
    #[must_use]
11
    pub fn file_name(&self) -> Option<AzString> {
11
        path_file_name(self.inner.as_str())
11
    }
    /// Returns the file extension of this path
    #[cfg(feature = "std")]
    #[must_use]
11
    pub fn extension(&self) -> Option<AzString> {
11
        path_extension(self.inner.as_str())
11
    }
    /// Checks if the path exists on the filesystem
    #[cfg(feature = "std")]
    #[must_use]
12
    pub fn exists(&self) -> bool {
12
        path_exists(self.inner.as_str())
12
    }
    /// Checks if the path is a file
    #[cfg(feature = "std")]
    #[must_use]
12
    pub fn is_file(&self) -> bool {
12
        path_is_file(self.inner.as_str())
12
    }
    /// Checks if the path is a directory
    #[cfg(feature = "std")]
    #[must_use]
13
    pub fn is_dir(&self) -> bool {
13
        path_is_dir(self.inner.as_str())
13
    }
    /// Checks if the path is absolute
    #[cfg(feature = "std")]
    #[must_use]
21
    pub fn is_absolute(&self) -> bool {
21
        Path::new(self.inner.as_str()).is_absolute()
21
    }
    /// Creates this directory and all parent directories
    #[cfg(feature = "std")]
    /// # Errors
    ///
    /// Returns a `FileError` if the filesystem operation fails (e.g. path not found, permission
    /// denied, or an I/O error).
2
    pub fn create_dir_all(&self) -> Result<EmptyStruct, FileError> {
2
        dir_create_all(self.inner.as_str())
2
    }
    /// Creates this directory (parent must exist)
    #[cfg(feature = "std")]
    /// # Errors
    ///
    /// Returns a `FileError` if the filesystem operation fails (e.g. path not found, permission
    /// denied, or an I/O error).
1
    pub fn create_dir(&self) -> Result<EmptyStruct, FileError> {
1
        dir_create(self.inner.as_str())
1
    }
    /// Removes this file
    #[cfg(feature = "std")]
    /// # Errors
    ///
    /// Returns a `FileError` if the filesystem operation fails (e.g. path not found, permission
    /// denied, or an I/O error).
3
    pub fn remove_file(&self) -> Result<EmptyStruct, FileError> {
3
        file_delete(self.inner.as_str())
3
    }
    /// Removes this directory (must be empty)
    #[cfg(feature = "std")]
    /// # Errors
    ///
    /// Returns a `FileError` if the filesystem operation fails (e.g. path not found, permission
    /// denied, or an I/O error).
2
    pub fn remove_dir(&self) -> Result<EmptyStruct, FileError> {
2
        dir_delete(self.inner.as_str())
2
    }
    /// Removes this directory and all contents
    #[cfg(feature = "std")]
    /// # Errors
    ///
    /// Returns a `FileError` if the filesystem operation fails (e.g. path not found, permission
    /// denied, or an I/O error).
2
    pub fn remove_dir_all(&self) -> Result<EmptyStruct, FileError> {
2
        dir_delete_all(self.inner.as_str())
2
    }
    /// Reads the entire file at this path as bytes, resuming `on_result`
    /// with a [`FileReadBytesResult`].
    ///
    /// Never blocks the calling activation in an observable way: the read
    /// happens here on desktop, and the callback runs as a fresh activation
    /// after the current one returns (same frame on desktop, a later task on
    /// web). `data` is handed back to the callback untouched.
    #[cfg(feature = "text_layout")]
    #[must_use]
    pub fn read_bytes(
        &self,
        data: azul_core::refany::RefAny,
        on_result: crate::callbacks::ResumeCallback,
    ) -> azul_core::task::RequestId {
        let result = self.read_bytes_blocking().into();
        crate::request::complete(data, on_result, FileReadBytesResult { result })
    }
    /// Reads the entire file at this path as a string, resuming `on_result`
    /// with a [`FileReadStringResult`]. See [`Self::read_bytes`].
    #[cfg(feature = "text_layout")]
    #[must_use]
    pub fn read_string(
        &self,
        data: azul_core::refany::RefAny,
        on_result: crate::callbacks::ResumeCallback,
    ) -> azul_core::task::RequestId {
        let result = self.read_string_blocking().into();
        crate::request::complete(data, on_result, FileReadStringResult { result })
    }
    /// The synchronous read behind [`Self::read_bytes`]. Not part of the
    /// public API (it cannot exist on web); framework-internal callers that
    /// are already on a worker thread may use it.
    #[cfg(feature = "std")]
    /// # Errors
    ///
    /// Returns a `FileError` if the filesystem operation fails (e.g. path not found, permission
    /// denied, or an I/O error).
2
    pub fn read_bytes_blocking(&self) -> Result<U8Vec, FileError> {
        // Canned e2e documents (`e2e://...`) are served from the mock store;
        // every other path is a real file.
        #[cfg(feature = "text_layout")]
2
        if let Some(bytes) = crate::request::mock::take_file_read(self.inner.as_str()) {
            return Ok(U8Vec::from_vec(bytes));
2
        }
2
        file_read(self.inner.as_str())
2
    }
    /// The synchronous read behind [`Self::read_string`]; see
    /// [`Self::read_bytes_blocking`].
    #[cfg(feature = "std")]
    /// # Errors
    ///
    /// Returns a `FileError` if the filesystem operation fails (e.g. path not found, permission
    /// denied, or an I/O error).
2
    pub fn read_string_blocking(&self) -> Result<AzString, FileError> {
        #[cfg(feature = "text_layout")]
2
        if let Some(bytes) = crate::request::mock::take_file_read(self.inner.as_str()) {
            return alloc::string::String::from_utf8(bytes)
                .map(AzString::from)
                .map_err(|_| FileError {
                    message: AzString::from_const_str("canned e2e document is not UTF-8"),
                    kind: FileErrorKind::Other,
                });
2
        }
2
        file_read_string(self.inner.as_str())
2
    }
    /// Writes bytes to the file at this path
    #[cfg(feature = "std")]
    /// # Errors
    ///
    /// Returns a `FileError` if the filesystem operation fails (e.g. path not found, permission
    /// denied, or an I/O error).
2
    pub fn write_bytes(&self, data: &U8Vec) -> Result<EmptyStruct, FileError> {
2
        file_write(self.inner.as_str(), data.as_ref())
2
    }
    /// Writes a string to the file at this path
    #[cfg(feature = "std")]
    /// # Errors
    ///
    /// Returns a `FileError` if the filesystem operation fails (e.g. path not found, permission
    /// denied, or an I/O error).
3
    pub fn write_string(&self, data: &AzString) -> Result<EmptyStruct, FileError> {
3
        file_write_string(self.inner.as_str(), data.as_str())
3
    }
    /// Copies a file from this path to another path
    #[cfg(feature = "std")]
    /// # Errors
    ///
    /// Returns a `FileError` if the filesystem operation fails (e.g. path not found, permission
    /// denied, or an I/O error).
2
    pub fn copy_to(&self, dest: &Self) -> Result<u64, FileError> {
2
        file_copy(self.inner.as_str(), dest.inner.as_str())
2
    }
    /// Renames/moves a file from this path to another path
    #[cfg(feature = "std")]
    /// # Errors
    ///
    /// Returns a `FileError` if the filesystem operation fails (e.g. path not found, permission
    /// denied, or an I/O error).
2
    pub fn rename_to(&self, dest: &Self) -> Result<EmptyStruct, FileError> {
2
        file_rename(self.inner.as_str(), dest.inner.as_str())
2
    }
    /// Returns the path as a string reference
    #[must_use]
59
    pub fn as_str(&self) -> &str {
59
        self.inner.as_str()
59
    }
    /// Returns the path as an `AzString`
    #[must_use]
7
    pub fn as_string(&self) -> AzString {
7
        self.inner.clone()
7
    }
    /// Lists directory contents, resuming `on_result` with a
    /// [`FileDirListResult`]. See [`Self::read_bytes`] for the contract.
    #[cfg(feature = "text_layout")]
    #[must_use]
    pub fn read_dir(
        &self,
        data: azul_core::refany::RefAny,
        on_result: crate::callbacks::ResumeCallback,
    ) -> azul_core::task::RequestId {
        let result = self.read_dir_blocking().into();
        crate::request::complete(data, on_result, FileDirListResult { result })
    }
    /// The synchronous listing behind [`Self::read_dir`]; see
    /// [`Self::read_bytes_blocking`].
    #[cfg(feature = "std")]
    /// # Errors
    ///
    /// Returns a `FileError` if the filesystem operation fails (e.g. path not found, permission
    /// denied, or an I/O error).
2
    pub fn read_dir_blocking(&self) -> Result<DirEntryVec, FileError> {
2
        dir_list(self.inner.as_str())
2
    }
    /// Returns metadata about the file/directory
    #[cfg(feature = "std")]
    /// # Errors
    ///
    /// Returns a `FileError` if the filesystem operation fails (e.g. path not found, permission
    /// denied, or an I/O error).
3
    pub fn metadata(&self) -> Result<FileMetadata, FileError> {
3
        file_metadata(self.inner.as_str())
3
    }
    /// Makes the path canonical (absolute, with no `.` or `..` components)
    #[cfg(feature = "std")]
    /// # Errors
    ///
    /// Returns a `FileError` if the filesystem operation fails (e.g. path not found, permission
    /// denied, or an I/O error).
1
    pub fn canonicalize(&self) -> Result<Self, FileError> {
1
        path_canonicalize(self.inner.as_str()).map(|p| Self { inner: p })
1
    }
}
impl From<String> for FilePath {
6
    fn from(s: String) -> Self {
6
        Self {
6
            inner: AzString::from(s),
6
        }
6
    }
}
impl From<&str> for FilePath {
6
    fn from(s: &str) -> Self {
6
        Self {
6
            inner: AzString::from(String::from(s)),
6
        }
6
    }
}
impl From<AzString> for FilePath {
6
    fn from(s: AzString) -> Self {
6
        Self { inner: s }
6
    }
}
#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    #[cfg(feature = "std")]
1
    fn test_temp_dir() {
1
        let temp = temp_dir();
1
        assert!(!temp.as_str().is_empty());
1
    }
    #[test]
    #[cfg(feature = "std")]
1
    fn test_path_join() {
1
        let joined = path_join("/home/user", "file.txt");
1
        assert!(joined.as_str().contains("file.txt"));
1
    }
}
#[cfg(test)]
#[allow(
    clippy::too_many_lines,
    clippy::cast_possible_truncation,
    clippy::redundant_clone,
    clippy::similar_names,
    clippy::case_sensitive_file_extension_comparisons
)]
mod autotest_generated {
    use alloc::string::ToString;
    use super::*;
    // ------------------------------------------------------------------
    // Harness: every test gets its own directory under the system temp dir,
    // removed on drop. Tests run in parallel in one process, so names must
    // not collide.
    // ------------------------------------------------------------------
    #[cfg(feature = "std")]
    #[derive(Debug)]
    struct CaseDir(String);
    #[cfg(feature = "std")]
    impl CaseDir {
        fn new(tag: &str) -> Self {
            use core::sync::atomic::{AtomicUsize, Ordering};
            static COUNTER: AtomicUsize = AtomicUsize::new(0);
            let n = COUNTER.fetch_add(1, Ordering::Relaxed);
            let name = format!("azul_autotest_file_{}_{}_{}", std::process::id(), tag, n);
            let dir = path_join(temp_dir().as_str(), &name).as_str().to_string();
            let _ = dir_delete_all(&dir);
            assert!(
                dir_create_all(&dir).is_ok(),
                "could not create case dir {dir}"
            );
            Self(dir)
        }
        fn path(&self) -> &str {
            &self.0
        }
        fn child(&self, name: &str) -> String {
            path_join(&self.0, name).as_str().to_string()
        }
    }
    #[cfg(feature = "std")]
    impl Drop for CaseDir {
        fn drop(&mut self) {
            let _ = dir_delete_all(&self.0);
        }
    }
    /// Paths that must never panic and never resolve to anything on disk.
    ///
    /// Deliberately excludes `"../".repeat(n)` and `"/".repeat(n)`: on unix both
    /// resolve to the root directory, so they *do* exist. See
    /// `traversal_above_root_and_repeated_slashes_resolve_to_root`.
    #[cfg(feature = "std")]
    fn hostile_paths() -> Vec<String> {
        vec![
            String::new(),
            "   ".to_string(),
            "\t\n".to_string(),
            "\0".to_string(),
            "a\0b".to_string(),
            "valid;garbage".to_string(),
            "0".to_string(),
            "-0".to_string(),
            i64::MAX.to_string(),
            i64::MIN.to_string(),
            "NaN".to_string(),
            "inf".to_string(),
            "\u{1F600}".to_string(),
            "e\u{301}\u{327}".to_string(),
            "x".repeat(100_000),
            "[".repeat(10_000),
        ]
    }
    #[cfg(feature = "std")]
    fn as_opt_string(s: Option<AzString>) -> Option<String> {
        s.map(|x| x.as_str().to_string())
    }
    // ==================================================================
    // path_to_azstring (private)
    // ==================================================================
    #[test]
    #[cfg(feature = "std")]
    fn path_to_azstring_preserves_utf8_and_empty() {
        assert_eq!(path_to_azstring(Path::new("")).as_str(), "");
        assert_eq!(
            path_to_azstring(Path::new("/tmp/a b/\u{1F600}.txt")).as_str(),
            "/tmp/a b/\u{1F600}.txt"
        );
    }
    #[test]
    #[cfg(all(feature = "std", unix))]
    fn path_to_azstring_is_lossy_never_panics_on_invalid_utf8() {
        use std::{ffi::OsStr, os::unix::ffi::OsStrExt};
        let os = OsStr::from_bytes(&[b'/', b't', 0xFF, 0xFE, b'p']);
        let s = path_to_azstring(Path::new(os));
        assert!(s.as_str().contains('\u{FFFD}'));
        assert!(s.as_str().starts_with("/t"));
        assert!(s.as_str().ends_with('p'));
    }
    // ==================================================================
    // FileError: constructor / io mapping / Display
    // ==================================================================
    #[test]
    fn file_error_new_keeps_fields_verbatim() {
        let e = FileError::new(FileErrorKind::NotFound, "boom");
        assert_eq!(e.kind, FileErrorKind::NotFound);
        assert_eq!(e.message.as_str(), "boom");
        let empty = FileError::new(FileErrorKind::Other, "");
        assert_eq!(empty.message.as_str(), "");
        assert_eq!(empty.to_string(), "");
    }
    #[test]
    fn file_error_new_survives_huge_and_unicode_messages() {
        let huge = "x".repeat(1_000_000);
        let e = FileError::new(FileErrorKind::IoError, huge.clone());
        assert_eq!(e.message.as_str().len(), 1_000_000);
        assert_eq!(e.message.as_str(), huge);
        let uni = FileError::new(FileErrorKind::InvalidPath, "\u{1F600} e\u{301} \u{202E}");
        assert_eq!(uni.message.as_str(), "\u{1F600} e\u{301} \u{202E}");
        assert_eq!(uni.to_string(), "\u{1F600} e\u{301} \u{202E}");
    }
    #[test]
    fn file_error_display_does_not_interpret_format_specifiers() {
        // The message is user/OS-supplied; it must be printed, not treated as a
        // format string.
        let e = FileError::new(FileErrorKind::Other, "{} {0} {{}} %s %n");
        assert_eq!(e.to_string(), "{} {0} {{}} %s %n");
        assert!(format!("{e:?}").contains("Other"));
    }
    #[test]
    #[cfg(feature = "std")]
    fn file_error_from_io_error_maps_every_known_kind() {
        use std::io::{Error, ErrorKind};
        let cases = [
            (ErrorKind::NotFound, FileErrorKind::NotFound),
            (ErrorKind::PermissionDenied, FileErrorKind::PermissionDenied),
            (ErrorKind::AlreadyExists, FileErrorKind::AlreadyExists),
            (ErrorKind::IsADirectory, FileErrorKind::IsDirectory),
            (
                ErrorKind::DirectoryNotEmpty,
                FileErrorKind::DirectoryNotEmpty,
            ),
            // everything else collapses to IoError
            (ErrorKind::InvalidData, FileErrorKind::IoError),
            (ErrorKind::InvalidInput, FileErrorKind::IoError),
            (ErrorKind::UnexpectedEof, FileErrorKind::IoError),
            (ErrorKind::WriteZero, FileErrorKind::IoError),
            (ErrorKind::Other, FileErrorKind::IoError),
        ];
        for (io_kind, expected) in cases {
            let e = FileError::from_io_error(Error::new(io_kind, "msg"));
            assert_eq!(e.kind, expected, "unexpected mapping for {io_kind:?}");
            assert_eq!(e.message.as_str(), "msg");
        }
    }
    #[test]
    #[cfg(feature = "std")]
    fn file_error_from_io_error_tolerates_empty_and_raw_os_errors() {
        use std::io::{Error, ErrorKind};
        let empty = FileError::from_io_error(Error::other(""));
        assert_eq!(empty.kind, FileErrorKind::IoError);
        assert_eq!(empty.message.as_str(), "");
        // ENOENT is 2 on every unix; the OS-error path must map like the
        // ErrorKind path.
        #[cfg(unix)]
        {
            let raw = FileError::from_io_error(Error::from_raw_os_error(2));
            assert_eq!(raw.kind, FileErrorKind::NotFound);
            assert!(!raw.message.as_str().is_empty());
        }
        // A nonsense errno must not panic and must not be silently classified.
        let bogus = FileError::from_io_error(Error::from_raw_os_error(i32::MAX));
        assert_eq!(bogus.kind, FileErrorKind::IoError);
    }
    // ==================================================================
    // file_read / file_write: round-trips and hostile paths
    // ==================================================================
    #[test]
    #[cfg(feature = "std")]
    fn file_write_read_roundtrip_bytes_including_invalid_utf8() {
        let case = CaseDir::new("rt_bytes");
        let p = case.child("blob.bin");
        let data: Vec<u8> = vec![0x00, 0xFF, 0xFE, 0x80, 0x7F, b'\n', 0x00];
        assert!(file_write(&p, &data).is_ok());
        let read = file_read(&p).expect("read back");
        assert_eq!(read.as_slice(), &data[..]);
        // The same bytes are not valid UTF-8: the string reader must reject
        // them instead of lossily decoding.
        let err = file_read_string(&p).expect_err("invalid utf-8 must not decode");
        assert_eq!(err.kind, FileErrorKind::IoError);
        assert!(!err.message.as_str().is_empty());
    }
    #[test]
    #[cfg(feature = "std")]
    fn file_write_read_roundtrip_empty_file() {
        let case = CaseDir::new("rt_empty");
        let p = case.child("empty.bin");
        assert!(file_write(&p, b"").is_ok());
        assert!(file_read(&p).expect("read").is_empty());
        assert_eq!(file_read_string(&p).expect("read str").as_str(), "");
        assert_eq!(file_metadata(&p).expect("meta").size, 0);
        assert!(path_exists(&p));
        assert!(path_is_file(&p));
    }
    #[test]
    #[cfg(feature = "std")]
    fn file_write_read_roundtrip_unicode_string() {
        let case = CaseDir::new("rt_unicode");
        let p = case.child("\u{1F600}_e\u{301}.txt");
        let content = "\u{1F600}\u{200D}\u{1F5A5}\u{FE0F} e\u{301}\u{327} \u{202E}rtl \u{0}nul";
        assert!(file_write_string(&p, content).is_ok());
        assert_eq!(file_read_string(&p).expect("read").as_str(), content);
        assert_eq!(
            file_read(&p).expect("read bytes").as_slice(),
            content.as_bytes()
        );
    }
    #[test]
    #[cfg(feature = "std")]
    fn file_write_read_roundtrip_one_megabyte() {
        let case = CaseDir::new("rt_big");
        let p = case.child("big.bin");
        let data: Vec<u8> = (0..1_000_000u32).map(|i| (i % 251) as u8).collect();
        assert!(file_write(&p, &data).is_ok());
        let read = file_read(&p).expect("read back");
        assert_eq!(read.len(), 1_000_000);
        assert_eq!(read.as_slice(), &data[..]);
        assert_eq!(file_metadata(&p).expect("meta").size, 1_000_000);
    }
    #[test]
    #[cfg(feature = "std")]
    fn file_read_rejects_every_hostile_path_without_panicking() {
        // Read-only probes only: these are relative paths resolved against the
        // test CWD, so a destructive op here could touch a real file.
        for p in hostile_paths() {
            let r = file_read(&p);
            assert!(r.is_err(), "file_read unexpectedly succeeded for {p:?}");
            let e = r.unwrap_err();
            assert!(
                !e.message.as_str().is_empty(),
                "empty error message for {p:?}"
            );
            assert!(file_read_string(&p).is_err());
            assert!(file_metadata(&p).is_err());
            assert!(path_canonicalize(&p).is_err());
            assert!(dir_list(&p).is_err());
        }
    }
    #[test]
    #[cfg(all(feature = "std", unix))]
    fn traversal_above_root_and_repeated_slashes_resolve_to_root() {
        // Two path shapes that look like "obviously invalid garbage" but are in
        // fact valid names for `/`: `..` at the root is the root, and runs of
        // separators collapse. Anything treating these as rejected input is
        // wrong.
        let climb = "../".repeat(64);
        // 512, not 1024: PATH_MAX is 1024 on macOS and 4096 on Linux, and a
        // 1024-BYTE path leaves no room for the NUL, so stat() returns
        // ENAMETOOLONG and the OS is right to reject it. This test is about
        // separator runs collapsing, which 512 shows exactly as well — the
        // old length made it a PATH_MAX test by accident, green on Linux and
        // red on every mac.
        let slashes = "/".repeat(512);
        for p in [climb.as_str(), slashes.as_str()] {
            assert!(path_exists(p), "{p:?} resolves to /, so it exists");
            assert!(path_is_dir(p));
            assert!(!path_is_file(p));
            assert_eq!(
                path_canonicalize(p).expect("resolves to root").as_str(),
                "/"
            );
        }
    }
    #[test]
    #[cfg(feature = "std")]
    fn file_read_interior_nul_path_is_an_io_error_not_a_crash() {
        let err = file_read("some\0path").expect_err("NUL byte cannot reach the OS");
        assert_eq!(err.kind, FileErrorKind::IoError);
    }
    #[test]
    #[cfg(feature = "std")]
    fn file_read_overlong_path_saturates_to_an_error() {
        let case = CaseDir::new("longpath");
        // A single component far beyond NAME_MAX.
        let p = case.child(&"n".repeat(5_000));
        let err = file_read(&p).expect_err("component exceeds NAME_MAX");
        assert_eq!(err.kind, FileErrorKind::IoError);
        assert!(!path_exists(&p));
    }
    #[test]
    #[cfg(all(feature = "std", unix))]
    fn file_read_on_a_directory_reports_is_directory() {
        let case = CaseDir::new("read_dir_as_file");
        let err = file_read(case.path()).expect_err("a directory is not readable as bytes");
        assert_eq!(err.kind, FileErrorKind::IsDirectory);
    }
    #[test]
    #[cfg(feature = "std")]
    fn file_write_into_missing_parent_reports_not_found() {
        let case = CaseDir::new("write_missing_parent");
        let p = path_join(&case.child("nope"), "f.txt").as_str().to_string();
        let err = file_write(&p, b"x").expect_err("parent does not exist");
        assert_eq!(err.kind, FileErrorKind::NotFound);
        assert!(file_write_string(&p, "x").is_err());
        assert!(!path_exists(&p));
    }
    #[test]
    #[cfg(feature = "std")]
    fn file_paths_are_never_trimmed() {
        let case = CaseDir::new("no_trim");
        let padded = case.child("  spaced  ");
        assert!(file_write_string(&padded, "payload").is_ok());
        assert_eq!(
            file_read_string(&padded).expect("exact name").as_str(),
            "payload"
        );
        // The trimmed name is a *different* file and must not resolve.
        let trimmed = case.child("spaced");
        assert!(file_read_string(&trimmed).is_err());
        assert!(!path_exists(&trimmed));
    }
    // ==================================================================
    // file_append / file_copy / file_rename / file_delete
    // ==================================================================
    #[test]
    #[cfg(feature = "std")]
    fn file_append_creates_then_concatenates() {
        let case = CaseDir::new("append");
        let p = case.child("log.bin");
        assert!(!path_exists(&p));
        assert!(
            file_append(&p, b"aa").is_ok(),
            "append must create the file"
        );
        assert!(
            file_append(&p, b"").is_ok(),
            "empty append is a no-op, not an error"
        );
        assert!(file_append(&p, &[0xFF, 0x00]).is_ok());
        assert_eq!(
            file_read(&p).expect("read").as_slice(),
            &[b'a', b'a', 0xFF, 0x00]
        );
    }
    #[test]
    #[cfg(feature = "std")]
    fn file_copy_returns_byte_count_and_duplicates_content() {
        let case = CaseDir::new("copy");
        let src = case.child("src.bin");
        let dst = case.child("dst.bin");
        let data: Vec<u8> = (0..=255u8).cycle().take(4096).collect();
        assert!(file_write(&src, &data).is_ok());
        assert_eq!(file_copy(&src, &dst).expect("copy"), 4096);
        assert_eq!(file_read(&dst).expect("read dst").as_slice(), &data[..]);
        assert!(path_exists(&src), "copy must not consume the source");
        // Copy overwrites an existing destination rather than failing.
        assert_eq!(file_copy(&src, &dst).expect("re-copy"), 4096);
        let missing = case.child("ghost.bin");
        assert_eq!(
            file_copy(&missing, &dst).expect_err("missing source").kind,
            FileErrorKind::NotFound
        );
    }
    #[test]
    #[cfg(feature = "std")]
    fn file_rename_moves_and_missing_source_is_not_found() {
        let case = CaseDir::new("rename");
        let src = case.child("a.txt");
        let dst = case.child("b.txt");
        assert!(file_write_string(&src, "payload").is_ok());
        assert!(file_rename(&src, &dst).is_ok());
        assert!(!path_exists(&src), "source must be gone after rename");
        assert_eq!(file_read_string(&dst).expect("read").as_str(), "payload");
        assert_eq!(
            file_rename(&src, &dst).expect_err("source gone").kind,
            FileErrorKind::NotFound
        );
    }
    #[test]
    #[cfg(feature = "std")]
    fn file_delete_is_not_idempotent_and_refuses_directories() {
        let case = CaseDir::new("delete");
        let p = case.child("victim.txt");
        assert!(file_write_string(&p, "x").is_ok());
        assert!(file_delete(&p).is_ok());
        assert!(!path_exists(&p));
        assert_eq!(
            file_delete(&p).expect_err("already deleted").kind,
            FileErrorKind::NotFound
        );
        // unlink() on a directory is EISDIR on Linux but EPERM on macOS, so only
        // assert that it fails rather than pinning the kind.
        assert!(
            file_delete(case.path()).is_err(),
            "file_delete must not remove a directory"
        );
        assert!(path_is_dir(case.path()));
    }
    // ==================================================================
    // path_exists / path_is_file / path_is_dir
    // ==================================================================
    #[test]
    #[cfg(feature = "std")]
    fn path_predicates_are_false_for_hostile_paths() {
        for p in hostile_paths() {
            assert!(!path_exists(&p), "{p:?} should not exist");
            assert!(!path_is_file(&p));
            assert!(!path_is_dir(&p));
        }
    }
    #[test]
    #[cfg(feature = "std")]
    fn path_is_file_and_is_dir_are_mutually_exclusive() {
        let case = CaseDir::new("predicates");
        let f = case.child("f.txt");
        assert!(file_write_string(&f, "x").is_ok());
        let candidates = [case.path().to_string(), f.clone(), case.child("ghost")];
        for p in &candidates {
            assert!(
                !(path_is_file(p) && path_is_dir(p)),
                "{p:?} claimed to be both a file and a directory"
            );
            assert_eq!(path_exists(p), path_is_file(p) || path_is_dir(p));
        }
        assert!(path_is_file(&f) && !path_is_dir(&f));
        assert!(path_is_dir(case.path()) && !path_is_file(case.path()));
    }
    // ==================================================================
    // file_metadata
    // ==================================================================
    #[test]
    #[cfg(feature = "std")]
    fn file_metadata_reports_size_type_and_mtime() {
        let case = CaseDir::new("meta");
        let f = case.child("f.bin");
        assert!(file_write(&f, &[1u8; 1234]).is_ok());
        let m = file_metadata(&f).expect("file metadata");
        assert_eq!(m.size, 1234);
        assert_eq!(m.file_type, FileType::File);
        assert!(!m.is_readonly);
        assert!(m.modified_secs > 0, "mtime must be a real unix timestamp");
        let d = file_metadata(case.path()).expect("dir metadata");
        assert_eq!(d.file_type, FileType::Directory);
        assert_eq!(
            file_metadata(&case.child("ghost"))
                .expect_err("missing")
                .kind,
            FileErrorKind::NotFound
        );
    }
    #[test]
    #[cfg(all(feature = "std", unix))]
    fn file_metadata_does_not_follow_symlinks_but_path_is_file_does() {
        let case = CaseDir::new("symlink_meta");
        let target = case.child("target.txt");
        let link = case.child("link.txt");
        assert!(file_write_string(&target, "hello").is_ok());
        std::os::unix::fs::symlink(&target, &link).expect("symlink");
        // symlink_metadata semantics: the link itself, not its target.
        let m = file_metadata(&link).expect("metadata");
        assert_eq!(m.file_type, FileType::Symlink);
        // ...while the predicates and readers *do* follow it.
        assert!(path_is_file(&link));
        assert_eq!(
            file_read_string(&link).expect("read through link").as_str(),
            "hello"
        );
        assert_eq!(
            path_canonicalize(&link).expect("canonicalize").as_str(),
            path_canonicalize(&target)
                .expect("canonicalize target")
                .as_str()
        );
    }
    #[test]
    #[cfg(all(feature = "std", unix))]
    fn file_metadata_detects_dangling_symlink_without_error() {
        let case = CaseDir::new("dangling");
        let link = case.child("dangling.txt");
        std::os::unix::fs::symlink(case.child("nowhere"), &link).expect("symlink");
        let m = file_metadata(&link).expect("symlink_metadata must not follow");
        assert_eq!(m.file_type, FileType::Symlink);
        // Everything that follows the link must fail cleanly.
        assert!(!path_exists(&link));
        assert_eq!(
            file_read(&link).expect_err("dangling target").kind,
            FileErrorKind::NotFound
        );
    }
    // ==================================================================
    // Directory operations
    // ==================================================================
    #[test]
    #[cfg(feature = "std")]
    fn dir_create_rejects_existing_and_missing_parent() {
        let case = CaseDir::new("dir_create");
        assert_eq!(
            dir_create(case.path()).expect_err("already exists").kind,
            FileErrorKind::AlreadyExists
        );
        let orphan = path_join(&case.child("missing"), "child")
            .as_str()
            .to_string();
        assert_eq!(
            dir_create(&orphan).expect_err("missing parent").kind,
            FileErrorKind::NotFound
        );
        assert!(!path_exists(&orphan));
        // create_all fills in the parents and is idempotent.
        assert!(dir_create_all(&orphan).is_ok());
        assert!(
            dir_create_all(&orphan).is_ok(),
            "create_all must be idempotent"
        );
        assert!(path_is_dir(&orphan));
    }
    #[test]
    #[cfg(feature = "std")]
    fn dir_create_all_handles_deep_nesting_without_stack_overflow() {
        let case = CaseDir::new("deep");
        let mut deep = case.child("d0");
        for i in 1..64 {
            deep = path_join(&deep, &format!("d{i}")).as_str().to_string();
        }
        assert!(dir_create_all(&deep).is_ok());
        assert!(path_is_dir(&deep));
        // Recursive removal of the same chain must also stay iterative.
        assert!(dir_delete_all(&case.child("d0")).is_ok());
        assert!(!path_exists(&deep));
    }
    #[test]
    #[cfg(feature = "std")]
    fn dir_delete_refuses_non_empty_but_delete_all_succeeds() {
        let case = CaseDir::new("dir_delete");
        let sub = case.child("sub");
        assert!(dir_create(&sub).is_ok());
        assert!(file_write_string(path_join(&sub, "f.txt").as_str(), "x").is_ok());
        let err = dir_delete(&sub).expect_err("non-empty directory");
        #[cfg(unix)]
        assert_eq!(err.kind, FileErrorKind::DirectoryNotEmpty);
        assert!(!err.message.as_str().is_empty());
        assert!(
            path_is_dir(&sub),
            "failed delete must not have removed anything"
        );
        assert!(dir_delete_all(&sub).is_ok());
        assert!(!path_exists(&sub));
        assert_eq!(
            dir_delete(&sub).expect_err("already gone").kind,
            FileErrorKind::NotFound
        );
    }
    #[test]
    #[cfg(feature = "std")]
    fn dir_list_enumerates_entries_with_matching_names_and_types() {
        let case = CaseDir::new("dir_list");
        let sub = case.child("subdir");
        let f = case.child("\u{1F600}.txt");
        assert!(dir_create(&sub).is_ok());
        assert!(file_write_string(&f, "x").is_ok());
        let entries = dir_list(case.path()).expect("list");
        assert_eq!(entries.len(), 2);
        for e in entries.iter() {
            assert!(!e.name.as_str().is_empty());
            assert!(
                e.path.as_str().ends_with(e.name.as_str()),
                "entry path {:?} must end with its name {:?}",
                e.path.as_str(),
                e.name.as_str()
            );
            assert!(path_exists(e.path.as_str()));
            match e.name.as_str() {
                "subdir" => assert_eq!(e.file_type, FileType::Directory),
                "\u{1F600}.txt" => assert_eq!(e.file_type, FileType::File),
                other => panic!("unexpected entry {other:?}"),
            }
        }
        assert!(dir_list(&sub).expect("empty dir").is_empty());
        assert!(dir_list(&f).is_err(), "listing a file must fail");
    }
    #[test]
    #[cfg(all(feature = "std", unix))]
    fn dir_list_reports_symlinks_as_symlinks() {
        let case = CaseDir::new("dir_list_symlink");
        let target = case.child("target.txt");
        assert!(file_write_string(&target, "x").is_ok());
        std::os::unix::fs::symlink(&target, case.child("link.txt")).expect("symlink");
        let entries = dir_list(case.path()).expect("list");
        let link = entries
            .iter()
            .find(|e| e.name.as_str() == "link.txt")
            .expect("link entry");
        assert_eq!(link.file_type, FileType::Symlink);
    }
    // ==================================================================
    // Path manipulation (pure, no filesystem)
    // ==================================================================
    #[test]
    #[cfg(all(feature = "std", unix))]
    fn path_join_absolute_component_replaces_the_base() {
        // std::path::Path::join semantics: an absolute second component wins.
        // This is the classic traversal footgun, so pin it down.
        assert_eq!(
            path_join("/home/user", "/etc/passwd").as_str(),
            "/etc/passwd"
        );
        assert_eq!(path_join("/srv/data", "/").as_str(), "/");
    }
    #[test]
    #[cfg(feature = "std")]
    fn path_join_does_not_normalize_parent_traversal() {
        let joined = path_join("/srv/data", "../../etc/passwd");
        assert!(
            joined.as_str().contains(".."),
            "path_join is purely lexical and must not silently resolve `..`: {:?}",
            joined.as_str()
        );
        assert_eq!(path_join("", "x").as_str(), "x");
        assert!(path_join("base", "").as_str().starts_with("base"));
        assert!(path_join("base", "\u{1F600}")
            .as_str()
            .ends_with("\u{1F600}"));
    }
    #[test]
    #[cfg(feature = "std")]
    fn path_parent_edge_cases() {
        assert_eq!(as_opt_string(path_parent("")), None);
        assert_eq!(as_opt_string(path_parent("..")), Some(String::new()));
        assert_eq!(as_opt_string(path_parent("a")), Some(String::new()));
        #[cfg(unix)]
        {
            assert_eq!(as_opt_string(path_parent("/")), None);
            assert_eq!(as_opt_string(path_parent("/a")), Some("/".to_string()));
            assert_eq!(
                as_opt_string(path_parent("/a/b/c")),
                Some("/a/b".to_string())
            );
            assert_eq!(as_opt_string(path_parent("/a/b/")), Some("/a".to_string()));
        }
    }
    #[test]
    #[cfg(all(feature = "std", unix))]
    fn path_parent_of_ten_thousand_components_does_not_stack_overflow() {
        let deep = format!("/{}", vec!["a"; 10_000].join("/"));
        let parent = path_parent(&deep).expect("parent of a deep path");
        assert_eq!(parent.as_str().len(), deep.len() - 2);
        assert!(parent.as_str().starts_with("/a/a/"));
    }
    #[test]
    #[cfg(feature = "std")]
    fn path_file_name_edge_cases() {
        assert_eq!(as_opt_string(path_file_name("")), None);
        assert_eq!(as_opt_string(path_file_name("..")), None);
        assert_eq!(as_opt_string(path_file_name(".")), None);
        assert_eq!(
            as_opt_string(path_file_name("foo.txt")),
            Some("foo.txt".to_string())
        );
        assert_eq!(
            as_opt_string(path_file_name("\u{1F600}.txt")),
            Some("\u{1F600}.txt".to_string())
        );
        #[cfg(unix)]
        {
            assert_eq!(as_opt_string(path_file_name("/")), None);
            // A trailing separator is stripped, not treated as an empty name.
            assert_eq!(
                as_opt_string(path_file_name("/a/b/")),
                Some("b".to_string())
            );
        }
    }
    #[test]
    #[cfg(feature = "std")]
    fn path_extension_edge_cases() {
        assert_eq!(as_opt_string(path_extension("")), None);
        assert_eq!(as_opt_string(path_extension("noext")), None);
        // A dotfile has no extension...
        assert_eq!(as_opt_string(path_extension(".hidden")), None);
        // ...but a trailing dot yields an *empty* extension, not None.
        assert_eq!(as_opt_string(path_extension("a.")), Some(String::new()));
        // Only the last segment counts.
        assert_eq!(
            as_opt_string(path_extension("a.tar.gz")),
            Some("gz".to_string())
        );
        assert_eq!(
            as_opt_string(path_extension("a.\u{1F600}")),
            Some("\u{1F600}".to_string())
        );
        assert_eq!(as_opt_string(path_extension("..")), None);
    }
    #[test]
    #[cfg(feature = "std")]
    fn path_canonicalize_requires_existence_and_returns_absolute() {
        let case = CaseDir::new("canon");
        let f = case.child("f.txt");
        assert!(file_write_string(&f, "x").is_ok());
        let canon = path_canonicalize(&f).expect("canonicalize");
        assert!(FilePath::from_str(canon.as_str()).is_absolute());
        assert!(path_exists(canon.as_str()));
        assert!(!canon.as_str().contains(".."));
        assert_eq!(
            path_canonicalize("").expect_err("empty path").kind,
            FileErrorKind::NotFound
        );
        assert_eq!(
            path_canonicalize(&case.child("ghost"))
                .expect_err("missing")
                .kind,
            FileErrorKind::NotFound
        );
        // `..` is resolved away — but only through components that really are
        // directories (`f.txt/../f.txt` is ENOTDIR, not a lexical rewrite).
        let sub = case.child("sub");
        assert!(dir_create(&sub).is_ok());
        let via_dotdot = path_join(path_join(&sub, "..").as_str(), "f.txt")
            .as_str()
            .to_string();
        assert_eq!(
            path_canonicalize(&via_dotdot)
                .expect("resolve .. through a real dir")
                .as_str(),
            canon.as_str()
        );
        // `f.txt/../f.txt` — `..` applied THROUGH a regular file.
        //
        // POSIX realpath(3) answers ENOTDIR, and so does Linux's
        // std::fs::canonicalize. macOS's does NOT: it resolves the path and
        // hands back the file. Verified directly, outside azul —
        // std::fs::canonicalize returns Ok on macOS for exactly this input
        // while Python's os.path.realpath(strict=True) on the same path raises
        // NotADirectoryError. It is a difference in std, not in this crate, and
        // asserting the Linux answer everywhere made every mac run red.
        //
        // What must hold on BOTH platforms is the part that matters: the path
        // does not ESCAPE. Whether it errors or resolves, it must never name
        // anything other than the file itself.
        let through_a_file = path_join(path_join(&f, "..").as_str(), "f.txt")
            .as_str()
            .to_string();
        match path_canonicalize(&through_a_file) {
            Err(_) => { /* POSIX answer: a file is not a directory component */ }
            Ok(resolved) => assert_eq!(
                resolved.as_str(),
                canon.as_str(),
                "resolving `..` through a regular file must not escape to a different path than \
                 the file itself"
            ),
        }
    }
    #[test]
    #[cfg(feature = "std")]
    fn temp_dir_is_a_real_directory() {
        let t = temp_dir();
        assert!(!t.as_str().is_empty());
        assert!(path_is_dir(t.as_str()));
        assert!(FilePath::from_str(t.as_str()).is_absolute());
    }
    // ==================================================================
    // FilePath: construction, invariants, delegation
    // ==================================================================
    #[test]
    fn file_path_constructors_agree_and_roundtrip_exactly() {
        let inputs = [
            "",
            "   ",
            "/usr/bin",
            "rel/path.txt",
            "\u{1F600}/e\u{301}",
            "with\0nul",
        ];
        for s in inputs {
            let from_str = FilePath::from_str(s);
            let new = FilePath::new(AzString::from(String::from(s)));
            let from_ref: FilePath = s.into();
            let from_string: FilePath = String::from(s).into();
            let from_az: FilePath = AzString::from(String::from(s)).into();
            assert_eq!(from_str.as_str(), s, "as_str must round-trip verbatim");
            assert_eq!(from_str, new);
            assert_eq!(from_str, from_ref);
            assert_eq!(from_str, from_string);
            assert_eq!(from_str, from_az);
            assert_eq!(from_str.as_string().as_str(), s);
        }
    }
    #[test]
    fn file_path_empty_and_default_are_the_neutral_value() {
        let e = FilePath::empty();
        assert_eq!(e, FilePath::default());
        assert_eq!(e, FilePath::from_str(""));
        assert!(e.as_str().is_empty());
        assert!(e.as_string().as_str().is_empty());
    }
    #[test]
    fn file_path_handles_a_100k_char_component() {
        let huge = "x".repeat(100_000);
        let p = FilePath::from_str(&huge);
        assert_eq!(p.as_str().len(), 100_000);
        assert_eq!(p.as_str(), huge);
        assert_eq!(p.clone(), p);
    }
    #[test]
    #[cfg(feature = "std")]
    fn file_path_eq_implies_equal_hashes() {
        use std::collections::HashSet;
        let mut set = HashSet::new();
        assert!(set.insert(FilePath::from_str("/a/b")));
        assert!(
            !set.insert(FilePath::new(AzString::from(String::from("/a/b")))),
            "equal FilePaths must hash equally"
        );
        assert!(
            set.insert(FilePath::from_str("/a/b/")),
            "trailing slash is a distinct string"
        );
        assert_eq!(set.len(), 2);
    }
    #[test]
    #[cfg(feature = "std")]
    fn file_path_accessors_delegate_to_the_free_functions() {
        let inputs = [
            "",
            "   ",
            "/",
            "..",
            "/a/b/c.tar.gz",
            "a.",
            ".hidden",
            "\u{1F600}.txt",
            "with\0nul",
        ];
        for s in inputs {
            let p = FilePath::from_str(s);
            assert_eq!(
                p.parent().map(|q| q.as_str().to_string()),
                as_opt_string(path_parent(s)),
                "parent() diverged from path_parent for {s:?}"
            );
            assert_eq!(
                as_opt_string(p.file_name()),
                as_opt_string(path_file_name(s))
            );
            assert_eq!(
                as_opt_string(p.extension()),
                as_opt_string(path_extension(s))
            );
            assert_eq!(p.exists(), path_exists(s));
            assert_eq!(p.is_file(), path_is_file(s));
            assert_eq!(p.is_dir(), path_is_dir(s));
            let joined = p.join(&FilePath::from_str("child"));
            assert_eq!(joined.as_str(), path_join(s, "child").as_str());
            let joined_str = p.join_str(&AzString::from(String::from("child")));
            assert_eq!(joined_str.as_str(), joined.as_str());
        }
    }
    #[test]
    #[cfg(all(feature = "std", unix))]
    fn file_path_is_absolute_edge_cases() {
        assert!(FilePath::from_str("/").is_absolute());
        assert!(FilePath::from_str("/etc/passwd").is_absolute());
        assert!(!FilePath::from_str("").is_absolute());
        assert!(!FilePath::from_str("   ").is_absolute());
        assert!(!FilePath::from_str("relative").is_absolute());
        assert!(!FilePath::from_str("./relative").is_absolute());
        assert!(!FilePath::from_str("../escape").is_absolute());
    }
    #[test]
    #[cfg(feature = "std")]
    fn empty_file_path_fails_every_filesystem_operation_cleanly() {
        let e = FilePath::empty();
        assert!(!e.exists());
        assert!(!e.is_file());
        assert!(!e.is_dir());
        assert!(e.read_bytes_blocking().is_err());
        assert!(e.read_string_blocking().is_err());
        assert!(e.read_dir_blocking().is_err());
        assert!(e.metadata().is_err());
        assert!(e.canonicalize().is_err());
        assert!(e.remove_file().is_err());
        assert!(e.remove_dir().is_err());
        assert!(e.remove_dir_all().is_err());
        assert!(e.create_dir().is_err());
        assert!(e.write_bytes(&U8Vec::from_vec(vec![1, 2, 3])).is_err());
        assert!(e.write_string(&AzString::from(String::from("x"))).is_err());
        assert!(e.copy_to(&FilePath::from_str("/tmp/whatever")).is_err());
        assert!(e.rename_to(&FilePath::from_str("/tmp/whatever")).is_err());
        // Pure path ops still work on the empty path.
        assert!(e.parent().is_none());
        assert!(e.file_name().is_none());
        assert!(e.extension().is_none());
    }
    #[test]
    #[cfg(feature = "std")]
    fn create_dir_all_on_the_empty_path_reports_success_but_creates_nothing() {
        // Inherited from std: `fs::create_dir_all` short-circuits `""` to
        // `Ok(())`. So this is the one directory op where the empty path does
        // NOT fail — callers cannot treat Ok as "the directory now exists".
        let e = FilePath::empty();
        assert!(e.create_dir_all().is_ok());
        assert!(dir_create_all("").is_ok());
        assert!(
            !e.exists(),
            "Ok(()) must not be read as `the dir was created`"
        );
        // The non-recursive variant does fail, so the two disagree on `""`.
        assert!(dir_create("").is_err());
    }
    #[test]
    #[cfg(feature = "std")]
    fn file_path_oop_roundtrip_write_read_copy_rename_remove() {
        let case = CaseDir::new("oop");
        let root = FilePath::from_str(case.path());
        let nested = root
            .join(&FilePath::from_str("a"))
            .join(&FilePath::from_str("b"));
        assert!(nested.create_dir_all().is_ok());
        assert!(nested.is_dir());
        let f = nested.join_str(&AzString::from(String::from("data.bin")));
        let payload = U8Vec::from_vec(vec![0u8, 0xFF, 0x41]);
        assert!(f.write_bytes(&payload).is_ok());
        assert_eq!(
            f.read_bytes_blocking().expect("read").as_slice(),
            payload.as_slice()
        );
        assert_eq!(f.metadata().expect("meta").size, 3);
        assert_eq!(f.file_name().expect("name").as_str(), "data.bin");
        assert_eq!(f.extension().expect("ext").as_str(), "bin");
        assert_eq!(f.parent().expect("parent").as_str(), nested.as_str());
        let text = f.join(&FilePath::empty());
        assert!(text.as_str().starts_with(f.as_str()));
        let copy = nested.join(&FilePath::from_str("copy.bin"));
        assert_eq!(f.copy_to(&copy).expect("copy"), 3);
        assert!(copy.is_file());
        let moved = nested.join(&FilePath::from_str("moved.bin"));
        assert!(copy.rename_to(&moved).is_ok());
        assert!(!copy.exists());
        assert!(moved.is_file());
        assert_eq!(nested.read_dir_blocking().expect("list").len(), 2);
        assert!(moved.remove_file().is_ok());
        assert!(f.remove_file().is_ok());
        assert!(
            nested.remove_dir().is_ok(),
            "now-empty dir must be removable"
        );
        assert!(root.join(&FilePath::from_str("a")).remove_dir_all().is_ok());
    }
    #[test]
    #[cfg(feature = "std")]
    fn file_path_write_string_overwrites_rather_than_appends() {
        let case = CaseDir::new("overwrite");
        let f = FilePath::from_str(&case.child("f.txt"));
        assert!(f
            .write_string(&AzString::from(String::from("first")))
            .is_ok());
        assert!(f.write_string(&AzString::from(String::from("2"))).is_ok());
        assert_eq!(f.read_string_blocking().expect("read").as_str(), "2");
        assert_eq!(f.metadata().expect("meta").size, 1);
    }
    #[test]
    #[cfg(feature = "std")]
    fn file_path_env_dirs_are_sane() {
        let t = FilePath::get_temp_dir();
        assert_eq!(t.as_str(), temp_dir().as_str());
        assert!(t.is_dir());
        let cwd = FilePath::get_current_dir().expect("current dir");
        assert!(cwd.is_absolute());
        assert!(cwd.is_dir());
    }
    #[test]
    #[cfg(all(feature = "std", feature = "extra"))]
    fn file_path_user_dirs_never_panic_and_are_never_empty_strings() {
        let probes: [(&str, Option<FilePath>); 17] = [
            ("home", FilePath::get_home_dir()),
            ("cache", FilePath::get_cache_dir()),
            ("config", FilePath::get_config_dir()),
            ("config_local", FilePath::get_config_local_dir()),
            ("data", FilePath::get_data_dir()),
            ("data_local", FilePath::get_data_local_dir()),
            ("desktop", FilePath::get_desktop_dir()),
            ("document", FilePath::get_document_dir()),
            ("download", FilePath::get_download_dir()),
            ("executable", FilePath::get_executable_dir()),
            ("font", FilePath::get_font_dir()),
            ("picture", FilePath::get_picture_dir()),
            ("preference", FilePath::get_preference_dir()),
            ("public", FilePath::get_public_dir()),
            ("runtime", FilePath::get_runtime_dir()),
            ("state", FilePath::get_state_dir()),
            ("audio", FilePath::get_audio_dir()),
        ];
        for (name, dir) in probes {
            if let Some(d) = dir {
                assert!(
                    !d.as_str().is_empty(),
                    "{name} dir resolved to an empty path"
                );
                assert!(
                    d.is_absolute(),
                    "{name} dir must be absolute: {:?}",
                    d.as_str()
                );
            }
        }
        // The remaining two go through the same `dirs` path; just prove they
        // do not panic.
        let _ = FilePath::get_video_dir();
        let _ = FilePath::get_template_dir();
    }
    // ==================================================================
    // Plain data types
    // ==================================================================
    #[test]
    fn file_metadata_holds_saturated_u64_fields() {
        let m = FileMetadata {
            size: u64::MAX,
            file_type: FileType::Other,
            is_readonly: true,
            modified_secs: u64::MAX,
            created_secs: 0,
        };
        let copy = m;
        assert_eq!(m, copy);
        assert_eq!(copy.size, u64::MAX);
        assert_eq!(copy.modified_secs, u64::MAX);
        assert!(format!("{m:?}").contains("18446744073709551615"));
    }
    #[test]
    fn dir_entry_vec_bounds_are_checked() {
        let empty = DirEntryVec::from_vec(Vec::new());
        assert!(empty.is_empty());
        assert_eq!(empty.len(), 0);
        assert!(empty.get(0).is_none());
        assert!(empty.get(usize::MAX).is_none());
        let one = DirEntryVec::from_vec(vec![DirEntry {
            name: AzString::from(String::from("f.txt")),
            path: AzString::from(String::from("/tmp/f.txt")),
            file_type: FileType::File,
        }]);
        assert_eq!(one.len(), 1);
        assert_eq!(one.get(0).expect("first").name.as_str(), "f.txt");
        assert!(one.get(1).is_none());
        assert!(one.get(usize::MAX).is_none());
    }
    // ==================================================================
    // no_std stubs: every entry point must fail closed, never panic.
    // ==================================================================
    #[test]
    #[cfg(not(feature = "std"))]
    fn no_std_stubs_fail_closed() {
        for p in ["", "   ", "/etc/passwd", "\u{1F600}"] {
            assert_eq!(file_read(p).unwrap_err().kind, FileErrorKind::Other);
            assert!(file_read_string(p).is_err());
            assert!(file_write(p, &[0xFF, 0x00]).is_err());
            assert!(file_write_string(p, "x").is_err());
            assert!(file_append(p, b"").is_err());
            assert!(file_copy(p, p).is_err());
            assert!(file_rename(p, p).is_err());
            assert!(file_delete(p).is_err());
            assert!(file_metadata(p).is_err());
            assert!(dir_create(p).is_err());
            assert!(dir_create_all(p).is_err());
            assert!(dir_delete(p).is_err());
            assert!(dir_delete_all(p).is_err());
            assert!(dir_list(p).is_err());
            assert!(path_canonicalize(p).is_err());
            assert!(!path_exists(p));
            assert!(!path_is_file(p));
            assert!(!path_is_dir(p));
            assert!(path_parent(p).is_none());
            assert!(path_file_name(p).is_none());
            assert!(path_extension(p).is_none());
            assert_eq!(path_join(p, p).as_str(), "");
        }
        assert_eq!(temp_dir().as_str(), "");
        assert_eq!(no_std_file_error().kind, FileErrorKind::Other);
        assert!(!no_std_file_error().message.as_str().is_empty());
    }
}