repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fs/src/hash.rs | yazi-fs/src/hash.rs | use std::hash::{BuildHasher, Hash};
use yazi_shared::url::AsUrl;
use yazi_shim::Twox128;
use crate::{File, cha::Cha};
pub trait FsHash64 {
fn hash_u64(&self) -> u64;
}
impl FsHash64 for File {
fn hash_u64(&self) -> u64 { foldhash::fast::FixedState::default().hash_one(self) }
}
impl<T: AsUrl> FsHash64 for T {
fn hash_u64(&self) -> u64 { foldhash::fast::FixedState::default().hash_one(self.as_url()) }
}
// Hash128
pub trait FsHash128 {
fn hash_u128(&self) -> u128;
}
impl FsHash128 for Cha {
fn hash_u128(&self) -> u128 {
let mut h = Twox128::default();
self.len.hash(&mut h);
self.btime_dur().ok().map(|d| d.as_nanos()).hash(&mut h);
self.mtime_dur().ok().map(|d| d.as_nanos()).hash(&mut h);
h.finish_128()
}
}
impl<T: AsUrl> FsHash128 for T {
fn hash_u128(&self) -> u128 {
let mut h = Twox128::default();
self.as_url().hash(&mut h);
h.finish_128()
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fs/src/files.rs | yazi-fs/src/files.rs | use std::{mem, ops::{Deref, DerefMut, Not}};
use hashbrown::{HashMap, HashSet};
use yazi_shared::{Id, path::{PathBufDyn, PathDyn}};
use super::{FilesSorter, Filter};
use crate::{FILES_TICKET, File, SortBy};
#[derive(Default)]
pub struct Files {
hidden: Vec<File>,
items: Vec<File>,
ticket: Id,
version: u64,
pub revision: u64,
pub sizes: HashMap<PathBufDyn, u64>,
sorter: FilesSorter,
filter: Option<Filter>,
show_hidden: bool,
}
impl Deref for Files {
type Target = Vec<File>;
fn deref(&self) -> &Self::Target { &self.items }
}
impl DerefMut for Files {
fn deref_mut(&mut self) -> &mut Self::Target { &mut self.items }
}
impl Files {
pub fn new(show_hidden: bool) -> Self { Self { show_hidden, ..Default::default() } }
pub fn update_full(&mut self, files: Vec<File>) {
self.ticket = FILES_TICKET.next();
let (hidden, items) = self.split_files(files);
if !(items.is_empty() && self.items.is_empty()) {
self.revision += 1;
}
(self.hidden, self.items) = (hidden, items);
}
pub fn update_part(&mut self, files: Vec<File>, ticket: Id) {
if !files.is_empty() {
if ticket != self.ticket {
return;
}
let (hidden, items) = self.split_files(files);
if !items.is_empty() {
self.revision += 1;
}
self.hidden.extend(hidden);
self.items.extend(items);
return;
}
self.ticket = ticket;
self.hidden.clear();
if !self.items.is_empty() {
self.revision += 1;
self.items.clear();
}
}
pub fn update_size(&mut self, mut sizes: HashMap<PathBufDyn, u64>) {
if sizes.len() <= 50 {
sizes.retain(|k, v| self.sizes.get(k) != Some(v));
}
if sizes.is_empty() {
return;
}
if self.sorter.by == SortBy::Size {
self.revision += 1;
}
self.sizes.extend(sizes);
}
pub fn update_ioerr(&mut self) {
self.ticket = FILES_TICKET.next();
self.hidden.clear();
self.items.clear();
}
pub fn update_creating(&mut self, files: Vec<File>) {
if files.is_empty() {
return;
}
macro_rules! go {
($dist:expr, $src:expr, $inc:literal) => {
let mut todo: HashMap<_, _> = $src.into_iter().map(|f| (f.urn().to_owned(), f)).collect();
for f in &$dist {
if todo.remove(&f.urn()).is_some() && todo.is_empty() {
break;
}
}
if !todo.is_empty() {
self.revision += $inc;
$dist.extend(todo.into_values());
}
};
}
let (hidden, items) = self.split_files(files);
if !items.is_empty() {
go!(self.items, items, 1);
}
if !hidden.is_empty() {
go!(self.hidden, hidden, 0);
}
}
#[cfg(unix)]
pub fn update_deleting(&mut self, urns: HashSet<PathBufDyn>) -> Vec<usize> {
use yazi_shared::path::PathLike;
if urns.is_empty() {
return vec![];
}
let (mut hidden, mut items) = if let Some(filter) = &self.filter {
urns.into_iter().partition(|u| (!self.show_hidden && u.is_hidden()) || !filter.matches(u))
} else if self.show_hidden {
(HashSet::new(), urns)
} else {
urns.into_iter().partition(|u| u.is_hidden())
};
let mut deleted = Vec::with_capacity(items.len());
if !items.is_empty() {
let mut i = 0;
self.items.retain(|f| {
let b = items.remove(&f.urn());
if b {
deleted.push(i);
}
i += 1;
!b
});
}
if !hidden.is_empty() {
self.hidden.retain(|f| !hidden.remove(&f.urn()));
}
self.revision += deleted.is_empty().not() as u64;
deleted
}
#[cfg(windows)]
pub fn update_deleting(&mut self, mut urns: HashSet<PathBufDyn>) -> Vec<usize> {
let mut deleted = Vec::with_capacity(urns.len());
if !urns.is_empty() {
let mut i = 0;
self.items.retain(|f| {
let b = urns.remove(&f.urn());
if b {
deleted.push(i)
}
i += 1;
!b
});
}
if !urns.is_empty() {
self.hidden.retain(|f| !urns.remove(&f.urn()));
}
self.revision += deleted.is_empty().not() as u64;
deleted
}
pub fn update_updating(
&mut self,
files: HashMap<PathBufDyn, File>,
) -> (HashMap<PathBufDyn, File>, HashMap<PathBufDyn, File>) {
if files.is_empty() {
return Default::default();
}
macro_rules! go {
($dist:expr, $src:expr, $inc:literal) => {
let mut b = true;
for i in 0..$dist.len() {
if let Some(f) = $src.remove(&$dist[i].urn()) {
b = b && $dist[i].cha.hits(f.cha);
b = b && $dist[i].urn() == f.urn();
$dist[i] = f;
if $src.is_empty() {
break;
}
}
}
self.revision += if b { 0 } else { $inc };
};
}
let (mut hidden, mut items) = if let Some(filter) = &self.filter {
files
.into_iter()
.partition(|(_, f)| (f.is_hidden() && !self.show_hidden) || !filter.matches(f.urn()))
} else if self.show_hidden {
(HashMap::new(), files)
} else {
files.into_iter().partition(|(_, f)| f.is_hidden())
};
if !items.is_empty() {
go!(self.items, items, 1);
}
if !hidden.is_empty() {
go!(self.hidden, hidden, 0);
}
(hidden, items)
}
pub fn update_upserting(&mut self, files: HashMap<PathBufDyn, File>) {
if files.is_empty() {
return;
}
self.update_deleting(
files.iter().filter(|&(u, f)| u != f.urn()).map(|(_, f)| f.urn().into()).collect(),
);
let (hidden, items) = self.update_updating(files);
if hidden.is_empty() && items.is_empty() {
return;
}
if !hidden.is_empty() {
self.hidden.extend(hidden.into_values());
}
if !items.is_empty() {
self.revision += 1;
self.items.extend(items.into_values());
}
}
pub fn catchup_revision(&mut self) -> bool {
if self.version == self.revision {
return false;
}
self.version = self.revision;
self.sorter.sort(&mut self.items, &self.sizes);
true
}
fn split_files(&self, files: impl IntoIterator<Item = File>) -> (Vec<File>, Vec<File>) {
if let Some(filter) = &self.filter {
files
.into_iter()
.partition(|f| (f.is_hidden() && !self.show_hidden) || !filter.matches(f.urn()))
} else if self.show_hidden {
(vec![], files.into_iter().collect())
} else {
files.into_iter().partition(|f| f.is_hidden())
}
}
}
impl Files {
// --- Items
#[inline]
pub fn position(&self, urn: PathDyn) -> Option<usize> { self.iter().position(|f| urn == f.urn()) }
// --- Ticket
#[inline]
pub fn ticket(&self) -> Id { self.ticket }
// --- Sorter
#[inline]
pub fn sorter(&self) -> &FilesSorter { &self.sorter }
pub fn set_sorter(&mut self, sorter: FilesSorter) {
if self.sorter != sorter {
self.sorter = sorter;
self.revision += 1;
}
}
// --- Filter
#[inline]
pub fn filter(&self) -> Option<&Filter> { self.filter.as_ref() }
pub fn set_filter(&mut self, filter: Option<Filter>) -> bool {
if self.filter == filter {
return false;
}
self.filter = filter;
if self.filter.is_none() {
let take = mem::take(&mut self.hidden);
let (hidden, items) = self.split_files(take);
self.hidden = hidden;
if !items.is_empty() {
self.items.extend(items);
self.sorter.sort(&mut self.items, &self.sizes);
}
return true;
}
let it = mem::take(&mut self.items).into_iter().chain(mem::take(&mut self.hidden));
(self.hidden, self.items) = self.split_files(it);
self.sorter.sort(&mut self.items, &self.sizes);
true
}
// --- Show hidden
pub fn set_show_hidden(&mut self, state: bool) {
if self.show_hidden == state {
return;
}
self.show_hidden = state;
if self.show_hidden && self.hidden.is_empty() {
return;
} else if !self.show_hidden && self.items.is_empty() {
return;
}
let take =
if self.show_hidden { mem::take(&mut self.hidden) } else { mem::take(&mut self.items) };
let (hidden, items) = self.split_files(take);
self.hidden.extend(hidden);
if !items.is_empty() {
self.revision += 1;
self.items.extend(items);
}
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fs/src/sorter.rs | yazi-fs/src/sorter.rs | use std::cmp::Ordering;
use hashbrown::HashMap;
use rand::{RngCore, SeedableRng, rngs::SmallRng};
use yazi_shared::{natsort, path::PathBufDyn, translit::Transliterator, url::UrlLike};
use crate::{File, SortBy};
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct FilesSorter {
pub by: SortBy,
pub sensitive: bool,
pub reverse: bool,
pub dir_first: bool,
pub translit: bool,
}
impl FilesSorter {
pub(super) fn sort(&self, items: &mut [File], sizes: &HashMap<PathBufDyn, u64>) {
if items.is_empty() {
return;
}
let by_alphabetical = |a: &File, b: &File| {
if self.sensitive {
self.cmp(a.urn().encoded_bytes(), b.urn().encoded_bytes(), self.promote(a, b))
} else {
self.cmp_insensitive(a.urn().encoded_bytes(), b.urn().encoded_bytes(), self.promote(a, b))
}
};
match self.by {
SortBy::None => {}
SortBy::Mtime => items.sort_unstable_by(|a, b| {
let ord = self.cmp(a.mtime, b.mtime, self.promote(a, b));
if ord == Ordering::Equal { by_alphabetical(a, b) } else { ord }
}),
SortBy::Btime => items.sort_unstable_by(|a, b| {
let ord = self.cmp(a.btime, b.btime, self.promote(a, b));
if ord == Ordering::Equal { by_alphabetical(a, b) } else { ord }
}),
SortBy::Extension => items.sort_unstable_by(|a, b| {
let ord = if self.sensitive {
self.cmp(a.url.ext(), b.url.ext(), self.promote(a, b))
} else {
self.cmp_insensitive(
a.url.ext().map_or(&[], |s| s.encoded_bytes()),
b.url.ext().map_or(&[], |s| s.encoded_bytes()),
self.promote(a, b),
)
};
if ord == Ordering::Equal { by_alphabetical(a, b) } else { ord }
}),
SortBy::Alphabetical => items.sort_unstable_by(by_alphabetical),
SortBy::Natural => self.sort_naturally(items),
SortBy::Size => items.sort_unstable_by(|a, b| {
let aa = if a.is_dir() { sizes.get(&a.urn()).copied() } else { None };
let bb = if b.is_dir() { sizes.get(&b.urn()).copied() } else { None };
let ord = self.cmp(aa.unwrap_or(a.len), bb.unwrap_or(b.len), self.promote(a, b));
if ord == Ordering::Equal { by_alphabetical(a, b) } else { ord }
}),
SortBy::Random => {
let mut rng = SmallRng::from_os_rng();
items.sort_unstable_by(|a, b| self.cmp(rng.next_u64(), rng.next_u64(), self.promote(a, b)))
}
}
}
fn sort_naturally(&self, items: &mut [File]) {
items.sort_unstable_by(|a, b| {
let promote = self.promote(a, b);
if promote != Ordering::Equal {
return promote;
}
let ordering = if self.translit {
natsort(
a.urn().encoded_bytes().transliterate().as_bytes(),
b.urn().encoded_bytes().transliterate().as_bytes(),
!self.sensitive,
)
} else {
natsort(a.urn().encoded_bytes(), b.urn().encoded_bytes(), !self.sensitive)
};
if self.reverse { ordering.reverse() } else { ordering }
});
}
#[inline(always)]
#[allow(clippy::collapsible_else_if)]
fn cmp<T: Ord>(&self, a: T, b: T, promote: Ordering) -> Ordering {
if promote != Ordering::Equal {
promote
} else {
if self.reverse { b.cmp(&a) } else { a.cmp(&b) }
}
}
#[inline(always)]
fn cmp_insensitive(&self, a: &[u8], b: &[u8], promote: Ordering) -> Ordering {
if promote != Ordering::Equal {
return promote;
}
let l = a.len().min(b.len());
let (lhs, rhs) = if self.reverse { (&b[..l], &a[..l]) } else { (&a[..l], &b[..l]) };
for i in 0..l {
match lhs[i].to_ascii_lowercase().cmp(&rhs[i].to_ascii_lowercase()) {
Ordering::Equal => (),
not_eq => return not_eq,
}
}
if self.reverse { b.len().cmp(&a.len()) } else { a.len().cmp(&b.len()) }
}
#[inline(always)]
fn promote(&self, a: &File, b: &File) -> Ordering {
if self.dir_first { b.is_dir().cmp(&a.is_dir()) } else { Ordering::Equal }
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fs/src/scheme.rs | yazi-fs/src/scheme.rs | use std::path::PathBuf;
use yazi_shared::scheme::{AsScheme, Scheme, SchemeRef};
use crate::Xdg;
pub trait FsScheme {
fn cache(&self) -> Option<PathBuf>;
}
impl FsScheme for SchemeRef<'_> {
fn cache(&self) -> Option<PathBuf> {
match self {
Self::Regular { .. } | Self::Search { .. } => None,
Self::Archive { domain, .. } => Some(
Xdg::cache_dir().join(format!("archive-{}", yazi_shared::scheme::Encode::domain(domain))),
),
Self::Sftp { domain, .. } => {
Some(Xdg::cache_dir().join(format!("sftp-{}", yazi_shared::scheme::Encode::domain(domain))))
}
}
}
}
impl FsScheme for Scheme {
fn cache(&self) -> Option<PathBuf> { self.as_scheme().cache() }
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fs/src/fns.rs | yazi-fs/src/fns.rs | use tokio::io;
use yazi_shared::url::{Component, UrlBuf, UrlLike};
#[inline]
pub fn ok_or_not_found<T: Default>(result: io::Result<T>) -> io::Result<T> {
match result {
Ok(t) => Ok(t),
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(T::default()),
Err(_) => result,
}
}
// Find the max common root in a list of urls
// e.g. /a/b/c, /a/b/d -> /a/b
// /aa/bb/cc, /aa/dd/ee -> /aa
pub fn max_common_root(urls: &[UrlBuf]) -> usize {
if urls.is_empty() {
return 0;
} else if urls.len() == 1 {
return urls[0].components().count() - 1;
}
let mut it = urls.iter().map(|u| u.parent());
let Some(first) = it.next().unwrap() else {
return 0; // The first URL has no parent
};
let mut common = first.components().count();
for parent in it {
let Some(parent) = parent else {
return 0; // One of the URLs has no parent
};
common = first
.components()
.zip(parent.components())
.take_while(|(a, b)| match (a, b) {
(Component::Scheme(a), Component::Scheme(b)) => a.covariant(*b),
(a, b) => a == b,
})
.count()
.min(common);
if common == 0 {
break; // No common root found
}
}
common
}
#[cfg(unix)]
#[test]
fn test_max_common_root() {
fn assert(input: &[&str], expected: &str) {
use std::{ffi::OsStr, str::FromStr};
let urls: Vec<_> =
input.iter().copied().map(UrlBuf::from_str).collect::<Result<_, _>>().unwrap();
let mut comp = urls[0].components();
for _ in 0..comp.clone().count() - max_common_root(&urls) {
comp.next_back();
}
assert_eq!(comp.os_str(), OsStr::new(expected));
}
assert_eq!(max_common_root(&[]), 0);
assert(&[""], "");
assert(&["a"], "");
assert(&["/a"], "/");
assert(&["/a/b"], "/a");
assert(&["/a/b/c", "/a/b/d"], "/a/b");
assert(&["/aa/bb/cc", "/aa/dd/ee"], "/aa");
assert(&["/aa/bb/cc", "/aa/bb/cc/dd/ee", "/aa/bb/cc/ff"], "/aa/bb");
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fs/src/cwd.rs | yazi-fs/src/cwd.rs | use std::{borrow::Cow, env::{current_dir, set_current_dir}, ops::Deref, path::{Path, PathBuf}, sync::{Arc, atomic::{AtomicBool, Ordering}}};
use arc_swap::ArcSwap;
use yazi_shared::{RoCell, url::{AsUrl, Url, UrlBuf, UrlLike}};
use crate::{FsUrl, Xdg};
pub static CWD: RoCell<Cwd> = RoCell::new();
pub struct Cwd(ArcSwap<UrlBuf>);
impl Deref for Cwd {
type Target = ArcSwap<UrlBuf>;
fn deref(&self) -> &Self::Target { &self.0 }
}
impl Default for Cwd {
fn default() -> Self {
let p = std::env::var_os("PWD")
.map(PathBuf::from)
.filter(|p| p.is_absolute())
.or_else(|| current_dir().ok())
.expect("failed to get current working directory");
Self(ArcSwap::new(Arc::new(UrlBuf::from(p))))
}
}
impl Cwd {
pub fn path(&self) -> PathBuf { self.0.load().as_url().unified_path().into_owned() }
pub fn set(&self, url: &UrlBuf, callback: fn()) -> bool {
if !url.is_absolute() {
return false;
} else if self.0.load().as_ref() == url {
return false;
}
self.0.store(Arc::new(url.clone()));
Self::sync_cwd(callback);
true
}
pub fn ensure(url: Url) -> Cow<Path> {
use std::{io::ErrorKind::{AlreadyExists, NotADirectory, NotFound}, path::Component as C};
let Some(cache) = url.cache() else {
return url.unified_path();
};
if !matches!(std::fs::create_dir_all(&cache), Err(e) if e.kind() == NotADirectory || e.kind() == AlreadyExists)
{
return cache.into();
}
let latter = cache.strip_prefix(Xdg::cache_dir()).expect("under cache dir");
let mut it = latter.components().peekable();
while it.peek() == Some(&C::CurDir) {
it.next().unwrap();
}
let mut count = 0;
for c in it {
match c {
C::Prefix(_) | C::RootDir | C::ParentDir => return cache.into(),
C::CurDir | C::Normal(_) => count += 1,
}
}
for n in (0..count).rev() {
let mut it = cache.components();
for _ in 0..n {
it.next_back().unwrap();
}
match std::fs::remove_file(it.as_path()) {
Ok(_) => break,
Err(e) if e.kind() == NotFound => break,
Err(_) => {}
}
}
std::fs::create_dir_all(&cache).ok();
cache.into()
}
fn sync_cwd(callback: fn()) {
static SYNCING: AtomicBool = AtomicBool::new(false);
if SYNCING.swap(true, Ordering::Relaxed) {
return;
}
tokio::task::spawn_blocking(move || {
let cwd = CWD.load();
let path = Self::ensure(cwd.as_url());
set_current_dir(&path).ok();
let cur = current_dir().unwrap_or_default();
unsafe { std::env::set_var("PWD", path.as_ref()) }
SYNCING.store(false, Ordering::Relaxed);
let cwd = CWD.load();
let path = Self::ensure(cwd.as_url());
if cur != path {
set_current_dir(&path).ok();
unsafe { std::env::set_var("PWD", path.as_ref()) }
}
callback();
});
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fs/src/error/serde.rs | yazi-fs/src/error/serde.rs | use std::io;
use anyhow::{Result, bail};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use super::Error;
pub(super) fn kind_to_str(kind: io::ErrorKind) -> &'static str {
use std::io::ErrorKind as K;
match kind {
K::NotFound => "NotFound",
K::PermissionDenied => "PermissionDenied",
K::ConnectionRefused => "ConnectionRefused",
K::ConnectionReset => "ConnectionReset",
K::HostUnreachable => "HostUnreachable",
K::NetworkUnreachable => "NetworkUnreachable",
K::ConnectionAborted => "ConnectionAborted",
K::NotConnected => "NotConnected",
K::AddrInUse => "AddrInUse",
K::AddrNotAvailable => "AddrNotAvailable",
K::NetworkDown => "NetworkDown",
K::BrokenPipe => "BrokenPipe",
K::AlreadyExists => "AlreadyExists",
K::WouldBlock => "WouldBlock",
K::NotADirectory => "NotADirectory",
K::IsADirectory => "IsADirectory",
K::DirectoryNotEmpty => "DirectoryNotEmpty",
K::ReadOnlyFilesystem => "ReadOnlyFilesystem",
// K::FilesystemLoop => "FilesystemLoop",
K::StaleNetworkFileHandle => "StaleNetworkFileHandle",
K::InvalidInput => "InvalidInput",
K::InvalidData => "InvalidData",
K::TimedOut => "TimedOut",
K::WriteZero => "WriteZero",
K::StorageFull => "StorageFull",
K::NotSeekable => "NotSeekable",
K::QuotaExceeded => "QuotaExceeded",
K::FileTooLarge => "FileTooLarge",
K::ResourceBusy => "ResourceBusy",
K::ExecutableFileBusy => "ExecutableFileBusy",
K::Deadlock => "Deadlock",
K::CrossesDevices => "CrossesDevices",
K::TooManyLinks => "TooManyLinks",
K::InvalidFilename => "InvalidFilename",
K::ArgumentListTooLong => "ArgumentListTooLong",
K::Interrupted => "Interrupted",
K::Unsupported => "Unsupported",
K::UnexpectedEof => "UnexpectedEof",
K::OutOfMemory => "OutOfMemory",
// K::InProgress => "InProgress",
K::Other => "Other",
_ => "Other",
}
}
pub(super) fn kind_from_str(s: &str) -> Result<io::ErrorKind> {
use std::io::ErrorKind as K;
Ok(match s {
"NotFound" => K::NotFound,
"PermissionDenied" => K::PermissionDenied,
"ConnectionRefused" => K::ConnectionRefused,
"ConnectionReset" => K::ConnectionReset,
"HostUnreachable" => K::HostUnreachable,
"NetworkUnreachable" => K::NetworkUnreachable,
"ConnectionAborted" => K::ConnectionAborted,
"NotConnected" => K::NotConnected,
"AddrInUse" => K::AddrInUse,
"AddrNotAvailable" => K::AddrNotAvailable,
"NetworkDown" => K::NetworkDown,
"BrokenPipe" => K::BrokenPipe,
"AlreadyExists" => K::AlreadyExists,
"WouldBlock" => K::WouldBlock,
"NotADirectory" => K::NotADirectory,
"IsADirectory" => K::IsADirectory,
"DirectoryNotEmpty" => K::DirectoryNotEmpty,
"ReadOnlyFilesystem" => K::ReadOnlyFilesystem,
// "FilesystemLoop" => K::FilesystemLoop,
"StaleNetworkFileHandle" => K::StaleNetworkFileHandle,
"InvalidInput" => K::InvalidInput,
"InvalidData" => K::InvalidData,
"TimedOut" => K::TimedOut,
"WriteZero" => K::WriteZero,
"StorageFull" => K::StorageFull,
"NotSeekable" => K::NotSeekable,
"QuotaExceeded" => K::QuotaExceeded,
"FileTooLarge" => K::FileTooLarge,
"ResourceBusy" => K::ResourceBusy,
"ExecutableFileBusy" => K::ExecutableFileBusy,
"Deadlock" => K::Deadlock,
"CrossesDevices" => K::CrossesDevices,
"TooManyLinks" => K::TooManyLinks,
"InvalidFilename" => K::InvalidFilename,
"ArgumentListTooLong" => K::ArgumentListTooLong,
"Interrupted" => K::Interrupted,
"Unsupported" => K::Unsupported,
"UnexpectedEof" => K::UnexpectedEof,
"OutOfMemory" => K::OutOfMemory,
// "InProgress" => K::InProgress,
"Other" => K::Other,
_ => bail!("unknown error kind: {s}"),
})
}
impl Serialize for Error {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
#[derive(Serialize)]
#[serde(tag = "type", rename_all = "kebab-case")]
enum Shadow<'a> {
Kind { kind: &'a str },
Raw { code: i32 },
Dyn { kind: &'a str, code: Option<i32>, message: &'a str },
}
match self {
Self::Kind(kind) => Shadow::Kind { kind: kind_to_str(*kind) }.serialize(serializer),
Self::Raw(code) => Shadow::Raw { code: *code }.serialize(serializer),
Self::Custom { kind, code, message } => {
Shadow::Dyn { kind: kind_to_str(*kind), code: *code, message }.serialize(serializer)
}
}
}
}
impl<'de> Deserialize<'de> for Error {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
#[derive(Deserialize)]
#[serde(tag = "type", rename_all = "kebab-case")]
enum Shadow {
Kind { kind: String },
Raw { code: i32 },
Dyn { kind: String, code: Option<i32>, message: String },
}
let shadow = Shadow::deserialize(deserializer)?;
Ok(match shadow {
Shadow::Kind { kind } => Self::Kind(kind_from_str(&kind).map_err(serde::de::Error::custom)?),
Shadow::Raw { code } => Self::Raw(code),
Shadow::Dyn { kind, code, message } => {
if !message.is_empty() {
Self::Custom {
kind: kind_from_str(&kind).map_err(serde::de::Error::custom)?,
code,
message: message.into(),
}
} else if let Some(code) = code {
Self::Raw(code)
} else {
Self::Kind(kind_from_str(&kind).map_err(serde::de::Error::custom)?)
}
}
})
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fs/src/error/error.rs | yazi-fs/src/error/error.rs | use std::{fmt, io, sync::Arc};
use anyhow::Result;
use crate::error::{kind_from_str, kind_to_str};
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Error {
Kind(io::ErrorKind),
Raw(i32),
Custom { kind: io::ErrorKind, code: Option<i32>, message: Arc<str> },
}
impl From<io::Error> for Error {
fn from(err: io::Error) -> Self {
if err.get_ref().is_some() {
Self::Custom {
kind: err.kind(),
code: err.raw_os_error(),
message: err.to_string().into(),
}
} else if let Some(code) = err.raw_os_error() {
Self::Raw(code)
} else {
Self::Kind(err.kind())
}
}
}
impl From<io::ErrorKind> for Error {
fn from(kind: io::ErrorKind) -> Self { Self::Kind(kind) }
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Kind(kind) => io::Error::from(*kind).fmt(f),
Self::Raw(code) => io::Error::from_raw_os_error(*code).fmt(f),
Self::Custom { message, .. } => write!(f, "{message}"),
}
}
}
impl Error {
pub fn custom(kind: &str, code: Option<i32>, message: &str) -> Result<Self> {
Ok(Self::Custom { kind: kind_from_str(kind)?, code, message: message.into() })
}
pub fn kind(&self) -> io::ErrorKind {
match self {
Self::Kind(kind) => *kind,
Self::Raw(code) => io::Error::from_raw_os_error(*code).kind(),
Self::Custom { kind, .. } => *kind,
}
}
pub fn kind_str(&self) -> &'static str { kind_to_str(self.kind()) }
pub fn raw_os_error(&self) -> Option<i32> {
match self {
Self::Kind(_) => None,
Self::Raw(code) => Some(*code),
Self::Custom { code, .. } => *code,
}
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fs/src/error/mod.rs | yazi-fs/src/error/mod.rs | yazi_macro::mod_flat!(error serde);
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fs/src/mounts/partitions.rs | yazi-fs/src/mounts/partitions.rs | use std::ops::Deref;
use parking_lot::RwLock;
use yazi_shared::RoCell;
use super::Partition;
use crate::cha::Cha;
pub(super) type Locked = RwLock<Partitions>;
pub static PARTITIONS: RoCell<Locked> = RoCell::new();
#[derive(Default)]
pub struct Partitions {
pub(super) inner: Vec<Partition>,
#[cfg(target_os = "linux")]
pub(super) linux_cache: hashbrown::HashSet<String>,
#[cfg(target_os = "macos")]
pub(super) need_update: bool,
}
impl Deref for Partitions {
type Target = Vec<Partition>;
fn deref(&self) -> &Self::Target { &self.inner }
}
impl Partitions {
#[cfg(unix)]
pub fn by_dev(&self, dev: u64) -> Option<&Partition> {
self.inner.iter().find(|p| p.rdev == Some(dev))
}
pub fn heuristic(&self, _cha: Cha) -> bool {
#[cfg(any(target_os = "linux", target_os = "macos"))]
{
self.by_dev(_cha.dev).is_none_or(|p| p.heuristic())
}
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
{
true
}
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fs/src/mounts/macos.rs | yazi-fs/src/mounts/macos.rs | use std::{ffi::{CStr, CString, OsString, c_void}, mem, os::unix::{ffi::OsStringExt, fs::MetadataExt}};
use anyhow::{Result, bail};
use core_foundation_sys::{array::CFArrayRef, base::{CFRelease, kCFAllocatorDefault}, runloop::{CFRunLoopGetCurrent, CFRunLoopRun, kCFRunLoopDefaultMode}};
use libc::{c_char, mach_port_t};
use objc2::{msg_send, runtime::AnyObject};
use scopeguard::defer;
use tracing::error;
use yazi_ffi::{CFDict, CFString, DADiskCopyDescription, DADiskCreateFromBSDName, DARegisterDiskAppearedCallback, DARegisterDiskDescriptionChangedCallback, DARegisterDiskDisappearedCallback, DASessionCreate, DASessionScheduleWithRunLoop, IOIteratorNext, IOObjectRelease, IORegistryEntryCreateCFProperty, IOServiceGetMatchingServices, IOServiceMatching};
use yazi_shared::natsort;
use super::{Locked, Partition, Partitions};
impl Partitions {
pub fn monitor<F>(me: &'static Locked, cb: F)
where
F: Fn() + Copy + Send + 'static,
{
tokio::task::spawn_blocking(move || {
let session = unsafe { DASessionCreate(kCFAllocatorDefault) };
if session.is_null() {
return error!("Cannot create a disk arbitration session");
}
defer! { unsafe { CFRelease(session) } };
extern "C" fn on_appeared(_disk: *const c_void, context: *mut c_void) {
let boxed = context as *mut Box<dyn Fn()>;
unsafe { (*boxed)() }
}
extern "C" fn on_changed(_disk: *const c_void, _keys: CFArrayRef, context: *mut c_void) {
let boxed = context as *mut Box<dyn Fn()>;
unsafe { (*boxed)() }
}
extern "C" fn on_disappeared(_disk: *const c_void, context: *mut c_void) {
let boxed = context as *mut Box<dyn Fn()>;
unsafe { (*boxed)() }
}
let create_context = || {
let boxed: Box<dyn Fn()> = Box::new(move || {
if mem::replace(&mut me.write().need_update, true) {
return;
}
Self::update(me, cb);
});
Box::into_raw(Box::new(boxed)) as *mut c_void
};
unsafe {
DARegisterDiskAppearedCallback(session, std::ptr::null(), on_appeared, create_context());
DARegisterDiskDescriptionChangedCallback(
session,
std::ptr::null(),
std::ptr::null(),
on_changed,
create_context(),
);
DARegisterDiskDisappearedCallback(
session,
std::ptr::null(),
on_disappeared,
create_context(),
);
DASessionScheduleWithRunLoop(session, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
CFRunLoopRun();
}
});
}
fn update(me: &'static Locked, cb: impl Fn() + Send + 'static) {
_ = tokio::task::spawn_blocking(move || {
let result = Self::all_names().and_then(Self::all_partitions);
if let Err(ref e) = result {
error!("Error encountered while updating mount points: {e:?}");
}
let mut guard = me.write();
if let Ok(new) = result {
guard.inner = new;
}
guard.need_update = false;
drop(guard);
cb();
});
}
fn all_partitions(names: Vec<CString>) -> Result<Vec<Partition>> {
let session = unsafe { DASessionCreate(kCFAllocatorDefault) };
if session.is_null() {
bail!("Cannot create a disk arbitration session");
}
defer! { unsafe { CFRelease(session) } };
let mut disks = Vec::with_capacity(names.len());
for name in names {
let disk = unsafe { DADiskCreateFromBSDName(kCFAllocatorDefault, session, name.as_ptr()) };
if disk.is_null() {
continue;
}
defer! { unsafe { CFRelease(disk) } };
let Ok(dict) = CFDict::take(unsafe { DADiskCopyDescription(disk) }) else {
continue;
};
let partition = Partition::new(&OsString::from_vec(name.into_bytes()));
let rdev = std::fs::metadata(&partition.src).map(|m| m.rdev() as _).ok();
disks.push(Partition {
dist: dict.path_buf("DAVolumePath").ok(),
rdev,
fstype: dict.os_string("DAVolumeKind").ok(),
label: dict.os_string("DAVolumeName").ok(),
capacity: dict.integer("DAMediaSize").unwrap_or_default() as u64,
external: dict.bool("DADeviceInternal").ok().map(|b| !b),
removable: dict.bool("DAMediaRemovable").ok(),
..partition
});
}
Ok(disks)
}
fn all_names() -> Result<Vec<CString>> {
let mut iterator: mach_port_t = 0;
let result = unsafe {
IOServiceGetMatchingServices(0, IOServiceMatching(c"IOService".as_ptr()), &mut iterator)
};
if result != 0 {
bail!("Cannot get the IO matching services");
}
defer! { unsafe { IOObjectRelease(iterator); } };
let mut names = vec![];
loop {
let service = unsafe { IOIteratorNext(iterator) };
if service == 0 {
break;
}
defer! { unsafe { IOObjectRelease(service); } };
if let Some(name) = Self::bsd_name(service).ok().filter(|s| s.as_bytes().starts_with(b"disk"))
{
names.push(name);
}
}
names.sort_unstable_by(|a, b| natsort(a.as_bytes(), b.as_bytes(), false));
Ok(names)
}
fn bsd_name(service: mach_port_t) -> Result<CString> {
let key = CFString::new("BSD Name")?;
let property =
unsafe { IORegistryEntryCreateCFProperty(service, *key, kCFAllocatorDefault, 1) };
if property.is_null() {
bail!("Cannot get the name property");
}
defer! { unsafe { CFRelease(property) } };
#[allow(unexpected_cfgs)]
let cstr: *const c_char = unsafe { msg_send![property as *const AnyObject, UTF8String] };
Ok(if cstr.is_null() {
bail!("Invalid value for the name property");
} else {
CString::from(unsafe { CStr::from_ptr(cstr) })
})
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fs/src/mounts/linux.rs | yazi-fs/src/mounts/linux.rs | use std::{borrow::Cow, ffi::{OsStr, OsString}, os::{fd::AsFd, unix::{ffi::{OsStrExt, OsStringExt}, fs::MetadataExt}}, time::Duration};
use anyhow::{Context, Result};
use hashbrown::{HashMap, HashSet};
use tokio::{io::{Interest, unix::AsyncFd}, time::sleep};
use tracing::error;
use yazi_shared::{natsort, replace_cow, replace_vec_cow};
use super::{Locked, Partition, Partitions};
impl Partitions {
pub fn monitor<F>(me: &'static Locked, cb: F)
where
F: Fn() + Copy + Send + 'static,
{
async fn wait_mounts(me: &'static Locked, cb: impl Fn()) -> Result<()> {
let f = std::fs::File::open("/proc/mounts")?;
let fd = AsyncFd::with_interest(f.as_fd(), Interest::READABLE)?;
loop {
let mut guard = fd.readable().await?;
guard.clear_ready();
Partitions::update(me).await;
cb();
}
}
async fn wait_partitions(me: &'static Locked, cb: impl Fn()) -> Result<()> {
loop {
let partitions = Partitions::partitions()?;
if me.read().linux_cache == partitions {
sleep(Duration::from_secs(3)).await;
continue;
}
me.write().linux_cache = partitions;
Partitions::update(me).await;
cb();
sleep(Duration::from_secs(3)).await;
}
}
tokio::spawn(async move {
loop {
if let Err(e) = wait_mounts(me, cb).await {
error!("Error encountered while monitoring /proc/mounts: {e:?}");
}
sleep(Duration::from_secs(5)).await;
}
});
tokio::spawn(async move {
loop {
if let Err(e) = wait_partitions(me, cb).await {
error!("Error encountered while monitoring /proc/partitions: {e:?}");
}
sleep(Duration::from_secs(5)).await;
}
});
}
fn partitions() -> Result<HashSet<String>> {
let mut set = HashSet::new();
let s = std::fs::read_to_string("/proc/partitions")?;
for line in s.lines().skip(2) {
let mut it = line.split_whitespace();
let Some(Ok(_major)) = it.next().map(|s| s.parse::<u16>()) else { continue };
let Some(Ok(_minor)) = it.next().map(|s| s.parse::<u16>()) else { continue };
let Some(Ok(_blocks)) = it.next().map(|s| s.parse::<u32>()) else { continue };
if let Some(name) = it.next() {
set.insert(Self::unmangle_octal(name).into_owned());
}
}
Ok(set)
}
async fn update(me: &'static Locked) {
_ = tokio::task::spawn_blocking(move || {
let mut guard = me.write();
match Self::all(&guard) {
Ok(new) => guard.inner = new,
Err(e) => error!("Error encountered while updating mount points: {e:?}"),
};
})
.await;
}
fn all(&self) -> Result<Vec<Partition>> {
let mut mounts = Self::mounts().context("Parsing /proc/mounts")?;
{
let set = &self.linux_cache;
let mut set: HashSet<&OsStr> = set.iter().map(AsRef::as_ref).collect();
mounts.iter().filter_map(|p| p.dev_name(true)).for_each(|s| _ = set.remove(s));
mounts.extend(set.into_iter().map(Partition::new));
mounts.sort_unstable_by(|a, b| natsort(a.src.as_bytes(), b.src.as_bytes(), false));
};
let mut removable: HashMap<OsString, Option<bool>> =
mounts.iter().filter_map(|p| p.dev_name(false)).map(|s| (s.to_owned(), None)).collect();
for (s, b) in &mut removable {
match std::fs::read(format!("/sys/block/{}/removable", s.to_string_lossy()))
.unwrap_or_default()
.trim_ascii()
{
b"0" => *b = Some(false),
b"1" => *b = Some(true),
_ => (),
}
}
let labels = Self::labels();
for mount in &mut mounts {
if !mount.src.as_bytes().starts_with(b"/dev/") {
continue;
}
if let Ok(meta) = std::fs::metadata(&mount.src) {
mount.rdev = Some(meta.rdev() as _);
mount.label = labels.get(&(meta.dev(), meta.ino())).cloned();
// TODO: mount.external
mount.removable = mount.dev_name(false).and_then(|s| removable.get(s).copied()).flatten();
}
}
Ok(mounts)
}
fn mounts() -> Result<Vec<Partition>> {
let mut vec = vec![];
let s = std::fs::read_to_string("/proc/mounts")?;
for line in s.lines() {
let mut it = line.split_whitespace();
let Some(src) = it.next() else { continue };
let Some(dist) = it.next() else { continue };
let Some(fstype) = it.next() else { continue };
vec.push(Partition {
src: Self::unmangle_octal(src).into_owned().into(),
dist: Some(Self::unmangle_octal(dist).into_owned().into()),
fstype: Some(Self::unmangle_octal(fstype).into_owned().into()),
..Default::default()
});
}
Ok(vec)
}
fn labels() -> HashMap<(u64, u64), OsString> {
let mut map = HashMap::new();
let Ok(it) = std::fs::read_dir("/dev/disk/by-label") else {
error!("Cannot read /dev/disk/by-label");
return map;
};
for entry in it.flatten() {
let Ok(meta) = std::fs::metadata(entry.path()) else { continue };
let name = entry.file_name();
map.insert(
(meta.dev(), meta.ino()),
match replace_vec_cow(name.as_bytes(), br"\x20", b" ") {
Cow::Borrowed(_) => name,
Cow::Owned(v) => OsString::from_vec(v),
},
);
}
map
}
// Unmangle '\t', '\n', ' ', '#', and r'\'
// https://elixir.bootlin.com/linux/v6.13-rc3/source/fs/proc_namespace.c#L89
fn unmangle_octal(s: &str) -> Cow<'_, str> {
let mut s = Cow::Borrowed(s);
for (a, b) in
[(r"\011", "\t"), (r"\012", "\n"), (r"\040", " "), (r"\043", "#"), (r"\134", r"\")]
{
s = replace_cow(s, a, b);
}
s
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fs/src/mounts/partition.rs | yazi-fs/src/mounts/partition.rs | use std::{ffi::OsString, path::PathBuf};
#[derive(Debug, Default)]
pub struct Partition {
pub src: OsString,
pub dist: Option<PathBuf>,
#[cfg(unix)]
pub rdev: Option<u64>,
pub label: Option<OsString>,
pub fstype: Option<OsString>,
pub capacity: u64,
pub external: Option<bool>,
pub removable: Option<bool>,
}
impl Partition {
pub fn heuristic(&self) -> bool {
let b: &[u8] = self.fstype.as_ref().map_or(b"", |s| s.as_encoded_bytes());
!matches!(b, b"exfat" | b"fuse.rclone")
}
#[rustfmt::skip]
pub fn systemic(&self) -> bool {
let _b: &[u8] = self.fstype.as_ref().map_or(b"", |s| s.as_encoded_bytes());
#[cfg(target_os = "linux")]
{
matches!(_b, b"autofs" | b"binfmt_misc" | b"bpf" | b"cgroup2" | b"configfs" | b"debugfs" | b"devpts" | b"devtmpfs" | b"fuse.gvfsd-fuse" | b"fusectl" | b"hugetlbfs" | b"mqueue" | b"proc" | b"pstore" | b"ramfs" | b"securityfs" | b"sysfs" | b"tmpfs" | b"tracefs")
}
#[cfg(target_os = "macos")]
{
_b.is_empty()
}
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
{
false
}
}
}
impl Partition {
#[cfg(any(target_os = "linux", target_os = "macos"))]
pub(super) fn new(name: &std::ffi::OsStr) -> Self {
Self { src: std::path::Path::new("/dev/").join(name).into(), ..Default::default() }
}
#[cfg(target_os = "linux")]
pub(super) fn dev_name(&self, full: bool) -> Option<&std::ffi::OsStr> {
use std::os::unix::ffi::OsStrExt;
let s = std::path::Path::new(&self.src).strip_prefix("/dev/").ok()?.as_os_str();
if full {
return Some(s);
}
let b = s.as_bytes();
if b.len() < 3 {
None
} else if b.starts_with(b"sd") || b.starts_with(b"hd") || b.starts_with(b"vd") {
Some(std::ffi::OsStr::from_bytes(&b[..3]))
} else if b.starts_with(b"nvme") || b.starts_with(b"mmcblk") {
let n = b.iter().position(|&b| b == b'p').unwrap_or(b.len());
Some(std::ffi::OsStr::from_bytes(&b[..n]))
} else {
None
}
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fs/src/mounts/mod.rs | yazi-fs/src/mounts/mod.rs | yazi_macro::mod_flat!(partition partitions);
#[cfg(target_os = "linux")]
yazi_macro::mod_flat!(linux);
#[cfg(target_os = "macos")]
yazi_macro::mod_flat!(macos);
pub(super) fn init() { PARTITIONS.init(<_>::default()); }
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fs/src/cha/type.rs | yazi-fs/src/cha/type.rs | use std::fs::FileType;
use crate::cha::ChaMode;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ChaType {
File,
Dir,
Link,
Block,
Char,
Sock,
FIFO,
Unknown,
}
impl From<ChaMode> for ChaType {
fn from(value: ChaMode) -> Self { *value }
}
impl From<FileType> for ChaType {
fn from(value: FileType) -> Self {
#[cfg(unix)]
{
use std::os::unix::fs::FileTypeExt;
if value.is_file() {
Self::File
} else if value.is_dir() {
Self::Dir
} else if value.is_symlink() {
Self::Link
} else if value.is_block_device() {
Self::Block
} else if value.is_char_device() {
Self::Char
} else if value.is_socket() {
Self::Sock
} else if value.is_fifo() {
Self::FIFO
} else {
Self::Unknown
}
}
#[cfg(windows)]
{
if value.is_file() {
Self::File
} else if value.is_dir() {
Self::Dir
} else if value.is_symlink() {
Self::Link
} else {
Self::Unknown
}
}
}
}
impl ChaType {
#[inline]
pub fn is_file(self) -> bool { self == Self::File }
#[inline]
pub fn is_dir(self) -> bool { self == Self::Dir }
#[inline]
pub fn is_block(self) -> bool { self == Self::Block }
#[inline]
pub fn is_char(self) -> bool { self == Self::Char }
#[inline]
pub fn is_sock(self) -> bool { self == Self::Sock }
#[inline]
pub fn is_fifo(self) -> bool { self == Self::FIFO }
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fs/src/cha/kind.rs | yazi-fs/src/cha/kind.rs | use std::fs::Metadata;
use bitflags::bitflags;
use yazi_shared::strand::AsStrand;
bitflags! {
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ChaKind: u8 {
const FOLLOW = 0b0000_0001;
const HIDDEN = 0b0000_0010;
const SYSTEM = 0b0000_0100;
const DUMMY = 0b0000_1000;
}
}
impl ChaKind {
#[inline]
pub(super) fn hidden<T>(_name: T, _meta: &Metadata) -> Self
where
T: AsStrand,
{
let mut me = Self::empty();
#[cfg(unix)]
{
if _name.as_strand().starts_with(".") {
me |= Self::HIDDEN;
}
}
#[cfg(windows)]
{
use std::os::windows::fs::MetadataExt;
use windows_sys::Win32::Storage::FileSystem::{FILE_ATTRIBUTE_HIDDEN, FILE_ATTRIBUTE_SYSTEM};
if _meta.file_attributes() & FILE_ATTRIBUTE_HIDDEN != 0 {
me |= Self::HIDDEN;
}
if _meta.file_attributes() & FILE_ATTRIBUTE_SYSTEM != 0 {
me |= Self::SYSTEM;
}
}
me
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fs/src/cha/mod.rs | yazi-fs/src/cha/mod.rs | yazi_macro::mod_flat!(cha kind mode r#type);
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fs/src/cha/cha.rs | yazi-fs/src/cha/cha.rs | use std::{fs::Metadata, ops::Deref, time::{Duration, SystemTime, UNIX_EPOCH}};
use anyhow::bail;
use yazi_macro::{unix_either, win_either};
use yazi_shared::{strand::AsStrand, url::AsUrl};
use super::ChaKind;
use crate::cha::{ChaMode, ChaType};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Cha {
pub kind: ChaKind,
pub mode: ChaMode,
pub len: u64,
pub atime: Option<SystemTime>,
pub btime: Option<SystemTime>,
pub ctime: Option<SystemTime>,
pub mtime: Option<SystemTime>,
pub dev: u64,
pub uid: u32,
pub gid: u32,
pub nlink: u64,
}
impl Deref for Cha {
type Target = ChaMode;
fn deref(&self) -> &Self::Target { &self.mode }
}
impl Default for Cha {
fn default() -> Self {
Self {
kind: ChaKind::DUMMY,
mode: ChaMode::empty(),
len: 0,
atime: None,
btime: None,
ctime: None,
mtime: None,
dev: 0,
uid: 0,
gid: 0,
nlink: 0,
}
}
}
impl Cha {
#[inline]
pub fn new<T>(name: T, meta: Metadata) -> Self
where
T: AsStrand,
{
Self::from_bare(&meta).attach(ChaKind::hidden(name, &meta))
}
pub fn from_dummy<U>(_url: U, r#type: Option<ChaType>) -> Self
where
U: AsUrl,
{
let mut kind = ChaKind::DUMMY;
let mode = r#type.map(ChaMode::from_bare).unwrap_or_default();
#[cfg(unix)]
if _url.as_url().urn().is_hidden() {
kind |= ChaKind::HIDDEN;
}
Self { kind, mode, ..Default::default() }
}
fn from_bare(m: &Metadata) -> Self {
#[cfg(unix)]
use std::os::unix::fs::MetadataExt;
#[cfg(unix)]
let mode = {
use std::os::unix::fs::PermissionsExt;
ChaMode::from_bits_retain(m.permissions().mode() as u16)
};
#[cfg(windows)]
let mode = {
if m.is_file() {
ChaMode::T_FILE
} else if m.is_dir() {
ChaMode::T_DIR
} else if m.is_symlink() {
ChaMode::T_LINK
} else {
ChaMode::empty()
}
};
Self {
kind: ChaKind::empty(),
mode,
len: m.len(),
atime: m.accessed().ok(),
btime: m.created().ok(),
ctime: unix_either!(
UNIX_EPOCH.checked_add(Duration::new(m.ctime() as u64, m.ctime_nsec() as u32)),
None
),
mtime: m.modified().ok(),
dev: unix_either!(m.dev(), 0) as _,
uid: unix_either!(m.uid(), 0) as _,
gid: unix_either!(m.gid(), 0) as _,
nlink: unix_either!(m.nlink(), 0) as _,
}
}
#[inline]
pub fn hits(self, c: Self) -> bool {
self.len == c.len
&& self.mtime == c.mtime
&& self.ctime == c.ctime
&& self.btime == c.btime
&& self.kind == c.kind
&& self.mode == c.mode
}
#[inline]
pub fn attach(mut self, kind: ChaKind) -> Self {
self.kind |= kind;
self
}
}
impl Cha {
#[inline]
pub fn is_link(self) -> bool {
self.kind.contains(ChaKind::FOLLOW) || *self.mode == ChaType::Link
}
#[inline]
pub fn is_orphan(self) -> bool {
*self.mode == ChaType::Link && self.kind.contains(ChaKind::FOLLOW)
}
#[inline]
pub const fn is_hidden(self) -> bool {
win_either!(
self.kind.contains(ChaKind::HIDDEN) || self.kind.contains(ChaKind::SYSTEM),
self.kind.contains(ChaKind::HIDDEN)
)
}
#[inline]
pub const fn is_dummy(self) -> bool { self.kind.contains(ChaKind::DUMMY) }
pub fn atime_dur(self) -> anyhow::Result<Duration> {
if let Some(atime) = self.atime {
Ok(atime.duration_since(UNIX_EPOCH)?)
} else {
bail!("atime not available");
}
}
pub fn btime_dur(self) -> anyhow::Result<Duration> {
if let Some(btime) = self.btime {
Ok(btime.duration_since(UNIX_EPOCH)?)
} else {
bail!("btime not available");
}
}
pub fn ctime_dur(self) -> anyhow::Result<Duration> {
if let Some(ctime) = self.ctime {
Ok(ctime.duration_since(UNIX_EPOCH)?)
} else {
bail!("ctime not available");
}
}
pub fn mtime_dur(self) -> anyhow::Result<Duration> {
if let Some(mtime) = self.mtime {
Ok(mtime.duration_since(UNIX_EPOCH)?)
} else {
bail!("mtime not available");
}
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fs/src/cha/mode.rs | yazi-fs/src/cha/mode.rs | use std::ops::Deref;
use anyhow::{anyhow, bail};
use bitflags::bitflags;
use crate::cha::ChaType;
bitflags! {
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ChaMode: u16 {
// File type
const T_MASK = 0b1111_0000_0000_0000;
const T_SOCK = 0b1100_0000_0000_0000;
const T_LINK = 0b1010_0000_0000_0000;
const T_FILE = 0b1000_0000_0000_0000;
const T_BLOCK = 0b0110_0000_0000_0000;
const T_DIR = 0b0100_0000_0000_0000;
const T_CHAR = 0b0010_0000_0000_0000;
const T_FIFO = 0b0001_0000_0000_0000;
// Special
const S_SUID = 0b0000_1000_0000_0000;
const S_SGID = 0b0000_0100_0000_0000;
const S_STICKY = 0b0000_0010_0000_0000;
// User
const U_MASK = 0b0000_0001_1100_0000;
const U_READ = 0b0000_0001_0000_0000;
const U_WRITE = 0b0000_0000_1000_0000;
const U_EXEC = 0b0000_0000_0100_0000;
// Group
const G_MASK = 0b0000_0000_0011_1000;
const G_READ = 0b0000_0000_0010_0000;
const G_WRITE = 0b0000_0000_0001_0000;
const G_EXEC = 0b0000_0000_0000_1000;
// Others
const O_MASK = 0b0000_0000_0000_0111;
const O_READ = 0b0000_0000_0000_0100;
const O_WRITE = 0b0000_0000_0000_0010;
const O_EXEC = 0b0000_0000_0000_0001;
}
}
impl Deref for ChaMode {
type Target = ChaType;
#[inline]
fn deref(&self) -> &Self::Target {
match *self & Self::T_MASK {
Self::T_FILE => &ChaType::File,
Self::T_DIR => &ChaType::Dir,
Self::T_LINK => &ChaType::Link,
Self::T_BLOCK => &ChaType::Block,
Self::T_CHAR => &ChaType::Char,
Self::T_SOCK => &ChaType::Sock,
Self::T_FIFO => &ChaType::FIFO,
_ => &ChaType::Unknown,
}
}
}
impl TryFrom<u16> for ChaMode {
type Error = anyhow::Error;
fn try_from(value: u16) -> Result<Self, Self::Error> {
let me = Self::from_bits(value).ok_or_else(|| anyhow!("invalid file mode: {value:04o}"))?;
match me & Self::T_MASK {
Self::T_FILE
| Self::T_DIR
| Self::T_LINK
| Self::T_BLOCK
| Self::T_CHAR
| Self::T_SOCK
| Self::T_FIFO => Ok(me),
_ => bail!("invalid file type: {value:04o}"),
}
}
}
#[cfg(unix)]
impl From<ChaMode> for std::fs::Permissions {
fn from(value: ChaMode) -> Self {
use std::os::unix::fs::PermissionsExt;
Self::from_mode(value.bits() as _)
}
}
impl ChaMode {
// Convert a file mode to a string representation
#[cfg(unix)]
#[allow(clippy::collapsible_else_if)]
pub fn permissions(self, dummy: bool) -> [u8; 10] {
let mut s = *b"-?????????";
// File type
s[0] = match *self {
ChaType::Dir => b'd',
ChaType::Link => b'l',
ChaType::Block => b'b',
ChaType::Char => b'c',
ChaType::Sock => b's',
ChaType::FIFO => b'p',
_ => b'-',
};
if dummy {
return s;
}
// User
s[1] = if self.contains(Self::U_READ) { b'r' } else { b'-' };
s[2] = if self.contains(Self::U_WRITE) { b'w' } else { b'-' };
s[3] = if self.contains(Self::U_EXEC) {
if self.contains(Self::S_SUID) { b's' } else { b'x' }
} else {
if self.contains(Self::S_SUID) { b'S' } else { b'-' }
};
// Group
s[4] = if self.contains(Self::G_READ) { b'r' } else { b'-' };
s[5] = if self.contains(Self::G_WRITE) { b'w' } else { b'-' };
s[6] = if self.contains(Self::G_EXEC) {
if self.contains(Self::S_SGID) { b's' } else { b'x' }
} else {
if self.contains(Self::S_SGID) { b'S' } else { b'-' }
};
// Others
s[7] = if self.contains(Self::O_READ) { b'r' } else { b'-' };
s[8] = if self.contains(Self::O_WRITE) { b'w' } else { b'-' };
s[9] = if self.contains(Self::O_EXEC) {
if self.contains(Self::S_STICKY) { b't' } else { b'x' }
} else {
if self.contains(Self::S_STICKY) { b'T' } else { b'-' }
};
s
}
pub(super) fn from_bare(r#type: ChaType) -> Self {
match r#type {
ChaType::File => Self::T_FILE,
ChaType::Dir => Self::T_DIR,
ChaType::Link => Self::T_LINK,
ChaType::Block => Self::T_BLOCK,
ChaType::Char => Self::T_CHAR,
ChaType::Sock => Self::T_SOCK,
ChaType::FIFO => Self::T_FIFO,
ChaType::Unknown => Self::empty(),
}
}
}
impl ChaMode {
// TODO: deprecate
#[inline]
pub const fn is_exec(self) -> bool { self.contains(Self::U_EXEC) }
#[inline]
pub const fn is_sticky(self) -> bool { self.contains(Self::S_STICKY) }
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fs/src/provider/attrs.rs | yazi-fs/src/provider/attrs.rs | use std::time::{Duration, SystemTime, UNIX_EPOCH};
use crate::cha::{Cha, ChaMode};
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct Attrs {
pub mode: Option<ChaMode>,
pub atime: Option<SystemTime>,
pub btime: Option<SystemTime>,
pub mtime: Option<SystemTime>,
}
impl From<Cha> for Attrs {
fn from(value: Cha) -> Self {
Self { mode: Some(value.mode), atime: value.atime, btime: value.btime, mtime: value.mtime }
}
}
impl TryFrom<Attrs> for std::fs::FileTimes {
type Error = ();
fn try_from(value: Attrs) -> Result<Self, Self::Error> {
if !value.has_times() {
return Err(());
}
let mut t = Self::new();
if let Some(atime) = value.atime {
t = t.set_accessed(atime);
}
#[cfg(target_os = "macos")]
if let Some(btime) = value.btime {
use std::os::macos::fs::FileTimesExt;
t = t.set_created(btime);
}
#[cfg(windows)]
if let Some(btime) = value.btime {
use std::os::windows::fs::FileTimesExt;
t = t.set_created(btime);
}
if let Some(mtime) = value.mtime {
t = t.set_modified(mtime);
}
Ok(t)
}
}
impl TryFrom<Attrs> for std::fs::Permissions {
type Error = ();
fn try_from(value: Attrs) -> Result<Self, Self::Error> {
#[cfg(unix)]
if let Some(mode) = value.mode {
return Ok(mode.into());
}
Err(())
}
}
impl Attrs {
pub fn has_times(self) -> bool {
self.atime.is_some() || self.btime.is_some() || self.mtime.is_some()
}
pub fn atime_dur(self) -> Option<Duration> { self.atime?.duration_since(UNIX_EPOCH).ok() }
pub fn btime_dur(self) -> Option<Duration> { self.btime?.duration_since(UNIX_EPOCH).ok() }
pub fn mtime_dur(self) -> Option<Duration> { self.mtime?.duration_since(UNIX_EPOCH).ok() }
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fs/src/provider/mod.rs | yazi-fs/src/provider/mod.rs | yazi_macro::mod_pub!(local);
yazi_macro::mod_flat!(attrs capabilities traits);
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fs/src/provider/traits.rs | yazi-fs/src/provider/traits.rs | use std::io;
use tokio::{io::{AsyncRead, AsyncSeek, AsyncWrite, AsyncWriteExt}, sync::mpsc};
use yazi_macro::ok_or_not_found;
use yazi_shared::{path::{AsPath, PathBufDyn}, strand::{AsStrand, StrandCow}, url::{AsUrl, Url, UrlBuf}};
use crate::{cha::{Cha, ChaType}, provider::{Attrs, Capabilities}};
pub trait Provider: Sized {
type File: AsyncRead + AsyncSeek + AsyncWrite + Unpin;
type Gate: FileBuilder<File = Self::File>;
type ReadDir: DirReader + 'static;
type UrlCow;
type Me<'a>: Provider;
fn absolute(&self) -> impl Future<Output = io::Result<Self::UrlCow>>;
fn canonicalize(&self) -> impl Future<Output = io::Result<UrlBuf>>;
fn capabilities(&self) -> Capabilities;
fn casefold(&self) -> impl Future<Output = io::Result<UrlBuf>>;
fn copy<P>(&self, to: P, attrs: Attrs) -> impl Future<Output = io::Result<u64>>
where
P: AsPath;
fn copy_with_progress<P, A>(
&self,
to: P,
attrs: A,
) -> io::Result<mpsc::Receiver<io::Result<u64>>>
where
P: AsPath,
A: Into<Attrs>;
fn create(&self) -> impl Future<Output = io::Result<Self::File>> {
async move { self.gate().write(true).create(true).truncate(true).open(self.url()).await }
}
fn create_dir(&self) -> impl Future<Output = io::Result<()>>;
fn create_dir_all(&self) -> impl Future<Output = io::Result<()>> {
async move {
let mut url = self.url();
if url.loc().is_empty() {
return Ok(());
}
let mut stack = Vec::new();
loop {
match Self::new(url).await?.create_dir().await {
Ok(()) => break,
Err(e) if e.kind() == io::ErrorKind::NotFound => {
if let Some(parent) = url.parent() {
stack.push(url);
url = parent;
} else {
return Err(io::Error::other("failed to create whole tree"));
}
}
Err(_) if Self::new(url).await?.metadata().await.is_ok_and(|m| m.is_dir()) => break,
Err(e) => return Err(e),
}
}
while let Some(u) = stack.pop() {
match Self::new(u).await?.create_dir().await {
Ok(()) => {}
Err(_) if Self::new(u).await?.metadata().await.is_ok_and(|m| m.is_dir()) => {}
Err(e) => return Err(e),
}
}
Ok(())
}
}
fn create_new(&self) -> impl Future<Output = io::Result<Self::File>> {
async move { self.gate().write(true).create_new(true).open(self.url()).await }
}
fn gate(&self) -> Self::Gate { Self::Gate::default() }
fn hard_link<P>(&self, to: P) -> impl Future<Output = io::Result<()>>
where
P: AsPath;
fn metadata(&self) -> impl Future<Output = io::Result<Cha>>;
fn new<'a>(url: Url<'a>) -> impl Future<Output = io::Result<Self::Me<'a>>>;
fn open(&self) -> impl Future<Output = io::Result<Self::File>> {
async move { self.gate().read(true).open(self.url()).await }
}
fn read_dir(self) -> impl Future<Output = io::Result<Self::ReadDir>>;
fn read_link(&self) -> impl Future<Output = io::Result<PathBufDyn>>;
fn remove_dir(&self) -> impl Future<Output = io::Result<()>>;
fn remove_dir_all(&self) -> impl Future<Output = io::Result<()>> {
async fn remove_dir_all_impl<P>(url: Url<'_>) -> io::Result<()>
where
P: Provider,
{
let mut it = ok_or_not_found!(P::new(url).await?.read_dir().await, return Ok(()));
while let Some(child) = it.next().await? {
let ft = ok_or_not_found!(child.file_type().await, continue);
let result = if ft.is_dir() {
Box::pin(remove_dir_all_impl::<P>(child.url().as_url())).await
} else {
P::new(child.url().as_url()).await?.remove_file().await
};
() = ok_or_not_found!(result);
}
Ok(ok_or_not_found!(P::new(url).await?.remove_dir().await))
}
async move {
let cha = ok_or_not_found!(self.symlink_metadata().await, return Ok(()));
if cha.is_link() {
self.remove_file().await
} else {
remove_dir_all_impl::<Self>(self.url()).await
}
}
}
fn remove_dir_clean(&self) -> impl Future<Output = io::Result<()>> {
let root = self.url().to_owned();
async move {
let mut stack = vec![(root, false)];
let mut result = Ok(());
while let Some((dir, visited)) = stack.pop() {
let Ok(provider) = Self::new(dir.as_url()).await else {
continue;
};
if visited {
result = provider.remove_dir().await;
} else if let Ok(mut it) = provider.read_dir().await {
stack.push((dir, true));
while let Ok(Some(ent)) = it.next().await {
if ent.file_type().await.is_ok_and(|t| t.is_dir()) {
stack.push((ent.url(), false));
}
}
}
}
result
}
}
fn remove_file(&self) -> impl Future<Output = io::Result<()>>;
fn rename<P>(&self, to: P) -> impl Future<Output = io::Result<()>>
where
P: AsPath;
fn symlink<S, F>(&self, original: S, _is_dir: F) -> impl Future<Output = io::Result<()>>
where
S: AsStrand,
F: AsyncFnOnce() -> io::Result<bool>;
fn symlink_dir<S>(&self, original: S) -> impl Future<Output = io::Result<()>>
where
S: AsStrand,
{
self.symlink(original, async || Ok(true))
}
fn symlink_file<S>(&self, original: S) -> impl Future<Output = io::Result<()>>
where
S: AsStrand,
{
self.symlink(original, async || Ok(false))
}
fn symlink_metadata(&self) -> impl Future<Output = io::Result<Cha>>;
fn trash(&self) -> impl Future<Output = io::Result<()>>;
fn url(&self) -> Url<'_>;
fn write<C>(&self, contents: C) -> impl Future<Output = io::Result<()>>
where
C: AsRef<[u8]>,
{
async move { self.create().await?.write_all(contents.as_ref()).await }
}
}
// --- DirReader
pub trait DirReader {
type Entry: FileHolder;
#[must_use]
fn next(&mut self) -> impl Future<Output = io::Result<Option<Self::Entry>>>;
}
// --- FileHolder
pub trait FileHolder {
#[must_use]
fn file_type(&self) -> impl Future<Output = io::Result<ChaType>>;
#[must_use]
fn metadata(&self) -> impl Future<Output = io::Result<Cha>>;
#[must_use]
fn name(&self) -> StrandCow<'_>;
#[must_use]
fn path(&self) -> PathBufDyn;
#[must_use]
fn url(&self) -> UrlBuf;
}
// --- FileBuilder
pub trait FileBuilder: Sized + Default {
type File: AsyncRead + AsyncSeek + AsyncWrite + Unpin;
fn append(&mut self, append: bool) -> &mut Self;
fn attrs(&mut self, attrs: Attrs) -> &mut Self;
fn create(&mut self, create: bool) -> &mut Self;
fn create_new(&mut self, create_new: bool) -> &mut Self;
fn open<U>(&self, url: U) -> impl Future<Output = io::Result<Self::File>>
where
U: AsUrl;
fn read(&mut self, read: bool) -> &mut Self;
fn truncate(&mut self, truncate: bool) -> &mut Self;
fn write(&mut self, write: bool) -> &mut Self;
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fs/src/provider/capabilities.rs | yazi-fs/src/provider/capabilities.rs | #[derive(Clone, Copy, Debug)]
pub struct Capabilities {
pub symlink: bool,
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fs/src/provider/local/casefold.rs | yazi-fs/src/provider/local/casefold.rs | use std::{io, path::{Path, PathBuf}};
pub async fn match_name_case(path: impl AsRef<Path>) -> bool {
let path = path.as_ref();
casefold(path).await.is_ok_and(|p| p.file_name() == path.file_name())
}
pub(super) async fn casefold(path: impl AsRef<Path>) -> io::Result<PathBuf> {
let path = path.as_ref().to_owned();
tokio::task::spawn_blocking(move || casefold_impl(path)).await?
}
#[cfg(any(
target_os = "macos",
target_os = "netbsd",
target_os = "openbsd",
target_os = "freebsd",
target_os = "windows"
))]
fn casefold_impl(path: PathBuf) -> io::Result<PathBuf> {
let mut it = path.components();
let mut parts = vec![];
loop {
let p = it.as_path();
let q = final_path(p)?;
if p != q {
parts.push(q);
} else if parts.is_empty() {
return Ok(q);
} else {
break;
}
if it.next_back().is_none() {
break;
}
}
let mut buf = it.as_path().to_path_buf();
for p in parts.into_iter().rev() {
if let Some(name) = p.file_name() {
buf.push(name);
} else {
return Err(io::Error::other("Cannot get filename"));
}
}
Ok(buf)
}
#[cfg(any(target_os = "linux", target_os = "android"))]
#[allow(irrefutable_let_patterns)]
fn casefold_impl(path: PathBuf) -> io::Result<PathBuf> {
use std::{ffi::{CString, OsStr, OsString}, fs::File, os::{fd::{AsRawFd, FromRawFd}, unix::{ffi::{OsStrExt, OsStringExt}, fs::MetadataExt}}};
use libc::{O_NOFOLLOW, O_PATH};
let cstr = CString::new(path.into_os_string().into_vec())?;
let path = Path::new(OsStr::from_bytes(cstr.as_bytes()));
let Some((parent, name)) = path.parent().zip(path.file_name()) else {
return Ok(PathBuf::from(OsString::from_vec(cstr.into_bytes())));
};
let file = match unsafe { libc::open(cstr.as_ptr(), O_PATH | O_NOFOLLOW) } {
ret if ret < 0 => return Err(io::Error::last_os_error()),
ret => unsafe { File::from_raw_fd(ret) },
};
// Fast path: if the `/proc/self/fd/N` matches
if let Ok(p) = std::fs::read_link(format!("/proc/self/fd/{}", file.as_raw_fd()))
&& let path = path.as_os_str()
&& let Some(b) = p.as_os_str().as_bytes().get(..path.len())
&& b.eq_ignore_ascii_case(path.as_bytes())
{
let mut b = p.into_os_string().into_vec();
b.truncate(path.len());
return Ok(PathBuf::from(OsString::from_vec(b)));
}
// Fast path: if the file isn't a symlink
let meta = file.metadata()?;
if !meta.is_symlink()
&& let Some(n) = path.canonicalize()?.file_name()
{
return Ok(parent.join(n));
}
// Fallback: scan the directory for matching inodes
let mut names = vec![];
for entry in std::fs::read_dir(parent)? {
let entry = entry?;
let n = entry.file_name(); // TODO: use `file_name_ref()` when stabilized
if n == name {
return Ok(PathBuf::from(OsString::from_vec(cstr.into_bytes())));
} else if let m = entry.metadata()?
&& m.ino() == meta.ino()
&& m.dev() == meta.dev()
{
names.push(n);
}
}
if names.len() == 1 {
// No hardlink that shares the same inode
Ok(parent.join(&names[0]))
} else if let mut it = names.iter().enumerate().filter(|&(_, n)| n.eq_ignore_ascii_case(name))
&& let Some((i, _)) = it.next()
&& it.next().is_none()
{
// Case-insensitive match
Ok(parent.join(&names[i]))
} else {
Err(io::Error::from(io::ErrorKind::NotFound))
}
}
#[cfg(any(
target_os = "macos",
target_os = "netbsd",
target_os = "openbsd",
target_os = "freebsd"
))]
fn final_path(path: &Path) -> io::Result<PathBuf> {
use std::{ffi::{CStr, CString, OsString}, os::{fd::{AsRawFd, FromRawFd, OwnedFd}, unix::ffi::{OsStrExt, OsStringExt}}};
use libc::{F_GETPATH, O_RDONLY, O_SYMLINK, PATH_MAX};
let cstr = CString::new(path.as_os_str().as_bytes())?;
let fd = match unsafe { libc::open(cstr.as_ptr(), O_RDONLY | O_SYMLINK) } {
ret if ret < 0 => return Err(io::Error::last_os_error()),
ret => unsafe { OwnedFd::from_raw_fd(ret) },
};
let mut buf = [0u8; PATH_MAX as usize];
if unsafe { libc::fcntl(fd.as_raw_fd(), F_GETPATH, buf.as_mut_ptr()) } < 0 {
return Err(io::Error::last_os_error());
}
let cstr = unsafe { CStr::from_ptr(buf.as_ptr() as *const i8) };
Ok(OsString::from_vec(cstr.to_bytes().to_vec()).into())
}
#[cfg(target_os = "windows")]
fn final_path(path: &Path) -> io::Result<PathBuf> {
use std::{ffi::OsString, fs::File, os::windows::{ffi::OsStringExt, fs::OpenOptionsExt, io::AsRawHandle}};
use windows_sys::Win32::{Foundation::HANDLE, Storage::FileSystem::{FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT, GetFinalPathNameByHandleW, VOLUME_NAME_DOS}};
use yazi_shared::Either;
let file = std::fs::OpenOptions::new()
.access_mode(0)
.custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)
.open(path)?;
fn inner(file: &File, buf: &mut [u16]) -> io::Result<Either<PathBuf, u32>> {
let len = unsafe {
GetFinalPathNameByHandleW(
file.as_raw_handle() as HANDLE,
buf.as_mut_ptr(),
buf.len() as u32,
VOLUME_NAME_DOS,
)
};
Ok(if len == 0 {
Err(io::Error::last_os_error())?
} else if len as usize > buf.len() {
Either::Right(len)
} else if buf.starts_with(&[92, 92, 63, 92]) {
Either::Left(PathBuf::from(OsString::from_wide(&buf[4..len as usize])))
} else {
Either::Left(PathBuf::from(OsString::from_wide(&buf[0..len as usize])))
})
}
match inner(&file, &mut [0u16; 512])? {
Either::Left(path) => Ok(path),
Either::Right(len) => inner(&file, &mut vec![0u16; len as usize])?
.left_or_err(|| io::Error::new(io::ErrorKind::InvalidData, "path too long")),
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fs/src/provider/local/local.rs | yazi-fs/src/provider/local/local.rs | use std::{io, path::Path, sync::Arc};
use tokio::sync::mpsc;
use yazi_shared::{path::{AsPath, PathBufDyn}, scheme::SchemeKind, strand::AsStrand, url::{Url, UrlBuf, UrlCow}};
use crate::{cha::Cha, provider::{Attrs, Capabilities, Provider}};
#[derive(Clone)]
pub struct Local<'a> {
url: Url<'a>,
path: &'a Path,
}
impl<'a> Provider for Local<'a> {
type File = tokio::fs::File;
type Gate = super::Gate;
type Me<'b> = Local<'b>;
type ReadDir = super::ReadDir;
type UrlCow = UrlCow<'a>;
async fn absolute(&self) -> io::Result<Self::UrlCow> {
super::try_absolute(self.url)
.ok_or_else(|| io::Error::other("Cannot get absolute path for local URL"))
}
#[inline]
async fn canonicalize(&self) -> io::Result<UrlBuf> {
tokio::fs::canonicalize(self.path).await.map(Into::into)
}
#[inline]
fn capabilities(&self) -> Capabilities { Capabilities { symlink: true } }
async fn casefold(&self) -> io::Result<UrlBuf> {
super::casefold(self.path).await.map(Into::into)
}
#[inline]
async fn copy<P>(&self, to: P, attrs: Attrs) -> io::Result<u64>
where
P: AsPath,
{
let to = to.as_path().to_os_owned()?;
let from = self.path.to_owned();
super::copy_impl(from, to, attrs).await
}
fn copy_with_progress<P, A>(&self, to: P, attrs: A) -> io::Result<mpsc::Receiver<io::Result<u64>>>
where
P: AsPath,
A: Into<Attrs>,
{
let to = to.as_path().to_os_owned()?;
let from = self.path.to_owned();
Ok(super::copy_with_progress_impl(from, to, attrs.into()))
}
#[inline]
async fn create_dir(&self) -> io::Result<()> { tokio::fs::create_dir(self.path).await }
#[inline]
async fn create_dir_all(&self) -> io::Result<()> { tokio::fs::create_dir_all(self.path).await }
#[inline]
async fn hard_link<P>(&self, to: P) -> io::Result<()>
where
P: AsPath,
{
let to = to.as_path().as_os()?;
tokio::fs::hard_link(self.path, to).await
}
#[inline]
async fn metadata(&self) -> io::Result<Cha> {
Ok(Cha::new(self.path.file_name().unwrap_or_default(), tokio::fs::metadata(self.path).await?))
}
#[inline]
async fn new<'b>(url: Url<'b>) -> io::Result<Self::Me<'b>> {
match url {
Url::Regular(loc) | Url::Search { loc, .. } => Ok(Self::Me { url, path: loc.as_inner() }),
Url::Archive { .. } | Url::Sftp { .. } => {
Err(io::Error::new(io::ErrorKind::InvalidInput, format!("Not a local URL: {url:?}")))
}
}
}
#[inline]
async fn read_dir(self) -> io::Result<Self::ReadDir> {
Ok(match self.url.kind() {
SchemeKind::Regular => Self::ReadDir::Regular(tokio::fs::read_dir(self.path).await?),
SchemeKind::Search => Self::ReadDir::Others {
reader: tokio::fs::read_dir(self.path).await?,
dir: Arc::new(self.url.to_owned()),
},
SchemeKind::Archive | SchemeKind::Sftp => Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!("Not a local URL: {:?}", self.url),
))?,
})
}
#[inline]
async fn read_link(&self) -> io::Result<PathBufDyn> {
Ok(tokio::fs::read_link(self.path).await?.into())
}
#[inline]
async fn remove_dir(&self) -> io::Result<()> { tokio::fs::remove_dir(self.path).await }
#[inline]
async fn remove_dir_all(&self) -> io::Result<()> { tokio::fs::remove_dir_all(self.path).await }
#[inline]
async fn remove_file(&self) -> io::Result<()> { tokio::fs::remove_file(self.path).await }
#[inline]
async fn rename<P>(&self, to: P) -> io::Result<()>
where
P: AsPath,
{
let to = to.as_path().as_os()?;
tokio::fs::rename(self.path, to).await
}
#[inline]
async fn symlink<S, F>(&self, original: S, _is_dir: F) -> io::Result<()>
where
S: AsStrand,
F: AsyncFnOnce() -> io::Result<bool>,
{
#[cfg(unix)]
{
let original = original.as_strand().as_os()?;
tokio::fs::symlink(original, self.path).await
}
#[cfg(windows)]
if _is_dir().await? {
self.symlink_dir(original).await
} else {
self.symlink_file(original).await
}
}
#[inline]
async fn symlink_dir<S>(&self, original: S) -> io::Result<()>
where
S: AsStrand,
{
let original = original.as_strand().as_os()?;
#[cfg(unix)]
{
tokio::fs::symlink(original, self.path).await
}
#[cfg(windows)]
{
tokio::fs::symlink_dir(original, self.path).await
}
}
#[inline]
async fn symlink_file<S>(&self, original: S) -> io::Result<()>
where
S: AsStrand,
{
let original = original.as_strand().as_os()?;
#[cfg(unix)]
{
tokio::fs::symlink(original, self.path).await
}
#[cfg(windows)]
{
tokio::fs::symlink_file(original, self.path).await
}
}
#[inline]
async fn symlink_metadata(&self) -> io::Result<Cha> {
Ok(Cha::new(
self.path.file_name().unwrap_or_default(),
tokio::fs::symlink_metadata(self.path).await?,
))
}
async fn trash(&self) -> io::Result<()> {
let path = self.path.to_owned();
tokio::task::spawn_blocking(move || {
#[cfg(target_os = "android")]
{
Err(io::Error::new(io::ErrorKind::Unsupported, "Unsupported OS for trash operation"))
}
#[cfg(target_os = "macos")]
{
use trash::{TrashContext, macos::{DeleteMethod, TrashContextExtMacos}};
let mut ctx = TrashContext::default();
ctx.set_delete_method(DeleteMethod::NsFileManager);
ctx.delete(path).map_err(io::Error::other)
}
#[cfg(all(not(target_os = "macos"), not(target_os = "android")))]
{
trash::delete(path).map_err(io::Error::other)
}
})
.await?
}
#[inline]
fn url(&self) -> Url<'_> { self.url }
#[inline]
async fn write<C>(&self, contents: C) -> io::Result<()>
where
C: AsRef<[u8]>,
{
tokio::fs::write(self.path, contents).await
}
}
impl<'a> Local<'a> {
#[inline]
pub async fn read(&self) -> io::Result<Vec<u8>> { tokio::fs::read(self.path).await }
#[inline]
pub async fn read_to_string(&self) -> io::Result<String> {
tokio::fs::read_to_string(self.path).await
}
#[inline]
pub fn regular<P>(path: &'a P) -> Self
where
P: ?Sized + AsRef<Path>,
{
Self { url: Url::regular(path), path: path.as_ref() }
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fs/src/provider/local/absolute.rs | yazi-fs/src/provider/local/absolute.rs | use std::path::PathBuf;
use yazi_shared::{loc::LocBuf, pool::InternStr, url::{AsUrl, Url, UrlBuf, UrlCow, UrlLike}};
use crate::CWD;
pub fn try_absolute<'a, U>(url: U) -> Option<UrlCow<'a>>
where
U: Into<UrlCow<'a>>,
{
try_absolute_impl(url.into())
}
fn try_absolute_impl<'a>(url: UrlCow<'a>) -> Option<UrlCow<'a>> {
if url.kind().is_virtual() {
return None;
}
let path = url.loc().as_os().expect("must be a local path");
let b = path.as_os_str().as_encoded_bytes();
let loc = if cfg!(windows) && b.len() == 2 && b[1] == b':' && b[0].is_ascii_alphabetic() {
LocBuf::<PathBuf>::with(
format!(r"{}:\", b[0].to_ascii_uppercase() as char).into(),
if url.has_base() { 0 } else { 2 },
if url.has_trail() { 0 } else { 2 },
)
.expect("Loc from drive letter")
} else if let Ok(rest) = path.strip_prefix("~/")
&& let Some(home) = dirs::home_dir()
&& home.is_absolute()
{
let add = home.components().count() - 1; // Home root ("~") has offset by the absolute root ("/")
LocBuf::<PathBuf>::with(
home.join(rest),
url.uri().components().count() + if url.has_base() { 0 } else { add },
url.urn().components().count() + if url.has_trail() { 0 } else { add },
)
.expect("Loc from home directory")
} else if !url.is_absolute() {
LocBuf::<PathBuf>::with(
CWD.path().join(path),
url.uri().components().count(),
url.urn().components().count(),
)
.expect("Loc from relative path")
} else {
return Some(url);
};
Some(match url.as_url() {
Url::Regular(_) => UrlBuf::Regular(loc).into(),
Url::Search { domain, .. } => UrlBuf::Search { loc, domain: domain.intern() }.into(),
Url::Archive { .. } | Url::Sftp { .. } => None?,
})
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fs/src/provider/local/gate.rs | yazi-fs/src/provider/local/gate.rs | use std::io;
use yazi_shared::url::AsUrl;
use crate::provider::{Attrs, FileBuilder};
#[derive(Default)]
pub struct Gate(tokio::fs::OpenOptions);
impl FileBuilder for Gate {
type File = tokio::fs::File;
fn append(&mut self, append: bool) -> &mut Self {
self.0.append(append);
self
}
fn attrs(&mut self, _attrs: Attrs) -> &mut Self {
#[cfg(unix)]
if let Some(mode) = _attrs.mode {
self.0.mode(mode.bits() as _);
}
self
}
fn create(&mut self, create: bool) -> &mut Self {
self.0.create(create);
self
}
fn create_new(&mut self, create_new: bool) -> &mut Self {
self.0.create_new(create_new);
self
}
async fn open<U>(&self, url: U) -> io::Result<Self::File>
where
U: AsUrl,
{
let url = url.as_url();
if let Some(path) = url.as_local() {
self.0.open(path).await
} else {
Err(io::Error::new(io::ErrorKind::InvalidInput, format!("Not a local URL: {url:?}")))
}
}
fn read(&mut self, read: bool) -> &mut Self {
self.0.read(read);
self
}
fn truncate(&mut self, truncate: bool) -> &mut Self {
self.0.truncate(truncate);
self
}
fn write(&mut self, write: bool) -> &mut Self {
self.0.write(write);
self
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fs/src/provider/local/dir_entry.rs | yazi-fs/src/provider/local/dir_entry.rs | use std::{io, sync::Arc};
use yazi_shared::{path::PathBufDyn, strand::StrandCow, url::{UrlBuf, UrlLike}};
use crate::{cha::{Cha, ChaType}, provider::FileHolder};
pub enum DirEntry {
Regular(tokio::fs::DirEntry),
Others { entry: tokio::fs::DirEntry, dir: Arc<UrlBuf> },
}
impl FileHolder for DirEntry {
async fn file_type(&self) -> io::Result<ChaType> {
match self {
Self::Regular(entry) | Self::Others { entry, .. } => entry.file_type().await.map(Into::into),
}
}
async fn metadata(&self) -> io::Result<Cha> {
let meta = match self {
Self::Regular(entry) | Self::Others { entry, .. } => entry.metadata().await?,
};
Ok(Cha::new(self.name(), meta)) // TODO: use `file_name_os_str` when stabilized
}
fn name(&self) -> StrandCow<'_> {
match self {
Self::Regular(entry) | Self::Others { entry, .. } => entry.file_name().into(),
}
}
fn path(&self) -> PathBufDyn {
match self {
Self::Regular(entry) | Self::Others { entry, .. } => entry.path().into(),
}
}
fn url(&self) -> UrlBuf {
match self {
Self::Regular(entry) => entry.path().into(),
Self::Others { entry, dir } => {
dir.try_join(entry.file_name()).expect("entry name is a valid component of the local URL")
}
}
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fs/src/provider/local/mod.rs | yazi-fs/src/provider/local/mod.rs | yazi_macro::mod_flat!(absolute calculator casefold copier dir_entry gate identical local read_dir);
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fs/src/provider/local/copier.rs | yazi-fs/src/provider/local/copier.rs | use std::{io, path::PathBuf};
use tokio::{select, sync::{mpsc, oneshot}};
use crate::provider::Attrs;
pub(super) async fn copy_impl(from: PathBuf, to: PathBuf, attrs: Attrs) -> io::Result<u64> {
#[cfg(any(target_os = "linux", target_os = "android"))]
{
use std::os::unix::fs::OpenOptionsExt;
tokio::task::spawn_blocking(move || {
let mut opts = std::fs::OpenOptions::new();
if let Some(mode) = attrs.mode {
opts.mode(mode.bits() as _);
}
let mut reader = std::fs::File::open(from)?;
let mut writer = opts.write(true).create(true).truncate(true).open(to)?;
let written = std::io::copy(&mut reader, &mut writer)?;
if let Some(mode) = attrs.mode {
writer.set_permissions(mode.into()).ok();
}
if let Ok(times) = attrs.try_into() {
writer.set_times(times).ok();
}
Ok(written)
})
.await?
}
#[cfg(not(any(target_os = "linux", target_os = "android")))]
{
tokio::task::spawn_blocking(move || {
let written = std::fs::copy(from, &to)?;
if let Ok(times) = attrs.try_into()
&& let Ok(file) = std::fs::File::options().write(true).open(to)
{
file.set_times(times).ok();
}
Ok(written)
})
.await?
}
}
pub(super) fn copy_with_progress_impl(
from: PathBuf,
to: PathBuf,
attrs: Attrs,
) -> mpsc::Receiver<Result<u64, io::Error>> {
let (prog_tx, prog_rx) = mpsc::channel(10);
let (done_tx, mut done_rx) = oneshot::channel();
tokio::spawn({
let to = to.clone();
async move {
done_tx.send(copy_impl(from, to, attrs).await).ok();
}
});
tokio::spawn({
let prog_tx = prog_tx.clone();
async move {
let mut last = 0;
let mut done = None;
loop {
select! {
res = &mut done_rx => done = Some(res.unwrap()),
_ = prog_tx.closed() => break,
_ = tokio::time::sleep(std::time::Duration::from_secs(3)) => {},
}
match done {
Some(Ok(len)) => {
if len > last {
prog_tx.send(Ok(len - last)).await.ok();
}
prog_tx.send(Ok(0)).await.ok();
break;
}
Some(Err(e)) => {
prog_tx.send(Err(e)).await.ok();
break;
}
None => {}
}
let len = tokio::fs::symlink_metadata(&to).await.map(|m| m.len()).unwrap_or(0);
if len > last {
prog_tx.send(Ok(len - last)).await.ok();
last = len;
}
}
}
});
prog_rx
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fs/src/provider/local/read_dir.rs | yazi-fs/src/provider/local/read_dir.rs | use std::{io, sync::Arc};
use yazi_shared::url::UrlBuf;
use crate::provider::DirReader;
pub enum ReadDir {
Regular(tokio::fs::ReadDir),
Others { reader: tokio::fs::ReadDir, dir: Arc<UrlBuf> },
}
impl DirReader for ReadDir {
type Entry = super::DirEntry;
async fn next(&mut self) -> io::Result<Option<Self::Entry>> {
Ok(match self {
Self::Regular(reader) => reader.next_entry().await?.map(Self::Entry::Regular),
Self::Others { reader, dir } => {
reader.next_entry().await?.map(|entry| Self::Entry::Others { entry, dir: dir.clone() })
}
})
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fs/src/provider/local/calculator.rs | yazi-fs/src/provider/local/calculator.rs | use std::{collections::VecDeque, future::poll_fn, io, mem, path::{Path, PathBuf}, pin::Pin, task::{Poll, ready}, time::{Duration, Instant}};
use tokio::task::JoinHandle;
use yazi_shared::Either;
type Task = Either<PathBuf, std::fs::ReadDir>;
pub enum SizeCalculator {
Idle((VecDeque<Task>, Option<u64>)),
Pending(JoinHandle<(VecDeque<Task>, Option<u64>)>),
}
impl SizeCalculator {
pub async fn new(path: &Path) -> io::Result<Self> {
let p = path.to_owned();
tokio::task::spawn_blocking(move || {
let meta = std::fs::symlink_metadata(&p)?;
if !meta.is_dir() {
return Ok(Self::Idle((VecDeque::new(), Some(meta.len()))));
}
let mut buf = VecDeque::from([Either::Right(std::fs::read_dir(&p)?)]);
let size = Self::next_chunk(&mut buf);
Ok(Self::Idle((buf, size)))
})
.await?
}
pub async fn total(path: &Path) -> io::Result<u64> {
let mut it = Self::new(path).await?;
let mut total = 0;
while let Some(n) = it.next().await? {
total += n;
}
Ok(total)
}
pub async fn next(&mut self) -> io::Result<Option<u64>> {
poll_fn(|cx| {
loop {
match self {
Self::Idle((buf, size)) => {
if let Some(s) = size.take() {
return Poll::Ready(Ok(Some(s)));
} else if buf.is_empty() {
return Poll::Ready(Ok(None));
}
let mut buf = mem::take(buf);
*self = Self::Pending(tokio::task::spawn_blocking(move || {
let size = Self::next_chunk(&mut buf);
(buf, size)
}));
}
Self::Pending(handle) => {
*self = Self::Idle(ready!(Pin::new(handle).poll(cx))?);
}
}
}
})
.await
}
fn next_chunk(buf: &mut VecDeque<Either<PathBuf, std::fs::ReadDir>>) -> Option<u64> {
let (mut i, mut size, now) = (0, 0, Instant::now());
macro_rules! pop_and_continue {
() => {{
buf.pop_front();
if buf.is_empty() {
return Some(size);
}
continue;
}};
}
while i < 5000 && now.elapsed() < Duration::from_millis(50) {
i += 1;
let front = buf.front_mut()?;
if let Either::Left(p) = front {
*front = match std::fs::read_dir(p) {
Ok(it) => Either::Right(it),
Err(_) => pop_and_continue!(),
};
}
let Some(next) = front.right_mut()?.next() else {
pop_and_continue!();
};
let Ok(ent) = next else { continue };
let Ok(ft) = ent.file_type() else { continue };
if ft.is_dir() {
buf.push_back(Either::Left(ent.path()));
} else if let Ok(meta) = ent.metadata() {
size += meta.len();
}
}
Some(size)
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fs/src/provider/local/identical.rs | yazi-fs/src/provider/local/identical.rs | use std::{io, path::{Path, PathBuf}};
#[inline]
pub async fn identical<P, Q>(a: P, b: Q) -> io::Result<bool>
where
P: AsRef<Path>,
Q: AsRef<Path>,
{
let (a, b) = (a.as_ref().to_owned(), b.as_ref().to_owned());
tokio::task::spawn_blocking(move || identical_impl(a, b)).await?
}
#[cfg(unix)]
fn identical_impl(a: PathBuf, b: PathBuf) -> io::Result<bool> {
use std::os::unix::fs::MetadataExt;
let (a_, b_) = (std::fs::symlink_metadata(&a)?, std::fs::symlink_metadata(&b)?);
Ok(
a_.ino() == b_.ino()
&& a_.dev() == b_.dev()
&& std::fs::canonicalize(a)? == std::fs::canonicalize(b)?,
)
}
#[cfg(windows)]
fn identical_impl(a: PathBuf, b: PathBuf) -> io::Result<bool> {
use std::{fs::OpenOptions, mem, os::windows::{fs::OpenOptionsExt, io::AsRawHandle}};
use windows_sys::Win32::{Foundation::HANDLE, Storage::FileSystem::{FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT, FILE_ID_INFO, FileIdInfo, GetFileInformationByHandleEx}};
fn file_id(path: PathBuf) -> io::Result<(u64, u128)> {
let file = OpenOptions::new()
.access_mode(0)
.custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)
.open(path)?;
let mut info: FILE_ID_INFO = unsafe { mem::zeroed() };
let ret = unsafe {
GetFileInformationByHandleEx(
file.as_raw_handle() as HANDLE,
FileIdInfo,
&mut info as *mut FILE_ID_INFO as _,
mem::size_of::<FILE_ID_INFO>() as u32,
)
};
if ret == 0 {
Err(io::Error::last_os_error())
} else {
Ok((info.VolumeSerialNumber, u128::from_le_bytes(info.FileId.Identifier)))
}
}
Ok(file_id(a)? == file_id(b)?)
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fs/src/path/expand.rs | yazi-fs/src/path/expand.rs | use std::borrow::Cow;
use yazi_shared::{loc::LocBuf, path::{PathBufDyn, PathCow, PathKind, PathLike}, pool::InternStr, url::{AsUrl, Url, UrlBuf, UrlCow, UrlLike}, wtf8::FromWtf8Vec};
#[inline]
pub fn expand_url<'a>(url: impl Into<UrlCow<'a>>) -> UrlCow<'a> { expand_url_impl(url.into()) }
fn expand_url_impl(url: UrlCow) -> UrlCow {
let (o_base, o_rest, o_urn) = url.triple();
let n_base = expand_variables(o_base.into());
let n_rest = expand_variables(o_rest.into());
let n_urn = expand_variables(o_urn.into());
if n_base.is_borrowed() && n_rest.is_borrowed() && n_urn.is_borrowed() {
return url;
}
let rest_diff = n_rest.components().count() as isize - o_rest.components().count() as isize;
let urn_diff = n_urn.components().count() as isize - o_urn.components().count() as isize;
let uri_count = url.uri().components().count() as isize;
let urn_count = url.urn().components().count() as isize;
let mut path = PathBufDyn::with_capacity(url.kind(), n_base.len() + n_rest.len() + n_urn.len());
path.try_extend([n_base, n_rest, n_urn]).expect("extend original parts should not fail");
let uri = (uri_count + rest_diff + urn_diff) as usize;
let urn = (urn_count + urn_diff) as usize;
match url.as_url() {
Url::Regular(_) => UrlBuf::Regular(
LocBuf::<std::path::PathBuf>::with(path.into_os().unwrap(), uri, urn).unwrap(),
),
Url::Search { domain, .. } => UrlBuf::Search {
loc: LocBuf::<std::path::PathBuf>::with(path.into_os().unwrap(), uri, urn).unwrap(),
domain: domain.intern(),
},
Url::Archive { domain, .. } => UrlBuf::Archive {
loc: LocBuf::<std::path::PathBuf>::with(path.into_os().unwrap(), uri, urn).unwrap(),
domain: domain.intern(),
},
Url::Sftp { domain, .. } => UrlBuf::Sftp {
loc: LocBuf::<typed_path::UnixPathBuf>::with(path.into_unix().unwrap(), uri, urn).unwrap(),
domain: domain.intern(),
},
}
.into()
}
fn expand_variables(p: PathCow) -> PathCow {
// ${HOME} or $HOME
#[cfg(unix)]
let re = regex::bytes::Regex::new(r"\$(?:\{([^}]+)\}|([a-zA-Z\d_]+))").unwrap();
// %USERPROFILE%
#[cfg(windows)]
let re = regex::bytes::Regex::new(r"%([^%]+)%").unwrap();
let b = p.encoded_bytes();
let b = re.replace_all(b, |caps: ®ex::bytes::Captures| {
let name = caps.get(2).or_else(|| caps.get(1)).unwrap();
str::from_utf8(name.as_bytes())
.ok()
.and_then(std::env::var_os)
.map_or_else(|| caps.get(0).unwrap().as_bytes().to_owned(), |s| s.into_encoded_bytes())
});
match (b, p.kind()) {
(Cow::Borrowed(_), _) => p,
(Cow::Owned(b), PathKind::Os) => {
PathBufDyn::Os(std::path::PathBuf::from_wtf8_vec(b).expect("valid WTF-8 path")).into()
}
(Cow::Owned(b), PathKind::Unix) => PathBufDyn::Unix(b.into()).into(),
}
}
#[cfg(test)]
mod tests {
use anyhow::Result;
use super::*;
#[cfg(unix)]
#[test]
fn test_expand_url() -> Result<()> {
yazi_shared::init_tests();
unsafe {
std::env::set_var("FOO", "foo");
std::env::set_var("BAR_BAZ", "bar/baz");
std::env::set_var("BAR/BAZ", "bar_baz");
std::env::set_var("EM/PT/Y", "");
}
let cases = [
// Zero extra component expanded
("archive:////tmp/test.zip/$FOO/bar", "archive:////tmp/test.zip/foo/bar"),
("archive://:1//tmp/test.zip/$FOO/bar", "archive://:1//tmp/test.zip/foo/bar"),
("archive://:2//tmp/test.zip/bar/$FOO", "archive://:2//tmp/test.zip/bar/foo"),
("archive://:3//tmp/test.zip/$FOO/bar", "archive://:3//tmp/test.zip/foo/bar"),
("archive://:3:1//tmp/test.zip/bar/$FOO", "archive://:3:1//tmp/test.zip/bar/foo"),
("archive://:3:2//tmp/test.zip/$FOO/bar", "archive://:3:2//tmp/test.zip/foo/bar"),
("archive://:3:3//tmp/test.zip/bar/$FOO", "archive://:3:3//tmp/test.zip/bar/foo"),
// +1 component
("archive:////tmp/test.zip/$BAR_BAZ", "archive:////tmp/test.zip/bar/baz"),
("archive://:1//tmp/test.zip/$BAR_BAZ", "archive://:2//tmp/test.zip/bar/baz"),
("archive://:2//$BAR_BAZ/tmp/test.zip", "archive://:2//bar/baz/tmp/test.zip"),
("archive://:2:1//tmp/test.zip/$BAR_BAZ", "archive://:3:2//tmp/test.zip/bar/baz"),
("archive://:2:2//tmp/$BAR_BAZ/test.zip", "archive://:3:3//tmp/bar/baz/test.zip"),
("archive://:2:2//$BAR_BAZ/tmp/test.zip", "archive://:2:2//bar/baz/tmp/test.zip"),
// -1 component
("archive:////tmp/test.zip/${BAR/BAZ}", "archive:////tmp/test.zip/bar_baz"),
("archive://:1//tmp/test.zip/${BAR/BAZ}", "archive://:1//tmp/test.zip/${BAR/BAZ}"),
("archive://:1//tmp/${BAR/BAZ}/test.zip", "archive://:1//tmp/bar_baz/test.zip"),
("archive://:2//tmp/test.zip/${BAR/BAZ}", "archive://:1//tmp/test.zip/bar_baz"),
("archive://:2//tmp/${BAR/BAZ}/test.zip", "archive://:2//tmp/${BAR/BAZ}/test.zip"),
("archive://:2:1//tmp/test.zip/${BAR/BAZ}", "archive://:2:1//tmp/test.zip/${BAR/BAZ}"),
("archive://:2:1//tmp/${BAR/BAZ}/test.zip", "archive://:2:1//tmp/${BAR/BAZ}/test.zip"),
("archive://:2:1//${BAR/BAZ}/tmp/test.zip", "archive://:2:1//bar_baz/tmp/test.zip"),
("archive://:3:2//tmp/test.zip/${BAR/BAZ}", "archive://:2:1//tmp/test.zip/bar_baz"),
("archive://:3:2//tmp/${BAR/BAZ}/test.zip", "archive://:3:2//tmp/${BAR/BAZ}/test.zip"),
("archive://:3:3//tmp/test.zip/${BAR/BAZ}", "archive://:2:2//tmp/test.zip/bar_baz"),
("archive://:3:3//tmp/${BAR/BAZ}/test.zip", "archive://:2:2//tmp/bar_baz/test.zip"),
// Zeros all components
("archive:////${EM/PT/Y}", "archive:////"),
("archive://:1//${EM/PT/Y}", "archive://:1//${EM/PT/Y}"),
("archive://:2//${EM/PT/Y}", "archive://:2//${EM/PT/Y}"),
("archive://:3//${EM/PT/Y}", "archive:////"),
("archive://:4//${EM/PT/Y}", "archive://:1//"),
];
for (input, expected) in cases {
let u: UrlBuf = input.parse()?;
assert_eq!(format!("{:?}", expand_url(u).as_url()), expected);
}
Ok(())
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fs/src/path/path.rs | yazi-fs/src/path/path.rs | use yazi_shared::{strand::StrandCow, url::{UrlBuf, UrlLike}};
pub fn skip_url(url: &UrlBuf, n: usize) -> StrandCow<'_> {
let mut it = url.components();
for _ in 0..n {
if it.next().is_none() {
return StrandCow::default();
}
}
it.strand()
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fs/src/path/mod.rs | yazi-fs/src/path/mod.rs | yazi_macro::mod_flat!(clean expand path percent relative);
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fs/src/path/percent.rs | yazi-fs/src/path/percent.rs | use std::{borrow::Cow, path::{Path, PathBuf}};
use anyhow::Result;
use percent_encoding::{AsciiSet, CONTROLS, percent_decode, percent_encode};
use yazi_shared::path::{PathCow, PathDyn, PathKind};
const SET: &AsciiSet =
&CONTROLS.add(b'"').add(b'*').add(b':').add(b'<').add(b'>').add(b'?').add(b'\\').add(b'|');
pub trait PercentEncoding<'a> {
fn percent_encode(self) -> Cow<'a, Path>;
fn percent_decode<K>(self, kind: K) -> Result<PathCow<'a>>
where
K: Into<PathKind>;
}
impl<'a> PercentEncoding<'a> for PathDyn<'a> {
fn percent_encode(self) -> Cow<'a, Path> {
match percent_encode(self.encoded_bytes(), SET).into() {
Cow::Borrowed(s) => Path::new(s).into(),
Cow::Owned(s) => PathBuf::from(s).into(),
}
}
fn percent_decode<K>(self, kind: K) -> Result<PathCow<'a>>
where
K: Into<PathKind>,
{
PathCow::with(kind, percent_decode(self.encoded_bytes()))
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fs/src/path/relative.rs | yazi-fs/src/path/relative.rs | use anyhow::{Result, bail};
use yazi_shared::path::{PathBufDyn, PathCow, PathDyn, PathLike};
pub fn path_relative_to<'a, 'b, P, Q>(from: P, to: Q) -> Result<PathCow<'b>>
where
P: Into<PathCow<'a>>,
Q: Into<PathCow<'b>>,
{
path_relative_to_impl(from.into(), to.into())
}
fn path_relative_to_impl<'a>(from: PathCow<'_>, to: PathCow<'a>) -> Result<PathCow<'a>> {
use yazi_shared::path::Component::*;
if from.is_absolute() != to.is_absolute() {
return if to.is_absolute() {
Ok(to)
} else {
bail!("Paths must be both absolute or both relative: {from:?} and {to:?}");
};
}
if from == to {
return Ok(PathDyn::with_str(from.kind(), ".").into());
}
let (mut f_it, mut t_it) = (from.components(), to.components());
let (f_head, t_head) = loop {
match (f_it.next(), t_it.next()) {
(Some(RootDir), Some(RootDir)) => {}
(Some(Prefix(a)), Some(Prefix(b))) if a == b => {}
(Some(Prefix(_) | RootDir), _) | (_, Some(Prefix(_) | RootDir)) => {
return Ok(to);
}
(None, None) => break (None, None),
(a, b) if a != b => break (a, b),
_ => (),
}
};
let dots = f_head.into_iter().chain(f_it).map(|_| ParentDir);
let rest = t_head.into_iter().chain(t_it);
let buf = PathBufDyn::from_components(from.kind(), dots.chain(rest))?;
Ok(buf.into())
}
#[cfg(test)]
mod tests {
use yazi_shared::path::PathDyn;
use super::*;
#[test]
fn test_path_relative_to() {
yazi_shared::init_tests();
#[cfg(unix)]
let cases = [
// Same paths
("", "", "."),
(".", ".", "."),
("/", "/", "."),
("/a", "/a", "."),
// Relative paths
("foo", "bar", "../bar"),
// Absolute paths
("/a/b", "/a/b/c", "c"),
("/a/b/c", "/a/b", ".."),
("/a/b/d", "/a/b/c", "../c"),
("/a/b/c", "/a", "../.."),
("/a/b/c/", "/a/d/", "../../d"),
("/a/b/b", "/a/a/b", "../../a/b"),
];
#[cfg(windows)]
let cases = [
(r"C:\a\b", r"C:\a\b\c", "c"),
(r"C:\a\b\c", r"C:\a\b", r".."),
(r"C:\a\b\d", r"C:\a\b\c", r"..\c"),
(r"C:\a\b\c", r"C:\a", r"..\.."),
(r"C:\a\b\b", r"C:\a\a\b", r"..\..\a\b"),
];
for (from, to, expected) in cases {
let from = PathDyn::Os(from.as_ref());
let to = PathDyn::Os(to.as_ref());
assert_eq!(path_relative_to(from, to).unwrap().to_str().unwrap(), expected);
}
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fs/src/path/clean.rs | yazi-fs/src/path/clean.rs | use yazi_shared::{path::{PathBufDyn, PathDyn}, url::{UrlBuf, UrlCow, UrlLike}};
pub fn clean_url<'a>(url: impl Into<UrlCow<'a>>) -> UrlBuf {
let cow: UrlCow = url.into();
let (path, uri, urn) = clean_path_impl(
cow.loc(),
cow.base().components().count() - 1,
cow.trail().components().count() - 1,
);
let scheme = cow.into_scheme().into_owned().with_ports(uri, urn);
(scheme, path).try_into().expect("UrlBuf from cleaned path")
}
fn clean_path_impl(path: PathDyn, base: usize, trail: usize) -> (PathBufDyn, usize, usize) {
use yazi_shared::path::Component::*;
let mut out = vec![];
let mut uri_count = 0;
let mut urn_count = 0;
macro_rules! push {
($i:ident, $c:ident) => {{
out.push(($i, $c));
if $i >= base {
uri_count += 1;
}
if $i >= trail {
urn_count += 1;
}
}};
}
macro_rules! pop {
() => {{
if let Some((i, _)) = out.pop() {
if i >= base {
uri_count -= 1;
}
if i >= trail {
urn_count -= 1;
}
}
}};
}
for (i, c) in path.components().enumerate() {
match c {
CurDir => {}
ParentDir => match out.last().map(|(_, c)| c) {
Some(RootDir) => {}
Some(Normal(_)) => pop!(),
None | Some(CurDir) | Some(ParentDir) | Some(Prefix(_)) => push!(i, c),
},
c => push!(i, c),
}
}
let kind = path.kind();
let path = if out.is_empty() {
PathBufDyn::with_str(kind, ".")
} else {
PathBufDyn::from_components(kind, out.into_iter().map(|(_, c)| c))
.expect("components with same kind")
};
(path, uri_count, urn_count)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_clean_url() -> anyhow::Result<()> {
yazi_shared::init_tests();
let cases = [
// CurDir
("archive://:3//./tmp/test.zip/foo/bar", "archive://:3//tmp/test.zip/foo/bar"),
("archive://:3//tmp/./test.zip/foo/bar", "archive://:3//tmp/test.zip/foo/bar"),
("archive://:3//tmp/./test.zip/./foo/bar", "archive://:3//tmp/test.zip/foo/bar"),
("archive://:3//tmp/./test.zip/./foo/./bar/.", "archive://:3//tmp/test.zip/foo/bar"),
// ParentDir
("archive://:3:2//../../tmp/test.zip/foo/bar", "archive://:3:2//tmp/test.zip/foo/bar"),
("archive://:3:2//tmp/../../test.zip/foo/bar", "archive://:3:2//test.zip/foo/bar"),
("archive://:4:2//tmp/test.zip/../../foo/bar", "archive://:2:2//foo/bar"),
("archive://:5:2//tmp/test.zip/../../foo/bar", "archive://:2:2//foo/bar"),
("archive://:4:4//tmp/test.zip/foo/bar/../../", "archive:////tmp/test.zip"),
("archive://:5:4//tmp/test.zip/foo/bar/../../", "archive://:1//tmp/test.zip"),
("archive://:4:4//tmp/test.zip/foo/bar/../../../", "archive:////tmp"),
("sftp://test//root/.config/yazi/../../Downloads", "sftp://test//root/Downloads"),
];
for (input, expected) in cases {
let input: UrlBuf = input.parse()?;
#[cfg(unix)]
assert_eq!(format!("{:?}", clean_url(input)), expected);
#[cfg(windows)]
assert_eq!(format!("{:?}", clean_url(input)).replace(r"\", "/"), expected.replace(r"\", "/"));
}
Ok(())
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/predictor.rs | yazi-shared/src/predictor.rs | // --- BytePredictor
pub trait BytePredictor {
fn predicate(&self, byte: u8) -> bool;
}
// --- Utf8BytePredictor
pub trait Utf8BytePredictor {
fn predicate(&self, byte: u8) -> bool;
}
// --- AnyAsciiChar
pub struct AnyAsciiChar<'a>(&'a [u8]);
impl<'a> AnyAsciiChar<'a> {
pub fn new(chars: &'a [u8]) -> Option<Self> {
if chars.iter().all(|&b| b <= 0x7f) { Some(Self(chars)) } else { None }
}
}
impl Utf8BytePredictor for AnyAsciiChar<'_> {
fn predicate(&self, byte: u8) -> bool { self.0.contains(&byte) }
}
impl<T> BytePredictor for T
where
T: Utf8BytePredictor,
{
fn predicate(&self, byte: u8) -> bool { self.predicate(byte) }
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/throttle.rs | yazi-shared/src/throttle.rs | use std::{fmt::Debug, mem, sync::atomic::{AtomicU64, AtomicUsize, Ordering}, time::Duration};
use parking_lot::Mutex;
use crate::timestamp_us;
#[derive(Debug)]
pub struct Throttle<T> {
total: AtomicUsize,
interval: Duration,
last: AtomicU64,
buf: Mutex<Vec<T>>,
}
impl<T> Throttle<T> {
pub fn new(total: usize, interval: Duration) -> Self {
Self {
total: AtomicUsize::new(total),
interval,
last: AtomicU64::new(timestamp_us() - interval.as_micros() as u64),
buf: Default::default(),
}
}
pub fn done<F>(&self, data: T, f: F)
where
F: FnOnce(Vec<T>),
{
let total = self.total.fetch_sub(1, Ordering::Relaxed);
if total == 1 {
return self.flush(data, f);
}
let last = self.last.load(Ordering::Relaxed);
let now = timestamp_us();
if now > self.interval.as_micros() as u64 + last {
self.last.store(now, Ordering::Relaxed);
return self.flush(data, f);
}
self.buf.lock().push(data);
}
#[inline]
fn flush<F>(&self, data: T, f: F)
where
F: FnOnce(Vec<T>),
{
let mut buf = mem::take(&mut *self.buf.lock());
buf.push(data);
f(buf)
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/bytes.rs | yazi-shared/src/bytes.rs | use std::fmt::Display;
use crate::BytePredictor;
pub trait BytesExt {
fn display(&self) -> impl Display;
fn kebab_cased(&self) -> bool;
fn rsplit_pred_once<P: BytePredictor>(&self, pred: P) -> Option<(&[u8], &[u8])>;
fn rsplit_seq_once(&self, sep: &[u8]) -> Option<(&[u8], &[u8])>;
fn split_seq_once(&self, sep: &[u8]) -> Option<(&[u8], &[u8])>;
}
impl BytesExt for [u8] {
fn display(&self) -> impl Display {
struct D<'a>(&'a [u8]);
impl Display for D<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for chunk in self.0.utf8_chunks() {
chunk.valid().fmt(f)?;
if !chunk.invalid().is_empty() {
char::REPLACEMENT_CHARACTER.fmt(f)?;
}
}
Ok(())
}
}
D(self)
}
fn kebab_cased(&self) -> bool {
self.iter().all(|&b| matches!(b, b'0'..=b'9' | b'a'..=b'z' | b'-'))
}
fn rsplit_pred_once<P: BytePredictor>(&self, pred: P) -> Option<(&[u8], &[u8])> {
for (i, &byte) in self.iter().enumerate().rev() {
if pred.predicate(byte) {
let (a, b) = self.split_at(i);
return Some((a, &b[1..]));
}
}
None
}
fn split_seq_once(&self, sep: &[u8]) -> Option<(&[u8], &[u8])> {
let idx = memchr::memmem::find(self, sep)?;
let (a, b) = self.split_at(idx);
Some((a, &b[sep.len()..]))
}
fn rsplit_seq_once(&self, sep: &[u8]) -> Option<(&[u8], &[u8])> {
let idx = memchr::memmem::rfind(self, sep)?;
let (a, b) = self.split_at(idx);
Some((a, &b[sep.len()..]))
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/source.rs | yazi-shared/src/source.rs | use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
pub enum Source {
#[default]
Unknown,
Key,
Emit,
Relay,
Ind,
}
impl Source {
#[inline]
pub fn is_key(self) -> bool { self == Self::Key }
#[inline]
pub fn is_ind(self) -> bool { self == Self::Ind }
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/lib.rs | yazi-shared/src/lib.rs | yazi_macro::mod_pub!(data errors event loc path pool scheme shell strand translit url wtf8);
yazi_macro::mod_flat!(alias bytes chars completion_token condition debounce either env id layer localset natsort os predictor ro_cell source sync_cell terminal tests throttle time utf8);
pub fn init() {
LOCAL_SET.with(tokio::task::LocalSet::new);
LOG_LEVEL.replace(<_>::from(std::env::var("YAZI_LOG").unwrap_or_default()));
#[cfg(unix)]
USERS_CACHE.with(<_>::default);
pool::init();
event::Event::init();
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/completion_token.rs | yazi-shared/src/completion_token.rs | use std::sync::{Arc, atomic::{AtomicU8, Ordering}};
use tokio::sync::Notify;
#[derive(Clone, Debug, Default)]
pub struct CompletionToken {
inner: Arc<(AtomicU8, Notify)>,
}
impl CompletionToken {
pub fn complete(&self, success: bool) {
let new = if success { 1 } else { 2 };
self.inner.0.compare_exchange(0, new, Ordering::Relaxed, Ordering::Relaxed).ok();
self.inner.1.notify_waiters();
}
pub fn completed(&self) -> Option<bool> {
let state = self.inner.0.load(Ordering::Relaxed);
if state == 0 { None } else { Some(state == 1) }
}
pub async fn future(&self) -> bool {
loop {
if let Some(state) = self.completed() {
return state;
}
let notified = self.inner.1.notified();
if let Some(state) = self.completed() {
return state;
}
notified.await;
}
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/tests.rs | yazi-shared/src/tests.rs | pub fn init_tests() {
static INIT: std::sync::OnceLock<()> = std::sync::OnceLock::new();
INIT.get_or_init(|| {
crate::init();
});
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/id.rs | yazi-shared/src/id.rs | use std::{fmt::Display, str::FromStr, sync::atomic::{AtomicU64, Ordering}};
use serde::{Deserialize, Serialize};
#[derive(
Clone, Copy, Debug, Default, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize,
)]
pub struct Id(pub u64);
impl Id {
#[inline]
pub const fn get(&self) -> u64 { self.0 }
pub fn unique() -> Self { Self(crate::timestamp_us()) }
}
impl Display for Id {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.0.fmt(f) }
}
impl FromStr for Id {
type Err = <u64 as FromStr>::Err;
fn from_str(s: &str) -> Result<Self, Self::Err> { s.parse().map(Self) }
}
impl From<u64> for Id {
fn from(value: u64) -> Self { Self(value) }
}
impl From<usize> for Id {
fn from(value: usize) -> Self { Self(value as u64) }
}
impl TryFrom<i64> for Id {
type Error = <u64 as TryFrom<i64>>::Error;
fn try_from(value: i64) -> Result<Self, Self::Error> { u64::try_from(value).map(Self) }
}
impl PartialEq<u64> for Id {
fn eq(&self, other: &u64) -> bool { self.0 == *other }
}
// --- Ids
pub struct Ids {
next: AtomicU64,
}
impl Ids {
#[inline]
pub const fn new() -> Self { Self { next: AtomicU64::new(1) } }
#[inline]
pub fn next(&self) -> Id {
loop {
let old = self.next.fetch_add(1, Ordering::Relaxed);
if old != 0 {
return Id(old);
}
}
}
#[inline]
pub fn current(&self) -> Id { Id(self.next.load(Ordering::Relaxed)) }
}
impl Default for Ids {
fn default() -> Self { Self::new() }
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/os.rs | yazi-shared/src/os.rs | #[cfg(unix)]
pub static USERS_CACHE: crate::RoCell<uzers::UsersCache> = crate::RoCell::new();
#[cfg(unix)]
pub fn hostname() -> Option<&'static str> {
static CACHE: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new();
CACHE.get_or_init(|| hostname_impl().ok()).as_deref()
}
#[cfg(unix)]
fn hostname_impl() -> Result<String, std::io::Error> {
use libc::{gethostname, strlen};
let mut s = [0; 256];
let len = unsafe {
if gethostname(s.as_mut_ptr() as *mut _, 255) == -1 {
return Err(std::io::Error::last_os_error());
}
strlen(s.as_ptr() as *const _)
};
std::str::from_utf8(&s[..len])
.map_err(|_| std::io::Error::other("invalid hostname"))
.map(|s| s.to_owned())
}
#[cfg(unix)]
pub fn session_leader() -> bool { unsafe { libc::getsid(0) == libc::getpid() } }
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/natsort.rs | yazi-shared/src/natsort.rs | // A natural sort implementation in Rust.
// Copyright (c) 2023, sxyazi.
//
// This is a port of the C version of Martin Pool's `strnatcmp.c`:
// http://sourcefrog.net/projects/natsort/
use std::cmp::Ordering;
macro_rules! return_unless_equal {
($ord:expr) => {
match $ord {
Ordering::Equal => {}
ord => return ord,
}
};
}
#[inline(always)]
fn compare_left(left: &[u8], right: &[u8], li: &mut usize, ri: &mut usize) -> Ordering {
let mut l;
let mut r;
loop {
l = left.get(*li);
r = right.get(*ri);
match (l.is_some_and(|b| b.is_ascii_digit()), r.is_some_and(|b| b.is_ascii_digit())) {
(true, true) => {
return_unless_equal!(unsafe { l.unwrap_unchecked().cmp(r.unwrap_unchecked()) })
}
(true, false) => return Ordering::Greater,
(false, true) => return Ordering::Less,
(false, false) => return Ordering::Equal,
}
*li += 1;
*ri += 1;
}
}
#[inline(always)]
fn compare_right(left: &[u8], right: &[u8], li: &mut usize, ri: &mut usize) -> Ordering {
let mut l;
let mut r;
let mut bias = Ordering::Equal;
loop {
l = left.get(*li);
r = right.get(*ri);
match (l.is_some_and(|b| b.is_ascii_digit()), r.is_some_and(|b| b.is_ascii_digit())) {
(true, true) => {
if bias == Ordering::Equal {
bias = unsafe { l.unwrap_unchecked().cmp(r.unwrap_unchecked()) };
}
}
(true, false) => return Ordering::Greater,
(false, true) => return Ordering::Less,
(false, false) => return bias,
}
*li += 1;
*ri += 1;
}
}
pub fn natsort(left: &[u8], right: &[u8], insensitive: bool) -> Ordering {
let mut li = 0;
let mut ri = 0;
let mut l = left.get(li);
let mut r = right.get(ri);
macro_rules! left_next {
() => {{
li += 1;
l = left.get(li);
}};
}
macro_rules! right_next {
() => {{
ri += 1;
r = right.get(ri);
}};
}
loop {
while l.is_some_and(|c| c.is_ascii_whitespace()) {
left_next!();
}
while r.is_some_and(|c| c.is_ascii_whitespace()) {
right_next!();
}
match (l, r) {
(Some(&ll), Some(&rr)) => {
if ll.is_ascii_digit() && rr.is_ascii_digit() {
if ll == b'0' || rr == b'0' {
return_unless_equal!(compare_left(left, right, &mut li, &mut ri));
} else {
return_unless_equal!(compare_right(left, right, &mut li, &mut ri));
}
l = left.get(li);
r = right.get(ri);
continue;
}
if insensitive {
return_unless_equal!(ll.to_ascii_lowercase().cmp(&rr.to_ascii_lowercase()));
} else {
return_unless_equal!(ll.cmp(&rr));
}
}
(Some(_), None) => return Ordering::Greater,
(None, Some(_)) => return Ordering::Less,
(None, None) => return Ordering::Equal,
}
left_next!();
right_next!();
}
}
#[cfg(test)]
mod tests {
use super::*;
fn cmp(left: &[&str]) {
let mut right = left.to_vec();
right.sort_by(|a, b| natsort(a.as_bytes(), b.as_bytes(), true));
assert_eq!(left, right);
}
#[test]
fn test_natsort() {
let dates = ["1999-3-3", "1999-12-25", "2000-1-2", "2000-1-10", "2000-3-23"];
let fractions = [
"1.002.01", "1.002.03", "1.002.08", "1.009.02", "1.009.10", "1.009.20", "1.010.12",
"1.011.02",
];
let words = [
"1-02",
"1-2",
"1-20",
"10-20",
"fred",
"jane",
"pic01",
"pic02",
"pic02a",
"pic02000",
"pic05",
"pic2",
"pic3",
"pic4",
"pic 4 else",
"pic 5",
"pic 5 ",
"pic 5 something",
"pic 6",
"pic 7",
"pic100",
"pic100a",
"pic120",
"pic121",
"tom",
"x2-g8",
"x2-y08",
"x2-y7",
"x8-y8",
];
cmp(&dates);
cmp(&fractions);
cmp(&words);
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/time.rs | yazi-shared/src/time.rs | use std::time::{SystemTime, UNIX_EPOCH};
#[inline]
pub fn timestamp_us() -> u64 {
SystemTime::now().duration_since(UNIX_EPOCH).expect("Time went backwards").as_micros() as _
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/chars.rs | yazi-shared/src/chars.rs | use core::str;
use std::borrow::Cow;
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum CharKind {
Space,
Punct,
Other,
}
impl CharKind {
pub fn new(c: char) -> Self {
if c.is_whitespace() {
Self::Space
} else if c.is_ascii_punctuation() {
Self::Punct
} else {
Self::Other
}
}
pub fn vary(self, other: Self, far: bool) -> bool {
if far { (self == Self::Space) != (other == Self::Space) } else { self != other }
}
}
pub fn strip_trailing_newline(mut s: String) -> String {
while s.ends_with('\n') || s.ends_with('\r') {
s.pop();
}
s
}
pub fn replace_cow<'a, T>(s: T, from: &str, to: &str) -> Cow<'a, str>
where
T: Into<Cow<'a, str>>,
{
let cow = s.into();
match replace_cow_impl(&cow, cow.match_indices(from), to) {
Cow::Borrowed(_) => cow,
Cow::Owned(new) => Cow::Owned(new),
}
}
pub fn replacen_cow<'a, T>(s: T, from: &str, to: &str, n: usize) -> Cow<'a, str>
where
T: Into<Cow<'a, str>>,
{
let cow = s.into();
match replace_cow_impl(&cow, cow.match_indices(from).take(n), to) {
Cow::Borrowed(_) => cow,
Cow::Owned(now) => Cow::Owned(now),
}
}
fn replace_cow_impl<'a, T>(src: &'a str, mut indices: T, to: &str) -> Cow<'a, str>
where
T: Iterator<Item = (usize, &'a str)>,
{
let Some((first_idx, first_sub)) = indices.next() else {
return Cow::Borrowed(src);
};
let mut result = String::with_capacity(src.len());
result += unsafe { src.get_unchecked(..first_idx) };
result += to;
let mut last = first_idx + first_sub.len();
for (idx, sub) in indices {
result += unsafe { src.get_unchecked(last..idx) };
result += to;
last = idx + sub.len();
}
Cow::Owned(result + unsafe { src.get_unchecked(last..) })
}
pub fn replace_vec_cow<'a>(v: &'a [u8], from: &[u8], to: &[u8]) -> Cow<'a, [u8]> {
let mut it = memchr::memmem::find_iter(v, from);
let Some(mut last) = it.next() else { return Cow::Borrowed(v) };
let mut out = Vec::with_capacity(v.len());
out.extend_from_slice(&v[..last]);
out.extend_from_slice(to);
last += from.len();
for idx in it {
out.extend_from_slice(&v[last..idx]);
out.extend_from_slice(to);
last = idx + from.len();
}
out.extend_from_slice(&v[last..]);
Cow::Owned(out)
}
pub fn replace_to_printable(b: &[u8], lf: bool, tab_size: u8, replacement: bool) -> Cow<'_, [u8]> {
// Fast path to skip over printable chars at the beginning of the string
let printable_len = b.iter().take_while(|&&c| !c.is_ascii_control()).count();
if printable_len >= b.len() {
return Cow::Borrowed(b);
}
let (printable, rest) = b.split_at(printable_len);
let mut out = Vec::new();
out.reserve_exact(b.len() | 15);
out.extend_from_slice(printable);
for &c in rest {
push_printable_char(&mut out, c, lf, tab_size, replacement);
}
Cow::Owned(out)
}
#[inline]
pub fn push_printable_char(buf: &mut Vec<u8>, c: u8, lf: bool, tab_size: u8, replacement: bool) {
match c {
b'\n' if lf => buf.push(b'\n'),
b'\t' => {
buf.extend((0..tab_size).map(|_| b' '));
}
b'\0'..=b'\x1F' => {
if replacement {
buf.extend_from_slice(&[0xef, 0xbf, 0xbd]);
} else {
buf.push(b'^');
buf.push(c + b'@');
}
}
0x7f => {
if replacement {
buf.extend_from_slice(&[0xef, 0xbf, 0xbd]);
} else {
buf.push(b'^');
buf.push(b'?');
}
}
_ => buf.push(c),
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/env.rs | yazi-shared/src/env.rs | use std::fmt::{Display, Formatter};
pub static LOG_LEVEL: crate::SyncCell<LogLevel> = crate::SyncCell::new(LogLevel::None);
#[inline]
pub fn env_exists(name: &str) -> bool { std::env::var_os(name).is_some_and(|s| !s.is_empty()) }
#[inline]
pub fn in_wsl() -> bool {
#[cfg(target_os = "linux")]
{
std::fs::symlink_metadata("/proc/sys/fs/binfmt_misc/WSLInterop").is_ok()
}
#[cfg(not(target_os = "linux"))]
{
false
}
}
#[inline]
pub fn in_ssh_connection() -> bool {
env_exists("SSH_CLIENT") || env_exists("SSH_TTY") || env_exists("SSH_CONNECTION")
}
// LogLevel
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LogLevel {
None,
Error,
Warn,
Info,
Debug,
}
impl LogLevel {
#[inline]
pub fn is_none(self) -> bool { self == Self::None }
}
impl From<String> for LogLevel {
fn from(mut s: String) -> Self {
s.make_ascii_uppercase();
match s.as_str() {
"ERROR" => Self::Error,
"WARN" => Self::Warn,
"INFO" => Self::Info,
"DEBUG" => Self::Debug,
_ => Self::None,
}
}
}
impl AsRef<str> for LogLevel {
fn as_ref(&self) -> &str {
match self {
Self::None => "yazi=NONE",
Self::Error => "yazi=ERROR",
Self::Warn => "yazi=WARN",
Self::Info => "yazi=INFO",
Self::Debug => "yazi=DEBUG",
}
}
}
impl Display for LogLevel {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.as_ref()) }
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/layer.rs | yazi-shared/src/layer.rs | use std::{fmt::Display, str::FromStr};
use serde::Deserialize;
#[derive(Debug, Default, PartialEq, Eq, Hash, Clone, Copy, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Layer {
#[default]
App,
Mgr,
Tasks,
Spot,
Pick,
Input,
Confirm,
Help,
Cmp,
Which,
}
impl Display for Layer {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::App => "app",
Self::Mgr => "mgr",
Self::Tasks => "tasks",
Self::Spot => "spot",
Self::Pick => "pick",
Self::Input => "input",
Self::Confirm => "confirm",
Self::Help => "help",
Self::Cmp => "cmp",
Self::Which => "which",
})
}
}
impl FromStr for Layer {
type Err = serde::de::value::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::deserialize(serde::de::value::StrDeserializer::new(s))
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/localset.rs | yazi-shared/src/localset.rs | use tokio::task::LocalSet;
use crate::RoCell;
pub static LOCAL_SET: RoCell<LocalSet> = RoCell::new();
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/ro_cell.rs | yazi-shared/src/ro_cell.rs | use std::{cell::UnsafeCell, fmt::{self, Display}, mem::MaybeUninit, ops::Deref};
// Read-only cell. It's safe to use this in a static variable, but it's not safe
// to mutate it. This is useful for storing static data that is expensive to
// initialize, but is immutable once.
pub struct RoCell<T> {
inner: UnsafeCell<MaybeUninit<T>>,
#[cfg(debug_assertions)]
initialized: UnsafeCell<bool>,
}
unsafe impl<T> Sync for RoCell<T> {}
impl<T> RoCell<T> {
#[inline]
pub const fn new() -> Self {
Self {
inner: UnsafeCell::new(MaybeUninit::uninit()),
#[cfg(debug_assertions)]
initialized: UnsafeCell::new(false),
}
}
#[inline]
pub const fn new_const(value: T) -> Self {
Self {
inner: UnsafeCell::new(MaybeUninit::new(value)),
#[cfg(debug_assertions)]
initialized: UnsafeCell::new(true),
}
}
#[inline]
pub fn init(&self, value: T) {
unsafe {
#[cfg(debug_assertions)]
assert!(!self.initialized.get().replace(true));
*self.inner.get() = MaybeUninit::new(value);
}
}
#[inline]
pub fn with<F>(&self, f: F)
where
F: FnOnce() -> T,
{
self.init(f());
}
#[inline]
pub fn drop(&self) -> T {
unsafe {
#[cfg(debug_assertions)]
assert!(self.initialized.get().replace(false));
self.inner.get().replace(MaybeUninit::uninit()).assume_init()
}
}
}
impl<T> Default for RoCell<T> {
fn default() -> Self { Self::new() }
}
impl<T> Deref for RoCell<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
unsafe {
#[cfg(debug_assertions)]
assert!(*self.initialized.get());
(*self.inner.get()).assume_init_ref()
}
}
}
impl<T> Display for RoCell<T>
where
T: Display,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.deref().fmt(f) }
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/either.rs | yazi-shared/src/either.rs | use serde::Serialize;
#[derive(Clone, Copy, Debug)]
pub enum Either<L, R> {
Left(L),
Right(R),
}
impl<L, R> Either<L, R> {
pub fn left(&self) -> Option<&L> {
match self {
Self::Left(l) => Some(l),
_ => None,
}
}
pub fn right(&self) -> Option<&R> {
match self {
Self::Right(r) => Some(r),
_ => None,
}
}
pub fn left_mut(&mut self) -> Option<&mut L> {
match self {
Self::Left(l) => Some(l),
_ => None,
}
}
pub fn right_mut(&mut self) -> Option<&mut R> {
match self {
Self::Right(r) => Some(r),
_ => None,
}
}
pub fn is_left_and<F: FnOnce(&L) -> bool>(&self, f: F) -> bool {
self.left().map(f).unwrap_or(false)
}
pub fn is_right_and<F: FnOnce(&R) -> bool>(&self, f: F) -> bool {
self.right().map(f).unwrap_or(false)
}
pub fn into_left(self) -> Option<L> {
match self {
Self::Left(l) => Some(l),
_ => None,
}
}
pub fn into_right(self) -> Option<R> {
match self {
Self::Right(r) => Some(r),
_ => None,
}
}
pub fn left_or_err<E, F: FnOnce() -> E>(self, f: F) -> Result<L, E> {
match self {
Self::Left(l) => Ok(l),
_ => Err(f()),
}
}
pub fn right_or_err<E, F: FnOnce() -> E>(self, f: F) -> Result<R, E> {
match self {
Self::Right(r) => Ok(r),
_ => Err(f()),
}
}
}
impl<L, R> Serialize for Either<L, R>
where
L: Serialize,
R: Serialize,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
match self {
Self::Left(l) => l.serialize(serializer),
Self::Right(r) => r.serialize(serializer),
}
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/debounce.rs | yazi-shared/src/debounce.rs | use std::{pin::Pin, task::{Context, Poll}, time::Duration};
use futures::{FutureExt, Stream, StreamExt};
use tokio::time::{Instant, Sleep, sleep};
pub struct Debounce<S>
where
S: Stream,
{
stream: S,
interval: Duration,
sleep: Sleep,
last: Option<S::Item>,
}
impl<S> Debounce<S>
where
S: Stream + Unpin,
{
pub fn new(stream: S, interval: Duration) -> Self {
Self { stream, interval, sleep: sleep(Duration::ZERO), last: None }
}
}
impl<S> Stream for Debounce<S>
where
S: Stream + Unpin,
{
type Item = S::Item;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let (mut stream, interval, mut sleep, last) = unsafe {
let me = self.get_unchecked_mut();
(Pin::new(&mut me.stream), me.interval, Pin::new_unchecked(&mut me.sleep), &mut me.last)
};
if sleep.poll_unpin(cx).is_ready()
&& let Some(last) = last.take()
{
return Poll::Ready(Some(last));
}
while let Poll::Ready(next) = stream.poll_next_unpin(cx) {
match next {
Some(next) => {
*last = Some(next);
}
None if last.is_none() => {
return Poll::Ready(None);
}
None => {
sleep.reset(Instant::now());
return Poll::Pending;
}
}
}
sleep.reset(Instant::now() + interval);
Poll::Pending
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/terminal.rs | yazi-shared/src/terminal.rs | use std::io::Write;
use crossterm::execute;
#[inline]
pub fn terminal_clear(mut w: impl Write) -> std::io::Result<()> {
execute!(
w,
crossterm::terminal::Clear(crossterm::terminal::ClearType::All),
crossterm::style::Print("\n")
)
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/alias.rs | yazi-shared/src/alias.rs | pub type SStr = std::borrow::Cow<'static, str>;
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/condition.rs | yazi-shared/src/condition.rs | use std::str::FromStr;
use anyhow::bail;
use serde::{Deserialize, Deserializer, de};
#[derive(Debug, PartialEq, Eq)]
pub enum ConditionOp {
Or,
And,
Not,
// Only used in `build()`
Space,
LeftParen,
RightParen,
Unknown,
// Only used in `eval()`
Term(String),
}
impl ConditionOp {
pub fn new(c: char) -> Self {
match c {
'|' => Self::Or,
'&' => Self::And,
'!' => Self::Not,
'(' => Self::LeftParen,
')' => Self::RightParen,
_ if c.is_ascii_whitespace() => Self::Space,
_ => Self::Unknown,
}
}
#[inline]
pub fn prec(&self) -> u8 {
match self {
Self::Or => 1,
Self::And => 2,
Self::Not => 3,
_ => 0,
}
}
}
#[derive(Debug)]
pub struct Condition {
ops: Vec<ConditionOp>,
}
impl FromStr for Condition {
type Err = anyhow::Error;
fn from_str(expr: &str) -> Result<Self, Self::Err> {
let cond = Self::build(expr);
if cond.eval(|_| true).is_none() {
bail!("Invalid condition: {expr}");
}
Ok(cond)
}
}
impl<'de> Deserialize<'de> for Condition {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
FromStr::from_str(&s).map_err(de::Error::custom)
}
}
impl Condition {
fn build(expr: &str) -> Self {
let mut stack: Vec<ConditionOp> = vec![];
let mut output: Vec<ConditionOp> = vec![];
let mut chars = expr.chars().peekable();
while let Some(token) = chars.next() {
let op = ConditionOp::new(token);
match op {
ConditionOp::Or | ConditionOp::And | ConditionOp::Not => {
while matches!(stack.last(), Some(last) if last.prec() >= op.prec()) {
output.push(stack.pop().unwrap());
}
stack.push(op);
}
ConditionOp::Space => continue,
ConditionOp::LeftParen => stack.push(op),
ConditionOp::RightParen => {
while matches!(stack.last(), Some(last) if last != &ConditionOp::LeftParen) {
output.push(stack.pop().unwrap());
}
stack.pop();
}
ConditionOp::Unknown => {
let mut s = String::from(token);
while matches!(chars.peek(), Some(&c) if ConditionOp::new(c) == op) {
s.push(chars.next().unwrap());
}
output.push(ConditionOp::Term(s));
}
ConditionOp::Term(_) => unreachable!(),
}
}
while let Some(op) = stack.pop() {
output.push(op);
}
Self { ops: output }
}
pub fn eval(&self, f: impl Fn(&str) -> bool) -> Option<bool> {
let mut stack: Vec<bool> = Vec::with_capacity(self.ops.len());
for op in &self.ops {
match op {
ConditionOp::Or => {
let b = stack.pop()? | stack.pop()?;
stack.push(b);
}
ConditionOp::And => {
let b = stack.pop()? & stack.pop()?;
stack.push(b);
}
ConditionOp::Not => {
let b = !stack.pop()?;
stack.push(b);
}
ConditionOp::Term(s) => {
stack.push(f(s));
}
_ => return None,
}
}
if stack.len() == 1 { Some(stack[0]) } else { None }
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/sync_cell.rs | yazi-shared/src/sync_cell.rs | use std::{cell::Cell, fmt::{Debug, Display, Formatter}, ops::Deref};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
/// [`SyncCell`], but [`Sync`].
///
/// This is just an `Cell`, except it implements `Sync`
/// if `T` implements `Sync`.
pub struct SyncCell<T: ?Sized>(Cell<T>);
unsafe impl<T: ?Sized + Sync> Sync for SyncCell<T> {}
impl<T> SyncCell<T> {
#[inline]
pub const fn new(value: T) -> Self { Self(Cell::new(value)) }
}
impl<T: Default> Default for SyncCell<T> {
fn default() -> Self { Self::new(T::default()) }
}
impl<T> Deref for SyncCell<T> {
type Target = Cell<T>;
#[inline]
fn deref(&self) -> &Self::Target { &self.0 }
}
impl<T: Copy> Clone for SyncCell<T> {
#[inline]
fn clone(&self) -> Self { Self::new(self.get()) }
}
impl<T: Copy + Debug> Debug for SyncCell<T> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { Debug::fmt(&self.get(), f) }
}
impl<T: Copy + Display> Display for SyncCell<T> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { Display::fmt(&self.get(), f) }
}
impl<T> Serialize for SyncCell<T>
where
T: Copy + Serialize,
{
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
self.0.serialize(serializer)
}
}
impl<'de, T> Deserialize<'de> for SyncCell<T>
where
T: Copy + Deserialize<'de>,
{
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
Ok(Self::new(T::deserialize(deserializer)?))
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/utf8.rs | yazi-shared/src/utf8.rs | // https://tools.ietf.org/html/rfc3629
const UTF8_CHAR_WIDTH: &[u8; 256] = &[
// 1 2 3 4 5 6 7 8 9 A B C D E F
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 2
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 3
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 8
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 9
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // A
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // B
0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // C
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // D
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, // E
4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // F
];
/// Given a first byte, determines how many bytes are in this UTF-8 character.
#[must_use]
#[inline]
pub const fn utf8_char_width(b: u8) -> usize { UTF8_CHAR_WIDTH[b as usize] as usize }
/// Finds the closest `x` not exceeding `index` where [`is_char_boundary(x)`] is
/// `true`.
///
/// This method can help you truncate a string so that it's still valid UTF-8,
/// but doesn't exceed a given number of bytes. Note that this is done purely at
/// the character level and can still visually split graphemes, even though the
/// underlying characters aren't split. For example, the emoji 🧑🔬 (scientist)
/// could be split so that the string only includes 🧑 (person) instead.
#[inline]
pub fn floor_char_boundary(s: &str, index: usize) -> usize {
if index >= s.len() {
s.len()
} else {
let lower_bound = index.saturating_sub(3);
let new_index =
s.as_bytes()[lower_bound..=index].iter().rposition(|&b| is_utf8_char_boundary(b));
// SAFETY: we know that the character boundary will be within four bytes
unsafe { lower_bound + new_index.unwrap_unchecked() }
}
}
#[inline]
const fn is_utf8_char_boundary(b: u8) -> bool {
// This is bit magic equivalent to: b < 128 || b >= 192
(b as i8) >= -0x40
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/wtf8/wtf8.rs | yazi-shared/src/wtf8/wtf8.rs | use std::ffi::{OsStr, OsString};
use anyhow::Result;
// --- AsWtf8
pub trait AsWtf8 {
fn as_wtf8(&self) -> &[u8];
}
impl AsWtf8 for OsStr {
fn as_wtf8(&self) -> &[u8] {
#[cfg(unix)]
{
use std::os::unix::ffi::OsStrExt;
self.as_bytes()
}
#[cfg(windows)]
{
self.as_encoded_bytes()
}
}
}
// --- FromWtf8
pub trait FromWtf8 {
fn from_wtf8(wtf8: &[u8]) -> Result<&Self>;
}
impl FromWtf8 for OsStr {
fn from_wtf8(wtf8: &[u8]) -> Result<&Self> {
#[cfg(unix)]
{
use std::os::unix::ffi::OsStrExt;
Ok(Self::from_bytes(wtf8))
}
#[cfg(windows)]
{
if super::valid_wtf8(wtf8) {
Ok(unsafe { Self::from_encoded_bytes_unchecked(wtf8) })
} else {
Err(anyhow::anyhow!("Invalid WTF-8 sequence"))
}
}
}
}
impl FromWtf8 for std::path::Path {
fn from_wtf8(wtf8: &[u8]) -> Result<&Self> { Ok(OsStr::from_wtf8(wtf8)?.as_ref()) }
}
// --- FromWtf8Vec
pub trait FromWtf8Vec {
fn from_wtf8_vec(wtf8: Vec<u8>) -> Result<Self>
where
Self: Sized;
}
impl FromWtf8Vec for OsString {
fn from_wtf8_vec(wtf8: Vec<u8>) -> Result<Self> {
#[cfg(unix)]
{
use std::os::unix::ffi::OsStringExt;
Ok(Self::from_vec(wtf8))
}
#[cfg(windows)]
{
if super::valid_wtf8(&wtf8) {
Ok(unsafe { Self::from_encoded_bytes_unchecked(wtf8) })
} else {
Err(anyhow::anyhow!("Invalid WTF-8 sequence"))
}
}
}
}
impl FromWtf8Vec for std::path::PathBuf {
fn from_wtf8_vec(wtf8: Vec<u8>) -> Result<Self> { Ok(OsString::from_wtf8_vec(wtf8)?.into()) }
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/wtf8/mod.rs | yazi-shared/src/wtf8/mod.rs | yazi_macro::mod_flat!(validator wtf8);
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/wtf8/validator.rs | yazi-shared/src/wtf8/validator.rs | #[cfg(windows)]
pub(super) fn valid_wtf8(bytes: &[u8]) -> bool {
let mut i = 0;
while i < bytes.len() {
let b = bytes[i];
if b < 0b1000_0000 {
// ASCII
i += 1;
continue;
}
// 2-byte: 110x_xxxx 10xx_xxxx
// first byte must be >= 0b1100_0010 to forbid overlongs
if (b & 0b1110_0000) == 0b1100_0000 {
if b < 0b1100_0010 {
return false;
}
if i + 1 >= bytes.len() {
return false;
}
if (bytes[i + 1] & 0b1100_0000) != 0b1000_0000 {
return false;
}
i += 2;
continue;
}
// 3-byte: 1110_xxxx 10xx_xxxx 10xx_xxxx
if (b & 0b1111_0000) == 0b1110_0000 {
if i + 2 >= bytes.len() {
return false;
}
let (b1, b2) = (bytes[i + 1], bytes[i + 2]);
if (b1 & 0b1100_0000) != 0b1000_0000 || (b2 & 0b1100_0000) != 0b1000_0000 {
return false;
}
if b == 0b1110_0000 && b1 < 0b1010_0000 {
// to forbid overlongs, second byte must be >= 0xA0
return false;
}
i += 3;
continue;
}
// 4-byte: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
if (b & 0b1111_1000) == 0b1111_0000 {
if b > 0b1111_0100 {
return false;
}
if i + 3 >= bytes.len() {
return false;
}
let (b1, b2, b3) = (bytes[i + 1], bytes[i + 2], bytes[i + 3]);
if (b1 & 0b1100_0000) != 0b1000_0000
|| (b2 & 0b1100_0000) != 0b1000_0000
|| (b3 & 0b1100_0000) != 0b1000_0000
{
return false;
}
if b == 0b1111_0000 && b1 < 0b1001_0000 {
// to forbid overlongs for > U+FFFF, second byte must be >= 0x90
return false;
} else if b == 0b1111_0100 && b1 > 0b1000_1111 {
// to stay <= U+10FFFF, second byte must be <= 0x8F
return false;
}
i += 4;
continue;
}
return false;
}
true
}
#[cfg(windows)]
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_valid_wtf8() {
let cases: &[(&[u8], bool)] = &[
// Valid ASCII
(b"hello", true),
// Valid 2-byte UTF-8
(&[0xc2, 0xa0], true), // U+00A0
// Invalid 2-byte: overlong encoding
(&[0xc0, 0x80], false), // overlong for U+0000
(&[0xc1, 0xbf], false), // overlong for U+007F
// Valid 3-byte UTF-8
(&[0xe0, 0xa0, 0x80], true), // U+0800
// Invalid 3-byte: overlong encoding
(&[0xe0, 0x9f, 0xbf], false), // overlong for U+07FF
// WTF-8 specific: unpaired surrogates (should be valid in WTF-8)
((&[0xed, 0xa0, 0x80]), true), // U+D800 = ED A0 80 (high surrogate)
((&[0xed, 0xbf, 0xbf]), true), // U+DFFF = ED BF BF (low surrogate)
// Valid 4-byte UTF-8
((&[0xf0, 0x90, 0x80, 0x80]), true), // U+10000
// Invalid 4-byte: overlong
((&[0xf0, 0x8f, 0xbf, 0xbf]), false), // overlong for U+FFFF
// Invalid 4-byte: beyond U+10FFFF
((&[0xf4, 0x90, 0x80, 0x80]), false), // U+110000
// Invalid continuation byte
((&[0xc2, 0x00]), false),
// Incomplete sequence
((&[0xc2]), false),
((&[0xe0, 0xa0]), false),
((&[0xf0, 0x90, 0x80]), false),
];
for &(input, expected) in cases {
assert_eq!(valid_wtf8(input), expected, "input: {:?}", input);
}
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/pool/mod.rs | yazi-shared/src/pool/mod.rs | yazi_macro::mod_flat!(cow pool ptr symbol traits);
static SYMBOLS: crate::RoCell<
parking_lot::Mutex<hashbrown::HashMap<SymbolPtr, u64, foldhash::fast::FixedState>>,
> = crate::RoCell::new();
pub(super) fn init() { SYMBOLS.with(<_>::default); }
#[inline]
pub(super) fn compute_hash<T: std::hash::Hash>(value: T) -> u64 {
use core::hash::BuildHasher;
foldhash::fast::FixedState::default().hash_one(value)
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/pool/cow.rs | yazi-shared/src/pool/cow.rs | use std::ops::Deref;
use crate::pool::{Pool, Symbol};
pub enum SymbolCow<'a, T: ?Sized> {
Borrowed(&'a T),
Owned(Symbol<T>),
}
impl<T: ?Sized> Clone for SymbolCow<'_, T> {
fn clone(&self) -> Self {
match self {
Self::Borrowed(t) => Self::Borrowed(t),
Self::Owned(t) => Self::Owned(t.clone()),
}
}
}
impl AsRef<[u8]> for SymbolCow<'_, [u8]> {
fn as_ref(&self) -> &[u8] {
match self {
Self::Borrowed(b) => b,
Self::Owned(b) => b.as_ref(),
}
}
}
impl AsRef<str> for SymbolCow<'_, str> {
fn as_ref(&self) -> &str {
match self {
Self::Borrowed(s) => s,
Self::Owned(s) => s.as_ref(),
}
}
}
// --- Deref
impl Deref for SymbolCow<'_, [u8]> {
type Target = [u8];
fn deref(&self) -> &Self::Target { self.as_ref() }
}
impl Deref for SymbolCow<'_, str> {
type Target = str;
fn deref(&self) -> &Self::Target { self.as_ref() }
}
// --- From
impl<'a, T: ?Sized> From<&'a T> for SymbolCow<'a, T> {
fn from(value: &'a T) -> Self { Self::Borrowed(value) }
}
impl<T: ?Sized> From<Symbol<T>> for SymbolCow<'_, T> {
fn from(value: Symbol<T>) -> Self { Self::Owned(value) }
}
impl From<SymbolCow<'_, [u8]>> for Symbol<[u8]> {
fn from(value: SymbolCow<'_, [u8]>) -> Self { value.into_owned() }
}
impl From<SymbolCow<'_, str>> for Symbol<str> {
fn from(value: SymbolCow<'_, str>) -> Self { value.into_owned() }
}
// --- Debug
impl std::fmt::Debug for SymbolCow<'_, [u8]> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "SymbolCow<[u8]>({:?})", self.as_ref())
}
}
impl std::fmt::Debug for SymbolCow<'_, str> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "SymbolCow<str>({:?})", self.as_ref())
}
}
impl SymbolCow<'_, [u8]> {
pub fn into_owned(self) -> Symbol<[u8]> {
match self {
Self::Borrowed(t) => Pool::<[u8]>::intern(t),
Self::Owned(t) => t,
}
}
}
impl SymbolCow<'_, str> {
pub fn into_owned(self) -> Symbol<str> {
match self {
Self::Borrowed(t) => Pool::<str>::intern(t),
Self::Owned(t) => t,
}
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/pool/ptr.rs | yazi-shared/src/pool/ptr.rs | use std::{borrow::Borrow, hash::{Hash, Hasher}, ops::Deref, ptr::NonNull};
use hashbrown::Equivalent;
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct SymbolPtr(NonNull<[u8]>);
unsafe impl Send for SymbolPtr {}
unsafe impl Sync for SymbolPtr {}
impl Deref for SymbolPtr {
type Target = NonNull<[u8]>;
fn deref(&self) -> &Self::Target { &self.0 }
}
impl Borrow<[u8]> for SymbolPtr {
fn borrow(&self) -> &[u8] { self.bytes() }
}
impl Hash for SymbolPtr {
fn hash<H: Hasher>(&self, state: &mut H) { self.bytes().hash(state); }
}
impl Equivalent<[u8]> for SymbolPtr {
fn equivalent(&self, key: &[u8]) -> bool { self.bytes() == key }
}
impl SymbolPtr {
#[inline]
pub(super) fn leaked(leaked: &'static mut [u8]) -> Self { Self(NonNull::from(leaked)) }
#[inline]
pub(super) fn bytes(&self) -> &[u8] { unsafe { self.0.as_ref() } }
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/pool/traits.rs | yazi-shared/src/pool/traits.rs | use crate::pool::{Pool, Symbol};
pub trait InternStr {
fn intern(&self) -> Symbol<str>;
}
impl<T: AsRef<str>> InternStr for T {
fn intern(&self) -> Symbol<str> { Pool::<str>::intern(self) }
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/pool/pool.rs | yazi-shared/src/pool/pool.rs | use std::marker::PhantomData;
use hashbrown::hash_map::RawEntryMut;
use crate::pool::{SYMBOLS, Symbol, SymbolPtr, compute_hash};
pub struct Pool<T: ?Sized> {
_phantom: PhantomData<T>,
}
impl Pool<[u8]> {
pub fn intern(value: &[u8]) -> Symbol<[u8]> {
let hash = compute_hash(value);
match SYMBOLS.lock().raw_entry_mut().from_key_hashed_nocheck(hash, value) {
RawEntryMut::Occupied(mut oe) => {
let (ptr, count) = oe.get_key_value_mut();
*count += 1;
Symbol::new(ptr.clone())
}
RawEntryMut::Vacant(ve) => {
let boxed = value.to_vec().into_boxed_slice();
let ptr = SymbolPtr::leaked(Box::leak(boxed));
ve.insert_hashed_nocheck(hash, ptr.clone(), 1);
Symbol::new(ptr)
}
}
}
}
impl Pool<str> {
pub fn intern(value: impl AsRef<str>) -> Symbol<str> {
let symbol = Pool::<[u8]>::intern(value.as_ref().as_bytes());
Symbol::new(symbol.into_ptr())
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/pool/symbol.rs | yazi-shared/src/pool/symbol.rs | use std::{hash::{Hash, Hasher}, marker::PhantomData, mem::ManuallyDrop, ops::Deref, str};
use hashbrown::hash_map::RawEntryMut;
use crate::pool::{Pool, SYMBOLS, SymbolPtr, compute_hash};
pub struct Symbol<T: ?Sized> {
ptr: SymbolPtr,
_phantom: PhantomData<T>,
}
unsafe impl<T: ?Sized> Send for Symbol<T> {}
unsafe impl<T: ?Sized> Sync for Symbol<T> {}
impl<T: ?Sized> Clone for Symbol<T> {
fn clone(&self) -> Self {
let hash = compute_hash(&self.ptr);
match SYMBOLS.lock().raw_entry_mut().from_key_hashed_nocheck(hash, &self.ptr) {
RawEntryMut::Occupied(mut oe) => *oe.get_mut() += 1,
RawEntryMut::Vacant(_) => unreachable!(),
}
Self::new(self.ptr.clone())
}
}
impl<T: ?Sized> Drop for Symbol<T> {
fn drop(&mut self) {
let hash = compute_hash(&self.ptr);
match SYMBOLS.lock().raw_entry_mut().from_key_hashed_nocheck(hash, &self.ptr) {
RawEntryMut::Occupied(mut oe) => {
let count = oe.get_mut();
*count -= 1;
if *count == 0 {
oe.remove();
drop(unsafe { Box::from_raw(self.ptr.as_ptr()) });
}
}
RawEntryMut::Vacant(_) => unreachable!(),
}
}
}
impl AsRef<[u8]> for Symbol<[u8]> {
fn as_ref(&self) -> &[u8] { self.ptr.bytes() }
}
impl AsRef<str> for Symbol<str> {
fn as_ref(&self) -> &str { unsafe { str::from_utf8_unchecked(self.ptr.bytes()) } }
}
impl Deref for Symbol<[u8]> {
type Target = [u8];
fn deref(&self) -> &Self::Target { self.as_ref() }
}
impl Deref for Symbol<str> {
type Target = str;
fn deref(&self) -> &Self::Target { self.as_ref() }
}
// --- Default
impl Default for Symbol<[u8]> {
fn default() -> Self { Pool::<[u8]>::intern(b"") }
}
impl Default for Symbol<str> {
fn default() -> Self { Pool::<str>::intern("") }
}
// --- Eq
impl<T: ?Sized> PartialEq for Symbol<T> {
fn eq(&self, other: &Self) -> bool { self.ptr == other.ptr }
}
impl<T: ?Sized> Eq for Symbol<T> {}
impl PartialEq<str> for Symbol<str> {
fn eq(&self, other: &str) -> bool { self.as_ref() == other }
}
impl PartialEq<[u8]> for Symbol<[u8]> {
fn eq(&self, other: &[u8]) -> bool { self.as_ref() == other }
}
// --- Hash
impl<T: ?Sized> Hash for Symbol<T> {
fn hash<H: Hasher>(&self, state: &mut H) { self.ptr.as_ptr().hash(state); }
}
// --- Ord
impl Ord for Symbol<[u8]> {
fn cmp(&self, other: &Self) -> std::cmp::Ordering { self.as_ref().cmp(other.as_ref()) }
}
impl Ord for Symbol<str> {
fn cmp(&self, other: &Self) -> std::cmp::Ordering { self.as_ref().cmp(other.as_ref()) }
}
// --- PartialOrd
impl PartialOrd for Symbol<[u8]> {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { Some(self.cmp(other)) }
}
impl PartialOrd for Symbol<str> {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { Some(self.cmp(other)) }
}
// --- Display
impl std::fmt::Display for Symbol<str> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.as_ref())
}
}
// --- Debug
impl std::fmt::Debug for Symbol<[u8]> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Symbol<[u8]>({:?})", self.as_ref())
}
}
impl std::fmt::Debug for Symbol<str> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Symbol<str>({:?})", self.as_ref())
}
}
impl<T: ?Sized> Symbol<T> {
#[inline]
pub(super) fn new(ptr: SymbolPtr) -> Self { Self { ptr, _phantom: PhantomData } }
#[inline]
pub(super) fn into_ptr(self) -> SymbolPtr { ManuallyDrop::new(self).ptr.clone() }
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/errors/peek.rs | yazi-shared/src/errors/peek.rs | use std::{error::Error, fmt::{self, Display}};
#[derive(Debug)]
pub enum PeekError {
Exceed(usize),
Unexpected(String),
}
impl Display for PeekError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Exceed(lines) => write!(f, "Exceed maximum lines {lines}"),
Self::Unexpected(msg) => write!(f, "{msg}"),
}
}
}
impl Error for PeekError {}
impl From<String> for PeekError {
fn from(error: String) -> Self { Self::Unexpected(error) }
}
impl From<&str> for PeekError {
fn from(error: &str) -> Self { Self::from(error.to_owned()) }
}
impl From<anyhow::Error> for PeekError {
fn from(error: anyhow::Error) -> Self { Self::from(error.to_string()) }
}
impl From<std::io::Error> for PeekError {
fn from(error: std::io::Error) -> Self { Self::from(error.to_string()) }
}
impl From<tokio::task::JoinError> for PeekError {
fn from(error: tokio::task::JoinError) -> Self { Self::from(error.to_string()) }
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/errors/mod.rs | yazi-shared/src/errors/mod.rs | yazi_macro::mod_flat!(input peek);
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/errors/input.rs | yazi-shared/src/errors/input.rs | use std::{error::Error, fmt::{self, Display}};
use crate::Id;
#[derive(Debug)]
pub enum InputError {
Typed(String),
Completed(String, Id),
Canceled(String),
}
impl Display for InputError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Typed(text) => write!(f, "Typed error: {text}"),
Self::Completed(text, _) => write!(f, "Completed error: {text}"),
Self::Canceled(text) => write!(f, "Canceled error: {text}"),
}
}
}
impl Error for InputError {}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/url/encode.rs | yazi-shared/src/url/encode.rs | use std::fmt::{self, Display};
use percent_encoding::{CONTROLS, percent_encode};
use crate::url::Url;
#[derive(Clone, Copy)]
pub struct Encode<'a>(pub Url<'a>);
impl Display for Encode<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use crate::scheme::Encode as E;
let loc = percent_encode(self.0.loc().encoded_bytes(), CONTROLS);
match self.0 {
Url::Regular(_) => write!(f, "regular~://{loc}"),
Url::Search { domain, .. } => {
write!(f, "search~://{}{}/{loc}", E::domain(domain), E::ports((*self).into()))
}
Url::Archive { domain, .. } => {
write!(f, "archive~://{}{}/{loc}", E::domain(domain), E::ports((*self).into()))
}
Url::Sftp { domain, .. } => {
write!(f, "sftp~://{}{}/{loc}", E::domain(domain), E::ports((*self).into()))
}
}
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/url/cov.rs | yazi-shared/src/url/cov.rs | use std::{hash::{Hash, Hasher}, ops::Deref, path::PathBuf};
use hashbrown::Equivalent;
use serde::{Deserialize, Serialize};
use crate::url::{AsUrl, Url, UrlBuf, UrlCow, UrlLike};
#[derive(Clone, Copy)]
pub struct UrlCov<'a>(Url<'a>);
impl<'a> Deref for UrlCov<'a> {
type Target = Url<'a>;
fn deref(&self) -> &Self::Target { &self.0 }
}
impl<'a> From<&'a UrlBufCov> for UrlCov<'a> {
fn from(value: &'a UrlBufCov) -> Self { Self(value.0.as_url()) }
}
impl PartialEq<UrlBufCov> for UrlCov<'_> {
fn eq(&self, other: &UrlBufCov) -> bool { self.0.covariant(&other.0) }
}
impl Hash for UrlCov<'_> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.0.loc().hash(state);
if self.0.kind().is_virtual() {
self.0.scheme().hash(state);
}
}
}
impl Equivalent<UrlBufCov> for UrlCov<'_> {
fn equivalent(&self, key: &UrlBufCov) -> bool { self == key }
}
impl<'a> UrlCov<'a> {
#[inline]
pub fn new(url: impl Into<Url<'a>>) -> Self { Self(url.into()) }
}
// --- Buf
#[derive(Clone, Debug, Deserialize, Eq, Serialize)]
pub struct UrlBufCov(pub UrlBuf);
impl Deref for UrlBufCov {
type Target = UrlBuf;
fn deref(&self) -> &Self::Target { &self.0 }
}
impl From<UrlBufCov> for UrlBuf {
fn from(value: UrlBufCov) -> Self { value.0 }
}
impl From<&UrlBufCov> for UrlBuf {
fn from(value: &UrlBufCov) -> Self { value.0.clone() }
}
impl From<UrlBuf> for UrlBufCov {
fn from(value: UrlBuf) -> Self { Self(value) }
}
impl From<PathBuf> for UrlBufCov {
fn from(value: PathBuf) -> Self { Self(UrlBuf::from(value)) }
}
impl From<UrlCow<'_>> for UrlBufCov {
fn from(value: UrlCow<'_>) -> Self { Self(value.into_owned()) }
}
impl From<Url<'_>> for UrlBufCov {
fn from(value: Url<'_>) -> Self { Self(value.to_owned()) }
}
impl From<&UrlCov<'_>> for UrlBufCov {
fn from(value: &UrlCov<'_>) -> Self { Self(UrlBuf::from(&value.0)) }
}
impl<'a> From<&'a UrlBufCov> for Url<'a> {
fn from(value: &'a UrlBufCov) -> Self { value.0.as_url() }
}
impl Hash for UrlBufCov {
fn hash<H: Hasher>(&self, state: &mut H) { UrlCov::from(self).hash(state) }
}
impl PartialEq for UrlBufCov {
fn eq(&self, other: &Self) -> bool { self.covariant(&other.0) }
}
impl PartialEq<UrlBuf> for UrlBufCov {
fn eq(&self, other: &UrlBuf) -> bool { self.covariant(other) }
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/url/like.rs | yazi-shared/src/url/like.rs | use std::{borrow::Cow, ffi::OsStr, path::Path};
use anyhow::Result;
use crate::{path::{AsPathRef, EndsWithError, JoinError, PathDyn, StartsWithError, StripPrefixError}, scheme::{SchemeKind, SchemeRef}, strand::{AsStrand, Strand}, url::{AsUrl, Components, Display, Url, UrlBuf, UrlCow}};
pub trait UrlLike
where
Self: AsUrl,
{
fn as_local(&self) -> Option<&Path> { self.as_url().as_local() }
fn base(&self) -> Url<'_> { self.as_url().base() }
fn components(&self) -> Components<'_> { self.as_url().into() }
fn covariant(&self, other: impl AsUrl) -> bool { self.as_url().covariant(other) }
fn display(&self) -> Display<'_> { Display(self.as_url()) }
fn ext(&self) -> Option<Strand<'_>> { self.as_url().ext() }
fn has_base(&self) -> bool { self.as_url().has_base() }
fn has_root(&self) -> bool { self.as_url().has_root() }
fn has_trail(&self) -> bool { self.as_url().has_trail() }
fn is_absolute(&self) -> bool { self.as_url().is_absolute() }
fn is_archive(&self) -> bool { self.as_url().is_archive() }
fn is_internal(&self) -> bool { self.as_url().is_internal() }
fn is_regular(&self) -> bool { self.as_url().is_regular() }
fn is_search(&self) -> bool { self.as_url().is_search() }
fn kind(&self) -> SchemeKind { self.as_url().kind() }
fn loc(&self) -> PathDyn<'_> { self.as_url().loc() }
fn name(&self) -> Option<Strand<'_>> { self.as_url().name() }
fn os_str(&self) -> Cow<'_, OsStr> { self.components().os_str() }
fn pair(&self) -> Option<(Url<'_>, PathDyn<'_>)> { self.as_url().pair() }
fn parent(&self) -> Option<Url<'_>> { self.as_url().parent() }
fn scheme(&self) -> SchemeRef<'_> { self.as_url().scheme() }
fn stem(&self) -> Option<Strand<'_>> { self.as_url().stem() }
fn trail(&self) -> Url<'_> { self.as_url().trail() }
fn triple(&self) -> (PathDyn<'_>, PathDyn<'_>, PathDyn<'_>) { self.as_url().triple() }
fn try_ends_with(&self, child: impl AsUrl) -> Result<bool, EndsWithError> {
self.as_url().try_ends_with(child)
}
fn try_join(&self, path: impl AsStrand) -> Result<UrlBuf, JoinError> {
self.as_url().try_join(path)
}
fn try_replace<'a>(&self, take: usize, path: impl AsPathRef<'a>) -> Result<UrlCow<'a>> {
self.as_url().try_replace(take, path)
}
fn try_starts_with(&self, base: impl AsUrl) -> Result<bool, StartsWithError> {
self.as_url().try_starts_with(base)
}
fn try_strip_prefix(&self, base: impl AsUrl) -> Result<PathDyn<'_>, StripPrefixError> {
self.as_url().try_strip_prefix(base)
}
fn uri(&self) -> PathDyn<'_> { self.as_url().uri() }
fn urn(&self) -> PathDyn<'_> { self.as_url().urn() }
}
impl UrlLike for UrlBuf {}
impl UrlLike for UrlCow<'_> {}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/url/url.rs | yazi-shared/src/url/url.rs | use std::{borrow::Cow, ffi::OsStr, fmt::{Debug, Formatter}, path::{Path, PathBuf}};
use anyhow::Result;
use hashbrown::Equivalent;
use serde::Serialize;
use super::Encode as EncodeUrl;
use crate::{loc::{Loc, LocBuf}, path::{AsPath, AsPathRef, EndsWithError, JoinError, PathBufDyn, PathDyn, PathDynError, PathLike, StartsWithError, StripPrefixError, StripSuffixError}, pool::InternStr, scheme::{Encode as EncodeScheme, SchemeCow, SchemeKind, SchemeRef}, strand::{AsStrand, Strand}, url::{AsUrl, Components, UrlBuf, UrlCow}};
#[derive(Clone, Copy, Eq, Hash, PartialEq)]
pub enum Url<'a> {
Regular(Loc<'a>),
Search { loc: Loc<'a>, domain: &'a str },
Archive { loc: Loc<'a>, domain: &'a str },
Sftp { loc: Loc<'a, &'a typed_path::UnixPath>, domain: &'a str },
}
// --- Eq
impl PartialEq<UrlBuf> for Url<'_> {
fn eq(&self, other: &UrlBuf) -> bool { *self == other.as_url() }
}
// --- Hash
impl Equivalent<UrlBuf> for Url<'_> {
fn equivalent(&self, key: &UrlBuf) -> bool { self == key }
}
// --- Debug
impl Debug for Url<'_> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
if self.is_regular() {
write!(f, "{}", self.loc().display())
} else {
write!(f, "{}{}", EncodeScheme(*self), self.loc().display())
}
}
}
impl Serialize for Url<'_> {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let (kind, loc) = (self.kind(), self.loc());
match (kind == SchemeKind::Regular, loc.to_str()) {
(true, Ok(s)) => serializer.serialize_str(s),
(false, Ok(s)) => serializer.serialize_str(&format!("{}{s}", EncodeScheme(*self))),
(_, Err(_)) => serializer.collect_str(&EncodeUrl(*self)),
}
}
}
impl<'a> Url<'a> {
#[inline]
pub fn as_local(self) -> Option<&'a Path> {
self.loc().as_os().ok().filter(|_| self.kind().is_local())
}
#[inline]
pub fn as_regular(self) -> Result<Self, PathDynError> {
Ok(Self::Regular(Loc::bare(self.loc().as_os()?)))
}
pub fn base(self) -> Self {
match self {
Self::Regular(loc) => Self::Regular(Loc::bare(loc.base())),
Self::Search { loc, domain } => Self::Search { loc: Loc::zeroed(loc.base()), domain },
Self::Archive { loc, domain } => Self::Archive { loc: Loc::zeroed(loc.base()), domain },
Self::Sftp { loc, domain } => Self::Sftp { loc: Loc::bare(loc.base()), domain },
}
}
#[inline]
pub fn components(self) -> Components<'a> { Components::from(self) }
#[inline]
pub fn covariant(self, other: impl AsUrl) -> bool {
let other = other.as_url();
self.loc() == other.loc() && self.scheme().covariant(other.scheme())
}
#[inline]
pub fn ext(self) -> Option<Strand<'a>> {
Some(match self {
Self::Regular(loc) => loc.extension()?.as_strand(),
Self::Search { loc, .. } => loc.extension()?.as_strand(),
Self::Archive { loc, .. } => loc.extension()?.as_strand(),
Self::Sftp { loc, .. } => loc.extension()?.as_strand(),
})
}
#[inline]
pub fn has_base(self) -> bool {
match self {
Self::Regular(loc) => loc.has_base(),
Self::Search { loc, .. } => loc.has_base(),
Self::Archive { loc, .. } => loc.has_base(),
Self::Sftp { loc, .. } => loc.has_base(),
}
}
#[inline]
pub fn has_root(self) -> bool { self.loc().has_root() }
#[inline]
pub fn has_trail(self) -> bool {
match self {
Self::Regular(loc) => loc.has_trail(),
Self::Search { loc, .. } => loc.has_trail(),
Self::Archive { loc, .. } => loc.has_trail(),
Self::Sftp { loc, .. } => loc.has_trail(),
}
}
#[inline]
pub fn is_absolute(self) -> bool { self.loc().is_absolute() }
#[inline]
pub fn is_archive(self) -> bool { matches!(self, Self::Archive { .. }) }
#[inline]
pub fn is_internal(self) -> bool {
match self {
Self::Regular(_) | Self::Sftp { .. } => true,
Self::Search { .. } => !self.uri().is_empty(),
Self::Archive { .. } => false,
}
}
#[inline]
pub fn is_regular(self) -> bool { matches!(self, Self::Regular(_)) }
#[inline]
pub fn is_search(self) -> bool { matches!(self, Self::Search { .. }) }
#[inline]
pub fn kind(self) -> SchemeKind {
match self {
Self::Regular(_) => SchemeKind::Regular,
Self::Search { .. } => SchemeKind::Search,
Self::Archive { .. } => SchemeKind::Archive,
Self::Sftp { .. } => SchemeKind::Sftp,
}
}
#[inline]
pub fn loc(self) -> PathDyn<'a> {
match self {
Self::Regular(loc) => loc.as_path(),
Self::Search { loc, .. } => loc.as_path(),
Self::Archive { loc, .. } => loc.as_path(),
Self::Sftp { loc, .. } => loc.as_path(),
}
}
#[inline]
pub fn name(self) -> Option<Strand<'a>> {
Some(match self {
Self::Regular(loc) => loc.file_name()?.as_strand(),
Self::Search { loc, .. } => loc.file_name()?.as_strand(),
Self::Archive { loc, .. } => loc.file_name()?.as_strand(),
Self::Sftp { loc, .. } => loc.file_name()?.as_strand(),
})
}
#[inline]
pub fn os_str(self) -> Cow<'a, OsStr> { self.components().os_str() }
#[inline]
pub fn pair(self) -> Option<(Self, PathDyn<'a>)> { Some((self.parent()?, self.urn())) }
pub fn parent(self) -> Option<Self> {
let uri = self.uri();
Some(match self {
// Regular
Self::Regular(loc) => Self::regular(loc.parent()?),
// Search
Self::Search { loc, .. } if uri.is_empty() => Self::regular(loc.parent()?),
Self::Search { loc, domain } => {
Self::Search { loc: Loc::new(loc.parent()?, loc.base(), loc.base()), domain }
}
// Archive
Self::Archive { loc, .. } if uri.is_empty() => Self::regular(loc.parent()?),
Self::Archive { loc, domain } if uri.components().nth(1).is_none() => {
Self::Archive { loc: Loc::zeroed(loc.parent()?), domain }
}
Self::Archive { loc, domain } => {
Self::Archive { loc: Loc::floated(loc.parent()?, loc.base()), domain }
}
// SFTP
Self::Sftp { loc, domain } => Self::Sftp { loc: Loc::bare(loc.parent()?), domain },
})
}
#[inline]
pub fn regular<T: AsRef<Path> + ?Sized>(path: &'a T) -> Self {
Self::Regular(Loc::bare(path.as_ref()))
}
#[inline]
pub fn scheme(self) -> SchemeRef<'a> {
let (uri, urn) = SchemeCow::retrieve_ports(self);
match self {
Self::Regular(_) => SchemeRef::Regular { uri, urn },
Self::Search { domain, .. } => SchemeRef::Search { domain, uri, urn },
Self::Archive { domain, .. } => SchemeRef::Archive { domain, uri, urn },
Self::Sftp { domain, .. } => SchemeRef::Sftp { domain, uri, urn },
}
}
#[inline]
pub fn stem(self) -> Option<Strand<'a>> {
Some(match self {
Self::Regular(loc) => loc.file_stem()?.as_strand(),
Self::Search { loc, .. } => loc.file_stem()?.as_strand(),
Self::Archive { loc, .. } => loc.file_stem()?.as_strand(),
Self::Sftp { loc, .. } => loc.file_stem()?.as_strand(),
})
}
#[inline]
pub fn to_owned(self) -> UrlBuf { self.into() }
pub fn trail(self) -> Self {
let uri = self.uri();
match self {
Self::Regular(loc) => Self::Regular(Loc::bare(loc.trail())),
Self::Search { loc, domain } if uri.is_empty() => {
Self::Search { loc: Loc::zeroed(loc.trail()), domain }
}
Self::Search { loc, domain } => {
Self::Search { loc: Loc::new(loc.trail(), loc.base(), loc.base()), domain }
}
Self::Archive { loc, domain } if uri.is_empty() => {
Self::Archive { loc: Loc::zeroed(loc.trail()), domain }
}
Self::Archive { loc, domain } => {
Self::Archive { loc: Loc::new(loc.trail(), loc.base(), loc.base()), domain }
}
Self::Sftp { loc, domain } => Self::Sftp { loc: Loc::bare(loc.trail()), domain },
}
}
pub fn triple(self) -> (PathDyn<'a>, PathDyn<'a>, PathDyn<'a>) {
match self {
Self::Regular(loc) | Self::Search { loc, .. } | Self::Archive { loc, .. } => {
let (base, rest, urn) = loc.triple();
(base.as_path(), rest.as_path(), urn.as_path())
}
Self::Sftp { loc, .. } => {
let (base, rest, urn) = loc.triple();
(base.as_path(), rest.as_path(), urn.as_path())
}
}
}
#[inline]
pub fn try_ends_with(self, child: impl AsUrl) -> Result<bool, EndsWithError> {
let child = child.as_url();
Ok(self.loc().try_ends_with(child.loc())? && self.scheme().covariant(child.scheme()))
}
pub fn try_join(self, path: impl AsStrand) -> Result<UrlBuf, JoinError> {
let joined = self.loc().try_join(path)?;
Ok(match self {
Self::Regular(_) => UrlBuf::Regular(joined.into_os()?.into()),
Self::Search { loc, domain } if joined.try_starts_with(loc.base())? => UrlBuf::Search {
loc: LocBuf::<PathBuf>::new(joined.try_into()?, loc.base(), loc.base()),
domain: domain.intern(),
},
Self::Search { domain, .. } => UrlBuf::Search {
loc: LocBuf::<PathBuf>::zeroed(joined.into_os()?),
domain: domain.intern(),
},
Self::Archive { loc, domain } if joined.try_starts_with(loc.base())? => UrlBuf::Archive {
loc: LocBuf::<PathBuf>::floated(joined.try_into()?, loc.base()),
domain: domain.intern(),
},
Self::Archive { domain, .. } => UrlBuf::Archive {
loc: LocBuf::<PathBuf>::zeroed(joined.into_os()?),
domain: domain.intern(),
},
Self::Sftp { domain, .. } => {
UrlBuf::Sftp { loc: joined.into_unix()?.into(), domain: domain.intern() }
}
})
}
pub fn try_replace<'b>(self, take: usize, to: impl AsPathRef<'b>) -> Result<UrlCow<'b>> {
self.try_replace_impl(take, to.as_path_ref())
}
fn try_replace_impl<'b>(self, take: usize, rep: PathDyn<'b>) -> Result<UrlCow<'b>> {
let b = rep.encoded_bytes();
if take == 0 {
return UrlCow::try_from(b);
} else if SchemeKind::parse(b)?.is_some() {
return UrlCow::try_from(b);
}
let loc = self.loc();
let mut path = PathBufDyn::from_components(loc.kind(), loc.components().take(take - 1))?;
path.try_push(rep)?;
let url = match self {
Self::Regular(_) => UrlBuf::from(path.into_os()?),
Self::Search { loc, domain } if path.try_starts_with(loc.trail())? => UrlBuf::Search {
loc: LocBuf::<PathBuf>::new(path.into_os()?, loc.base(), loc.trail()),
domain: domain.intern(),
},
Self::Archive { loc, domain } if path.try_starts_with(loc.trail())? => UrlBuf::Archive {
loc: LocBuf::<std::path::PathBuf>::new(path.into_os()?, loc.base(), loc.trail()),
domain: domain.intern(),
},
Self::Sftp { loc, domain } if path.try_starts_with(loc.trail())? => UrlBuf::Sftp {
loc: LocBuf::<typed_path::UnixPathBuf>::new(path.into_unix()?, loc.base(), loc.trail()),
domain: domain.intern(),
},
Self::Search { domain, .. } => UrlBuf::Search {
loc: LocBuf::<std::path::PathBuf>::saturated(path.into_os()?, self.kind()),
domain: domain.intern(),
},
Self::Archive { domain, .. } => UrlBuf::Archive {
loc: LocBuf::<std::path::PathBuf>::saturated(path.into_os()?, self.kind()),
domain: domain.intern(),
},
Self::Sftp { domain, .. } => UrlBuf::Sftp {
loc: LocBuf::<typed_path::UnixPathBuf>::saturated(path.into_unix()?, self.kind()),
domain: domain.intern(),
},
};
Ok(url.into())
}
#[inline]
pub fn try_starts_with(self, base: impl AsUrl) -> Result<bool, StartsWithError> {
let base = base.as_url();
Ok(self.loc().try_starts_with(base.loc())? && self.scheme().covariant(base.scheme()))
}
pub fn try_strip_prefix(self, base: impl AsUrl) -> Result<PathDyn<'a>, StripPrefixError> {
use StripPrefixError::{Exotic, NotPrefix};
use Url as U;
let base = base.as_url();
let prefix = self.loc().try_strip_prefix(base.loc())?;
match (self, base) {
// Same scheme
(U::Regular(_), U::Regular(_)) => Ok(prefix),
(U::Search { .. }, U::Search { .. }) => Ok(prefix),
(U::Archive { domain: a, .. }, U::Archive { domain: b, .. }) => {
Some(prefix).filter(|_| a == b).ok_or(Exotic)
}
(U::Sftp { domain: a, .. }, U::Sftp { domain: b, .. }) => {
Some(prefix).filter(|_| a == b).ok_or(Exotic)
}
// Both are local files
(U::Regular(_), U::Search { .. }) => Ok(prefix),
(U::Search { .. }, U::Regular(_)) => Ok(prefix),
// Only the entry of archives is a local file
(U::Regular(_), U::Archive { .. }) => {
Some(prefix).filter(|_| base.uri().is_empty()).ok_or(NotPrefix)
}
(U::Search { .. }, U::Archive { .. }) => {
Some(prefix).filter(|_| base.uri().is_empty()).ok_or(NotPrefix)
}
(U::Archive { .. }, U::Regular(_)) => {
Some(prefix).filter(|_| self.uri().is_empty()).ok_or(NotPrefix)
}
(U::Archive { .. }, U::Search { .. }) => {
Some(prefix).filter(|_| self.uri().is_empty()).ok_or(NotPrefix)
}
// Independent virtual file space
(U::Regular(_), U::Sftp { .. }) => Err(Exotic),
(U::Search { .. }, U::Sftp { .. }) => Err(Exotic),
(U::Archive { .. }, U::Sftp { .. }) => Err(Exotic),
(U::Sftp { .. }, U::Regular(_)) => Err(Exotic),
(U::Sftp { .. }, U::Search { .. }) => Err(Exotic),
(U::Sftp { .. }, U::Archive { .. }) => Err(Exotic),
}
}
pub fn try_strip_suffix(self, other: impl AsUrl) -> Result<PathDyn<'a>, StripSuffixError> {
use StripSuffixError::{Exotic, NotSuffix};
use Url as U;
let other = other.as_url();
let suffix = self.loc().try_strip_suffix(other.loc())?;
match (self, other) {
// Same scheme
(U::Regular(_), U::Regular(_)) => Ok(suffix),
(U::Search { .. }, U::Search { .. }) => Ok(suffix),
(U::Archive { domain: a, .. }, U::Archive { domain: b, .. }) => {
Some(suffix).filter(|_| a == b).ok_or(Exotic)
}
(U::Sftp { domain: a, .. }, U::Sftp { domain: b, .. }) => {
Some(suffix).filter(|_| a == b).ok_or(Exotic)
}
// Both are local files
(U::Regular(_), U::Search { .. }) => Ok(suffix),
(U::Search { .. }, U::Regular(_)) => Ok(suffix),
// Only the entry of archives is a local file
(U::Regular(_), U::Archive { .. }) => {
Some(suffix).filter(|_| other.uri().is_empty()).ok_or(NotSuffix)
}
(U::Search { .. }, U::Archive { .. }) => {
Some(suffix).filter(|_| other.uri().is_empty()).ok_or(NotSuffix)
}
(U::Archive { .. }, U::Regular(_)) => {
Some(suffix).filter(|_| self.uri().is_empty()).ok_or(NotSuffix)
}
(U::Archive { .. }, U::Search { .. }) => {
Some(suffix).filter(|_| self.uri().is_empty()).ok_or(NotSuffix)
}
// Independent virtual file space
(U::Regular(_), U::Sftp { .. }) => Err(Exotic),
(U::Search { .. }, U::Sftp { .. }) => Err(Exotic),
(U::Archive { .. }, U::Sftp { .. }) => Err(Exotic),
(U::Sftp { .. }, U::Regular(_)) => Err(Exotic),
(U::Sftp { .. }, U::Search { .. }) => Err(Exotic),
(U::Sftp { .. }, U::Archive { .. }) => Err(Exotic),
}
}
#[inline]
pub fn uri(self) -> PathDyn<'a> {
match self {
Self::Regular(loc) => loc.uri().as_path(),
Self::Search { loc, .. } => loc.uri().as_path(),
Self::Archive { loc, .. } => loc.uri().as_path(),
Self::Sftp { loc, .. } => loc.uri().as_path(),
}
}
#[inline]
pub fn urn(self) -> PathDyn<'a> {
match self {
Self::Regular(loc) => loc.urn().as_path(),
Self::Search { loc, .. } => loc.urn().as_path(),
Self::Archive { loc, .. } => loc.urn().as_path(),
Self::Sftp { loc, .. } => loc.urn().as_path(),
}
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/url/display.rs | yazi-shared/src/url/display.rs | use crate::{scheme::Encode, url::Url};
pub struct Display<'a>(pub Url<'a>);
impl std::fmt::Display for Display<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let (kind, loc) = (self.0.kind(), self.0.loc());
if kind.is_virtual() {
Encode(self.0).fmt(f)?;
}
loc.display().fmt(f)
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/url/mod.rs | yazi-shared/src/url/mod.rs | yazi_macro::mod_flat!(buf component components cov cow display encode like traits url);
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/url/cow.rs | yazi-shared/src/url/cow.rs | use std::{borrow::Cow, hash::{Hash, Hasher}, path::PathBuf};
use anyhow::{Result, anyhow};
use serde::{Deserialize, Deserializer, Serialize};
use crate::{loc::{Loc, LocBuf}, path::{PathBufDyn, PathCow, PathDyn}, pool::SymbolCow, scheme::{AsScheme, Scheme, SchemeCow, SchemeKind, SchemeRef}, url::{AsUrl, Url, UrlBuf}};
#[derive(Clone, Debug)]
pub enum UrlCow<'a> {
Regular(LocBuf),
Search { loc: LocBuf, domain: SymbolCow<'a, str> },
Archive { loc: LocBuf, domain: SymbolCow<'a, str> },
Sftp { loc: LocBuf<typed_path::UnixPathBuf>, domain: SymbolCow<'a, str> },
RegularRef(Loc<'a>),
SearchRef { loc: Loc<'a>, domain: SymbolCow<'a, str> },
ArchiveRef { loc: Loc<'a>, domain: SymbolCow<'a, str> },
SftpRef { loc: Loc<'a, &'a typed_path::UnixPath>, domain: SymbolCow<'a, str> },
}
// FIXME: remove
impl Default for UrlCow<'_> {
fn default() -> Self { Self::RegularRef(Default::default()) }
}
impl<'a> From<Url<'a>> for UrlCow<'a> {
fn from(value: Url<'a>) -> Self {
match value {
Url::Regular(loc) => Self::RegularRef(loc),
Url::Search { loc, domain } => Self::SearchRef { loc, domain: domain.into() },
Url::Archive { loc, domain } => Self::ArchiveRef { loc, domain: domain.into() },
Url::Sftp { loc, domain } => Self::SftpRef { loc, domain: domain.into() },
}
}
}
impl<'a, T> From<&'a T> for UrlCow<'a>
where
T: AsUrl + ?Sized,
{
fn from(value: &'a T) -> Self { value.as_url().into() }
}
impl From<UrlBuf> for UrlCow<'_> {
fn from(value: UrlBuf) -> Self {
match value {
UrlBuf::Regular(loc) => Self::Regular(loc),
UrlBuf::Search { loc, domain } => Self::Search { loc, domain: domain.into() },
UrlBuf::Archive { loc, domain } => Self::Archive { loc, domain: domain.into() },
UrlBuf::Sftp { loc, domain } => Self::Sftp { loc, domain: domain.into() },
}
}
}
impl From<PathBuf> for UrlCow<'_> {
fn from(value: PathBuf) -> Self { UrlBuf::from(value).into() }
}
impl From<UrlCow<'_>> for UrlBuf {
fn from(value: UrlCow<'_>) -> Self { value.into_owned() }
}
impl From<&UrlCow<'_>> for UrlBuf {
fn from(value: &UrlCow<'_>) -> Self { value.as_url().into() }
}
impl<'a> TryFrom<&'a [u8]> for UrlCow<'a> {
type Error = anyhow::Error;
fn try_from(value: &'a [u8]) -> Result<Self, Self::Error> { SchemeCow::parse(value)?.try_into() }
}
impl TryFrom<Vec<u8>> for UrlCow<'_> {
type Error = anyhow::Error;
fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
Ok(UrlCow::try_from(value.as_slice())?.into_owned().into())
}
}
impl<'a> TryFrom<&'a str> for UrlCow<'a> {
type Error = anyhow::Error;
fn try_from(value: &'a str) -> Result<Self, Self::Error> { Self::try_from(value.as_bytes()) }
}
impl TryFrom<String> for UrlCow<'_> {
type Error = anyhow::Error;
fn try_from(value: String) -> Result<Self, Self::Error> {
Ok(UrlCow::try_from(value.as_str())?.into_owned().into())
}
}
impl<'a> TryFrom<Cow<'a, str>> for UrlCow<'a> {
type Error = anyhow::Error;
fn try_from(value: Cow<'a, str>) -> Result<Self, Self::Error> {
match value {
Cow::Borrowed(s) => UrlCow::try_from(s),
Cow::Owned(s) => UrlCow::try_from(s),
}
}
}
impl<'a> TryFrom<(SchemeRef<'a>, PathDyn<'a>)> for UrlCow<'a> {
type Error = anyhow::Error;
fn try_from((scheme, path): (SchemeRef<'a>, PathDyn<'a>)) -> Result<Self, Self::Error> {
(SchemeCow::Borrowed(scheme), path).try_into()
}
}
impl<'a> TryFrom<(SchemeRef<'a>, PathCow<'a>)> for UrlCow<'a> {
type Error = anyhow::Error;
fn try_from((scheme, path): (SchemeRef<'a>, PathCow<'a>)) -> Result<Self, Self::Error> {
(SchemeCow::Borrowed(scheme), path).try_into()
}
}
impl TryFrom<(Scheme, PathBufDyn)> for UrlCow<'_> {
type Error = anyhow::Error;
fn try_from((scheme, path): (Scheme, PathBufDyn)) -> Result<Self, Self::Error> {
(SchemeCow::Owned(scheme), path).try_into()
}
}
impl<'a> TryFrom<(SchemeCow<'a>, PathCow<'a>)> for UrlCow<'a> {
type Error = anyhow::Error;
fn try_from((scheme, path): (SchemeCow<'a>, PathCow<'a>)) -> Result<Self, Self::Error> {
match path {
PathCow::Borrowed(path) => (scheme, path).try_into(),
PathCow::Owned(path) => (scheme, path).try_into(),
}
}
}
impl<'a> TryFrom<(SchemeCow<'a>, PathDyn<'a>)> for UrlCow<'a> {
type Error = anyhow::Error;
fn try_from((scheme, path): (SchemeCow<'a>, PathDyn<'a>)) -> Result<Self, Self::Error> {
let kind = scheme.as_scheme().kind();
let (uri, urn) = scheme.as_scheme().ports();
let domain = scheme.into_domain();
Ok(match kind {
SchemeKind::Regular => Self::RegularRef(Loc::bare(path.as_os()?)),
SchemeKind::Search => Self::SearchRef {
loc: Loc::with(path.as_os()?, uri, urn)?,
domain: domain.ok_or_else(|| anyhow!("missing domain for search scheme"))?,
},
SchemeKind::Archive => Self::ArchiveRef {
loc: Loc::with(path.as_os()?, uri, urn)?,
domain: domain.ok_or_else(|| anyhow!("missing domain for archive scheme"))?,
},
SchemeKind::Sftp => Self::SftpRef {
loc: Loc::with(path.as_unix()?, uri, urn)?,
domain: domain.ok_or_else(|| anyhow!("missing domain for sftp scheme"))?,
},
})
}
}
impl<'a> TryFrom<(SchemeCow<'a>, PathBufDyn)> for UrlCow<'a> {
type Error = anyhow::Error;
fn try_from((scheme, path): (SchemeCow<'a>, PathBufDyn)) -> Result<Self, Self::Error> {
let kind = scheme.as_scheme().kind();
let (uri, urn) = scheme.as_scheme().ports();
let domain = scheme.into_domain();
Ok(match kind {
SchemeKind::Regular => Self::Regular(path.into_os()?.into()),
SchemeKind::Search => Self::Search {
loc: LocBuf::<std::path::PathBuf>::with(path.try_into()?, uri, urn)?,
domain: domain.ok_or_else(|| anyhow!("missing domain for search scheme"))?,
},
SchemeKind::Archive => Self::Archive {
loc: LocBuf::<std::path::PathBuf>::with(path.try_into()?, uri, urn)?,
domain: domain.ok_or_else(|| anyhow!("missing domain for archive scheme"))?,
},
SchemeKind::Sftp => Self::Sftp {
loc: LocBuf::<typed_path::UnixPathBuf>::with(path.try_into()?, uri, urn)?,
domain: domain.ok_or_else(|| anyhow!("missing domain for sftp scheme"))?,
},
})
}
}
// --- Eq
impl PartialEq for UrlCow<'_> {
fn eq(&self, other: &Self) -> bool { self.as_url() == other.as_url() }
}
impl PartialEq<UrlBuf> for UrlCow<'_> {
fn eq(&self, other: &UrlBuf) -> bool { self.as_url() == other.as_url() }
}
impl Eq for UrlCow<'_> {}
// --- Hash
impl Hash for UrlCow<'_> {
fn hash<H: Hasher>(&self, state: &mut H) { self.as_url().hash(state); }
}
impl<'a> UrlCow<'a> {
pub fn is_owned(&self) -> bool {
match self {
Self::Regular(_) | Self::Search { .. } | Self::Archive { .. } | Self::Sftp { .. } => true,
Self::RegularRef(_)
| Self::SearchRef { .. }
| Self::ArchiveRef { .. }
| Self::SftpRef { .. } => false,
}
}
pub fn into_owned(self) -> UrlBuf {
match self {
Self::Regular(loc) => UrlBuf::Regular(loc),
Self::Search { loc, domain } => UrlBuf::Search { loc, domain: domain.into() },
Self::Archive { loc, domain } => UrlBuf::Archive { loc, domain: domain.into() },
Self::Sftp { loc, domain } => UrlBuf::Sftp { loc, domain: domain.into() },
Self::RegularRef(loc) => UrlBuf::Regular(loc.into()),
Self::SearchRef { loc, domain } => {
UrlBuf::Search { loc: loc.into(), domain: domain.into() }
}
Self::ArchiveRef { loc, domain } => {
UrlBuf::Archive { loc: loc.into(), domain: domain.into() }
}
Self::SftpRef { loc, domain } => UrlBuf::Sftp { loc: loc.into(), domain: domain.into() },
}
}
pub fn into_scheme(self) -> SchemeCow<'a> {
let (uri, urn) = self.as_url().scheme().ports();
match self {
Self::Regular(_) => Scheme::Regular { uri, urn }.into(),
Self::RegularRef(_) => SchemeRef::Regular { uri, urn }.into(),
Self::Search { domain, .. } | Self::SearchRef { domain, .. } => match domain {
SymbolCow::Borrowed(domain) => SchemeRef::Search { domain, uri, urn }.into(),
SymbolCow::Owned(domain) => Scheme::Search { domain, uri, urn }.into(),
},
Self::Archive { domain, .. } | Self::ArchiveRef { domain, .. } => match domain {
SymbolCow::Borrowed(domain) => SchemeRef::Archive { domain, uri, urn }.into(),
SymbolCow::Owned(domain) => Scheme::Archive { domain, uri, urn }.into(),
},
Self::Sftp { domain, .. } | Self::SftpRef { domain, .. } => match domain {
SymbolCow::Borrowed(domain) => SchemeRef::Sftp { domain, uri, urn }.into(),
SymbolCow::Owned(domain) => Scheme::Sftp { domain, uri, urn }.into(),
},
}
}
pub fn into_static(self) -> UrlCow<'static> {
match self {
UrlCow::Regular(loc) => UrlCow::Regular(loc),
UrlCow::Search { loc, domain } => UrlCow::Search { loc, domain: domain.into_owned().into() },
UrlCow::Archive { loc, domain } => {
UrlCow::Archive { loc, domain: domain.into_owned().into() }
}
UrlCow::Sftp { loc, domain } => UrlCow::Sftp { loc, domain: domain.into_owned().into() },
UrlCow::RegularRef(loc) => UrlCow::Regular(loc.into()),
UrlCow::SearchRef { loc, domain } => {
UrlCow::Search { loc: loc.into(), domain: domain.into_owned().into() }
}
UrlCow::ArchiveRef { loc, domain } => {
UrlCow::Archive { loc: loc.into(), domain: domain.into_owned().into() }
}
UrlCow::SftpRef { loc, domain } => {
UrlCow::Sftp { loc: loc.into(), domain: domain.into_owned().into() }
}
}
}
#[inline]
pub fn to_owned(&self) -> UrlBuf { self.as_url().into() }
}
impl Serialize for UrlCow<'_> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
self.as_url().serialize(serializer)
}
}
impl<'de> Deserialize<'de> for UrlCow<'_> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
UrlBuf::deserialize(deserializer).map(UrlCow::from)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::url::UrlLike;
#[test]
fn test_parse() -> Result<()> {
struct Case {
url: &'static str,
urn: &'static str,
uri: &'static str,
trail: &'static str,
base: &'static str,
}
let cases = [
// Regular
Case {
url: "/root/music/rock/song.mp3",
urn: "song.mp3",
uri: "song.mp3",
trail: "/root/music/rock/",
base: "/root/music/rock/",
},
// Search portal
Case {
url: "search://keyword//root/Documents/reports",
urn: "",
uri: "",
trail: "search://keyword//root/Documents/reports",
base: "search://keyword//root/Documents/reports",
},
// Search item
Case {
url: "search://keyword:2:2//root/Documents/reports/2023/summary.docx",
urn: "2023/summary.docx",
uri: "2023/summary.docx",
trail: "search://keyword//root/Documents/reports/",
base: "search://keyword//root/Documents/reports/",
},
// Archive portal
Case {
url: "archive://domain//root/Downloads/images.zip",
urn: "",
uri: "",
trail: "archive://domain//root/Downloads/images.zip",
base: "archive://domain//root/Downloads/images.zip",
},
// Archive item
Case {
url: "archive://domain:2:1//root/Downloads/images.zip/2025/city.jpg",
urn: "city.jpg",
uri: "2025/city.jpg",
trail: "archive://domain:1:1//root/Downloads/images.zip/2025/",
base: "archive://domain//root/Downloads/images.zip/",
},
// SFTP
Case {
url: "sftp://my-server//root/docs/report.pdf",
urn: "report.pdf",
uri: "report.pdf",
trail: "sftp://my-server//root/docs/",
base: "sftp://my-server//root/docs/",
},
];
for case in cases {
let url = UrlCow::try_from(case.url)?;
assert_eq!(url.urn().to_str()?, case.urn);
assert_eq!(url.uri().to_str()?, case.uri);
assert_eq!(
format!("{:?}", url.trail()),
format!("{:?}", UrlCow::try_from(case.trail)?.as_url())
);
assert_eq!(
format!("{:?}", url.base()),
format!("{:?}", UrlCow::try_from(case.base)?.as_url())
);
}
Ok(())
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/url/components.rs | yazi-shared/src/url/components.rs | use std::{borrow::Cow, ffi::{OsStr, OsString}, iter::FusedIterator, ops::Not};
use crate::{loc::Loc, path, scheme::{Encode as EncodeScheme, SchemeCow, SchemeRef}, strand::{StrandBuf, StrandCow}, url::{Component, Encode as EncodeUrl, Url}};
#[derive(Clone)]
pub struct Components<'a> {
inner: path::Components<'a>,
url: Url<'a>,
back_yields: usize,
scheme_yielded: bool,
}
impl<'a> From<Url<'a>> for Components<'a> {
fn from(value: Url<'a>) -> Self {
Self {
inner: value.loc().components(),
url: value,
back_yields: 0,
scheme_yielded: false,
}
}
}
impl<'a> Components<'a> {
pub fn covariant(&self, other: &Self) -> bool {
match (self.scheme_yielded, other.scheme_yielded) {
(true, true) => {}
(false, false) if self.scheme().covariant(other.scheme()) => {}
_ => return false,
}
self.inner == other.inner
}
pub fn os_str(&self) -> Cow<'a, OsStr> {
let Ok(os) = self.inner.strand().as_os() else {
return OsString::from(EncodeUrl(self.url()).to_string()).into();
};
if self.url.is_regular() || self.scheme_yielded {
return os.into();
}
let mut s = OsString::from(EncodeScheme(self.url()).to_string());
s.reserve_exact(os.len());
s.push(os);
s.into()
}
pub fn scheme(&self) -> SchemeRef<'a> {
let left = self.inner.clone().count();
let (uri, urn) = SchemeCow::retrieve_ports(self.url);
let (uri, urn) = (
uri.saturating_sub(self.back_yields).min(left),
urn.saturating_sub(self.back_yields).min(left),
);
match self.url {
Url::Regular(_) => SchemeRef::Regular { uri, urn },
Url::Search { domain, .. } => SchemeRef::Search { domain, uri, urn },
Url::Archive { domain, .. } => SchemeRef::Archive { domain, uri, urn },
Url::Sftp { domain, .. } => SchemeRef::Sftp { domain, uri, urn },
}
}
pub fn strand(&self) -> StrandCow<'a> {
let s = self.inner.strand();
if self.url.is_regular() || self.scheme_yielded {
return s.into();
}
let mut buf = StrandBuf::with_str(s.kind(), EncodeScheme(self.url()).to_string());
buf.reserve_exact(s.len());
buf.try_push(s).expect("strand with same kind");
buf.into()
}
pub fn url(&self) -> Url<'a> {
let path = self.inner.path();
let (uri, urn) = self.scheme().ports();
match self.url {
Url::Regular(_) => Url::Regular(Loc::with(path.as_os().unwrap(), uri, urn).unwrap()),
Url::Search { domain, .. } => {
Url::Search { loc: Loc::with(path.as_os().unwrap(), uri, urn).unwrap(), domain }
}
Url::Archive { domain, .. } => {
Url::Archive { loc: Loc::with(path.as_os().unwrap(), uri, urn).unwrap(), domain }
}
Url::Sftp { domain, .. } => {
Url::Sftp { loc: Loc::with(path.as_unix().unwrap(), uri, urn).unwrap(), domain }
}
}
}
}
impl<'a> Iterator for Components<'a> {
type Item = Component<'a>;
fn next(&mut self) -> Option<Self::Item> {
if !self.scheme_yielded {
self.scheme_yielded = true;
Some(Component::Scheme(self.scheme()))
} else {
self.inner.next().map(Into::into)
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
let (min, max) = self.inner.size_hint();
let scheme = self.scheme_yielded.not() as usize;
(min + scheme, max.map(|n| n + scheme))
}
}
impl<'a> DoubleEndedIterator for Components<'a> {
fn next_back(&mut self) -> Option<Self::Item> {
if let Some(c) = self.inner.next_back() {
self.back_yields += 1;
Some(c.into())
} else if !self.scheme_yielded {
self.scheme_yielded = true;
Some(Component::Scheme(self.scheme()))
} else {
None
}
}
}
impl<'a> FusedIterator for Components<'a> {}
impl<'a> PartialEq for Components<'a> {
fn eq(&self, other: &Self) -> bool {
if self.inner != other.inner {
return false;
}
match (self.scheme_yielded, other.scheme_yielded) {
(true, true) => true,
(false, false) if self.scheme() == other.scheme() => true,
_ => false,
}
}
}
// --- Tests
#[cfg(test)]
mod tests {
use anyhow::Result;
use crate::{scheme::SchemeRef, url::{Component, UrlBuf, UrlLike}};
#[test]
fn test_url() -> Result<()> {
use Component::*;
use SchemeRef as S;
crate::init_tests();
let search: UrlBuf = "search://keyword//root/projects/yazi".parse()?;
assert_eq!(search.uri(), "");
assert_eq!(search.scheme(), S::Search { domain: "keyword", uri: 0, urn: 0 });
let src = search.try_join("src")?;
assert_eq!(src.uri(), "src");
assert_eq!(src.scheme(), S::Search { domain: "keyword", uri: 1, urn: 1 });
let main = src.try_join("main.rs")?;
assert_eq!(main.urn(), "src/main.rs");
assert_eq!(main.scheme(), S::Search { domain: "keyword", uri: 2, urn: 2 });
let mut it = main.components();
assert_eq!(it.url().scheme(), S::Search { domain: "keyword", uri: 2, urn: 2 });
assert_eq!(it.next_back(), Some(Normal("main.rs".into())));
assert_eq!(it.url().scheme(), S::Search { domain: "keyword", uri: 1, urn: 1 });
assert_eq!(it.next_back(), Some(Normal("src".into())));
assert_eq!(it.url().scheme(), S::Search { domain: "keyword", uri: 0, urn: 0 });
assert_eq!(it.next_back(), Some(Normal("yazi".into())));
assert_eq!(it.url().scheme(), S::Search { domain: "keyword", uri: 0, urn: 0 });
let mut it = main.components();
assert_eq!(it.next(), Some(Scheme(S::Search { domain: "keyword", uri: 2, urn: 2 })));
assert_eq!(it.next(), Some(RootDir));
assert_eq!(it.next(), Some(Normal("root".into())));
assert_eq!(it.next(), Some(Normal("projects".into())));
assert_eq!(it.next(), Some(Normal("yazi".into())));
assert_eq!(it.url().scheme(), S::Search { domain: "keyword", uri: 2, urn: 2 });
assert_eq!(it.next(), Some(Normal("src".into())));
assert_eq!(it.url().scheme(), S::Search { domain: "keyword", uri: 1, urn: 1 });
assert_eq!(it.next_back(), Some(Normal("main.rs".into())));
assert_eq!(it.url().scheme(), S::Search { domain: "keyword", uri: 0, urn: 0 });
assert_eq!(it.next(), None);
assert_eq!(it.url().scheme(), S::Search { domain: "keyword", uri: 0, urn: 0 });
Ok(())
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/url/traits.rs | yazi-shared/src/url/traits.rs | use std::path::{Path, PathBuf};
use crate::{loc::Loc, url::{Url, UrlBuf, UrlCow}};
// --- AsUrl
pub trait AsUrl {
fn as_url(&self) -> Url<'_>;
}
impl AsUrl for Path {
#[inline]
fn as_url(&self) -> Url<'_> { Url::Regular(Loc::bare(self)) }
}
impl AsUrl for &Path {
#[inline]
fn as_url(&self) -> Url<'_> { (*self).as_url() }
}
impl AsUrl for PathBuf {
#[inline]
fn as_url(&self) -> Url<'_> { self.as_path().as_url() }
}
impl AsUrl for &PathBuf {
#[inline]
fn as_url(&self) -> Url<'_> { (*self).as_path().as_url() }
}
impl AsUrl for Url<'_> {
#[inline]
fn as_url(&self) -> Url<'_> { *self }
}
impl AsUrl for UrlBuf {
#[inline]
fn as_url(&self) -> Url<'_> {
match self {
Self::Regular(loc) => Url::Regular(loc.as_loc()),
Self::Search { loc, domain } => Url::Search { loc: loc.as_loc(), domain },
Self::Archive { loc, domain } => Url::Archive { loc: loc.as_loc(), domain },
Self::Sftp { loc, domain } => Url::Sftp { loc: loc.as_loc(), domain },
}
}
}
impl AsUrl for &UrlBuf {
#[inline]
fn as_url(&self) -> Url<'_> { (**self).as_url() }
}
impl AsUrl for &mut UrlBuf {
#[inline]
fn as_url(&self) -> Url<'_> { (**self).as_url() }
}
impl AsUrl for UrlCow<'_> {
fn as_url(&self) -> Url<'_> {
match self {
Self::Regular(loc) => Url::Regular(loc.as_loc()),
Self::Search { loc, domain } => Url::Search { loc: loc.as_loc(), domain },
Self::Archive { loc, domain } => Url::Archive { loc: loc.as_loc(), domain },
Self::Sftp { loc, domain } => Url::Sftp { loc: loc.as_loc(), domain },
Self::RegularRef(loc) => Url::Regular(*loc),
Self::SearchRef { loc, domain } => Url::Search { loc: *loc, domain },
Self::ArchiveRef { loc, domain } => Url::Archive { loc: *loc, domain },
Self::SftpRef { loc, domain } => Url::Sftp { loc: *loc, domain },
}
}
}
impl AsUrl for &UrlCow<'_> {
fn as_url(&self) -> Url<'_> { (**self).as_url() }
}
impl AsUrl for super::Components<'_> {
fn as_url(&self) -> Url<'_> { self.url() }
}
impl<'a, T> From<&'a T> for Url<'a>
where
T: AsUrl + ?Sized,
{
fn from(value: &'a T) -> Self { value.as_url() }
}
impl<'a, T> From<&'a mut T> for Url<'a>
where
T: AsUrl + ?Sized,
{
fn from(value: &'a mut T) -> Self { value.as_url() }
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/url/buf.rs | yazi-shared/src/url/buf.rs | use std::{borrow::Cow, fmt::{Debug, Formatter}, hash::{Hash, Hasher}, path::{Path, PathBuf}, str::FromStr};
use anyhow::Result;
use serde::{Deserialize, Serialize};
use crate::{loc::LocBuf, path::{PathBufDyn, PathDynError, SetNameError}, pool::{InternStr, Pool, Symbol}, scheme::Scheme, strand::AsStrand, url::{AsUrl, Url, UrlCow, UrlLike}};
#[derive(Clone, Eq)]
pub enum UrlBuf {
Regular(LocBuf),
Search { loc: LocBuf, domain: Symbol<str> },
Archive { loc: LocBuf, domain: Symbol<str> },
Sftp { loc: LocBuf<typed_path::UnixPathBuf>, domain: Symbol<str> },
}
// FIXME: remove
impl Default for UrlBuf {
fn default() -> Self { Self::Regular(Default::default()) }
}
impl From<&Self> for UrlBuf {
fn from(url: &Self) -> Self { url.clone() }
}
impl From<Url<'_>> for UrlBuf {
fn from(url: Url<'_>) -> Self {
match url {
Url::Regular(loc) => Self::Regular(loc.into()),
Url::Search { loc, domain } => Self::Search { loc: loc.into(), domain: domain.intern() },
Url::Archive { loc, domain } => Self::Archive { loc: loc.into(), domain: domain.intern() },
Url::Sftp { loc, domain } => Self::Sftp { loc: loc.into(), domain: domain.intern() },
}
}
}
impl From<&Url<'_>> for UrlBuf {
fn from(url: &Url<'_>) -> Self { (*url).into() }
}
impl From<LocBuf> for UrlBuf {
fn from(loc: LocBuf) -> Self { Self::Regular(loc) }
}
impl From<PathBuf> for UrlBuf {
fn from(path: PathBuf) -> Self { LocBuf::from(path).into() }
}
impl From<&PathBuf> for UrlBuf {
fn from(path: &PathBuf) -> Self { path.to_owned().into() }
}
impl From<&Path> for UrlBuf {
fn from(path: &Path) -> Self { path.to_path_buf().into() }
}
impl FromStr for UrlBuf {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(UrlCow::try_from(s)?.into_owned()) }
}
impl TryFrom<String> for UrlBuf {
type Error = anyhow::Error;
fn try_from(value: String) -> Result<Self, Self::Error> {
Ok(UrlCow::try_from(value)?.into_owned())
}
}
impl TryFrom<(Scheme, PathBufDyn)> for UrlBuf {
type Error = anyhow::Error;
fn try_from(value: (Scheme, PathBufDyn)) -> Result<Self, Self::Error> {
Ok(UrlCow::try_from(value)?.into_owned())
}
}
impl AsRef<Self> for UrlBuf {
fn as_ref(&self) -> &Self { self }
}
impl<'a> From<&'a UrlBuf> for Cow<'a, UrlBuf> {
fn from(url: &'a UrlBuf) -> Self { Cow::Borrowed(url) }
}
impl From<UrlBuf> for Cow<'_, UrlBuf> {
fn from(url: UrlBuf) -> Self { Cow::Owned(url) }
}
impl From<Cow<'_, Self>> for UrlBuf {
fn from(url: Cow<'_, Self>) -> Self { url.into_owned() }
}
// --- Eq
impl PartialEq for UrlBuf {
fn eq(&self, other: &Self) -> bool { self.as_url() == other.as_url() }
}
impl PartialEq<UrlBuf> for &UrlBuf {
fn eq(&self, other: &UrlBuf) -> bool { self.as_url() == other.as_url() }
}
impl PartialEq<Url<'_>> for UrlBuf {
fn eq(&self, other: &Url) -> bool { self.as_url() == *other }
}
impl PartialEq<Url<'_>> for &UrlBuf {
fn eq(&self, other: &Url) -> bool { self.as_url() == *other }
}
impl PartialEq<UrlCow<'_>> for UrlBuf {
fn eq(&self, other: &UrlCow) -> bool { self.as_url() == other.as_url() }
}
impl PartialEq<UrlCow<'_>> for &UrlBuf {
fn eq(&self, other: &UrlCow) -> bool { self.as_url() == other.as_url() }
}
// --- Hash
impl Hash for UrlBuf {
fn hash<H: Hasher>(&self, state: &mut H) { self.as_url().hash(state) }
}
impl UrlBuf {
#[inline]
pub fn new() -> &'static Self {
static U: UrlBuf = UrlBuf::Regular(LocBuf::empty());
&U
}
#[inline]
pub fn into_loc(self) -> PathBufDyn {
match self {
Self::Regular(loc) => loc.into_inner().into(),
Self::Search { loc, .. } => loc.into_inner().into(),
Self::Archive { loc, .. } => loc.into_inner().into(),
Self::Sftp { loc, .. } => loc.into_inner().into(),
}
}
#[inline]
pub fn into_local(self) -> Option<PathBuf> {
if self.kind().is_local() { self.into_loc().into_os().ok() } else { None }
}
pub fn try_set_name(&mut self, name: impl AsStrand) -> Result<(), SetNameError> {
let name = name.as_strand();
Ok(match self {
Self::Regular(loc) => loc.try_set_name(name.as_os()?)?,
Self::Search { loc, .. } => loc.try_set_name(name.as_os()?)?,
Self::Archive { loc, .. } => loc.try_set_name(name.as_os()?)?,
Self::Sftp { loc, .. } => loc.try_set_name(name.encoded_bytes())?,
})
}
pub fn rebase(&self, base: &Path) -> Self {
match self {
Self::Regular(loc) => Self::Regular(loc.rebase(base)),
Self::Search { loc, domain } => {
Self::Search { loc: loc.rebase(base), domain: domain.clone() }
}
Self::Archive { loc, domain } => {
Self::Archive { loc: loc.rebase(base), domain: domain.clone() }
}
Self::Sftp { loc, domain } => {
todo!();
// Self::Sftp { loc: loc.rebase(base), domain: domain.clone() }
}
}
}
}
impl UrlBuf {
#[inline]
pub fn to_regular(&self) -> Result<Self, PathDynError> { Ok(self.as_url().as_regular()?.into()) }
#[inline]
pub fn into_regular(self) -> Result<Self, PathDynError> {
Ok(Self::Regular(self.into_loc().into_os()?.into()))
}
#[inline]
pub fn to_search(&self, domain: impl AsRef<str>) -> Result<Self, PathDynError> {
Ok(Self::Search {
loc: LocBuf::<PathBuf>::zeroed(self.loc().to_os_owned()?),
domain: Pool::<str>::intern(domain),
})
}
#[inline]
pub fn into_search(self, domain: impl AsRef<str>) -> Result<Self, PathDynError> {
Ok(Self::Search {
loc: LocBuf::<PathBuf>::zeroed(self.into_loc().into_os()?),
domain: Pool::<str>::intern(domain),
})
}
}
impl Debug for UrlBuf {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { self.as_url().fmt(f) }
}
impl Serialize for UrlBuf {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
self.as_url().serialize(serializer)
}
}
impl<'de> Deserialize<'de> for UrlBuf {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
Self::try_from(s).map_err(serde::de::Error::custom)
}
}
// --- Tests
#[cfg(test)]
mod tests {
use anyhow::Result;
use super::*;
use crate::url::UrlLike;
#[test]
fn test_join() -> anyhow::Result<()> {
crate::init_tests();
let cases = [
// Regular
("/a", "b/c", "/a/b/c"),
// Search
("search://kw//a", "b/c", "search://kw:2:2//a/b/c"),
("search://kw:2:2//a/b/c", "d/e", "search://kw:4:4//a/b/c/d/e"),
// Archive
("archive:////a/b.zip", "c/d", "archive://:2:1//a/b.zip/c/d"),
("archive://:2:1//a/b.zip/c/d", "e/f", "archive://:4:1//a/b.zip/c/d/e/f"),
("archive://:2:2//a/b.zip/c/d", "e/f", "archive://:4:1//a/b.zip/c/d/e/f"),
// SFTP
("sftp://remote//a", "b/c", "sftp://remote//a/b/c"),
("sftp://remote:1:1//a/b/c", "d/e", "sftp://remote//a/b/c/d/e"),
// Relative
("search://kw", "b/c", "search://kw:2:2/b/c"),
("search://kw/", "b/c", "search://kw:2:2/b/c"),
];
for (base, path, expected) in cases {
let base: UrlBuf = base.parse()?;
#[cfg(unix)]
assert_eq!(format!("{:?}", base.try_join(path)?), expected);
#[cfg(windows)]
assert_eq!(
format!("{:?}", base.try_join(path)?).replace(r"\", "/"),
expected.replace(r"\", "/")
);
}
Ok(())
}
#[test]
fn test_parent() -> anyhow::Result<()> {
crate::init_tests();
let cases = [
// Regular
("/a", Some("/")),
("/", None),
// Search
("search://kw:2:2//a/b/c", Some("search://kw:1:1//a/b")),
("search://kw:1:1//a/b", Some("search://kw//a")),
("search://kw//a", Some("/")),
// Archive
("archive://:2:1//a/b.zip/c/d", Some("archive://:1:1//a/b.zip/c")),
("archive://:1:1//a/b.zip/c", Some("archive:////a/b.zip")),
("archive:////a/b.zip", Some("/a")),
// SFTP
("sftp://remote:3:1//a/b", Some("sftp://remote//a")),
("sftp://remote:2:1//a", Some("sftp://remote//")),
("sftp://remote:1:1//a", Some("sftp://remote//")),
("sftp://remote//a", Some("sftp://remote//")),
("sftp://remote:1//", None),
("sftp://remote//", None),
// Relative
("search://kw:2:2/a/b", Some("search://kw:1:1/a")),
("search://kw:1:1/a", None),
("search://kw/", None),
];
for (path, expected) in cases {
let path: UrlBuf = path.parse()?;
assert_eq!(path.parent().map(|u| format!("{u:?}")).as_deref(), expected);
}
Ok(())
}
#[test]
fn test_into_search() -> Result<()> {
crate::init_tests();
const S: char = std::path::MAIN_SEPARATOR;
let u: UrlBuf = "/root".parse()?;
assert_eq!(format!("{u:?}"), "/root");
let u = u.into_search("kw")?;
assert_eq!(format!("{u:?}"), "search://kw//root");
assert_eq!(format!("{:?}", u.parent().unwrap()), "/");
let u = u.try_join("examples")?;
assert_eq!(format!("{u:?}"), format!("search://kw:1:1//root{S}examples"));
let u = u.try_join("README.md")?;
assert_eq!(format!("{u:?}"), format!("search://kw:2:2//root{S}examples{S}README.md"));
let u = u.parent().unwrap();
assert_eq!(format!("{u:?}"), format!("search://kw:1:1//root{S}examples"));
let u = u.parent().unwrap();
assert_eq!(format!("{u:?}"), "search://kw//root");
let u = u.parent().unwrap();
assert_eq!(format!("{u:?}"), "/");
Ok(())
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/url/component.rs | yazi-shared/src/url/component.rs | use std::path::PrefixComponent;
use anyhow::Result;
use crate::{path::{self, PathDynError}, scheme::SchemeRef, strand::Strand};
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Component<'a> {
Scheme(SchemeRef<'a>),
Prefix(PrefixComponent<'a>),
RootDir,
CurDir,
ParentDir,
Normal(Strand<'a>),
}
impl<'a> From<path::Component<'a>> for Component<'a> {
fn from(value: path::Component<'a>) -> Self {
match value {
path::Component::Prefix(p) => Self::Prefix(p),
path::Component::RootDir => Self::RootDir,
path::Component::CurDir => Self::CurDir,
path::Component::ParentDir => Self::ParentDir,
path::Component::Normal(s) => Self::Normal(s),
}
}
}
impl<'a> Component<'a> {
pub fn downgrade(self) -> Option<path::Component<'a>> {
Some(match self {
Self::Scheme(_) => None?,
Self::Prefix(p) => path::Component::Prefix(p),
Self::RootDir => path::Component::RootDir,
Self::CurDir => path::Component::CurDir,
Self::ParentDir => path::Component::ParentDir,
Self::Normal(s) => path::Component::Normal(s),
})
}
}
// impl<'a> FromIterator<Component<'a>> for Result<UrlBuf> {
// fn from_iter<I: IntoIterator<Item = Component<'a>>>(iter: I) -> Self {
// let mut buf = PathBuf::new();
// let mut scheme = None;
// iter.into_iter().for_each(|c| match c {
// Component::Scheme(s) => scheme = Some(s),
// Component::Prefix(p) => buf.push(path::Component::Prefix(p)),
// Component::RootDir => buf.push(path::Component::RootDir),
// Component::CurDir => buf.push(path::Component::CurDir),
// Component::ParentDir => buf.push(path::Component::ParentDir),
// Component::Normal(s) => buf.push(path::Component::Normal(s)),
// });
// Ok(if let Some(s) = scheme {
// UrlCow::try_from((s, PathCow::Owned(PathBufDyn::Os(buf))))?.into_owned()
// } else {
// buf.into()
// })
// }
// }
impl<'a> FromIterator<Component<'a>> for Result<std::path::PathBuf, PathDynError> {
fn from_iter<I: IntoIterator<Item = Component<'a>>>(iter: I) -> Self {
iter.into_iter().filter_map(|c| c.downgrade()).map(std::path::Component::try_from).collect()
}
}
impl<'a> FromIterator<Component<'a>> for Result<typed_path::UnixPathBuf, PathDynError> {
fn from_iter<I: IntoIterator<Item = Component<'a>>>(iter: I) -> Self {
iter
.into_iter()
.filter_map(|c| c.downgrade())
.map(typed_path::UnixComponent::try_from)
.collect()
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/strand/view.rs | yazi-shared/src/strand/view.rs | use std::ffi::OsStr;
// --- AsStrandView
pub trait AsStrandView<'a, T> {
fn as_strand_view(self) -> T;
}
impl<'a> AsStrandView<'a, &'a OsStr> for &'a OsStr {
fn as_strand_view(self) -> &'a OsStr { self }
}
impl<'a> AsStrandView<'a, &'a OsStr> for &'a std::path::Path {
fn as_strand_view(self) -> &'a OsStr { self.as_os_str() }
}
impl<'a> AsStrandView<'a, &'a OsStr> for std::path::Components<'a> {
fn as_strand_view(self) -> &'a OsStr { self.as_path().as_os_str() }
}
impl<'a> AsStrandView<'a, &'a [u8]> for &'a [u8] {
fn as_strand_view(self) -> &'a [u8] { self }
}
impl<'a> AsStrandView<'a, &'a [u8]> for &'a typed_path::UnixPath {
fn as_strand_view(self) -> &'a [u8] { self.as_bytes() }
}
impl<'a> AsStrandView<'a, &'a [u8]> for typed_path::UnixComponents<'a> {
fn as_strand_view(self) -> &'a [u8] { self.as_path::<typed_path::UnixEncoding>().as_bytes() }
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/strand/like.rs | yazi-shared/src/strand/like.rs | use std::{borrow::Cow, ffi::OsStr, fmt::Display};
use crate::strand::{AsStrand, StrandBuf, StrandCow, StrandError, StrandKind};
// --- StrandLike
pub trait StrandLike: AsStrand {
fn as_os(&self) -> Result<&OsStr, StrandError> { self.as_strand().as_os() }
fn as_utf8(&self) -> Result<&str, StrandError> { self.as_strand().as_utf8() }
#[cfg(windows)]
fn backslash_to_slash(&self) -> StrandCow<'_> { self.as_strand().backslash_to_slash() }
fn contains(&self, x: impl AsStrand) -> bool { self.as_strand().contains(x) }
fn display(&self) -> impl Display { self.as_strand().display() }
fn encoded_bytes(&self) -> &[u8] { self.as_strand().encoded_bytes() }
fn eq_ignore_ascii_case(&self, other: impl AsStrand) -> bool {
self.as_strand().eq_ignore_ascii_case(other)
}
fn is_empty(&self) -> bool { self.as_strand().is_empty() }
fn kind(&self) -> StrandKind { self.as_strand().kind() }
fn len(&self) -> usize { self.as_strand().len() }
fn starts_with(&self, needle: impl AsStrand) -> bool { self.as_strand().starts_with(needle) }
fn to_owned(&self) -> StrandBuf { self.as_strand().to_owned() }
fn to_str(&self) -> Result<&str, std::str::Utf8Error> { self.as_strand().to_str() }
fn to_string_lossy(&self) -> Cow<'_, str> { self.as_strand().to_string_lossy() }
}
impl<S> From<&S> for StrandBuf
where
S: StrandLike,
{
fn from(value: &S) -> Self { value.to_owned() }
}
impl StrandLike for StrandBuf {}
impl StrandLike for StrandCow<'_> {}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/strand/kind.rs | yazi-shared/src/strand/kind.rs | use crate::{path::PathKind, scheme::SchemeKind};
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum StrandKind {
Utf8 = 0,
Os = 1,
Bytes = 2,
}
impl From<PathKind> for StrandKind {
fn from(value: PathKind) -> Self {
match value {
PathKind::Os => Self::Os,
PathKind::Unix => Self::Bytes,
}
}
}
impl From<SchemeKind> for StrandKind {
fn from(value: SchemeKind) -> Self {
match value {
SchemeKind::Regular => Self::Os,
SchemeKind::Search => Self::Os,
SchemeKind::Archive => Self::Os,
SchemeKind::Sftp => Self::Bytes,
}
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/strand/error.rs | yazi-shared/src/strand/error.rs | use thiserror::Error;
// --- StrandError
#[derive(Debug, Error)]
pub enum StrandError {
#[error("conversion to OS string failed")]
AsOs,
#[error("conversion to UTF-8 string failed")]
AsUtf8,
}
impl From<StrandError> for std::io::Error {
fn from(err: StrandError) -> Self { Self::other(err) }
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/strand/conversion.rs | yazi-shared/src/strand/conversion.rs | use std::{borrow::Cow, ffi::{OsStr, OsString}};
use crate::{path::{PathBufDyn, PathCow, PathDyn}, strand::{Strand, StrandBuf, StrandCow}, url::AsUrl};
// --- AsStrand
pub trait AsStrand {
fn as_strand(&self) -> Strand<'_>;
}
impl AsStrand for [u8] {
fn as_strand(&self) -> Strand<'_> { Strand::Bytes(self) }
}
impl AsStrand for &[u8] {
fn as_strand(&self) -> Strand<'_> { Strand::Bytes(self) }
}
impl AsStrand for str {
fn as_strand(&self) -> Strand<'_> { Strand::Utf8(self) }
}
impl AsStrand for &str {
fn as_strand(&self) -> Strand<'_> { Strand::Utf8(self) }
}
impl AsStrand for String {
fn as_strand(&self) -> Strand<'_> { Strand::Utf8(self) }
}
impl AsStrand for &String {
fn as_strand(&self) -> Strand<'_> { Strand::Utf8(self) }
}
impl AsStrand for OsStr {
fn as_strand(&self) -> Strand<'_> { Strand::Os(self) }
}
impl AsStrand for &OsStr {
fn as_strand(&self) -> Strand<'_> { Strand::Os(self) }
}
impl AsStrand for OsString {
fn as_strand(&self) -> Strand<'_> { Strand::Os(self) }
}
impl AsStrand for &std::path::Path {
fn as_strand(&self) -> Strand<'_> { Strand::Os(self.as_os_str()) }
}
impl AsStrand for &std::path::PathBuf {
fn as_strand(&self) -> Strand<'_> { Strand::Os(self.as_os_str()) }
}
impl AsStrand for &typed_path::UnixPath {
fn as_strand(&self) -> Strand<'_> { Strand::Bytes(self.as_bytes()) }
}
impl AsStrand for crate::path::Components<'_> {
fn as_strand(&self) -> Strand<'_> { self.strand() }
}
impl AsStrand for Cow<'_, [u8]> {
fn as_strand(&self) -> Strand<'_> { Strand::Bytes(self) }
}
impl AsStrand for Cow<'_, OsStr> {
fn as_strand(&self) -> Strand<'_> { Strand::Os(self) }
}
impl AsStrand for PathDyn<'_> {
fn as_strand(&self) -> Strand<'_> {
match self {
Self::Os(p) => Strand::Os(p.as_os_str()),
Self::Unix(p) => Strand::Bytes(p.as_bytes()),
}
}
}
impl AsStrand for PathBufDyn {
fn as_strand(&self) -> Strand<'_> {
match self {
Self::Os(p) => Strand::Os(p.as_os_str()),
Self::Unix(p) => Strand::Bytes(p.as_bytes()),
}
}
}
impl AsStrand for &PathBufDyn {
fn as_strand(&self) -> Strand<'_> { (**self).as_strand() }
}
impl AsStrand for PathCow<'_> {
fn as_strand(&self) -> Strand<'_> {
match self {
Self::Borrowed(p) => p.as_strand(),
Self::Owned(p) => p.as_strand(),
}
}
}
impl AsStrand for &PathCow<'_> {
fn as_strand(&self) -> Strand<'_> { (**self).as_strand() }
}
impl AsStrand for Strand<'_> {
fn as_strand(&self) -> Strand<'_> { *self }
}
impl AsStrand for StrandBuf {
fn as_strand(&self) -> Strand<'_> {
match self {
Self::Os(s) => Strand::Os(s),
Self::Utf8(s) => Strand::Utf8(s),
Self::Bytes(b) => Strand::Bytes(b),
}
}
}
impl AsStrand for &StrandBuf {
fn as_strand(&self) -> Strand<'_> { (**self).as_strand() }
}
impl AsStrand for StrandCow<'_> {
fn as_strand(&self) -> Strand<'_> {
match self {
StrandCow::Borrowed(s) => *s,
StrandCow::Owned(s) => s.as_strand(),
}
}
}
impl AsStrand for &StrandCow<'_> {
fn as_strand(&self) -> Strand<'_> { (**self).as_strand() }
}
// --- ToStrand
pub trait ToStrand {
fn to_strand(&self) -> StrandCow<'_>;
}
impl ToStrand for String {
fn to_strand(&self) -> StrandCow<'_> { self.as_strand().into() }
}
impl<T> ToStrand for T
where
T: AsUrl,
{
fn to_strand(&self) -> StrandCow<'_> { self.as_url().components().strand() }
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/strand/extensions.rs | yazi-shared/src/strand/extensions.rs | use crate::strand::{AsStrand, Strand, StrandBuf, StrandLike, ToStrand};
// --- StrandJoin
pub trait AsStrandJoin {
fn join(self, sep: Strand) -> StrandBuf;
}
impl<T> AsStrandJoin for T
where
T: IntoIterator,
T::Item: AsStrand,
{
fn join(self, sep: Strand) -> StrandBuf {
let mut kind = sep.kind();
let mut buf = Vec::new();
for (i, item) in self.into_iter().enumerate() {
if i > 0 {
buf.extend(sep.encoded_bytes());
}
let s = item.as_strand();
buf.extend(s.encoded_bytes());
if s.kind() > kind {
kind = s.kind();
}
}
unsafe { StrandBuf::from_encoded_bytes(kind, buf) }
}
}
// --- ToStrandJoin
pub trait ToStrandJoin {
fn join(self, sep: Strand) -> StrandBuf;
}
impl<T> ToStrandJoin for T
where
T: IntoIterator,
T::Item: ToStrand,
{
fn join(self, sep: Strand) -> StrandBuf {
let mut kind = sep.kind();
let mut buf = Vec::new();
for (i, item) in self.into_iter().enumerate() {
if i > 0 {
buf.extend(sep.encoded_bytes());
}
let s = item.to_strand();
buf.extend(s.encoded_bytes());
if s.kind() > kind {
kind = s.kind();
}
}
unsafe { StrandBuf::from_encoded_bytes(kind, buf) }
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/strand/strand.rs | yazi-shared/src/strand/strand.rs | use std::{borrow::Cow, ffi::OsStr, fmt::Display};
use anyhow::Result;
use crate::{BytesExt, strand::{AsStrand, StrandBuf, StrandError, StrandKind}, wtf8::FromWtf8};
// --- Strand
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialOrd)]
pub enum Strand<'p> {
Os(&'p OsStr),
Utf8(&'p str),
Bytes(&'p [u8]),
}
impl Default for Strand<'_> {
fn default() -> Self { Self::Utf8("") }
}
impl<'a> From<&'a OsStr> for Strand<'a> {
fn from(value: &'a OsStr) -> Self { Self::Os(value) }
}
impl<'a> From<&'a str> for Strand<'a> {
fn from(value: &'a str) -> Self { Self::Utf8(value) }
}
impl<'a> From<&'a [u8]> for Strand<'a> {
fn from(value: &'a [u8]) -> Self { Self::Bytes(value) }
}
impl<'a> From<&'a StrandBuf> for Strand<'a> {
fn from(value: &'a StrandBuf) -> Self {
match value {
StrandBuf::Os(s) => Self::Os(s),
StrandBuf::Utf8(s) => Self::Utf8(s),
StrandBuf::Bytes(s) => Self::Bytes(s),
}
}
}
impl PartialEq for Strand<'_> {
fn eq(&self, other: &Self) -> bool {
match *other {
Self::Os(s) => *self == s,
Self::Utf8(s) => *self == s,
Self::Bytes(b) => *self == b,
}
}
}
impl PartialEq<&OsStr> for Strand<'_> {
fn eq(&self, other: &&OsStr) -> bool {
match *self {
Self::Os(s) => s == *other,
Self::Utf8(s) => s == *other,
Self::Bytes(b) => b == other.as_encoded_bytes(),
}
}
}
impl PartialEq<&str> for Strand<'_> {
fn eq(&self, other: &&str) -> bool {
match *self {
Self::Os(s) => s == *other,
Self::Utf8(s) => s == *other,
Self::Bytes(b) => b == other.as_bytes(),
}
}
}
impl PartialEq<&[u8]> for Strand<'_> {
fn eq(&self, other: &&[u8]) -> bool {
match *self {
Self::Os(s) => s.as_encoded_bytes() == *other,
Self::Utf8(s) => s.as_bytes() == *other,
Self::Bytes(b) => b == *other,
}
}
}
impl<'a> Strand<'a> {
#[inline]
pub fn as_os(self) -> Result<&'a OsStr, StrandError> {
match self {
Self::Os(s) => Ok(s),
Self::Utf8(s) => Ok(OsStr::new(s)),
Self::Bytes(b) => OsStr::from_wtf8(b).map_err(|_| StrandError::AsOs),
}
}
#[inline]
pub fn as_utf8(self) -> Result<&'a str, StrandError> {
match self {
Self::Os(s) => s.to_str().ok_or(StrandError::AsUtf8),
Self::Utf8(s) => Ok(s),
Self::Bytes(b) => str::from_utf8(b).map_err(|_| StrandError::AsUtf8),
}
}
#[cfg(windows)]
pub fn backslash_to_slash(self) -> super::StrandCow<'a> {
let bytes = self.encoded_bytes();
// Fast path to skip if there are no backslashes
let skip_len = bytes.iter().take_while(|&&b| b != b'\\').count();
if skip_len >= bytes.len() {
return self.into();
}
let (skip, rest) = bytes.split_at(skip_len);
let mut out = Vec::new();
out.reserve_exact(bytes.len());
out.extend(skip);
for &b in rest {
out.push(if b == b'\\' { b'/' } else { b });
}
unsafe { StrandBuf::from_encoded_bytes(self.kind(), out) }.into()
}
pub fn contains(self, x: impl AsStrand) -> bool {
memchr::memmem::find(self.encoded_bytes(), x.as_strand().encoded_bytes()).is_some()
}
pub fn display(self) -> impl Display {
struct D<'a>(Strand<'a>);
impl<'a> Display for D<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self.0 {
Strand::Os(s) => s.display().fmt(f),
Strand::Utf8(s) => s.fmt(f),
Strand::Bytes(b) => b.display().fmt(f),
}
}
}
D(self)
}
#[inline]
pub fn encoded_bytes(self) -> &'a [u8] {
match self {
Self::Os(s) => s.as_encoded_bytes(),
Self::Utf8(s) => s.as_bytes(),
Self::Bytes(b) => b,
}
}
pub fn eq_ignore_ascii_case(self, other: impl AsStrand) -> bool {
self.encoded_bytes().eq_ignore_ascii_case(other.as_strand().encoded_bytes())
}
#[inline]
pub unsafe fn from_encoded_bytes(kind: impl Into<StrandKind>, bytes: &'a [u8]) -> Self {
match kind.into() {
StrandKind::Utf8 => Self::Utf8(unsafe { str::from_utf8_unchecked(bytes) }),
StrandKind::Os => Self::Os(unsafe { OsStr::from_encoded_bytes_unchecked(bytes) }),
StrandKind::Bytes => Self::Bytes(bytes),
}
}
pub fn is_empty(self) -> bool { self.encoded_bytes().is_empty() }
pub fn kind(self) -> StrandKind {
match self {
Self::Utf8(_) => StrandKind::Utf8,
Self::Os(_) => StrandKind::Os,
Self::Bytes(_) => StrandKind::Bytes,
}
}
pub fn len(self) -> usize { self.encoded_bytes().len() }
pub fn starts_with(self, needle: impl AsStrand) -> bool {
self.encoded_bytes().starts_with(needle.as_strand().encoded_bytes())
}
pub fn to_owned(self) -> StrandBuf {
match self {
Self::Os(s) => StrandBuf::Os(s.to_owned()),
Self::Utf8(s) => StrandBuf::Utf8(s.to_owned()),
Self::Bytes(b) => StrandBuf::Bytes(b.to_owned()),
}
}
pub fn to_str(self) -> Result<&'a str, std::str::Utf8Error> {
str::from_utf8(self.encoded_bytes())
}
pub fn to_string_lossy(self) -> Cow<'a, str> { String::from_utf8_lossy(self.encoded_bytes()) }
pub fn with<K, S>(kind: K, strand: &'a S) -> Result<Self>
where
K: Into<StrandKind>,
S: ?Sized + AsStrand,
{
let strand = strand.as_strand();
Ok(match kind.into() {
StrandKind::Utf8 => Self::Utf8(strand.as_utf8()?),
StrandKind::Os => Self::Os(strand.as_os()?),
StrandKind::Bytes => Self::Bytes(strand.encoded_bytes()),
})
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/strand/mod.rs | yazi-shared/src/strand/mod.rs | yazi_macro::mod_flat!(buf conversion cow error extensions kind like strand view);
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/strand/cow.rs | yazi-shared/src/strand/cow.rs | use std::{borrow::Cow, ffi::{OsStr, OsString}};
use anyhow::Result;
use crate::strand::{AsStrand, Strand, StrandBuf, StrandKind};
pub enum StrandCow<'a> {
Borrowed(Strand<'a>),
Owned(StrandBuf),
}
impl Default for StrandCow<'_> {
fn default() -> Self { Self::Borrowed(Strand::default()) }
}
impl From<OsString> for StrandCow<'_> {
fn from(value: OsString) -> Self { Self::Owned(StrandBuf::Os(value)) }
}
impl<'a> From<Cow<'a, OsStr>> for StrandCow<'a> {
fn from(value: Cow<'a, OsStr>) -> Self {
match value {
Cow::Borrowed(s) => Self::Borrowed(Strand::Os(s)),
Cow::Owned(s) => Self::Owned(StrandBuf::Os(s)),
}
}
}
impl<'a> From<Strand<'a>> for StrandCow<'a> {
fn from(value: Strand<'a>) -> Self { Self::Borrowed(value) }
}
impl From<StrandBuf> for StrandCow<'_> {
fn from(value: StrandBuf) -> Self { Self::Owned(value) }
}
impl<'a, T> From<&'a T> for StrandCow<'a>
where
T: ?Sized + AsStrand,
{
fn from(value: &'a T) -> Self { Self::Borrowed(value.as_strand()) }
}
impl PartialEq<Strand<'_>> for StrandCow<'_> {
fn eq(&self, other: &Strand) -> bool { self.as_strand() == *other }
}
impl<'a> StrandCow<'a> {
pub fn into_owned(self) -> StrandBuf {
match self {
Self::Borrowed(s) => s.to_owned(),
Self::Owned(s) => s,
}
}
pub fn into_string_lossy(self) -> String {
match self {
Self::Borrowed(s) => s.to_string_lossy().into_owned(),
Self::Owned(s) => s.into_string_lossy(),
}
}
pub fn with<K, T>(kind: K, bytes: T) -> Result<Self>
where
K: Into<StrandKind>,
T: Into<Cow<'a, [u8]>>,
{
Ok(match bytes.into() {
Cow::Borrowed(b) => Strand::with(kind, b)?.into(),
Cow::Owned(b) => StrandBuf::with(kind, b)?.into(),
})
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/strand/buf.rs | yazi-shared/src/strand/buf.rs | use std::{borrow::Cow, ffi::OsString, hash::{Hash, Hasher}};
use anyhow::Result;
use crate::{path::PathDyn, strand::{AsStrand, Strand, StrandCow, StrandError, StrandKind}, wtf8::FromWtf8Vec};
// --- StrandBuf
#[derive(Clone, Debug, Eq)]
pub enum StrandBuf {
Os(OsString),
Utf8(String),
Bytes(Vec<u8>),
}
impl Default for StrandBuf {
fn default() -> Self { Self::Utf8(String::new()) }
}
impl From<OsString> for StrandBuf {
fn from(value: OsString) -> Self { Self::Os(value) }
}
impl From<&str> for StrandBuf {
fn from(value: &str) -> Self { Self::Utf8(value.to_owned()) }
}
impl From<String> for StrandBuf {
fn from(value: String) -> Self { Self::Utf8(value) }
}
impl From<PathDyn<'_>> for StrandBuf {
fn from(value: PathDyn) -> Self {
match value {
PathDyn::Os(p) => Self::Os(p.as_os_str().to_owned()),
PathDyn::Unix(p) => Self::Bytes(p.as_bytes().to_owned()),
}
}
}
impl From<StrandCow<'_>> for StrandBuf {
fn from(value: StrandCow<'_>) -> Self { value.into_owned() }
}
impl PartialEq for StrandBuf {
fn eq(&self, other: &Self) -> bool { self.as_strand() == other.as_strand() }
}
impl PartialEq<Strand<'_>> for StrandBuf {
fn eq(&self, other: &Strand<'_>) -> bool { self.as_strand() == *other }
}
impl Hash for StrandBuf {
fn hash<H: Hasher>(&self, state: &mut H) { self.as_strand().hash(state); }
}
impl StrandBuf {
pub fn clear(&mut self) {
match self {
Self::Os(buf) => buf.clear(),
Self::Utf8(buf) => buf.clear(),
Self::Bytes(buf) => buf.clear(),
}
}
#[inline]
pub unsafe fn from_encoded_bytes(kind: impl Into<StrandKind>, bytes: Vec<u8>) -> Self {
match kind.into() {
StrandKind::Utf8 => Self::Utf8(unsafe { String::from_utf8_unchecked(bytes) }),
StrandKind::Os => Self::Os(unsafe { OsString::from_encoded_bytes_unchecked(bytes) }),
StrandKind::Bytes => Self::Bytes(bytes),
}
}
pub fn into_encoded_bytes(self) -> Vec<u8> {
match self {
Self::Os(s) => s.into_encoded_bytes(),
Self::Utf8(s) => s.into_bytes(),
Self::Bytes(b) => b,
}
}
pub fn into_string_lossy(self) -> String {
match self {
Self::Os(s) => match s.to_string_lossy() {
Cow::Borrowed(_) => unsafe { String::from_utf8_unchecked(s.into_encoded_bytes()) },
Cow::Owned(s) => s,
},
Self::Utf8(s) => s,
Self::Bytes(b) => match String::from_utf8_lossy(&b) {
Cow::Borrowed(_) => unsafe { String::from_utf8_unchecked(b) },
Cow::Owned(s) => s,
},
}
}
pub fn new(kind: impl Into<StrandKind>) -> Self { Self::with_str(kind, "") }
pub fn push_str(&mut self, s: impl AsRef<str>) {
let s = s.as_ref();
match self {
Self::Os(buf) => buf.push(s),
Self::Utf8(buf) => buf.push_str(s),
Self::Bytes(buf) => buf.extend(s.as_bytes()),
}
}
pub fn reserve_exact(&mut self, additional: usize) {
match self {
Self::Os(buf) => buf.reserve_exact(additional),
Self::Utf8(buf) => buf.reserve_exact(additional),
Self::Bytes(buf) => buf.reserve_exact(additional),
}
}
pub fn try_push<T>(&mut self, s: T) -> Result<(), StrandError>
where
T: AsStrand,
{
let s = s.as_strand();
Ok(match self {
Self::Os(buf) => buf.push(s.as_os()?),
Self::Utf8(buf) => buf.push_str(s.as_utf8()?),
Self::Bytes(buf) => buf.extend(s.encoded_bytes()),
})
}
pub fn with<K>(kind: K, bytes: Vec<u8>) -> Result<Self>
where
K: Into<StrandKind>,
{
Ok(match kind.into() {
StrandKind::Utf8 => Self::Utf8(String::from_utf8(bytes)?),
StrandKind::Os => Self::Os(OsString::from_wtf8_vec(bytes)?),
StrandKind::Bytes => Self::Bytes(bytes),
})
}
pub fn with_capacity<K>(kind: K, capacity: usize) -> Self
where
K: Into<StrandKind>,
{
match kind.into() {
StrandKind::Utf8 => Self::Utf8(String::with_capacity(capacity)),
StrandKind::Os => Self::Os(OsString::with_capacity(capacity)),
StrandKind::Bytes => Self::Bytes(Vec::with_capacity(capacity)),
}
}
pub fn with_str<K, S>(kind: K, s: S) -> Self
where
K: Into<StrandKind>,
S: Into<String>,
{
let s = s.into();
match kind.into() {
StrandKind::Utf8 => Self::Utf8(s),
StrandKind::Os => Self::Os(s.into()),
StrandKind::Bytes => Self::Bytes(s.into_bytes()),
}
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/scheme/ref.rs | yazi-shared/src/scheme/ref.rs | use std::{hash::Hash, ops::Deref};
use crate::{pool::InternStr, scheme::{AsScheme, Scheme, SchemeKind}};
#[derive(Clone, Copy, Debug)]
pub enum SchemeRef<'a> {
Regular { uri: usize, urn: usize },
Search { domain: &'a str, uri: usize, urn: usize },
Archive { domain: &'a str, uri: usize, urn: usize },
Sftp { domain: &'a str, uri: usize, urn: usize },
}
impl Deref for SchemeRef<'_> {
type Target = SchemeKind;
#[inline]
fn deref(&self) -> &Self::Target {
match self {
Self::Regular { .. } => &SchemeKind::Regular,
Self::Search { .. } => &SchemeKind::Search,
Self::Archive { .. } => &SchemeKind::Archive,
Self::Sftp { .. } => &SchemeKind::Sftp,
}
}
}
impl Hash for SchemeRef<'_> {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.kind().hash(state);
self.domain().hash(state);
}
}
impl PartialEq<SchemeRef<'_>> for SchemeRef<'_> {
fn eq(&self, other: &SchemeRef) -> bool {
self.kind() == other.kind() && self.domain() == other.domain()
}
}
impl From<SchemeRef<'_>> for Scheme {
fn from(value: SchemeRef) -> Self { value.to_owned() }
}
impl<'a> SchemeRef<'a> {
#[inline]
pub fn covariant(self, other: impl AsScheme) -> bool {
let other = other.as_scheme();
if self.is_virtual() || other.is_virtual() { self == other } else { true }
}
#[inline]
pub const fn domain(self) -> Option<&'a str> {
match self {
Self::Regular { .. } => None,
Self::Search { domain, .. } | Self::Archive { domain, .. } | Self::Sftp { domain, .. } => {
Some(domain)
}
}
}
#[inline]
pub const fn kind(self) -> SchemeKind {
match self {
Self::Regular { .. } => SchemeKind::Regular,
Self::Search { .. } => SchemeKind::Search,
Self::Archive { .. } => SchemeKind::Archive,
Self::Sftp { .. } => SchemeKind::Sftp,
}
}
#[inline]
pub const fn ports(self) -> (usize, usize) {
match self {
Self::Regular { uri, urn } => (uri, urn),
Self::Search { uri, urn, .. } => (uri, urn),
Self::Archive { uri, urn, .. } => (uri, urn),
Self::Sftp { uri, urn, .. } => (uri, urn),
}
}
pub fn to_owned(self) -> Scheme {
match self {
Self::Regular { uri, urn } => Scheme::Regular { uri, urn },
Self::Search { domain, uri, urn } => Scheme::Search { domain: domain.intern(), uri, urn },
Self::Archive { domain, uri, urn } => Scheme::Archive { domain: domain.intern(), uri, urn },
Self::Sftp { domain, uri, urn } => Scheme::Sftp { domain: domain.intern(), uri, urn },
}
}
pub const fn with_ports(self, uri: usize, urn: usize) -> Self {
match self {
Self::Regular { .. } => Self::Regular { uri, urn },
Self::Search { domain, .. } => Self::Search { domain, uri, urn },
Self::Archive { domain, .. } => Self::Archive { domain, uri, urn },
Self::Sftp { domain, .. } => Self::Sftp { domain, uri, urn },
}
}
#[inline]
pub const fn zeroed(self) -> Self { self.with_ports(0, 0) }
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/scheme/encode.rs | yazi-shared/src/scheme/encode.rs | use std::fmt::{self, Display};
use percent_encoding::{AsciiSet, CONTROLS, PercentEncode, percent_encode};
use crate::{scheme::SchemeKind, url::Url};
#[derive(Clone, Copy)]
pub struct Encode<'a>(pub Url<'a>);
impl<'a> From<crate::url::Encode<'a>> for Encode<'a> {
fn from(value: crate::url::Encode<'a>) -> Self { Self(value.0) }
}
impl<'a> Encode<'a> {
#[inline]
pub fn domain<'s>(s: &'s str) -> PercentEncode<'s> {
const SET: &AsciiSet = &CONTROLS.add(b'/').add(b':');
percent_encode(s.as_bytes(), SET)
}
pub(crate) fn ports(self) -> impl Display {
struct D<'a>(Encode<'a>);
impl Display for D<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
macro_rules! w {
($default_uri:expr, $default_urn:expr) => {{
let (uri, urn) = self.0.0.scheme().ports();
match (uri != $default_uri, urn != $default_urn) {
(true, true) => write!(f, ":{uri}:{urn}"),
(true, false) => write!(f, ":{uri}"),
(false, true) => write!(f, "::{urn}"),
(false, false) => Ok(()),
}
}};
}
match self.0.0.kind() {
SchemeKind::Regular => Ok(()),
SchemeKind::Search | SchemeKind::Archive => w!(0, 0),
SchemeKind::Sftp => {
w!(self.0.0.loc().name().is_some() as usize, self.0.0.loc().name().is_some() as usize)
}
}
}
}
D(self)
}
}
impl Display for Encode<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.0 {
Url::Regular(_) => write!(f, "regular://"),
Url::Search { domain, .. } => write!(f, "search://{}{}/", Self::domain(domain), self.ports()),
Url::Archive { domain, .. } => {
write!(f, "archive://{}{}/", Self::domain(domain), self.ports())
}
Url::Sftp { domain, .. } => write!(f, "sftp://{}{}/", Self::domain(domain), self.ports()),
}
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/scheme/kind.rs | yazi-shared/src/scheme/kind.rs | use anyhow::{Result, bail};
use crate::{BytesExt, scheme::{AsScheme, SchemeRef}};
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum SchemeKind {
Regular,
Search,
Archive,
Sftp,
}
impl<T> From<T> for SchemeKind
where
T: AsScheme,
{
fn from(value: T) -> Self {
match value.as_scheme() {
SchemeRef::Regular { .. } => Self::Regular,
SchemeRef::Search { .. } => Self::Search,
SchemeRef::Archive { .. } => Self::Archive,
SchemeRef::Sftp { .. } => Self::Sftp,
}
}
}
impl TryFrom<&[u8]> for SchemeKind {
type Error = anyhow::Error;
fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
match value {
b"regular" => Ok(Self::Regular),
b"search" => Ok(Self::Search),
b"archive" => Ok(Self::Archive),
b"sftp" => Ok(Self::Sftp),
_ => bail!("invalid scheme kind: {}", String::from_utf8_lossy(value)),
}
}
}
impl SchemeKind {
#[inline]
pub const fn as_str(self) -> &'static str {
match self {
Self::Regular => "regular",
Self::Search => "search",
Self::Archive => "archive",
Self::Sftp => "sftp",
}
}
#[inline]
pub fn is_local(self) -> bool {
match self {
Self::Regular | Self::Search => true,
Self::Archive | Self::Sftp => false,
}
}
#[inline]
pub fn is_remote(self) -> bool {
match self {
Self::Regular | Self::Search | Self::Archive => false,
Self::Sftp => true,
}
}
#[inline]
pub fn is_virtual(self) -> bool {
match self {
Self::Regular | Self::Search => false,
Self::Archive | Self::Sftp => true,
}
}
#[inline]
pub(super) const fn offset(self, tilde: bool) -> usize {
3 + self.as_str().len() + tilde as usize
}
pub fn parse(bytes: &[u8]) -> Result<Option<(Self, bool)>> {
let Some((kind, _)) = bytes.split_seq_once(b"://") else {
return Ok(None);
};
Ok(Some(if let Some(stripped) = kind.strip_suffix(b"~") {
(Self::try_from(stripped)?, true)
} else {
(Self::try_from(kind)?, false)
}))
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/scheme/mod.rs | yazi-shared/src/scheme/mod.rs | yazi_macro::mod_flat!(cow encode kind r#ref scheme traits);
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/scheme/cow.rs | yazi-shared/src/scheme/cow.rs | use std::borrow::Cow;
use anyhow::{Result, ensure};
use percent_encoding::percent_decode;
use crate::{path::{PathCow, PathLike}, pool::{InternStr, SymbolCow}, scheme::{AsScheme, Scheme, SchemeKind, SchemeRef}, url::Url};
#[derive(Clone, Debug)]
pub enum SchemeCow<'a> {
Borrowed(SchemeRef<'a>),
Owned(Scheme),
}
impl<'a> From<SchemeRef<'a>> for SchemeCow<'a> {
fn from(value: SchemeRef<'a>) -> Self { Self::Borrowed(value) }
}
impl<'a, T> From<&'a T> for SchemeCow<'a>
where
T: AsScheme + ?Sized,
{
fn from(value: &'a T) -> Self { Self::Borrowed(value.as_scheme()) }
}
impl From<Scheme> for SchemeCow<'_> {
fn from(value: Scheme) -> Self { Self::Owned(value) }
}
impl From<SchemeCow<'_>> for Scheme {
fn from(value: SchemeCow<'_>) -> Self { value.into_owned() }
}
impl PartialEq<SchemeRef<'_>> for SchemeCow<'_> {
fn eq(&self, other: &SchemeRef) -> bool { self.as_scheme() == *other }
}
impl<'a> SchemeCow<'a> {
pub fn regular(uri: usize, urn: usize) -> Self { SchemeRef::Regular { uri, urn }.into() }
pub fn search<T>(domain: T, uri: usize, urn: usize) -> Self
where
T: Into<Cow<'a, str>>,
{
match domain.into() {
Cow::Borrowed(domain) => SchemeRef::Search { domain, uri, urn }.into(),
Cow::Owned(domain) => Scheme::Search { domain: domain.intern(), uri, urn }.into(),
}
}
pub fn archive<T>(domain: T, uri: usize, urn: usize) -> Self
where
T: Into<Cow<'a, str>>,
{
match domain.into() {
Cow::Borrowed(domain) => SchemeRef::Archive { domain, uri, urn }.into(),
Cow::Owned(domain) => Scheme::Archive { domain: domain.intern(), uri, urn }.into(),
}
}
pub fn sftp<T>(domain: T, uri: usize, urn: usize) -> Self
where
T: Into<Cow<'a, str>>,
{
match domain.into() {
Cow::Borrowed(domain) => SchemeRef::Sftp { domain, uri, urn }.into(),
Cow::Owned(domain) => Scheme::Sftp { domain: domain.intern(), uri, urn }.into(),
}
}
pub fn parse(bytes: &'a [u8]) -> Result<(Self, PathCow<'a>)> {
let Some((kind, tilde)) = SchemeKind::parse(bytes)? else {
let path = Self::decode_path(SchemeKind::Regular, false, bytes)?;
let (uri, urn) = Self::normalize_ports(SchemeKind::Regular, None, None, &path)?;
return Ok((Self::regular(uri, urn), path));
};
// Decode domain and ports
let mut skip = kind.offset(tilde);
let (domain, uri, urn) = match kind {
SchemeKind::Regular => ("".into(), None, None),
SchemeKind::Search => Self::decode_param(&bytes[skip..], &mut skip)?,
SchemeKind::Archive => Self::decode_param(&bytes[skip..], &mut skip)?,
SchemeKind::Sftp => Self::decode_param(&bytes[skip..], &mut skip)?,
};
// Decode path
let path = Self::decode_path(kind, tilde, &bytes[skip..])?;
// Build scheme
let (uri, urn) = Self::normalize_ports(kind, uri, urn, &path)?;
let scheme = match kind {
SchemeKind::Regular => Self::regular(uri, urn),
SchemeKind::Search => Self::search(domain, uri, urn),
SchemeKind::Archive => Self::archive(domain, uri, urn),
SchemeKind::Sftp => Self::sftp(domain, uri, urn),
};
Ok((scheme, path))
}
fn decode_param(
bytes: &'a [u8],
skip: &mut usize,
) -> Result<(Cow<'a, str>, Option<usize>, Option<usize>)> {
let mut len = bytes.iter().copied().take_while(|&b| b != b'/').count();
let slash = bytes.get(len).is_some_and(|&b| b == b'/');
*skip += len + slash as usize;
let (uri, urn) = Self::decode_ports(&bytes[..len], &mut len)?;
let domain = match Cow::from(percent_decode(&bytes[..len])) {
Cow::Borrowed(b) => str::from_utf8(b)?.into(),
Cow::Owned(b) => String::from_utf8(b)?.into(),
};
Ok((domain, uri, urn))
}
fn decode_ports(bytes: &[u8], skip: &mut usize) -> Result<(Option<usize>, Option<usize>)> {
let Some(a_idx) = bytes.iter().rposition(|&b| b == b':') else { return Ok((None, None)) };
let a_len = bytes.len() - a_idx;
*skip -= a_len;
let a = if a_len == 1 { None } else { Some(str::from_utf8(&bytes[a_idx + 1..])?.parse()?) };
let Some(b_idx) = bytes[..a_idx].iter().rposition(|&b| b == b':') else {
return Ok((a, None));
};
let b_len = bytes[..a_idx].len() - b_idx;
*skip -= b_len;
let b =
if b_len == 1 { None } else { Some(str::from_utf8(&bytes[b_idx + 1..a_idx])?.parse()?) };
Ok((b, a))
}
fn decode_path(kind: SchemeKind, tilde: bool, bytes: &'a [u8]) -> Result<PathCow<'a>> {
let bytes: Cow<_> = if tilde { percent_decode(bytes).into() } else { bytes.into() };
PathCow::with(kind, bytes)
}
fn normalize_ports(
kind: SchemeKind,
uri: Option<usize>,
urn: Option<usize>,
path: &PathCow,
) -> Result<(usize, usize)> {
Ok(match kind {
SchemeKind::Regular => {
ensure!(uri.is_none() && urn.is_none(), "Regular scheme cannot have ports");
(path.name().is_some() as usize, path.name().is_some() as usize)
}
SchemeKind::Search => {
let (uri, urn) = (uri.unwrap_or(0), urn.unwrap_or(0));
ensure!(uri == urn, "Search scheme requires URI and URN to be equal");
(uri, urn)
}
SchemeKind::Archive => (uri.unwrap_or(0), urn.unwrap_or(0)),
SchemeKind::Sftp => {
let uri = uri.unwrap_or(path.name().is_some() as usize);
let urn = urn.unwrap_or(path.name().is_some() as usize);
(uri, urn)
}
})
}
pub fn retrieve_ports(url: Url) -> (usize, usize) {
match url {
Url::Regular(loc) => (loc.file_name().is_some() as usize, loc.file_name().is_some() as usize),
Url::Search { loc, .. } => (loc.uri().components().count(), loc.urn().components().count()),
Url::Archive { loc, .. } => (loc.uri().components().count(), loc.urn().components().count()),
Url::Sftp { loc, .. } => (loc.uri().components().count(), loc.urn().components().count()),
}
}
}
impl<'a> SchemeCow<'a> {
#[inline]
pub fn into_domain(self) -> Option<SymbolCow<'a, str>> {
Some(match self {
SchemeCow::Borrowed(s) => s.domain()?.into(),
SchemeCow::Owned(s) => s.into_domain()?.into(),
})
}
#[inline]
pub fn into_owned(self) -> Scheme {
match self {
Self::Borrowed(s) => s.to_owned(),
Self::Owned(s) => s,
}
}
pub fn with_ports(self, uri: usize, urn: usize) -> Self {
match self {
Self::Borrowed(s) => s.with_ports(uri, urn).into(),
Self::Owned(s) => s.with_ports(uri, urn).into(),
}
}
#[inline]
pub fn zeroed(self) -> Self { self.with_ports(0, 0) }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_decode_ports() -> Result<()> {
fn assert(s: &str, len: usize, uri: Option<usize>, urn: Option<usize>) -> Result<()> {
let mut n = usize::MAX;
let port = SchemeCow::decode_ports(s.as_bytes(), &mut n)?;
assert_eq!((usize::MAX - n, port.0, port.1), (len, uri, urn));
Ok(())
}
// Zeros
assert("", 0, None, None)?;
assert(":", 1, None, None)?;
assert("::", 2, None, None)?;
// URI
assert(":2", 2, Some(2), None)?;
assert(":2:", 3, Some(2), None)?;
assert(":22:", 4, Some(22), None)?;
// URN
assert("::1", 3, None, Some(1))?;
assert(":2:1", 4, Some(2), Some(1))?;
assert(":22:11", 6, Some(22), Some(11))?;
Ok(())
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.