Struct nu_protocol::record::Record

source ·
pub struct Record { /* private fields */ }

Implementations§

source§

impl Record

source

pub fn new() -> Self

source

pub fn with_capacity(capacity: usize) -> Self

source

pub fn from_raw_cols_vals( cols: Vec<String>, vals: Vec<Value>, input_span: Span, creation_site_span: Span ) -> Result<Self, ShellError>

Create a Record from a Vec of columns and a Vec of Values

Returns an error if cols and vals have different lengths.

For perf reasons, this will not validate the rest of the record assumptions:

  • unique keys
source

pub fn iter(&self) -> Iter<'_>

source

pub fn iter_mut(&mut self) -> IterMut<'_>

source

pub fn is_empty(&self) -> bool

source

pub fn len(&self) -> usize

source

pub fn push(&mut self, col: impl Into<String>, val: Value)

Naive push to the end of the datastructure.

May duplicate data!

Consider to use Record::insert instead

source

pub fn insert<K>(&mut self, col: K, val: Value) -> Option<Value>
where K: AsRef<str> + Into<String>,

Insert into the record, replacing preexisting value if found.

Returns Some(previous_value) if found. Else None

source

pub fn contains(&self, col: impl AsRef<str>) -> bool

source

pub fn index_of(&self, col: impl AsRef<str>) -> Option<usize>

source

pub fn get(&self, col: impl AsRef<str>) -> Option<&Value>

source

pub fn get_mut(&mut self, col: impl AsRef<str>) -> Option<&mut Value>

source

pub fn get_index(&self, idx: usize) -> Option<(&String, &Value)>

source

pub fn remove(&mut self, col: impl AsRef<str>) -> Option<Value>

Remove single value by key

Returns None if key not found

Note: makes strong assumption that keys are unique

source

pub fn retain<F>(&mut self, keep: F)
where F: FnMut(&str, &Value) -> bool,

Remove elements in-place that do not satisfy keep

use nu_protocol::{record, Value};

let mut rec = record!(
    "a" => Value::test_nothing(),
    "b" => Value::test_int(42),
    "c" => Value::test_nothing(),
    "d" => Value::test_int(42),
);
rec.retain(|_k, val| !val.is_nothing());
let mut iter_rec = rec.columns();
assert_eq!(iter_rec.next().map(String::as_str), Some("b"));
assert_eq!(iter_rec.next().map(String::as_str), Some("d"));
assert_eq!(iter_rec.next(), None);
source

pub fn retain_mut<F>(&mut self, keep: F)
where F: FnMut(&str, &mut Value) -> bool,

Remove elements in-place that do not satisfy keep while allowing mutation of the value.

This can for example be used to recursively prune nested records.

use nu_protocol::{record, Record, Value};

fn remove_foo_recursively(val: &mut Value) {
    if let Value::Record {val, ..} = val {
        val.to_mut().retain_mut(keep_non_foo);
    }
}

fn keep_non_foo(k: &str, v: &mut Value) -> bool {
    if k == "foo" {
        return false;
    }
    remove_foo_recursively(v);
    true
}

let mut test = Value::test_record(record!(
    "foo" => Value::test_nothing(),
    "bar" => Value::test_record(record!(
        "foo" => Value::test_nothing(),
        "baz" => Value::test_nothing(),
        ))
    ));

remove_foo_recursively(&mut test);
let expected = Value::test_record(record!(
    "bar" => Value::test_record(record!(
        "baz" => Value::test_nothing(),
        ))
    ));
assert_eq!(test, expected);
source

pub fn truncate(&mut self, len: usize)

Truncate record to the first len elements.

len > self.len() will be ignored

use nu_protocol::{record, Value};

let mut rec = record!(
    "a" => Value::test_nothing(),
    "b" => Value::test_int(42),
    "c" => Value::test_nothing(),
    "d" => Value::test_int(42),
);
rec.truncate(42); // this is fine
assert_eq!(rec.columns().map(String::as_str).collect::<String>(), "abcd");
rec.truncate(2); // truncate
assert_eq!(rec.columns().map(String::as_str).collect::<String>(), "ab");
rec.truncate(0); // clear the record
assert_eq!(rec.len(), 0);
source

