rgpui 1.2.1

GUI UI framework
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
use super::paths::{PathStyle, is_absolute};
use anyhow::{Context as _, Result, anyhow};
use serde::{Deserialize, Serialize};
use std::{
    borrow::{Borrow, Cow},
    fmt,
    ops::Deref,
    path::{Path, PathBuf},
    sync::Arc,
};

/// 保证为相对路径且已规范化的文件系统路径。
///
/// 此类型可用于以统一方式表示路径,无论其引用的是 Windows 还是 POSIX 文件系统,
/// 也无论宿主平台是什么。
///
/// 内部以 POSIX('/' 分隔)格式存储路径,但可以 POSIX 或 Windows 格式显示。
///
/// 相对路径还保证是有效的 unicode。
#[repr(transparent)]
#[derive(PartialEq, Eq, Hash, Serialize)]
pub struct RelPath(str);

/// 文件系统路径的所有权表示,保证为相对路径且已规范化。
///
/// 此类型之于 [`RelPath`],犹如 [`std::path::PathBuf`] 之于 [`std::path::Path`]
#[derive(PartialEq, Eq, Clone, Ord, PartialOrd, Serialize)]
pub struct RelPathBuf(String);

impl RelPath {
    /// 创建一个空的 [`RelPath`]。
    pub fn empty() -> &'static Self {
        Self::new_unchecked("")
    }

    /// 将给定样式的路径转换为 [`RelPath`]。
    ///
    /// 如果路径是绝对路径或不是有效的 unicode,则返回错误。
    ///
    /// 此方法将通过移除 `.` 组件、处理 `..` 组件和移除尾部分隔符来规范化路径。
    /// 除非需要重新格式化路径,否则不会分配内存。
    #[track_caller]
    pub fn new<'a>(path: &'a Path, path_style: PathStyle) -> Result<Cow<'a, Self>> {
        let mut path = path.to_str().context("non utf-8 path")?;

        let (prefixes, suffixes): (&[_], &[_]) = match path_style {
            PathStyle::Posix => (&["./"], &['/']),
            PathStyle::Windows => (&["./", ".\\"], &['/', '\\']),
        };

        while prefixes.iter().any(|prefix| path.starts_with(prefix)) {
            path = &path[prefixes[0].len()..];
        }
        while let Some(prefix) = path.strip_suffix(suffixes)
            && !prefix.is_empty()
        {
            path = prefix;
        }

        if is_absolute(&path, path_style) {
            return Err(anyhow!("absolute path not allowed: {path:?}"));
        }

        let mut string = Cow::Borrowed(path);
        if path_style == PathStyle::Windows && path.contains('\\') {
            string = Cow::Owned(string.as_ref().replace('\\', "/"))
        }

        let mut result = match string {
            Cow::Borrowed(string) => Cow::Borrowed(Self::new_unchecked(string)),
            Cow::Owned(string) => Cow::Owned(RelPathBuf(string)),
        };

        if result
            .components()
            .any(|component| component == "" || component == "." || component == "..")
        {
            let mut normalized = RelPathBuf::new();
            for component in result.components() {
                match component {
                    "" => {}
                    "." => {}
                    ".." => {
                        if !normalized.pop() {
                            return Err(anyhow!("path is not relative: {result:?}"));
                        }
                    }
                    other => normalized.push(RelPath::new_unchecked(other)),
                }
            }
            result = Cow::Owned(normalized)
        }

        Ok(result)
    }

    /// 将已规范化且使用 '/' 分隔符的路径转换为 [`RelPath`]。
    ///
    /// 如果路径格式不正确,则返回错误。
    #[track_caller]
    pub fn unix<S: AsRef<Path> + ?Sized>(path: &S) -> anyhow::Result<&Self> {
        let path = path.as_ref();
        match Self::new(path, PathStyle::Posix)? {
            Cow::Borrowed(path) => Ok(path),
            Cow::Owned(_) => Err(anyhow!("invalid relative path {path:?}")),
        }
    }

    fn new_unchecked(s: &str) -> &Self {
        // Safety: `RelPath` is a transparent wrapper around `str`.
        unsafe { &*(s as *const str as *const Self) }
    }

    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    pub fn components(&self) -> RelPathComponents<'_> {
        RelPathComponents(&self.0)
    }

    pub fn ancestors(&self) -> RelPathAncestors<'_> {
        RelPathAncestors(Some(&self.0))
    }

    pub fn file_name(&self) -> Option<&str> {
        self.components().next_back()
    }

    pub fn file_stem(&self) -> Option<&str> {
        Some(self.as_std_path().file_stem()?.to_str().unwrap())
    }

    pub fn extension(&self) -> Option<&str> {
        Some(self.as_std_path().extension()?.to_str().unwrap())
    }

    pub fn parent(&self) -> Option<&Self> {
        let mut components = self.components();
        components.next_back()?;
        Some(components.rest())
    }

    pub fn starts_with(&self, other: &Self) -> bool {
        self.strip_prefix(other).is_ok()
    }

    pub fn ends_with(&self, other: &Self) -> bool {
        if let Some(suffix) = self.0.strip_suffix(&other.0) {
            if suffix.ends_with('/') {
                return true;
            } else if suffix.is_empty() {
                return true;
            }
        }
        false
    }

    pub fn strip_prefix<'a>(&'a self, other: &Self) -> Result<&'a Self, StripPrefixError> {
        if other.is_empty() {
            return Ok(self);
        }
        if let Some(suffix) = self.0.strip_prefix(&other.0) {
            if let Some(suffix) = suffix.strip_prefix('/') {
                return Ok(Self::new_unchecked(suffix));
            } else if suffix.is_empty() {
                return Ok(Self::empty());
            }
        }
        Err(StripPrefixError)
    }

    pub fn len(&self) -> usize {
        self.0.matches('/').count() + 1
    }

    pub fn last_n_components(&self, count: usize) -> Option<&Self> {
        let len = self.len();
        if len >= count {
            let mut components = self.components();
            for _ in 0..(len - count) {
                components.next()?;
            }
            Some(components.rest())
        } else {
            None
        }
    }

    pub fn join(&self, other: &Self) -> Arc<Self> {
        let result = if self.0.is_empty() {
            Cow::Borrowed(&other.0)
        } else if other.0.is_empty() {
            Cow::Borrowed(&self.0)
        } else {
            Cow::Owned(format!("{}/{}", &self.0, &other.0))
        };
        Arc::from(Self::new_unchecked(result.as_ref()))
    }

    pub fn to_rel_path_buf(&self) -> RelPathBuf {
        RelPathBuf(self.0.to_string())
    }

    pub fn into_arc(&self) -> Arc<Self> {
        Arc::from(self)
    }

    /// 将路径转换为线路表示。
    pub fn to_proto(&self) -> String {
        self.as_unix_str().to_owned()
    }

    /// 从线路表示加载路径。
    pub fn from_proto(path: &str) -> Result<Arc<Self>> {
        Ok(Arc::from(Self::unix(path)?))
    }

    /// 将路径转换为指定路径样式的字符串。
    ///
    /// 每当向用户展示路径时,都应通过此方法将其转换为字符串。
    pub fn display(&self, style: PathStyle) -> Cow<'_, str> {
        match style {
            PathStyle::Posix => Cow::Borrowed(&self.0),
            PathStyle::Windows if self.0.contains('/') => Cow::Owned(self.0.replace('/', "\\")),
            PathStyle::Windows => Cow::Borrowed(&self.0),
        }
    }

    /// 获取路径的内部 unix 格式表示。
    ///
    /// 不应向用户展示此内容。
    pub fn as_unix_str(&self) -> &str {
        &self.0
    }

    /// 将路径解释为 [`std::path::Path`],适用于文件系统调用。
    ///
    /// 无论宿主平台如何,都保证这是有效路径,因为 Windows 上也接受 `/` 作为路径分隔符。
    ///
    /// 不应向用户展示此内容。
    pub fn as_std_path(&self) -> &Path {
        Path::new(&self.0)
    }
}

