Add Value::coerce_str (#11885)

# Description
Following #11851, this PR adds one final conversion function for
`Value`. `Value::coerce_str` takes a `&Value` and converts it to a
`Cow<str>`, creating an owned `String` for types that needed converting.
Otherwise, it returns a borrowed `str` for `String` and `Binary`
`Value`s which avoids a clone/allocation. Where possible, `coerce_str`
and `coerce_into_string` should be used instead of `coerce_string`,
since `coerce_string` always allocates a new `String`.
This commit is contained in:
Ian Manske
2024-02-18 16:47:10 +00:00
committed by GitHub
parent fb4251aba7
commit 68fcd71898
34 changed files with 115 additions and 83 deletions

View File

@ -1008,7 +1008,7 @@ fn cmd_input_key_event(buf: &mut CommandBuf, key: &KeyEvent) -> bool {
}
fn value_as_style(style: &mut nu_ansi_term::Style, value: &Value) -> bool {
match value.coerce_string() {
match value.coerce_str() {
Ok(s) => {
*style = lookup_ansi_color_style(&s);
true

View File

@ -331,8 +331,8 @@ impl View for RecordView<'_> {
if let Some(hm) = cfg.config.get("table").and_then(create_map) {
self.theme = theme_from_config(&hm);
if let Some(orientation) = hm.get("orientation").and_then(|v| v.coerce_string().ok()) {
let orientation = match orientation.as_str() {
if let Some(orientation) = hm.get("orientation").and_then(|v| v.coerce_str().ok()) {
let orientation = match orientation.as_ref() {
"left" => Some(Orientation::Left),
"top" => Some(Orientation::Top),
_ => None,
@ -859,7 +859,7 @@ fn config_get_bool(config: &ConfigMap, key: &str, default: bool) -> bool {
fn config_get_usize(config: &ConfigMap, key: &str, default: usize) -> usize {
config
.get(key)
.and_then(|v| v.coerce_string().ok())
.and_then(|v| v.coerce_str().ok())
.and_then(|s| s.parse::<usize>().ok())
.unwrap_or(default)
}