From a4711af952ad6c2d1a484f5a780561d82ecd76a5 Mon Sep 17 00:00:00 2001 From: Bahex <17417311+Bahex@users.noreply.github.com> Date: Mon, 11 Aug 2025 20:47:50 +0300 Subject: [PATCH] feat: impl for (From/Into)Value for Cow<'_, B> where B::Owned: (From/Into)Value (#16380) # Description Implements `FromValue` and `IntoValue` for `Cow`, which makes it easy to use it in types that need to implement these traits. I don't think it will have a significant impact, but it can let us avoid allocations where we can use static values. # Tests + Formatting No need, the implementations are delegated to `B::Owned`. Co-authored-by: Bahex --- crates/nu-protocol/src/value/from_value.rs | 20 ++++++++++++++++++++ crates/nu-protocol/src/value/into_value.rs | 20 +++++++++++++++++++- 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/crates/nu-protocol/src/value/from_value.rs b/crates/nu-protocol/src/value/from_value.rs index 5fdcb9faf00..708f1f69c5b 100644 --- a/crates/nu-protocol/src/value/from_value.rs +++ b/crates/nu-protocol/src/value/from_value.rs @@ -7,6 +7,7 @@ use crate::{ use chrono::{DateTime, FixedOffset}; use std::{ any, + borrow::Cow, cmp::Ordering, collections::{HashMap, VecDeque}, fmt, @@ -564,6 +565,25 @@ where } } +/// This blanket implementation permits the use of [`Cow<'_, B>`] ([`Cow<'_, str>`] etc) based on +/// the [FromValue] implementation of `B`'s owned form ([str] => [String]). +/// +/// It's meant to make using the [FromValue] derive macro on types that contain [Cow] fields +/// possible. +impl FromValue for Cow<'_, B> +where + B: ?Sized + ToOwned, + B::Owned: FromValue, +{ + fn from_value(v: Value) -> Result { + ::from_value(v).map(Cow::Owned) + } + + fn expected_type() -> Type { + ::expected_type() + } +} + impl FromValue for HashMap where V: FromValue, diff --git a/crates/nu-protocol/src/value/into_value.rs b/crates/nu-protocol/src/value/into_value.rs index eec66ca86d9..218047e69d7 100644 --- a/crates/nu-protocol/src/value/into_value.rs +++ b/crates/nu-protocol/src/value/into_value.rs @@ -1,6 +1,9 @@ use crate::{Range, Record, ShellError, Span, Value, ast::CellPath, engine::Closure}; use chrono::{DateTime, FixedOffset}; -use std::{borrow::Borrow, collections::HashMap}; +use std::{ + borrow::{Borrow, Cow}, + collections::HashMap, +}; /// A trait for converting a value into a [`Value`]. /// @@ -202,6 +205,21 @@ where } } +/// This blanket implementation permits the use of [`Cow<'_, B>`] ([`Cow<'_, str>`] etc) based on +/// the [IntoValue] implementation of `B`'s owned form ([str] => [String]). +/// +/// It's meant to make using the [IntoValue] derive macro on types that contain [Cow] fields +/// possible. +impl IntoValue for Cow<'_, B> +where + B: ?Sized + ToOwned, + B::Owned: IntoValue, +{ + fn into_value(self, span: Span) -> Value { + ::into_value(self.into_owned(), span) + } +} + impl IntoValue for HashMap where K: Borrow + Into,