#[derive(Debug)]
pub struct StripPrefixError;

impl std::fmt::Display for StripPrefixError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("prefix not found")
    }
}

impl std::error::Error for StripPrefixError {}

impl ToOwned for RelPath {
    type Owned = RelPathBuf;

    fn to_owned(&self) -> Self::Owned {
        self.to_rel_path_buf()
    }
}

impl Borrow<RelPath> for RelPathBuf {
    fn borrow(&self) -> &RelPath {
        self.as_rel_path()
    }
}

impl PartialOrd for RelPath {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for RelPath {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.components().cmp(other.components())
    }
}

impl fmt::Debug for RelPath {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&self.0, f)
    }
}

impl fmt::Debug for RelPathBuf {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&self.0, f)
    }
}

impl RelPathBuf {
    pub fn new() -> Self {
        Self(String::new())
    }

    pub fn pop(&mut self) -> bool {
        if let Some(ix) = self.0.rfind('/') {
            self.0.truncate(ix);
            true
        } else if !self.is_empty() {
            self.0.clear();
            true
        } else {
            false
        }
    }

    pub fn push(&mut self, path: &RelPath) {
        if !self.is_empty() {
            self.0.push('/');
        }
        self.0.push_str(&path.0);
    }

    pub fn as_rel_path(&self) -> &RelPath {
        RelPath::new_unchecked(self.0.as_str())
    }

