ronantakizawa/codereview-bench huggingface dataset:
Repository: sxyazi/yazi
File: yazi-core/src/mgr/commands/update_mimes.rs (Rust)

Code before:

impl TryFrom<CmdCow> for Opt {
	type Error = ();

	fn try_from(mut c: CmdCow) -> Result<Self, Self::Error> {
		Ok(Self { updates: c.try_take("updates").ok_or(())?.into_dict_string() })
	}
}

impl Mgr {
	pub fn update_mimes(&mut self, opt: impl TryInto<Opt>, tasks: &Tasks) {
		let Ok(opt): Result<Opt, _> = opt.try_into() else {
			return error!("invalid arguments for update_mimes");
		};

		let linked = LINKED.read();
		let updates = opt
			.updates
			.into_iter()
			.map(|(url, mime)| (Url::from(url.into_owned()), mime))
			.filter(|(url, mime)| self.mimetype.by_url(url) != Some(mime))
			.fold(HashMap::new(), |mut map, (u, m)| {
				for u in linked.from_file(&u) {
					map.insert(u, m.to_string());
				}
				map.insert(u, m.into_owned());
				map
			});

		drop(linked);
		if updates.is_empty() {
			return;
		}

		let affected: Vec<_> = self
			.current()
			.paginate(self.current().page)
			.iter()
			.filter(|&f| updates.contains_key(&f.url))
			.cloned()
			.collect();

		let repeek = self.hovered().is_some_and(|f| updates.contains_key(&f.url));
		self.mimetype.extend(updates);

		if repeek {
			self.peek(false);
		}
		tasks.fetch_paged(&affected, &self.mimetype);
		tasks.preload_paged(&affected, &self.mimetype);


Review comment (suggestion):
[nitpick] Inserting a `String` into a `HashMap<Cow<'static, str>, Cow<'static, str>>` relies on implicit coercion. Consider calling `.into()` explicitly for clarity: `map.insert(u, m.into());`.
```suggestion
				map.insert(u, m.into());
```

Code after:

impl TryFrom<CmdCow> for Opt {
	type Error = ();

	fn try_from(mut c: CmdCow) -> Result<Self, Self::Error> {
		Ok(Self { updates: c.try_take("updates").ok_or(())?.into_dict_string() })
	}
}

impl Mgr {
	pub fn update_mimes(&mut self, opt: impl TryInto<Opt>, tasks: &Tasks) {
		let Ok(opt): Result<Opt, _> = opt.try_into() else {
			return error!("invalid arguments for update_mimes");
		};

		let linked = LINKED.read();
		let updates = opt
			.updates
			.into_iter()
			.map(|(url, mime)| (Url::from(url.as_ref()), mime))
			.filter(|(url, mime)| self.mimetype.by_url(url) != Some(mime))
			.fold(HashMap::new(), |mut map, (u, m)| {
				for u in linked.from_file(&u) {
					map.insert(u, m.to_string());
				}
				map.insert(u, m.into_owned());
				map
			});

		drop(linked);
		if updates.is_empty() {
			return;
		}

		let affected: Vec<_> = self
			.current()
			.paginate(self.current().page)
			.iter()
			.filter(|&f| updates.contains_key(&f.url))
			.cloned()
			.collect();

		let repeek = self.hovered().is_some_and(|f| updates.contains_key(&f.url));
		self.mimetype.extend(updates);

		if repeek {
			self.peek(false);
		}
		tasks.fetch_paged(&affected, &self.mimetype);
		tasks.preload_paged(&affected, &self.mimetype);
Repository: sxyazi/yazi
File: yazi-plugin/src/composer.rs (Rust)

Code before:
use mlua::{IntoLua, Lua, MetaMethod, Table, Value};

pub struct Composer;

impl Composer {
	pub fn make<F>(lua: &Lua, cap: usize, f: F) -> mlua::Result<Value>
	where
		F: Fn(&Lua, &[u8]) -> mlua::Result<Value> + 'static,
	{
		let index = lua.create_function(move |lua, (ts, key): (Table, mlua::String)| {
			let v = f(lua, &key.as_bytes())?;
			ts.raw_set(key, v.clone())?;
			Ok(v)
		})?;

		let tbl = lua.create_table_with_capacity(0, cap)?;
		tbl.set_metatable(Some(lua.create_table_from([(MetaMethod::Index.name(), index)])?));
		tbl.into_lua(lua)
	}
}


Review comment (suggestion):
The public signature of `Composer::make` has changed; consider updating any documentation or comments to reflect the removed `cap` parameter and the switch to `create_table()`.
```suggestion
impl Composer {
	/// Creates a new Lua table with a metatable that uses the provided function `f` for indexing.
	/// 
	/// Note: The `cap` parameter has been removed from this function's signature. Instead, 
	/// `create_table()` is used to initialize the table without any capacity constraints.
```

Code after:
use mlua::{IntoLua, Lua, MetaMethod, Table, Value};

pub struct Composer;

impl Composer {
	pub fn make<F>(lua: &Lua, f: F) -> mlua::Result<Value>
	where
		F: Fn(&Lua, &[u8]) -> mlua::Result<Value> + 'static,
	{
		let index = lua.create_function(move |lua, (ts, key): (Table, mlua::String)| {
			let v = f(lua, &key.as_bytes())?;
			ts.raw_set(key, v.clone())?;
			Ok(v)
		})?;

		let tbl = lua.create_table()?;
		tbl.set_metatable(Some(lua.create_table_from([(MetaMethod::Index.name(), index)])?));
		tbl.into_lua(lua)
	}
}
Repository: sxyazi/yazi
File: yazi-plugin/src/pubsub/pubsub.rs (Rust)

Code before:
use mlua::{ExternalResult, Function, Lua, Value};
use yazi_binding::Id;
use yazi_dds::body::Body;

use crate::runtime::RtRef;

pub struct Pubsub;

impl Pubsub {
	pub(super) fn r#pub(lua: &Lua) -> mlua::Result<Function> {
		lua.create_function(|_, (kind, value): (mlua::String, Value)| {
			yazi_dds::Pubsub::r#pub(Body::from_lua(&kind.to_str()?, value)?);
			Ok(())
		})
	}

	pub(super) fn pub_to(lua: &Lua) -> mlua::Result<Function> {
		lua.create_function(|_, (receiver, kind, value): (Id, mlua::String, Value)| {
			yazi_dds::Pubsub::pub_to(*receiver, Body::from_lua(&kind.to_str()?, value)?);
			Ok(())
		})
	}

	pub(super) fn sub(lua: &Lua) -> mlua::Result<Function> {
		lua.create_function(|lua, (kind, f): (mlua::String, Function)| {
			let rt = lua.named_registry_value::<RtRef>("ir")?;
			let Some(cur) = rt.current() else {
				return Err("`sub()` must be called in a sync plugin").into_lua_err();
			};
			if !yazi_dds::Pubsub::sub(cur, &kind.to_str()?, f) {
				return Err("`sub()` called twice").into_lua_err();

Review comment (refactor):
`use crate::runtime` is unused now that all lookups use `runtime!` macro. Remove this import to avoid a warning.
```suggestion

```

Code after:
use mlua::{ExternalResult, Function, Lua, Value};
use yazi_binding::Id;
use yazi_dds::body::Body;

use crate::runtime;

pub struct Pubsub;

impl Pubsub {
	pub(super) fn r#pub(lua: &Lua) -> mlua::Result<Function> {
		lua.create_function(|_, (kind, value): (mlua::String, Value)| {
			yazi_dds::Pubsub::r#pub(Body::from_lua(&kind.to_str()?, value)?);
			Ok(())
		})
	}

	pub(super) fn pub_to(lua: &Lua) -> mlua::Result<Function> {
		lua.create_function(|_, (receiver, kind, value): (Id, mlua::String, Value)| {
			yazi_dds::Pubsub::pub_to(*receiver, Body::from_lua(&kind.to_str()?, value)?);
			Ok(())
		})
	}

	pub(super) fn sub(lua: &Lua) -> mlua::Result<Function> {
		lua.create_function(|lua, (kind, f): (mlua::String, Function)| {
			let rt = runtime!(lua)?;
			let Some(cur) = rt.current() else {
				return Err("`sub()` must be called in a sync plugin").into_lua_err();
			};
			if !yazi_dds::Pubsub::sub(cur, &kind.to_str()?, f) {
				return Err("`sub()` called twice").into_lua_err();
Repository: sxyazi/yazi
File: yazi-shared/src/url/url.rs (Rust)

Code before:

	fn try_from(value: String) -> Result<Self, Self::Error> { value.as_bytes().try_into() }
}

// impl From<&String> for Url {
// 	fn from(path: &String) -> Self { path.as_str().into() }
// }

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

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

impl AsRef<OsStr> for Url {
	fn as_ref(&self) -> &OsStr { self.loc.as_os_str() }
}

impl Display for Url {
	fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
		if matches!(self.scheme, Scheme::Regular | Scheme::SearchItem) {
			return write!(f, "{}", self.loc.display());
		}

		let scheme = match self.scheme {
			Scheme::Regular | Scheme::SearchItem => unreachable!(),
			Scheme::Search => "search://",
			Scheme::Archive => "archive://",
		};
		let path = percent_encode(self.loc.as_os_str().as_encoded_bytes(), ENCODE_SET);

		write!(f, "{scheme}{path}")?;
		if !self.frag.is_empty() {
			write!(f, "#{}", percent_encode(self.frag.as_encoded_bytes(), ENCODE_SET))?;
		}

		Ok(())
	}
}

impl From<&Url> for String {
	fn from(url: &Url) -> Self { url.to_string() }
}

impl Url {
	#[inline]
	pub fn join(&self, path: impl AsRef<Path>) -> Self {
		match self.scheme {
			Scheme::Regular => Self::from(self.loc.join(path)),

Review comment (suggestion):
Ensure that the fragment is consistently percent-encoded so that it can be correctly reversed by the corresponding decoding logic. Adding an inline comment explaining this design decision could help future maintainers.
```suggestion
		if !self.frag.is_empty() {
			// Percent-encode the fragment to ensure it can be correctly reversed by decoding logic.
			// This consistent encoding prevents issues with URL parsing and maintains data integrity.
```

Code after:

	fn try_from(value: String) -> Result<Self, Self::Error> { value.as_bytes().try_into() }
}

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

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

impl AsRef<OsStr> for Url {
	fn as_ref(&self) -> &OsStr { self.loc.as_os_str() }
}

impl Display for Url {
	fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
		if matches!(self.scheme, Scheme::Regular | Scheme::SearchItem) {
			return write!(f, "{}", self.loc.display());
		}

		let loc = percent_encode(self.loc.as_os_str().as_encoded_bytes(), ENCODE_SET);
		write!(f, "{}://{loc}", self.scheme)?;

		if !self.frag.is_empty() {
			write!(f, "#{}", percent_encode(self.frag.as_encoded_bytes(), ENCODE_SET))?;
		}

		Ok(())
	}
}

impl From<&Url> for String {
	fn from(url: &Url) -> Self { url.to_string() }
}

impl Url {
	#[inline]
	pub fn join(&self, path: impl AsRef<Path>) -> Self {
		match self.scheme {
			Scheme::Regular => Self::from(self.loc.join(path)),
			Scheme::Search => {
				let loc = Loc::from(&self.loc, self.loc.join(path));
				Self::from(loc).into_search_item()
			}
			Scheme::SearchItem => {
				let loc = Loc::from(self.loc.base(), self.loc.join(path));
				Self::from(loc).into_search_item()
			}
			Scheme::Archive => Self::from(self.loc.join(path)).into_archive(),
Repository: sxyazi/yazi
File: yazi-macro/src/fmt.rs (Rust)

Code before:
#[macro_export]
macro_rules! try_format {
	($($arg:tt)*) => {{
		use std::fmt::Write;

		fn inner(args: std::fmt::Arguments<'_>) -> Result<String, std::fmt::Error> {
			if let Some(s) = args.as_str() {
				Ok(s.to_owned())
			} else {
				let mut output = String::new();
				output.write_fmt(args).map(|_| output)
			}
		}

		inner(format_args!($($arg)*))
	}}
}


Review comment (suggestion):
The `as_str()` method on `std::fmt::Arguments` is an unstable API and not available on stable Rust; this may cause a compilation error. Consider using only stable formatting APIs or feature-gating this branch.
```suggestion
			let mut output = String::new();
			output.write_fmt(args).map(|_| output)
```

Code after:
#[macro_export]
macro_rules! try_format {
	($($arg:tt)*) => {{
		use std::fmt::Write;

		let mut output = String::new();
		output.write_fmt(format_args!($($arg)*)).map(|_| output)
	}}
}
Repository: sxyazi/yazi
File: yazi-plugin/src/utils/cache.rs (Rust)

Code before:
use mlua::{Function, Lua, Table};
use twox_hash::XxHash3_128;
use yazi_binding::Url;
use yazi_config::YAZI;

use super::Utils;
use crate::file::FileRef;

impl Utils {
	pub(super) fn file_cache(lua: &Lua) -> mlua::Result<Function> {
		lua.create_function(|_, t: Table| {
			let file: FileRef = t.raw_get("file")?;
			if file.url.parent() == Some(&YAZI.preview.cache_dir) {
				return Ok(None);
			}

			let hex = {
				let mut h = XxHash3_128::new();
				h.write(file.url.as_os_str().as_encoded_bytes());
				h.write(format!("//{:?}//{}", file.cha.mtime, t.raw_get("skip").unwrap_or(0)).as_bytes());
				format!("{:x}", h.finish_128())
			};

			Ok(Some(Url::new(YAZI.preview.cache_dir.join(hex))))
		})
	}
}


Review comment (bug):
[nitpick] Using `unwrap_or` on `raw_get` will silence any Lua errors—consider using `t.get` with a default or explicitly handling the error so that genuine lookup failures aren't masked.
```suggestion
				t.get("skip").unwrap_or(Ok(0usize))?.hash(&mut h);
```

Code after:
use std::hash::Hash;

use mlua::{Function, Lua, Table};
use yazi_binding::Url;
use yazi_config::YAZI;

use super::Utils;
use crate::{Twox128, file::FileRef};

impl Utils {
	pub(super) fn file_cache(lua: &Lua) -> mlua::Result<Function> {
		lua.create_function(|_, t: Table| {
			let file: FileRef = t.raw_get("file")?;
			if file.url.parent() == Some(&YAZI.preview.cache_dir) {
				return Ok(None);
			}

			let hex = {
				let mut h = Twox128::default();
				file.hash(&mut h);
				t.raw_get("skip").unwrap_or(0usize).hash(&mut h);
				format!("{:x}", h.finish_128())
			};

			Ok(Some(Url::new(YAZI.preview.cache_dir.join(hex))))
		})
	}
}
Repository: sxyazi/yazi
File: yazi-plugin/preset/components/preview.lua (Lua)

Code before:
Preview = {
	_id = "preview",
}

function Preview:new(area, tab)
	return setmetatable({
		_area = area,
		_tab = tab,
		_folder = tab.preview.folder,
	}, { __index = self })
end

function Preview:reflow() return { self } end

function Preview:redraw() return {} end

-- Mouse events
function Preview:click(event, up)
	if up or not event.is_left then
		return
	end

	local y = event.y - self._area.y + 1
	local window = self._folder and self._folder.window or {}
	if window[y] then
		ya.emit("reveal", { window[y].url })
	else
		ya.emit("enter", {})
	end
end

function Preview:scroll(event, step) ya.emit("seek", { step }) end

function Preview:touch(event, step) end


Review comment (refactor):
[nitpick] The same click-delegation logic appears in both `preview.lua` and `parent.lua`. Consider extracting a shared helper or mixin to reduce duplication.

Code after:
Preview = {
	_id = "preview",
}

function Preview:new(area, tab)
	return setmetatable({
		_area = area,
		_tab = tab,
		_folder = tab.preview.folder,
	}, { __index = self })
end

function Preview:reflow() return { self } end

function Preview:redraw() return {} end

-- Mouse events
function Preview:click(event, up)
	local y = event.y - self._area.y + 1
	local window = self._folder and self._folder.window or {}
	if window[y] then
		Entity:new(window[y]):click(event, up)
	elseif not up and event.is_left then
		ya.emit("enter", {})
	end
end

function Preview:scroll(event, step) ya.emit("seek", { step }) end

function Preview:touch(event, step) end
Repository: sxyazi/yazi
File: yazi-core/src/mgr/commands/open.rs (Rust)

Code before:
		}
		let Some(hovered) = self.hovered().map(|h| h.url_owned()) else {
			return;
		};

		let selected = if opt.hovered { vec![&hovered] } else { self.selected_or_hovered().collect() };
		if Self::quit_with_selected(opt, &selected) {
			return;
		}

		let cwd = self.cwd().clone();
		let (mut done, mut todo) = (Vec::with_capacity(selected.len()), vec![]);
		for u in selected {
			if self.mimetype.contains(u) {
				done.push((u.clone(), ""));
			} else if self.guess_folder(u) {
				done.push((u.clone(), MIME_DIR));
			} else {
				todo.push(u.clone());
			}
		}

		if todo.is_empty() {
			return self
				.open_do(OpenDoOpt { cwd, hovered, targets: done, interactive: opt.interactive }, tasks);
		}

		tokio::spawn(async move {
			let mut files = Vec::with_capacity(todo.len());
			for u in todo {
				if let Ok(f) = File::new(u).await {
					files.push(f);
				}
			}

			done.extend(files.iter().map(|f| (f.url_owned(), "")));
			for (fetcher, files) in YAZI.plugin.mime_fetchers(files) {
				if let Err(e) = isolate::fetch(CmdCow::from(&fetcher.run), files).await {
					error!("Fetch mime failed on opening: {e}");
				}
			}

			MgrProxy::open_do(OpenDoOpt { cwd, hovered, targets: done, interactive: opt.interactive });
		});
	}

	#[yazi_codegen::command]
	pub fn open_do(&mut self, opt: OpenDoOpt, tasks: &Tasks) {
		let targets: Vec<_> = opt
			.targets
			.into_iter()

Review comment (refactor):
This `todo.push(i)` inside the `map` closure is a side effect; consider refactoring to use a single `fold` or a two-pass approach to avoid external mutation.

Code after:
		}
		let Some(hovered) = self.hovered().map(|h| h.url_owned()) else {
			return;
		};

		let mut selected =
			if opt.hovered { Box::new(iter::once(&hovered)) } else { self.selected_or_hovered() };
		if Self::quit_with_selected(opt, &mut selected) {
			return;
		}

		let mut todo = vec![];
		let targets: Vec<_> = selected
			.cloned()
			.enumerate()
			.map(|(i, u)| {
				if self.mimetype.contains(&u) {
					(u, "")
				} else if self.guess_folder(&u) {
					(u, MIME_DIR)
				} else {
					todo.push(i);
					(u, "")
				}
			})
			.collect();

		let cwd = self.cwd().clone();
		if todo.is_empty() {
			return self
				.open_do(OpenDoOpt { cwd, hovered, targets, interactive: opt.interactive }, tasks);
		}

		tokio::spawn(async move {
			let mut files = Vec::with_capacity(todo.len());
			for i in todo {
				if let Ok(f) = File::new(targets[i].0.clone()).await {
					files.push(f);
				}
			}

			for (fetcher, files) in YAZI.plugin.mime_fetchers(files) {
				if let Err(e) = isolate::fetch(CmdCow::from(&fetcher.run), files).await {
					error!("Fetch mime failed on opening: {e}");
				}
			}

			MgrProxy::open_do(OpenDoOpt { cwd, hovered, targets, interactive: opt.interactive });
		});
	}
Repository: sxyazi/yazi
File: yazi-core/src/mgr/commands/open.rs (Rust)

Code before:
		}
		let Some(hovered) = self.hovered().map(|h| h.url_owned()) else {
			return;
		};

		let selected = if opt.hovered { vec![&hovered] } else { self.selected_or_hovered().collect() };
		if Self::quit_with_selected(opt, &selected) {
			return;
		}

		let cwd = self.cwd().clone();
		let (mut done, mut todo) = (Vec::with_capacity(selected.len()), vec![]);
		for u in selected {
			if self.mimetype.contains(u) {
				done.push((u.clone(), ""));
			} else if self.guess_folder(u) {
				done.push((u.clone(), MIME_DIR));
			} else {
				todo.push(u.clone());
			}
		}

		if todo.is_empty() {
			return self
				.open_do(OpenDoOpt { cwd, hovered, targets: done, interactive: opt.interactive }, tasks);
		}

		tokio::spawn(async move {
			let mut files = Vec::with_capacity(todo.len());
			for u in todo {
				if let Ok(f) = File::new(u).await {
					files.push(f);
				}
			}

			done.extend(files.iter().map(|f| (f.url_owned(), "")));
			for (fetcher, files) in YAZI.plugin.mime_fetchers(files) {
				if let Err(e) = isolate::fetch(CmdCow::from(&fetcher.run), files).await {
					error!("Fetch mime failed on opening: {e}");
				}
			}

			MgrProxy::open_do(OpenDoOpt { cwd, hovered, targets: done, interactive: opt.interactive });
		});
	}

	#[yazi_codegen::command]
	pub fn open_do(&mut self, opt: OpenDoOpt, tasks: &Tasks) {
		let targets: Vec<_> = opt
			.targets
			.into_iter()

Review comment (performance):
[nitpick] Collecting all targets eagerly into a `Vec` could be costly for very large selections; consider streaming or batching to reduce peak memory usage.

Code after:
		}
		let Some(hovered) = self.hovered().map(|h| h.url_owned()) else {
			return;
		};

		let mut selected =
			if opt.hovered { Box::new(iter::once(&hovered)) } else { self.selected_or_hovered() };
		if Self::quit_with_selected(opt, &mut selected) {
			return;
		}

		let mut todo = vec![];
		let targets: Vec<_> = selected
			.cloned()
			.enumerate()
			.map(|(i, u)| {
				if self.mimetype.contains(&u) {
					(u, "")
				} else if self.guess_folder(&u) {
					(u, MIME_DIR)
				} else {
					todo.push(i);
					(u, "")
				}
			})
			.collect();

		let cwd = self.cwd().clone();
		if todo.is_empty() {
			return self
				.open_do(OpenDoOpt { cwd, hovered, targets, interactive: opt.interactive }, tasks);
		}

		tokio::spawn(async move {
			let mut files = Vec::with_capacity(todo.len());
			for i in todo {
				if let Ok(f) = File::new(targets[i].0.clone()).await {
					files.push(f);
				}
			}

			for (fetcher, files) in YAZI.plugin.mime_fetchers(files) {
				if let Err(e) = isolate::fetch(CmdCow::from(&fetcher.run), files).await {
					error!("Fetch mime failed on opening: {e}");
				}
			}

			MgrProxy::open_do(OpenDoOpt { cwd, hovered, targets, interactive: opt.interactive });
		});
	}
Repository: sxyazi/yazi
File: yazi-fs/src/mounts/linux.rs (Rust)

Code before:
			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 = match replace_cow(&s, a, b) {
				Cow::Borrowed(_) => s,
				Cow::Owned(new) => Cow::Owned(new),
			};
		}
		s
	}
}


Review comment (suggestion):
Variable `s` is originally a `String`, but `replace_cow(s, a, b)` returns a `Cow<str>`. Assigning a `Cow<str>` back to `String` will not compile. Consider calling `replace_cow(&s, a, b)` or changing `s`’s type to `Cow<str>` and converting back to `String` at the end.
```suggestion
			s = replace_cow(&s, a, b);
```

Code after:
			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
	}
}
Repository: sxyazi/yazi
File: yazi-widgets/src/input/commands/replace.rs (Rust)

Code before:

use crate::input::{Input, InputMode, op::InputOp};

impl Input {
	#[yazi_codegen::command]
	pub fn replace(&mut self, _: CmdCow) {
		let snap = self.snap_mut();
		if snap.mode == InputMode::Normal {
			snap.op = InputOp::None;
			snap.mode = InputMode::Replace;
			render!();
		}
	}

	pub fn replace_str(&mut self, s: &str) {
		let snap = self.snap_mut();
		snap.mode = InputMode::Normal;

		let start = snap.idx(snap.cursor).unwrap();
		let mut it = snap.value[start..].char_indices();
		match (it.next(), it.next()) {
			(None, _) => {}
			(Some(_), None) => snap.value.replace_range(start..snap.len(), s),
			(Some(_), Some((len, _))) => snap.value.replace_range(start..start + len, s),
		}

		render!();
		self.snaps.tag(self.limit).then(|| self.flush_value());
	}
}


Review comment (suggestion):
[nitpick] Similar to the `type_str` change, using `s.as_ref()` instead of `&s` would make it clear you’re converting the `Cow<str>` into a `&str` for the `replace_range` call.
```suggestion
			(Some(_), None) => snap.value.replace_range(start..snap.len(), s.as_ref()),
			(Some(_), Some((len, _))) => snap.value.replace_range(start..start + len, s.as_ref()),
```

Code after:

use crate::input::{Input, InputMode, op::InputOp};

impl Input {
	#[yazi_codegen::command]
	pub fn replace(&mut self, _: CmdCow) {
		let snap = self.snap_mut();
		if snap.mode == InputMode::Normal {
			snap.op = InputOp::None;
			snap.mode = InputMode::Replace;
			render!();
		}
	}

	pub fn replace_str(&mut self, s: &str) {
		let s = replace_cow(replace_cow(s, "\r", " "), "\n", " ");

		let snap = self.snap_mut();
		snap.mode = InputMode::Normal;

		let start = snap.idx(snap.cursor).unwrap();
		let mut it = snap.value[start..].char_indices();
		match (it.next(), it.next()) {
			(None, _) => {}
			(Some(_), None) => snap.value.replace_range(start..snap.len(), &s),
			(Some(_), Some((len, _))) => snap.value.replace_range(start..start + len, &s),
		}

		render!();
		self.snaps.tag(self.limit).then(|| self.flush_value());
	}
}