pub fn columns(&self) -> Columns<'_>

source

pub fn into_columns(self) -> IntoColumns

source

pub fn values(&self) -> Values<'_>

source

pub fn into_values(self) -> IntoValues

source

pub fn drain<R>(&mut self, range: R) -> Drain<'_>
where R: RangeBounds<usize> + Clone,

Obtain an iterator to remove elements in range

Elements not consumed from the iterator will be dropped

use nu_protocol::{record, Value};

let mut rec = record!(
    "a" => Value::test_nothing(),
    "b" => Value::test_int(42),
    "c" => Value::test_string("foo"),
);
{
    let mut drainer = rec.drain(1..);
    assert_eq!(drainer.next(), Some(("b".into(), Value::test_int(42))));
    // Dropping the `Drain`
}
let mut rec_iter = rec.into_iter();
assert_eq!(rec_iter.next(), Some(("a".into(), Value::test_nothing())));
assert_eq!(rec_iter.next(), None);
source

pub fn sort_cols(&mut self)

Sort the record by its columns.

use nu_protocol::{record, Value};

let mut rec = record!(
    "c" => Value::test_string("foo"),
    "b" => Value::test_int(42),
    "a" => Value::test_nothing(),
);

rec.sort_cols();

assert_eq!(
    Value::test_record(rec),
    Value::test_record(record!(
        "a" => Value::test_nothing(),
        "b" => Value::test_int(42),
        "c" => Value::test_string("foo"),
    ))
);

Trait Implementations§

source§

impl Clone for Record

source§

fn clone(&self) -> Record

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for Record

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Default for Record

source§

fn default() -> Record

Returns the “default value” for a type. Read more
source§

impl<'de> Deserialize<'de> for Record

source§

fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>,

Special deserialization implementation that turns a map-pattern into a Record

Denies duplicate keys

use serde_json::{from_str, Result};
use nu_protocol::{Record, Value, record};

// A `Record` in json is a Record with a packed `Value`
// The `Value` record has a single key indicating its type and the inner record describing
// its representation of value and the associated `Span`
let ok = r#"{"a": {"Int": {"val": 42, "span": {"start": 0, "end": 0}}},
             "b": {"Int": {"val": 37, "span": {"start": 0, "end": 0}}}}"#;
let ok_rec: Record = from_str(ok).unwrap();
assert_eq!(Value::test_record(ok_rec),
           Value::test_record(record!{"a" => Value::test_int(42),
                                      "b" => Value::test_int(37)}));
// A repeated key will lead to a deserialization error
let bad = r#"{"a": {"Int": {"val": 42, "span": {"start": 0, "end": 0}}},
              "a": {"Int": {"val": 37, "span": {"start": 0, "end": 0}}}}"#;
let bad_rec: Result<Record> = from_str(bad);
assert!(bad_rec.is_err());
source§

impl Extend<(String, Value)> for Record

source§

fn extend<T: IntoIterator<Item = (String, Value)>>(&mut self, iter: T)

Extends a collection with the contents of an iterator. Read more
source§

fn extend_one(&mut self, item: A)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
source§

impl FromIterator<(String, Value)> for Record

source§

fn from_iter<T: IntoIterator<Item = (String, Value)>>(iter: T) -> Self

Creates a value from an iterator. Read more
source§

impl FromValue for Record

source§

impl<'a> IntoIterator for &'a Record

§

type Item = (&'a String, &'a Value)

The type of the elements being iterated over.
§

type IntoIter = Iter<'a>

Which kind of iterator are we turning this into?
source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
source§

impl<'a> IntoIterator for &'a mut Record

§

type Item = (&'a String, &'a mut Value)

The type of the elements being iterated over.
§

type IntoIter = IterMut<'a>

Which kind of iterator are we turning this into?
source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
source§

impl IntoIterator for Record

§

type Item = (String, Value)

The type of the elements being iterated over.
§