    pub fn set_extension(&mut self, extension: &str) -> bool {
        if let Some(filename) = self.file_name() {
            let mut filename = PathBuf::from(filename);
            filename.set_extension(extension);
            self.pop();
            self.0.push_str(filename.to_str().unwrap());
            true
        } else {
            false
        }
    }
}

impl<'de> Deserialize<'de> for RelPathBuf {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let path = String::deserialize(deserializer)?;
        let rel_path =
            RelPath::new(Path::new(&path), PathStyle::local()).map_err(serde::de::Error::custom)?;
        Ok(rel_path.into_owned())
    }
}

impl Into<Arc<RelPath>> for RelPathBuf {
    fn into(self) -> Arc<RelPath> {
        Arc::from(self.as_rel_path())
    }
}

impl AsRef<Path> for RelPathBuf {
    fn as_ref(&self) -> &Path {
        self.as_std_path()
    }
}

impl AsRef<Path> for RelPath {
    fn as_ref(&self) -> &Path {
        self.as_std_path()
    }
}

impl AsRef<RelPath> for RelPathBuf {
    fn as_ref(&self) -> &RelPath {
        self.as_rel_path()
    }
}

impl AsRef<RelPath> for RelPath {
    fn as_ref(&self) -> &RelPath {
        self
    }
}

impl Deref for RelPathBuf {
    type Target = RelPath;

    fn deref(&self) -> &Self::Target {
        self.as_ref()
    }
}

impl<'a> From<&'a RelPath> for Cow<'a, RelPath> {
    fn from(value: &'a RelPath) -> Self {
        Self::Borrowed(value)
    }
}

impl From<&RelPath> for Arc<RelPath> {
    fn from(rel_path: &RelPath) -> Self {
        let bytes: Arc<str> = Arc::from(&rel_path.0);
        unsafe { Arc::from_raw(Arc::into_raw(bytes) as *const RelPath) }
    }
}

#[cfg(any(test, feature = "test-support"))]
#[track_caller]
pub fn rel_path(path: &str) -> &RelPath {
    RelPath::unix(path).unwrap()
}

#[cfg(any(test, feature = "test-support"))]
#[track_caller]
pub fn rel_path_buf(path: &str) -> RelPathBuf {
    RelPath::unix(path).unwrap().to_rel_path_buf()
}

impl PartialEq<str> for RelPath {
    fn eq(&self, other: &str) -> bool {
        self.0 == *other
    }
}

