refactor: introduce the SStr type for static strings (#2957)

This commit is contained in:
三咲雅 misaki masa 2025-07-06 22:16:29 +08:00 committed by GitHub
parent a426d449f4
commit 52ecb31f5a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
27 changed files with 75 additions and 99 deletions

View file

@ -1,6 +1,7 @@
use std::{borrow::Cow, fmt::Display};
use mlua::{ExternalError, FromLua, Lua, MetaMethod, UserData, UserDataFields, UserDataMethods, Value};
use yazi_shared::SStr;
const EXPECTED: &str = "expected a Error";
@ -8,7 +9,7 @@ pub enum Error {
Io(std::io::Error),
IoKind(std::io::ErrorKind),
Serde(serde_json::Error),
Custom(Cow<'static, str>),
Custom(SStr),
}
impl Error {
@ -18,7 +19,7 @@ impl Error {
lua.globals().raw_set("Error", lua.create_table_from([("custom", new)])?)
}
pub fn into_string(self) -> Cow<'static, str> {
pub fn into_string(self) -> SStr {
match self {
Error::Io(e) => Cow::Owned(e.to_string()),
Error::IoKind(e) => Cow::Owned(e.to_string()),

View file

@ -4,7 +4,7 @@ use anyhow::{Context, Result, bail};
use serde::{Deserialize, Serialize};
use yazi_codegen::DeserializeOver2;
use yazi_fs::{Xdg, expand_path};
use yazi_shared::timestamp_us;
use yazi_shared::{SStr, timestamp_us};
use super::PreviewWrap;
@ -35,10 +35,10 @@ impl Preview {
}
#[inline]
pub fn indent(&self) -> Cow<'static, str> { Self::indent_with(self.tab_size as usize) }
pub fn indent(&self) -> SStr { Self::indent_with(self.tab_size as usize) }
#[inline]
pub fn indent_with(n: usize) -> Cow<'static, str> {
pub fn indent_with(n: usize) -> SStr {
if let Some(s) = TABS.get(n) { Cow::Borrowed(s) } else { Cow::Owned(" ".repeat(n)) }
}
}

View file

@ -1,7 +1,7 @@
use std::{borrow::Cow, collections::HashMap, path::PathBuf};
use yazi_fs::File;
use yazi_shared::{MIME_DIR, url::{Scheme, Url}};
use yazi_shared::{MIME_DIR, SStr, url::{Scheme, Url}};
#[derive(Default)]
pub struct Mimetype(HashMap<PathBuf, String>);
@ -19,7 +19,7 @@ impl Mimetype {
}
#[inline]
pub fn by_url_owned(&self, url: &Url) -> Option<Cow<'static, str>> {
pub fn by_url_owned(&self, url: &Url) -> Option<SStr> {
self.by_url(url).map(|s| Cow::Owned(s.to_owned()))
}
@ -29,7 +29,7 @@ impl Mimetype {
}
#[inline]
pub fn by_file_owned(&self, file: &File) -> Option<Cow<'static, str>> {
pub fn by_file_owned(&self, file: &File) -> Option<SStr> {
if file.is_dir() { Some(Cow::Borrowed(MIME_DIR)) } else { self.by_url_owned(&file.url) }
}

View file

@ -1,12 +1,10 @@
use std::borrow::Cow;
use tokio_util::sync::CancellationToken;
use yazi_config::YAZI;
use yazi_fs::File;
use yazi_macro::render;
use yazi_parser::tab::SpotLock;
use yazi_plugin::isolate;
use yazi_shared::url::Url;
use yazi_shared::{SStr, url::Url};
#[derive(Default)]
pub struct Spot {
@ -17,7 +15,7 @@ pub struct Spot {
}
impl Spot {
pub fn go(&mut self, file: File, mime: Cow<'static, str>) {
pub fn go(&mut self, file: File, mime: SStr) {
if mime.is_empty() {
return; // Wait till mimetype is resolved to avoid flickering
} else if self.same_lock(&file, &mime) {

View file

@ -9,7 +9,7 @@ use yazi_fs::{File, Files, FilesOp, cha::Cha};
use yazi_macro::render;
use yazi_parser::tab::PreviewLock;
use yazi_plugin::{external::Highlighter, isolate};
use yazi_shared::{MIME_DIR, url::Url};
use yazi_shared::{MIME_DIR, SStr, url::Url};
#[derive(Default)]
pub struct Preview {
@ -21,7 +21,7 @@ pub struct Preview {
}
impl Preview {
pub fn go(&mut self, file: File, mime: Cow<'static, str>, force: bool) {
pub fn go(&mut self, file: File, mime: SStr, force: bool) {
if mime.is_empty() {
return; // Wait till mimetype is resolved to avoid flickering
} else if !force && self.same_lock(&file, &mime) {

View file

@ -1,8 +1,8 @@
use std::{borrow::Cow, collections::HashMap};
use std::collections::HashMap;
use mlua::{ExternalResult, IntoLua, Lua, Value};
use serde::{Deserialize, Serialize};
use yazi_shared::Id;
use yazi_shared::{Id, SStr};
use super::{Body, BodyHi};
use crate::Peer;
@ -10,7 +10,7 @@ use crate::Peer;
#[derive(Debug, Serialize, Deserialize)]
pub struct BodyHey {
pub peers: HashMap<Id, Peer>,
pub version: Cow<'static, str>,
pub version: SStr,
}
impl BodyHey {

View file

@ -2,6 +2,7 @@ use std::{borrow::Cow, collections::HashSet};
use mlua::{ExternalResult, IntoLua, Lua, Value};
use serde::{Deserialize, Serialize};
use yazi_shared::SStr;
use super::Body;
@ -10,7 +11,7 @@ use super::Body;
pub struct BodyHi<'a> {
/// Specifies the kinds of events that the client can handle
pub abilities: HashSet<Cow<'a, str>>,
pub version: Cow<'static, str>,
pub version: SStr,
}
impl<'a> BodyHi<'a> {

View file

@ -1,12 +1,12 @@
use std::{borrow::Cow, path::PathBuf};
use std::path::PathBuf;
use yazi_proxy::options::CmpItem;
use yazi_shared::{Id, event::{Cmd, CmdCow, Data}};
use yazi_shared::{Id, SStr, event::{Cmd, CmdCow, Data}};
pub struct ShowOpt {
pub cache: Vec<CmpItem>,
pub cache_name: PathBuf,
pub word: Cow<'static, str>,
pub word: SStr,
pub ticket: Id,
}

View file

@ -1,9 +1,7 @@
use std::borrow::Cow;
use yazi_shared::{Id, event::{CmdCow, Data}};
use yazi_shared::{Id, SStr, event::{CmdCow, Data}};
pub struct TriggerOpt {
pub word: Cow<'static, str>,
pub word: SStr,
pub ticket: Id,
}

View file

@ -1,12 +1,10 @@
use std::borrow::Cow;
use yazi_shared::event::CmdCow;
use yazi_shared::{SStr, event::CmdCow};
pub struct RenameOpt {
pub hovered: bool,
pub force: bool,
pub empty: Cow<'static, str>,
pub cursor: Cow<'static, str>,
pub empty: SStr,
pub cursor: SStr,
}
impl From<CmdCow> for RenameOpt {

View file

@ -1,9 +1,7 @@
use std::borrow::Cow;
use yazi_shared::event::CmdCow;
use yazi_shared::{SStr, event::CmdCow};
pub struct CopyOpt {
pub r#type: Cow<'static, str>,
pub r#type: SStr,
}
impl From<CmdCow> for CopyOpt {

View file

@ -1,9 +1,7 @@
use std::borrow::Cow;
use yazi_shared::event::CmdCow;
use yazi_shared::{SStr, event::CmdCow};
pub struct SwipeOpt {
pub step: Cow<'static, str>,
pub step: SStr,
}
impl From<CmdCow> for SwipeOpt {

View file

@ -1,9 +1,9 @@
use std::{borrow::Cow, ffi::OsStr, path::Path};
use yazi_shared::event::CmdCow;
use yazi_shared::{SStr, event::CmdCow};
pub struct CopyOpt {
pub r#type: Cow<'static, str>,
pub r#type: SStr,
pub separator: CopySeparator,
pub hovered: bool,
}

View file

@ -1,11 +1,9 @@
use std::borrow::Cow;
use yazi_fs::FilterCase;
use yazi_shared::event::CmdCow;
use yazi_shared::{SStr, event::CmdCow};
#[derive(Default)]
pub struct FilterOpt {
pub query: Cow<'static, str>,
pub query: SStr,
pub case: FilterCase,
pub done: bool,
}

View file

@ -1,10 +1,8 @@
use std::borrow::Cow;
use yazi_fs::FilterCase;
use yazi_shared::event::CmdCow;
use yazi_shared::{SStr, event::CmdCow};
pub struct FindOpt {
pub query: Option<Cow<'static, str>>,
pub query: Option<SStr>,
pub prev: bool,
pub case: FilterCase,
}

View file

@ -1,10 +1,8 @@
use std::borrow::Cow;
use anyhow::bail;
use yazi_shared::{event::{CmdCow, Data}, url::Url};
use yazi_shared::{SStr, event::{CmdCow, Data}, url::Url};
pub struct ShellOpt {
pub run: Cow<'static, str>,
pub run: SStr,
pub cwd: Option<Url>,
pub block: bool,

View file

@ -1,5 +1,3 @@
use std::borrow::Cow;
use mlua::{ExternalError, HookTriggers, IntoLua, ObjectLike, VmState};
use tokio::{runtime::Handle, select};
use tokio_util::sync::CancellationToken;
@ -8,7 +6,7 @@ use yazi_binding::{File, elements::Rect};
use yazi_config::LAYOUT;
use yazi_dds::Sendable;
use yazi_proxy::{AppProxy, options::{PluginCallback, PluginOpt}};
use yazi_shared::event::Cmd;
use yazi_shared::{SStr, event::Cmd};
use super::slim_lua;
use crate::loader::LOADER;
@ -16,7 +14,7 @@ use crate::loader::LOADER;
pub fn peek(
cmd: &'static Cmd,
file: yazi_fs::File,
mime: Cow<'static, str>,
mime: SStr,
skip: usize,
) -> Option<CancellationToken> {
let ct = CancellationToken::new();
@ -47,7 +45,7 @@ pub fn peek(
Some(ct)
}
fn peek_sync(cmd: &'static Cmd, file: yazi_fs::File, mime: Cow<'static, str>, skip: usize) {
fn peek_sync(cmd: &'static Cmd, file: yazi_fs::File, mime: SStr, skip: usize) {
let cb: PluginCallback = Box::new(move |lua, plugin| {
let job = lua.create_table_from([
("area", Rect::from(LAYOUT.get().preview).into_lua(lua)?),
@ -66,7 +64,7 @@ fn peek_sync(cmd: &'static Cmd, file: yazi_fs::File, mime: Cow<'static, str>, sk
fn peek_async(
cmd: &'static Cmd,
file: yazi_fs::File,
mime: Cow<'static, str>,
mime: SStr,
skip: usize,
ct: CancellationToken,
) {

View file

@ -1,24 +1,17 @@
use std::borrow::Cow;
use mlua::{ExternalError, ExternalResult, HookTriggers, IntoLua, ObjectLike, VmState};
use tokio::{runtime::Handle, select};
use tokio_util::sync::CancellationToken;
use tracing::error;
use yazi_binding::{File, Id};
use yazi_dds::Sendable;
use yazi_shared::{Ids, event::Cmd};
use yazi_shared::{Ids, SStr, event::Cmd};
use super::slim_lua;
use crate::loader::LOADER;
static IDS: Ids = Ids::new();
pub fn spot(
cmd: &'static Cmd,
file: yazi_fs::File,
mime: Cow<'static, str>,
skip: usize,
) -> CancellationToken {
pub fn spot(cmd: &'static Cmd, file: yazi_fs::File, mime: SStr, skip: usize) -> CancellationToken {
let ct = CancellationToken::new();
let (ct1, ct2) = (ct.clone(), ct.clone());

View file

@ -1,14 +1,14 @@
use std::{borrow::Cow, collections::HashMap, fmt::Debug};
use std::{collections::HashMap, fmt::Debug};
use anyhow::bail;
use mlua::{Lua, Table};
use yazi_shared::event::{Cmd, CmdCow, Data, DataKey};
use yazi_shared::{SStr, event::{Cmd, CmdCow, Data, DataKey}};
pub type PluginCallback = Box<dyn FnOnce(&Lua, Table) -> mlua::Result<()> + Send + Sync>;
#[derive(Default)]
pub struct PluginOpt {
pub id: Cow<'static, str>,
pub id: SStr,
pub args: HashMap<DataKey, Data>,
pub mode: PluginMode,
pub cb: Option<PluginCallback>,
@ -50,7 +50,7 @@ impl Debug for PluginOpt {
}
impl PluginOpt {
pub fn new_callback(id: impl Into<Cow<'static, str>>, cb: PluginCallback) -> Self {
pub fn new_callback(id: impl Into<SStr>, cb: PluginCallback) -> Self {
Self { id: id.into(), mode: PluginMode::Sync, cb: Some(cb), ..Default::default() }
}
}

View file

@ -1,12 +1,10 @@
use std::borrow::Cow;
use yazi_shared::event::CmdCow;
use yazi_shared::{SStr, event::CmdCow};
pub struct SearchOpt {
pub via: SearchOptVia,
pub subject: Cow<'static, str>,
pub subject: SStr,
pub args: Vec<String>,
pub args_raw: Cow<'static, str>,
pub args_raw: SStr,
}
impl TryFrom<CmdCow> for SearchOpt {

View file

@ -1,7 +1,7 @@
use std::borrow::Cow;
use yazi_macro::emit;
use yazi_shared::{event::Cmd, url::Url};
use yazi_shared::{SStr, event::Cmd, url::Url};
use crate::options::SearchOpt;
@ -16,7 +16,7 @@ impl TabProxy {
emit!(Call(Cmd::args("mgr:reveal", [target]).with("raw", true).with("no-dummy", true)));
}
pub fn arrow(step: impl Into<Cow<'static, str>>) {
pub fn arrow(step: impl Into<SStr>) {
emit!(Call(Cmd::args("mgr:arrow", [step.into()])));
}

1
yazi-shared/src/alias.rs Normal file
View file

@ -0,0 +1 @@
pub type SStr = std::borrow::Cow<'static, str>;

View file

@ -4,11 +4,11 @@ use anyhow::{Result, bail};
use serde::{Deserialize, de};
use super::{Data, DataKey};
use crate::{Layer, url::Url};
use crate::{Layer, SStr, url::Url};
#[derive(Debug, Default)]
pub struct Cmd {
pub name: Cow<'static, str>,
pub name: SStr,
pub args: HashMap<DataKey, Data>,
pub layer: Layer,
}
@ -16,7 +16,7 @@ pub struct Cmd {
impl Cmd {
pub fn new<N>(name: N) -> Self
where
N: Into<Cow<'static, str>>,
N: Into<SStr>,
{
Self::new_or(name, Default::default())
.unwrap_or_else(|_| Self { name: "null".into(), ..Default::default() })
@ -24,9 +24,9 @@ impl Cmd {
pub fn new_or<N>(name: N, default: Layer) -> Result<Self>
where
N: Into<Cow<'static, str>>,
N: Into<SStr>,
{
let cow: Cow<'static, str> = name.into();
let cow: SStr = name.into();
let (layer, name) = match cow.find(':') {
None => (default, cow),
Some(i) => (cow[..i].parse()?, match cow {
@ -43,7 +43,7 @@ impl Cmd {
pub fn args<N, D, I>(name: N, args: I) -> Self
where
N: Into<Cow<'static, str>>,
N: Into<SStr>,
D: Into<Data>,
I: IntoIterator<Item = D>,
{
@ -116,7 +116,7 @@ impl Cmd {
}
#[inline]
pub fn take_str(&mut self, name: impl Into<DataKey>) -> Option<Cow<'static, str>> {
pub fn take_str(&mut self, name: impl Into<DataKey>) -> Option<SStr> {
if let Some(Data::String(s)) = self.take(name) { Some(s) } else { None }
}
@ -124,7 +124,7 @@ impl Cmd {
pub fn take_first(&mut self) -> Option<Data> { self.take(0) }
#[inline]
pub fn take_first_str(&mut self) -> Option<Cow<'static, str>> {
pub fn take_first_str(&mut self) -> Option<SStr> {
if let Some(Data::String(s)) = self.take_first() { Some(s) } else { None }
}

View file

@ -1,7 +1,7 @@
use std::{borrow::Cow, ops::Deref};
use super::{Cmd, Data, DataKey};
use crate::url::Url;
use crate::{SStr, url::Url};
#[derive(Debug)]
pub enum CmdCow {
@ -38,7 +38,7 @@ impl CmdCow {
}
#[inline]
pub fn take_str(&mut self, name: impl Into<DataKey>) -> Option<Cow<'static, str>> {
pub fn take_str(&mut self, name: impl Into<DataKey>) -> Option<SStr> {
match self {
Self::Owned(c) => c.take_str(name),
Self::Borrowed(c) => c.str(name).map(Cow::Borrowed),
@ -54,7 +54,7 @@ impl CmdCow {
}
#[inline]
pub fn take_first_str(&mut self) -> Option<Cow<'static, str>> {
pub fn take_first_str(&mut self) -> Option<SStr> {
match self {
Self::Owned(c) => c.take_first_str(),
Self::Borrowed(c) => c.first_str().map(Cow::Borrowed),

View file

@ -3,7 +3,7 @@ use std::{any::Any, borrow::Cow, collections::HashMap};
use ordered_float::OrderedFloat;
use serde::{Deserialize, Serialize, de};
use crate::{Id, url::{Url, UrnBuf}};
use crate::{Id, SStr, url::{Url, UrnBuf}};
// --- Data
#[derive(Debug, Serialize, Deserialize)]
@ -13,7 +13,7 @@ pub enum Data {
Boolean(bool),
Integer(i64),
Number(f64),
String(Cow<'static, str>),
String(SStr),
List(Vec<Data>),
Dict(HashMap<DataKey, Data>),
Id(Id),
@ -47,7 +47,7 @@ impl Data {
}
#[inline]
pub fn into_string(self) -> Option<Cow<'static, str>> {
pub fn into_string(self) -> Option<SStr> {
match self {
Self::String(s) => Some(s),
_ => None,
@ -115,8 +115,8 @@ impl From<String> for Data {
fn from(value: String) -> Self { Self::String(Cow::Owned(value)) }
}
impl From<Cow<'static, str>> for Data {
fn from(value: Cow<'static, str>) -> Self { Self::String(value) }
impl From<SStr> for Data {
fn from(value: SStr) -> Self { Self::String(value) }
}
impl From<Id> for Data {
@ -140,7 +140,7 @@ pub enum DataKey {
#[serde(deserialize_with = "Self::deserialize_integer")]
Integer(i64),
Number(OrderedFloat<f64>),
String(Cow<'static, str>),
String(SStr),
Id(Id),
#[serde(skip_deserializing)]
Url(Url),

View file

@ -2,7 +2,7 @@
yazi_macro::mod_pub!(errors event shell translit url);
yazi_macro::mod_flat!(bytes chars condition debounce either env id layer natsort os osstr rand ro_cell sync_cell terminal throttle time utf8);
yazi_macro::mod_flat!(alias bytes chars condition debounce either env id layer natsort os osstr rand ro_cell sync_cell terminal throttle time utf8);
pub fn init() {
LOG_LEVEL.replace(<_>::from(std::env::var("YAZI_LOG").unwrap_or_default()));

View file

@ -1,12 +1,12 @@
use std::{borrow::Cow, ops::RangeBounds};
use std::ops::RangeBounds;
use yazi_macro::render;
use yazi_shared::{CharKind, event::CmdCow};
use yazi_shared::{CharKind, SStr, event::CmdCow};
use crate::input::Input;
struct Opt {
kind: Cow<'static, str>,
kind: SStr,
}
impl From<CmdCow> for Opt {