type IntoIter = IntoIter

Which kind of iterator are we turning this into?
source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
source§

impl Serialize for Record

source§

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

§

impl Freeze for Record

§

impl !RefUnwindSafe for Record

§

impl Send for Record

§

impl Sync for Record

§

impl Unpin for Record

§

impl !UnwindSafe for Record

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> IntoEither for T

source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
source§

impl<T> IntoSpanned for T

source§

fn into_spanned(self, span: Span) -> Spanned<T>

Wrap items together with a span into Spanned. Read more
source§

impl<D> OwoColorize for D

source§

fn fg<C>(&self) -> FgColorDisplay<'_, C, Self>
where C: Color,

Set the foreground color generically Read more
source§

fn bg<C>(&self) -> BgColorDisplay<'_, C, Self>
where C: Color,

Set the background color generically. Read more
source§

fn black(&self) -> FgColorDisplay<'_, Black, Self>

Change the foreground color to black
source§

fn on_black(&self) -> BgColorDisplay<'_, Black, Self>

Change the background color to black
source§

fn red(&self) -> FgColorDisplay<'_, Red, Self>

Change the foreground color to red
source§

fn on_red(&self) -> BgColorDisplay<'_, Red, Self>

Change the background color to red
source§

fn green(&self) -> FgColorDisplay<'_, Green, Self>

Change the foreground color to green
source§

fn on_green(&self) -> BgColorDisplay<'_, Green, Self>

Change the background color to green
source§

fn yellow(&self) -> FgColorDisplay<'_, Yellow, Self>

Change the foreground color to yellow
source§

fn on_yellow(&self) -> BgColorDisplay<'_, Yellow, Self>

Change the background color to yellow
source§

fn blue(&self) -> FgColorDisplay<'_, Blue, Self>

Change the foreground color to blue
source§

fn on_blue(&self) -> BgColorDisplay<'_, Blue, Self>

Change the background color to blue
source§

fn magenta(&self) -> FgColorDisplay<'_, Magenta, Self>

Change the foreground color to magenta
source§

fn on_magenta(&self) -> BgColorDisplay<'_, Magenta, Self>

Change the background color to magenta
source§

fn purple(&self) -> FgColorDisplay<'_, Magenta, Self>

Change the foreground color to purple
source§

fn on_purple(&self) -> BgColorDisplay<'_, Magenta, Self>

Change the background color to purple
source§

fn cyan(&self) -> FgColorDisplay<'_, Cyan, Self>

Change the foreground color to cyan
source§

fn on_cyan(&self) -> BgColorDisplay<'_, Cyan, Self>

Change the background color to cyan
source§

fn white(&self) -> FgColorDisplay<'_, White, Self>

Change the foreground color to white
source§

fn on_white(&self) -> BgColorDisplay<'_, White, Self>

Change the background color to white
source§

fn default_color(&self) -> FgColorDisplay<'_, Default, Self>

Change the foreground color to the terminal default
source§

fn on_default_color(&self) -> BgColorDisplay<'_, Default, Self>

Change the background color to the terminal default
source§

fn bright_black(&self) -> FgColorDisplay<'_, BrightBlack, Self>

Change the foreground color to bright black
source§

fn on_bright_black(&self) -> BgColorDisplay<'_, BrightBlack, Self>

Change the background color to bright black
source§

fn bright_red(&self) -> FgColorDisplay<'_, BrightRed, Self>

Change the foreground color to bright red
source§

fn on_bright_red(&self) -> BgColorDisplay<'_, BrightRed, Self>

Change the background color to bright red
source§

fn bright_green(&self) -> FgColorDisplay<'_, BrightGreen, Self>

Change the foreground color to bright green
source§

fn on_bright_green(&self) -> BgColorDisplay<'_, BrightGreen, Self>

Change the background color to bright green
source§

fn bright_yellow(&self) -> FgColorDisplay<'_, BrightYellow, Self>

Change the foreground color to bright yellow
source§

fn on_bright_yellow(&self) -> BgColorDisplay<'_, BrightYellow, Self>