pub trait PathExt {
    fn to_rel_path_buf(&self) -> Result<RelPathBuf>;
}

impl<T: AsRef<Path> + ?Sized> PathExt for T {
    fn to_rel_path_buf(&self) -> Result<RelPathBuf> {
        Ok(RelPath::new(self.as_ref(), PathStyle::local())?.into_owned())
    }
}

#[derive(Default)]
pub struct RelPathComponents<'a>(&'a str);

pub struct RelPathAncestors<'a>(Option<&'a str>);

const SEPARATOR: char = '/';

impl<'a> RelPathComponents<'a> {
    pub fn rest(&self) -> &'a RelPath {
        RelPath::new_unchecked(self.0)
    }
}

impl<'a> Iterator for RelPathComponents<'a> {
    type Item = &'a str;

    fn next(&mut self) -> Option<Self::Item> {
        if let Some(sep_ix) = self.0.find(SEPARATOR) {
            let (head, tail) = self.0.split_at(sep_ix);
            self.0 = &tail[1..];
            Some(head)
        } else if self.0.is_empty() {
            None
        } else {
            let result = self.0;
            self.0 = "";
            Some(result)
        }
    }
}

impl<'a> Iterator for RelPathAncestors<'a> {
    type Item = &'a RelPath;

    fn next(&mut self) -> Option<Self::Item> {
        let result = self.0?;
        if let Some(sep_ix) = result.rfind(SEPARATOR) {
            self.0 = Some(&result[..sep_ix]);
        } else if !result.is_empty() {
            self.0 = Some("");
        } else {
            self.0 = None;
        }
        Some(RelPath::new_unchecked(result))
    }
}

