Struct magnus::RArray

source ·
#[repr(transparent)]
pub struct RArray(_);
Expand description

A Value pointer to a RArray struct, Ruby’s internal representation of an Array.

All Value methods should be available on this type through Deref, but some may be missed by this documentation.

Implementations§

Return Some(RArray) if val is a RArray, None otherwise.

Examples
use magnus::{eval, RArray};

assert!(RArray::from_value(eval(r#"[true, 0, "example"]"#).unwrap()).is_some());
assert!(RArray::from_value(eval(r#"{"answer" => 42}"#).unwrap()).is_none());
assert!(RArray::from_value(eval(r"nil").unwrap()).is_none());

Create a new empty RArray.

Examples
use magnus::{eval, RArray};

let ary = RArray::new();
assert!(ary.is_empty());

Create a new empty RArray with capacity for n elements pre-allocated.

Examples
use magnus::{eval, RArray};

let ary = RArray::with_capacity(16);
assert!(ary.is_empty());

Create a new RArray that is a duplicate of self.

The new array is only a shallow clone.

Examples
use magnus::{eval, RArray};

let a = RArray::from_vec(vec![1, 2, 3]);
let b = a.dup();
let res: bool = eval!("a == b", a, b).unwrap();
assert!(res);
a.push(4);
b.push(5);
let res: bool = eval!("a == [1, 2, 3, 4]", a).unwrap();
assert!(res);
let res: bool = eval!("b == [1, 2, 3, 5]", b).unwrap();
assert!(res);

Return the number of entries in self as a Rust usize.

Examples
use magnus::{eval, RArray};

let ary = RArray::new();
assert_eq!(ary.len(), 0);

let ary = eval::<RArray>("[:a, :b, :c]").unwrap();
assert_eq!(ary.len(), 3)

Return whether self contains any entries or not.

Examples
use magnus::{eval, RArray};

let ary = RArray::new();
assert!(ary.is_empty());

Returns true if val is in self, false otherwise.

Examples
use magnus::{eval, RArray, Symbol, QNIL};

let ary = eval::<RArray>(r#"[:foo, "bar", 2]"#).unwrap();
assert!(ary.includes(Symbol::new("foo")));
assert!(ary.includes("bar"));
assert!(ary.includes(2));
// 2.0 == 2 in Ruby
assert!(ary.includes(2.0));
assert!(!ary.includes("foo"));
assert!(!ary.includes(QNIL));

Concatenate elements from the slice s to self.

Returns Err if self is frozen.

Examples
use magnus::{eval, Integer, QNIL, RArray, Symbol};

let ary = RArray::new();
ary.cat(&[*Symbol::new("a"), *Integer::from_i64(1), *QNIL]).unwrap();
let res: bool = eval!("ary == [:a, 1, nil]", ary).unwrap();
assert!(res);
use magnus::{eval, RArray, Symbol};

let ary = RArray::new();
ary.cat(&[Symbol::new("a"), Symbol::new("b"), Symbol::new("c")]).unwrap();
let res: bool = eval!("ary == [:a, :b, :c]", ary).unwrap();
assert!(res);

Concatenate elements from Ruby array other to self.

Returns Err if self is frozen.

Examples
use magnus::{eval, Integer, QNIL, RArray, Symbol};

let a = RArray::from_vec(vec![1, 2, 3]);
let b = RArray::from_vec(vec!["a", "b", "c"]);
a.concat(b).unwrap();
let res: bool = eval!(r#"a == [1, 2, 3, "a", "b", "c"]"#, a).unwrap();
assert!(res);
let res: bool = eval!(r#"b == ["a", "b", "c"]"#, b).unwrap();
assert!(res);

Create a new RArray containing the both the elements in self and other.

Examples
use magnus::{eval, Integer, QNIL, RArray, Symbol};

let a = RArray::from_vec(vec![1, 2, 3]);
let b = RArray::from_vec(vec!["a", "b", "c"]);
let c = a.plus(b);
let res: bool = eval!(r#"c == [1, 2, 3, "a", "b", "c"]"#, c).unwrap();
assert!(res);
let res: bool = eval!(r#"a == [1, 2, 3]"#, a).unwrap();
assert!(res);
let res: bool = eval!(r#"b == ["a", "b", "c"]"#, b).unwrap();
assert!(res);

Create a new RArray containing the elements in slice.

Examples
use magnus::{eval, Integer, QNIL, RArray, Symbol};

let ary = RArray::from_slice(&[*Symbol::new("a"), *Integer::from_i64(1), *QNIL]);
let res: bool = eval!("ary == [:a, 1, nil]", ary).unwrap();
assert!(res);
use magnus::{eval, RArray, Symbol};

let ary = RArray::from_slice(&[Symbol::new("a"), Symbol::new("b"), Symbol::new("c")]);
let res: bool = eval!("ary == [:a, :b, :c]", ary).unwrap();
assert!(res);

Add item to the end of self.

Returns Err if self is frozen.

Examples
use magnus::{eval, RArray, Symbol};

let ary = RArray::new();
ary.push(Symbol::new("a")).unwrap();
ary.push(1).unwrap();
ary.push(()).unwrap();
let res: bool = eval!("ary == [:a, 1, nil]", ary).unwrap();
assert!(res);

Remove and return the last element of self, converting it to a T.

Errors if self is frozen or if the conversion fails.

Examples
use magnus::{eval, RArray};

let ary = eval::<RArray>("[1, 2, 3]").unwrap();
assert_eq!(ary.pop::<i64>().unwrap(), 3);
assert_eq!(ary.pop::<i64>().unwrap(), 2);
assert_eq!(ary.pop::<i64>().unwrap(), 1);
assert!(ary.pop::<i64>().is_err());
use magnus::{eval, RArray};

let ary = eval::<RArray>("[1, 2, 3]").unwrap();
assert_eq!(ary.pop::<Option<i64>>().unwrap(), Some(3));
assert_eq!(ary.pop::<Option<i64>>().unwrap(), Some(2));
assert_eq!(ary.pop::<Option<i64>>().unwrap(), Some(1));
assert_eq!(ary.pop::<Option<i64>>().unwrap(), None);

Add item to the beginning of self.

Returns Err if self is frozen.

Examples
use magnus::{eval, RArray, Symbol};

let ary = RArray::new();
ary.unshift(Symbol::new("a"));
ary.unshift(1);
ary.unshift(());
let res: bool = eval!("ary == [nil, 1, :a]", ary).unwrap();
assert!(res);

Remove and return the first element of self, converting it to a T.

Errors if self is frozen or if the conversion fails.

Examples
use magnus::{eval, RArray};

let ary = eval::<RArray>("[1, 2, 3]").unwrap();
assert_eq!(ary.shift::<i64>().unwrap(), 1);
assert_eq!(ary.shift::<i64>().unwrap(), 2);
assert_eq!(ary.shift::<i64>().unwrap(), 3);
assert!(ary.shift::<i64>().is_err());
use magnus::{eval, RArray};

let ary = eval::<RArray>("[1, 2, 3]").unwrap();
assert_eq!(ary.shift::<Option<i64>>().unwrap(), Some(1));
assert_eq!(ary.shift::<Option<i64>>().unwrap(), Some(2));
assert_eq!(ary.shift::<Option<i64>>().unwrap(), Some(3));
assert_eq!(ary.shift::<Option<i64>>().unwrap(), None);

Remove all elements from self that match item’s == method.

Returns Err if self is frozen.

Examples
use magnus::{eval, RArray};

let ary = RArray::from_vec(vec![1, 1, 2, 3]);
ary.delete(1).unwrap();
let res: bool = eval!("ary == [2, 3]", ary).unwrap();
assert!(res);

Remove and return the element of self at index, converting it to a T.

index may be negative, in which case it counts backward from the end of the array.

Returns Err if self is frozen or if the conversion fails.

The returned element will be Ruby’s nil when index is out of bounds this makes it impossible to distingush between out of bounds and removing nil without an additional length check.

Examples
use magnus::{eval, RArray};

let ary = RArray::from_vec(vec!["a", "b", "c"]);
let removed: Option::<String> = ary.delete_at(1).unwrap();
assert_eq!(removed, Some(String::from("b")));
let res: bool = eval!(r#"ary == ["a", "c"]"#, ary).unwrap();
assert!(res);

Remove all elements from self

Returns Err if self is frozen.

Examples
use magnus::{eval, RArray};

let ary = RArray::from_vec::<i64>(vec![1, 2, 3]);
ary.clear().unwrap();
let res: bool = eval!("ary == []", ary).unwrap();
assert!(res);

Expand or shrink the length of self.

When increasing the length of the array empty positions will be filled with nil.

Returns Err if self is frozen.

Examples
use magnus::{eval, RArray};

let ary = RArray::from_vec::<i64>(vec![1, 2, 3]);
ary.resize(5).unwrap();
let res: bool = eval!("ary == [1, 2, 3, nil, nil]", ary).unwrap();
assert!(res);
ary.resize(2).unwrap();
let res: bool = eval!("ary == [1, 2]", ary).unwrap();
assert!(res);

Reverses the order of self in place.

Returns Err if self is frozen.

Examples
use magnus::{eval, RArray};

let ary = RArray::from_vec::<i64>(vec![1, 2, 3]);
ary.reverse().unwrap();
let res: bool = eval!("ary == [3, 2, 1]", ary).unwrap();
assert!(res);

Rotates the elements of self in place by rot positions.

If rot is positive elements are rotated to the left, if negative, to the right.

Returns Err if self is frozen.

Examples
use magnus::{eval, RArray};

let ary = RArray::from_vec::<i64>(vec![1, 2, 3, 4, 5, 6, 7]);
ary.rotate(3).unwrap();
let res: bool = eval!("ary == [4, 5, 6, 7, 1, 2, 3]", ary).unwrap();
assert!(res);
use magnus::{eval, RArray};

let ary = RArray::from_vec::<i64>(vec![1, 2, 3, 4, 5, 6, 7]);
ary.rotate(-3).unwrap();
let res: bool = eval!("ary == [5, 6, 7, 1, 2, 3, 4]", ary).unwrap();
assert!(res);

Storts the elements of self in place using Ruby’s <=> operator.

Returns Err if self is frozen.

Examples
use magnus::{eval, RArray};

let ary = RArray::from_vec::<i64>(vec![2, 1, 3]);
ary.sort().unwrap();
let res: bool = eval!("ary == [1, 2, 3]", ary).unwrap();
assert!(res);

Create a new RArray from a Rust vector.

Examples
use magnus::{eval, RArray};

let ary = RArray::from_vec(vec![1, 2, 3]);
let res: bool = eval!("ary == [1, 2, 3]", ary).unwrap();
assert!(res);

Return self as a slice of Values.

Safety

This is directly viewing memory owned and managed by Ruby. Ruby may modify or free the memory backing the returned slice, the caller must ensure this does not happen.

Ruby must not be allowed to garbage collect or modify self while a refrence to the slice is held.

Examples
use magnus::{eval, RArray};

let ary = eval::<RArray>("[1, 2, 3, 4, 5]").unwrap();
// must not call any Ruby api that may modify ary while we have a
// refrence to the return value of ::from_slice()
let middle = unsafe { RArray::from_slice(&ary.as_slice()[1..4]) };
let res: bool = eval!("middle == [2, 3, 4]", middle).unwrap();
assert!(res);

Convert self to a Rust vector of Ts. Errors if converting any element in the array fails.

This will only convert to a map of ‘owned’ Rust native types. The types representing Ruby objects can not be stored in a heap-allocated datastructure like a Vec as they are hidden from the mark phase of Ruby’s garbage collector, and thus may be prematurely garbage collected in the following sweep phase.

Examples
use magnus::{eval, RArray};

let ary = eval::<RArray>("[1, 2, 3]").unwrap();
assert_eq!(ary.to_vec::<i64>().unwrap(), vec![1, 2, 3]);

Convert self to a Rust array of Values, of length N.

Errors if the Ruby array is not of length N.

Examples
use magnus::{eval, RArray};

let ary = eval::<RArray>("[1, 2, 3]").unwrap();
assert!(ary.to_value_array::<3>().is_ok());
assert!(ary.to_value_array::<2>().is_err());
assert!(ary.to_value_array::<4>().is_err());

Convert self to a Rust array of Ts, of length N.

Errors if converting any element in the array fails, or if the Ruby array is not of length N.

Examples
use magnus::{eval, RArray};

let ary = eval::<RArray>("[1, 2, 3]").unwrap();
assert_eq!(ary.to_array::<i64, 3>().unwrap(), [1, 2, 3]);
assert!(ary.to_array::<i64, 2>().is_err());
assert!(ary.to_array::<i64, 4>().is_err());

Stringify the contents of self and join the sequence with sep.

Examples
use magnus::{eval, Integer, RArray, Symbol, QNIL};

let ary = RArray::from_slice(&[*Symbol::new("a"), *Integer::from_i64(1), *QNIL]);
assert_eq!(ary.join(", ").unwrap().to_string().unwrap(), "a, 1, ")

Return the element at offset, converting it to a T.

Errors if the conversion fails.

An offset out of range will return nil.

Examples
use magnus::{eval, RArray};

let ary: RArray = eval(r#"["a", "b", "c"]"#).unwrap();

assert_eq!(ary.entry::<String>(0).unwrap(), String::from("a"));
assert_eq!(ary.entry::<char>(0).unwrap(), 'a');
assert_eq!(ary.entry::<Option<String>>(0).unwrap(), Some(String::from("a")));
assert_eq!(ary.entry::<String>(1).unwrap(), String::from("b"));
assert_eq!(ary.entry::<String>(-1).unwrap(), String::from("c"));
assert_eq!(ary.entry::<Option<String>>(3).unwrap(), None);

assert!(ary.entry::<i64>(0).is_err());
assert!(ary.entry::<String>(3).is_err());

Set the element at offset.

If offset is beyond the current size of the array the array will be expanded and padded with nil.

Returns Err if self is frozen.

Examples
use magnus::{eval, RArray, Symbol};

let ary = RArray::from_vec(vec![Symbol::new("a"), Symbol::new("b"), Symbol::new("c")]);
ary.store(0, Symbol::new("d"));
ary.store(5, Symbol::new("e"));
ary.store(6, Symbol::new("f"));
ary.store(-1, Symbol::new("g"));
let res: bool = eval!("ary == [:d, :b, :c, nil, nil, :e, :g]", ary).unwrap();
assert!(res);

Returns an Enumerator over self.

Examples
use magnus::{eval, RArray};

let mut res = Vec::new();
for i in eval::<RArray>("[1, 2, 3]").unwrap().each() {
    res.push(i.unwrap().try_convert::<i64>().unwrap());
}
assert_eq!(res, vec![1, 2, 3]);

Returns true if both self and other share the same backing storage.

It is possible for two Ruby Arrays to share the same backing storage, and only when one of them is modified will the copy-on-write cost be paid.

Currently, this method will only return true if self and other are of the same length, even though Ruby may continue to use the same backing storage after popping a value from either of the arrays.

Examples
use magnus::{eval, RArray, Value};

let ary = RArray::from_vec((0..256).collect());
let copy = RArray::new();
copy.replace(ary);
assert!(ary.is_shared(copy));
assert!(copy.is_shared(ary));
copy.push(11);
assert!(!ary.is_shared(copy));
assert!(!copy.is_shared(ary));

Replace the contents of self with from.

from is unmodified, and self becomes a copy of from. self’s former contents are abandoned.

This is a very cheep operation, self will point at from’s backing storage until one is modified, and only then will the copy-on-write cost be paid.

Returns Err if self is frozen.

Examples
use magnus::{eval, RArray};

let ary = RArray::from_vec((0..256).collect());
let copy = RArray::new();
copy.replace(ary);
assert!(copy.is_shared(ary));
copy.push(11);
assert!(!copy.is_shared(ary));

Create a new array from a subsequence of self.

This is a very cheep operation, as self and the new array will share thier backing storage until one is modified.

Examples
use magnus::{eval, RArray, Value};

let ary = RArray::from_vec(vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
let a = ary.subseq(0, 5).unwrap();
let b = ary.subseq(5, 5).unwrap();
assert_eq!(a.to_vec::<i64>().unwrap(), vec![1, 2, 3, 4, 5]);
assert_eq!(b.to_vec::<i64>().unwrap(), vec![6, 7, 8, 9, 10]);

Methods from Deref<Target = Value>§

Convert self to a Rust string.

Safety

This may return a direct view of memory owned and managed by Ruby. Ruby may modify or free the memory backing the returned str, the caller must ensure this does not happen.

This can be used safely by immediately calling into_owned on the return value.

Examples
use magnus::{eval, QTRUE};

let value = QTRUE;
// safe as we neve give Ruby a chance to free the string.
let s = unsafe { value.to_s() }.unwrap().into_owned();
assert_eq!(s, "true");

Return the name of self’s class.

Safety

Ruby may modify or free the memory backing the returned str, the caller must ensure this does not happen.

This can be used safely by immediately calling into_owned on the return value.

Examples
use magnus::{eval, RHash};

let value = RHash::new();
// safe as we never give Ruby a chance to free the string.
let s = unsafe { value.classname() }.into_owned();
assert_eq!(s, "Hash");

Trait Implementations§

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Formats the value using the given formatter. Read more
The resulting type after dereferencing.
Dereferences the value.
Formats the value using the given formatter. Read more
Converts to this type from the input type.
Creates a value from an iterator. Read more
Define a singleton method in self’s scope. Read more
Get the value for the instance variable name within self’s scope. Read more
Set the value for the instance variable name within self’s scope. Read more
Finds or creates the singleton class of self. Read more
Extend self with module. Read more
Convert val into Self.

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

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

The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
Converts the given value to a String. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.