Change the background color to bright yellow
source§

fn bright_blue(&self) -> FgColorDisplay<'_, BrightBlue, Self>

Change the foreground color to bright blue
source§

fn on_bright_blue(&self) -> BgColorDisplay<'_, BrightBlue, Self>

Change the background color to bright blue
source§

fn bright_magenta(&self) -> FgColorDisplay<'_, BrightMagenta, Self>

Change the foreground color to bright magenta
source§

fn on_bright_magenta(&self) -> BgColorDisplay<'_, BrightMagenta, Self>

Change the background color to bright magenta
source§

fn bright_purple(&self) -> FgColorDisplay<'_, BrightMagenta, Self>

Change the foreground color to bright purple
source§

fn on_bright_purple(&self) -> BgColorDisplay<'_, BrightMagenta, Self>

Change the background color to bright purple
source§

fn bright_cyan(&self) -> FgColorDisplay<'_, BrightCyan, Self>

Change the foreground color to bright cyan
source§

fn on_bright_cyan(&self) -> BgColorDisplay<'_, BrightCyan, Self>

Change the background color to bright cyan
source§

fn bright_white(&self) -> FgColorDisplay<'_, BrightWhite, Self>

Change the foreground color to bright white
source§

fn on_bright_white(&self) -> BgColorDisplay<'_, BrightWhite, Self>

Change the background color to bright white
source§

fn bold(&self) -> BoldDisplay<'_, Self>

Make the text bold
source§

fn dimmed(&self) -> DimDisplay<'_, Self>

Make the text dim
source§

fn italic(&self) -> ItalicDisplay<'_, Self>

Make the text italicized
source§

fn underline(&self) -> UnderlineDisplay<'_, Self>

Make the text italicized
Make the text blink
Make the text blink (but fast!)
source§

fn reversed(&self) -> ReversedDisplay<'_, Self>

Swap the foreground and background colors
source§

fn hidden(&self) -> HiddenDisplay<'_, Self>

Hide the text
source§

fn strikethrough(&self) -> StrikeThroughDisplay<'_, Self>

Cross out the text
source§

fn color<Color>(&self, color: Color) -> FgDynColorDisplay<'_, Color, Self>
where Color: DynColor,

Set the foreground color at runtime. Only use if you do not know which color will be used at compile-time. If the color is constant, use either OwoColorize::fg or a color-specific method, such as OwoColorize::green, Read more
source§

fn on_color<Color>(&self, color: Color) -> BgDynColorDisplay<'_, Color, Self>
where Color: DynColor,

Set the background color at runtime. Only use if you do not know what color to use at compile-time. If the color is constant, use either OwoColorize::bg or a color-specific method, such as OwoColorize::on_yellow, Read more
source§

fn fg_rgb<const R: u8, const G: u8, const B: u8>( &self ) -> FgColorDisplay<'_, CustomColor<R, G, B>, Self>

Set the foreground color to a specific RGB value.
source§

fn bg_rgb<const R: u8, const G: u8, const B: u8>( &self ) -> BgColorDisplay<'_, CustomColor<R, G, B>, Self>

Set the background color to a specific RGB value.
source§

fn truecolor(&self, r: u8, g: u8, b: u8) -> FgDynColorDisplay<'_, Rgb, Self>

Sets the foreground color to an RGB value.
source§

fn on_truecolor(&self, r: u8, g: u8, b: u8) -> BgDynColorDisplay<'_, Rgb, Self>

Sets the background color to an RGB value.
source§

fn style(&self, style: Style) -> Styled<&Self>

Apply a runtime-determined style
source§

impl<T> Pointable for T

source§

const ALIGN: usize = _

The alignment of pointer.
§

type Init = T

The type for initializers.
source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
source§

impl<T> Serialize for T
where T: Serialize + ?Sized,

source§

fn erased_serialize(&self, serializer: &mut dyn Serializer) -> Result<(), Error>

source§

fn do_erased_serialize( &self, serializer: &mut dyn Serializer ) -> Result<(), ErrorImpl>

source§

impl<T> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,