impl<'a> DoubleEndedIterator for RelPathComponents<'a> {
    fn next_back(&mut self) -> Option<Self::Item> {
        if let Some(sep_ix) = self.0.rfind(SEPARATOR) {
            let (head, tail) = self.0.split_at(sep_ix);
            self.0 = head;
            Some(&tail[1..])
        } else if self.0.is_empty() {
            None
        } else {
            let result = self.0;
            self.0 = "";
            Some(result)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use itertools::Itertools;
    use pretty_assertions::assert_matches;

    #[test]
    fn test_rel_path_new() {
        assert!(RelPath::new(Path::new("/"), PathStyle::local()).is_err());
        assert!(RelPath::new(Path::new("//"), PathStyle::local()).is_err());
        assert!(RelPath::new(Path::new("/foo/"), PathStyle::local()).is_err());

        let path = RelPath::new("foo/".as_ref(), PathStyle::local()).unwrap();
        assert_eq!(path, rel_path("foo").into());
        assert_matches!(path, Cow::Borrowed(_));

        let path = RelPath::new("foo\\".as_ref(), PathStyle::Windows).unwrap();
        assert_eq!(path, rel_path("foo").into());
        assert_matches!(path, Cow::Borrowed(_));

        assert_eq!(
            RelPath::new("foo/bar/../baz/./quux/".as_ref(), PathStyle::local())
                .unwrap()
                .as_ref(),
            rel_path("foo/baz/quux")
        );

        let path = RelPath::new("./foo/bar".as_ref(), PathStyle::Posix).unwrap();
        assert_eq!(path.as_ref(), rel_path("foo/bar"));
        assert_matches!(path, Cow::Borrowed(_));

        let path = RelPath::new(".\\foo".as_ref(), PathStyle::Windows).unwrap();
        assert_eq!(path, rel_path("foo").into());
        assert_matches!(path, Cow::Borrowed(_));

        let path = RelPath::new("./.\\./foo/\\/".as_ref(), PathStyle::Windows).unwrap();
        assert_eq!(path, rel_path("foo").into());
        assert_matches!(path, Cow::Borrowed(_));

        let path = RelPath::new("foo/./bar".as_ref(), PathStyle::Posix).unwrap();
        assert_eq!(path.as_ref(), rel_path("foo/bar"));
        assert_matches!(path, Cow::Owned(_));

        let path = RelPath::new("./foo/bar".as_ref(), PathStyle::Windows).unwrap();
        assert_eq!(path.as_ref(), rel_path("foo/bar"));
        assert_matches!(path, Cow::Borrowed(_));

        let path = RelPath::new(".\\foo\\bar".as_ref(), PathStyle::Windows).unwrap();
        assert_eq!(path.as_ref(), rel_path("foo/bar"));
        assert_matches!(path, Cow::Owned(_));
    }

    #[test]
    fn test_rel_path_components() {
        let path = rel_path("foo/bar/baz");
        assert_eq!(
            path.components().collect::<Vec<_>>(),
            vec!["foo", "bar", "baz"]
        );
        assert_eq!(
            path.components().rev().collect::<Vec<_>>(),
            vec!["baz", "bar", "foo"]
        );

        let path = rel_path("");
        let mut components = path.components();
        assert_eq!(components.next(), None);
    }

    #[test]
    fn test_rel_path_ancestors() {
        let path = rel_path("foo/bar/baz");
        let mut ancestors = path.ancestors();
        assert_eq!(ancestors.next(), Some(rel_path("foo/bar/baz")));
        assert_eq!(ancestors.next(), Some(rel_path("foo/bar")));
        assert_eq!(ancestors.next(), Some(rel_path("foo")));
        assert_eq!(ancestors.next(), Some(rel_path("")));
        assert_eq!(ancestors.next(), None);

        let path = rel_path("foo");
        let mut ancestors = path.ancestors();
        assert_eq!(ancestors.next(), Some(rel_path("foo")));
        assert_eq!(ancestors.next(), Some(RelPath::empty()));
        assert_eq!(ancestors.next(), None);

        let path = RelPath::empty();
        let mut ancestors = path.ancestors();
        assert_eq!(ancestors.next(), Some(RelPath::empty()));
        assert_eq!(ancestors.next(), None);
    }

    #[test]
    fn test_rel_path_parent() {
        assert_eq!(rel_path("foo/bar/baz").parent(), Some(rel_path("foo/bar")));
        assert_eq!(rel_path("foo").parent(), Some(RelPath::empty()));
        assert_eq!(rel_path("").parent(), None);
    }

    #[test]
    fn test_rel_path_partial_ord_is_compatible_with_std() {
        let test_cases = ["a/b/c", "relative/path/with/dot.", "relative/path/with.dot"];
        for [lhs, rhs] in test_cases.iter().array_combinations::<2>() {
            assert_eq!(
                Path::new(lhs).cmp(Path::new(rhs)),
                RelPath::unix(lhs)
                    .unwrap()
                    .cmp(&RelPath::unix(rhs).unwrap())
            );
        }
    }

    #[test]
    fn test_strip_prefix() {
        let parent = rel_path("");
        let child = rel_path(".foo");

        assert!(child.starts_with(parent));
        assert_eq!(child.strip_prefix(parent).unwrap(), child);
    }

    #[test]
    fn test_rel_path_constructors_absolute_path() {
        assert!(RelPath::new(Path::new("/a/b"), PathStyle::Windows).is_err());
        assert!(RelPath::new(Path::new("\\a\\b"), PathStyle::Windows).is_err());
        assert!(RelPath::new(Path::new("/a/b"), PathStyle::Posix).is_err());
        assert!(RelPath::new(Path::new("C:/a/b"), PathStyle::Windows).is_err());
        assert!(RelPath::new(Path::new("C:\\a\\b"), PathStyle::Windows).is_err());
        assert!(RelPath::new(Path::new("C:/a/b"), PathStyle::Posix).is_ok());
    }

    #[test]
    fn test_pop() {
        let mut path = rel_path("a/b").to_rel_path_buf();
        path.pop();
        assert_eq!(path.as_rel_path().as_unix_str(), "a");
        path.pop();
        assert_eq!(path.as_rel_path().as_unix_str(), "");
        path.pop();
        assert_eq!(path.as_rel_path().as_unix_str(), "");
    }
}