#[repr(transparent)]
pub struct RString(_);
Expand description

A Value pointer to a RString struct, Ruby’s internal representation of strings.

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

Implementations

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

Examples
use magnus::{eval, RString};

assert!(RString::from_value(eval(r#""example""#).unwrap()).is_some());
assert!(RString::from_value(eval(":example").unwrap()).is_none());

Create a new Ruby string from the Rust string s.

The encoding of the Ruby string will be UTF-8.

Examples
use magnus::{eval, RString};

let val = RString::new("example");
let res: bool = eval!(r#"val == "example""#, val).unwrap();
assert!(res);

Create a new Ruby string with capacity n.

The encoding will be set to ASCII-8BIT (aka BINARY). See also with_capacity.

Examples
use magnus::{eval, RString};

let buf = RString::buf_new(4096);
buf.cat(&[13, 14, 10, 13, 11, 14, 14, 15]);
let res: bool = eval!(r#"buf == "\r\x0E\n\r\v\x0E\x0E\x0F""#, buf).unwrap();
assert!(res);

Create a new Ruby string with capacity n.

The encoding will be set to UTF-8. See also buf_new.

Examples
use magnus::{eval, RString};

let s = RString::with_capacity(9);
s.cat("foo");
s.cat("bar");
s.cat("baz");
let res: bool = eval!(r#"s == "foobarbaz""#, s).unwrap();
assert!(res);

Create a new Ruby string from the Rust slice s.

The encoding of the Ruby string will be set to ASCII-8BIT (aka BINARY).

Examples
use magnus::{eval, RString};

let buf = RString::from_slice(&[13, 14, 10, 13, 11, 14, 14, 15]);
let res: bool = eval!(r#"buf == "\r\x0E\n\r\v\x0E\x0E\x0F""#, buf).unwrap();
assert!(res);

Create a new Ruby string from the value s with the encoding enc.

Examples
use magnus::{eval, encoding::RbEncoding, RString};

let val = RString::enc_new("example", RbEncoding::usascii());
let res: bool = eval!(r#"val == "example""#, val).unwrap();
assert!(res);
use magnus::{eval, encoding::RbEncoding, RString};

let val = RString::enc_new([255, 128, 128], RbEncoding::ascii8bit());
let res: bool = eval!(r#"val == "\xFF\x80\x80".force_encoding("BINARY")"#, val).unwrap();
assert!(res);

Create a new Ruby string from the Rust char c.

The encoding of the Ruby string will be UTF-8.

Examples
use magnus::{eval, RString};

let c = RString::from_char('a');
let res: bool = eval!(r#"c == "a""#, c).unwrap();
assert!(res);
use magnus::{eval, RString};

let c = RString::from_char('🦀');
let res: bool = eval!(r#"c == "🦀""#, c).unwrap();
assert!(res);

Create a new Ruby string containing the codepoint code in the encoding enc.

The encoding of the Ruby string will be the passed encoding enc.

Examples
use magnus::{eval, encoding::RbEncoding, RString};

let c = RString::chr(97, RbEncoding::usascii()).unwrap();
let res: bool = eval!(r#"c == "a""#, c).unwrap();
assert!(res);
use magnus::{eval, encoding::RbEncoding, RString};

let c = RString::chr(129408, RbEncoding::utf8()).unwrap();
let res: bool = eval!(r#"c == "🦀""#, c).unwrap();
assert!(res);

Create a new Ruby string that shares the same backing data as s.

Both string objects will point at the same underlying data until one is modified, and only then will the data be duplicated. This operation is cheep, and useful for cases where you may need to modify a string, but don’t want to mutate a value passed to your function.

Examples
use magnus::{eval, RString};

let s = RString::new("example");
let dup = RString::new_shared(s);
let res: bool = eval!("s == dup", s, dup).unwrap();
assert!(res);
// mutating one doesn't mutate both
dup.cat("foo");
let res: bool = eval!("s != dup", s, dup).unwrap();
assert!(res);

Create a new Ruby string that is a frozen copy of s.

This can be used to get a copy of a string that is guranteed not to be modified while you are referencing it.

Examples
use magnus::{eval, RString};

let orig = RString::new("example");
let frozen = RString::new_frozen(orig);
let res: bool = eval!(r#"frozen == "example""#, frozen).unwrap();
assert!(res);
// mutating original doesn't impact the frozen copy
orig.cat("foo");
let res: bool = eval!(r#"frozen == "example""#, frozen).unwrap();
assert!(res);

Return self as a slice of bytes.

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::RString;

let s = RString::new("example");
// safe as we don't give Ruby the chance to mess with the string while
// we hold a refrence to the slice.
unsafe { assert_eq!(s.as_slice(), [101, 120, 97, 109, 112, 108, 101]) };

Return an iterator over self’s codepoints.

Safety

The returned iterator references memory owned and managed by Ruby. Ruby may modify or free that memory, the caller must ensure this does not happen at any time while still holding a reference to the iterator.

Examples
use magnus::{Error, RString};

let s = RString::new("🦀 café");

let codepoints = unsafe {
    // ensure string isn't mutated during iteration by creating a
    // frozen copy and iterating over that
    let f = RString::new_frozen(s);
    f.codepoints().collect::<Result<Vec<_>, Error>>().unwrap()
};

assert_eq!(codepoints, [129408, 32, 99, 97, 102, 233]);

Return an iterator over self’s chars as slices of bytes.

Safety

The returned iterator references memory owned and managed by Ruby. Ruby may modify or free that memory, the caller must ensure this does not happen at any time while still holding a reference to the iterator.

Examples
use magnus::RString;

let s = RString::new("🦀 café");

// ensure string isn't mutated during iteration by creating a frozen
// copy and iterating over that
let f = RString::new_frozen(s);
let codepoints = unsafe {
    f.char_bytes().collect::<Vec<_>>()
};

assert_eq!(codepoints, [&[240, 159, 166, 128][..], &[32], &[99], &[97], &[102], &[195, 169]]);

Returns true if the encoding for this string is UTF-8 or US-ASCII, false otherwise.

The encoding on a Ruby String is just a label, it provides no guarantee that the String really is valid UTF-8.

Examples
use magnus::{eval, RString};

let s: RString = eval!(r#""café""#).unwrap();
assert!(s.is_utf8_compatible_encoding());
use magnus::{eval, RString};

let s: RString = eval!(r#""café".encode("ISO-8859-1")"#).unwrap();
assert!(!s.is_utf8_compatible_encoding());
👎 Deprecated since 0.3.0:

please use r_string.conv_enc(RbEncoding::utf8()) instead

Returns a new string by reencoding self from its current encoding to UTF-8.

Returns a new string by reencoding self from its current encoding to the given enc.

Examples
use magnus::{encoding::RbEncoding, eval, RString};

let s: RString = eval!(r#""café".encode("ISO-8859-1")"#).unwrap();
// safe as we don't give Ruby the chance to mess with the string while
// we hold a refrence to the slice.
unsafe { assert_eq!(s.as_slice(), &[99, 97, 102, 233]) };
let e = s.conv_enc(RbEncoding::utf8()).unwrap();
unsafe { assert_eq!(e.as_slice(), &[99, 97, 102, 195, 169]) };

Returns the cached coderange value that describes how self relates to its encoding.

See also enc_coderange_scan.

Examples
use magnus::{encoding::Coderange, RString};

// Coderange is unknown on creation.
let s = RString::new("test");
assert_eq!(s.enc_coderange(), Coderange::Unknown);

// Methods that operate on the string using the encoding will set the
// coderange as a side effect.
let _: usize = s.funcall("length", ()).unwrap();
assert_eq!(s.enc_coderange(), Coderange::SevenBit);

// Operations with two strings with known coderanges will set it
// appropriately.
let t = RString::new("🦀");
let _: usize = t.funcall("length", ()).unwrap();
assert_eq!(t.enc_coderange(), Coderange::Valid);
s.append(t).unwrap();
assert_eq!(s.enc_coderange(), Coderange::Valid);

// Operations that modify the string with an unknown coderange will
// set the coderange back to unknown.
s.cat([128]);
assert_eq!(s.enc_coderange(), Coderange::Unknown);

// Which may leave the string with a broken encoding.
let _: usize = s.funcall("length", ()).unwrap();
assert_eq!(s.enc_coderange(), Coderange::Broken);

Scans self to establish its coderange.

If the coderange is already known, simply returns the known value. See also enc_coderange.

Examples
use magnus::{encoding::Coderange, RString};

let s = RString::new("test");
assert_eq!(s.enc_coderange_scan(), Coderange::SevenBit);

Clear self’s cached coderange, setting it to Unknown.

Examples
use magnus::{encoding::Coderange, RString};

let s = RString::new("🦀");
// trigger setting coderange
let _: usize = s.funcall("length", ()).unwrap();
assert_eq!(s.enc_coderange(), Coderange::Valid);

s.enc_coderange_clear();
assert_eq!(s.enc_coderange(), Coderange::Unknown);

Sets self’s cached coderange.

Rather than using the method it is recommended to set the coderange to Unknown with enc_coderange_clear and let Ruby determine the coderange lazily when needed.

Safety

This must be set correctly. SevenBit if all codepoints are within 0..=127, Valid if the string is valid for its encoding, or Broken if it is not. Unknown can be set safely with enc_coderange_clear.

Examples
use magnus::{encoding::{self, Coderange, EncodingCapable}, exception, Error, RString};

fn crabbify(s: RString) -> Result<(), Error> {
    if s.enc_get() != encoding::Index::utf8() {
        return Err(Error::new(exception::encoding_error(), "expected utf-8"));
    }
    let original = s.enc_coderange();
    // ::cat() will clear the coderange
    s.cat("🦀");
    // we added a multibyte char, so if we started with `SevenBit` it
    // should be upgraded to `Valid`, and if it was `Valid` it is still
    // `Valid`.
    if original == Coderange::SevenBit || original == Coderange::Valid {
        unsafe {
            s.enc_coderange_set(Coderange::Valid);
        }
    }
    Ok(())
}

let s = RString::new("test");
// trigger setting coderange
let _: usize = s.funcall("length", ()).unwrap();

crabbify(s).unwrap();
assert_eq!(s.enc_coderange(), Coderange::Valid);

Returns a Rust &str reference to the value of self.

Returns None if self’s encoding is not UTF-8 (or US-ASCII), or if the string is not valid UTF-8.

Safety

This is directly viewing 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.

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

Examples
use magnus::RString;

let s = RString::new("example");
// safe as we don't give Ruby the chance to mess with the string while
// we hold a refrence to the slice.
unsafe { assert_eq!(s.test_as_str().unwrap(), "example") };

Returns a Rust &str reference to the value of self.

Errors if self’s encoding is not UTF-8 (or US-ASCII), or if the string is not valid UTF-8.

Safety

This is directly viewing 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.

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

Examples
use magnus::RString;

let s = RString::new("example");
// safe as we don't give Ruby the chance to mess with the string while
// we hold a refrence to the slice.
unsafe { assert_eq!(s.as_str().unwrap(), "example") };

Returns self as a Rust string, ignoring the Ruby encoding and dropping any non-UTF-8 characters. If self is valid UTF-8 this will return a &str reference.

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.

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

Examples
use magnus::RString;

let s = RString::new("example");
// safe as we don't give Ruby the chance to mess with the string while
// we hold a refrence to the slice.
unsafe { assert_eq!(s.to_string_lossy(), "example") };

Returns self as an owned Rust String. The Ruby string will be reencoded as UTF-8 if required. Errors if the string can not be encoded as UTF-8.

Examples
use magnus::RString;

let s = RString::new("example");
assert_eq!(s.to_string().unwrap(), "example");

Converts self to a char. Errors if the string is more than one character or can not be encoded as UTF-8.

Examples
use magnus::RString;

let s = RString::new("a");
assert_eq!(s.to_char().unwrap(), 'a');

Returns whether self is a frozen interned string. Interned strings are usually string literals with the in files with the # frozen_string_literal: true ‘magic comment’.

Interned strings won’t be garbage collected or modified, so should be safe to store on the heap or hold a &str refrence to. See as_interned_str.

Examples
use magnus::{eval, RString};

let s: RString = eval!(r#"
# frozen_string_literal: true

"example"
"#).unwrap();
assert!(s.is_interned());
use magnus::{eval, RString};

let s: RString = eval!(r#""example""#).unwrap();
assert!(!s.is_interned());

Returns Some(FString) if self is interned, None otherwise.

Interned strings won’t be garbage collected or modified, so should be safe to store on the heap or hold a &str refrence to. The FString type returned by this function provides a way to encode this property into the type system, and provides safe methods to access the string as a &str or slice.

Examples
use magnus::{eval, RString};

let s: RString = eval!(r#"
# frozen_string_literal: true

"example"
"#).unwrap();
assert!(s.as_interned_str().is_some());
use magnus::{eval, RString};

let s: RString = eval!(r#""example""#).unwrap();
assert!(s.as_interned_str().is_none());

Mutate self, adding other to the end. Errors if self and other`’s encodings are not compatible.

Examples
use magnus::RString;

let a = RString::new("foo");
let b = RString::new("bar");
a.append(b).unwrap();
assert_eq!(a.to_string().unwrap(), "foobar");

Mutate self, adding buf to the end.

Note: This ignore’s self’s encoding, and may result in self containing invalid bytes for its encoding. It’s assumed this will more often be used with ASCII-8BIT (aka BINARY) encoded strings. See buf_new and from_slice.

Examples
use magnus::{eval, RString};

let buf = RString::buf_new(4096);
buf.cat(&[102, 111, 111]);
buf.cat("bar");
assert_eq!(buf.to_string().unwrap(), "foobar");

Returns the number of bytes in self.

See also length.

Examples
use magnus::{eval, RString};

let s = RString::new("🦀 Hello, Ferris");
assert_eq!(s.len(), 18);

Returns the number of characters in self.

See also len.

Examples
use magnus::{eval, RString};

let s = RString::new("🦀 Hello, Ferris");
assert_eq!(s.length(), 15);

Return whether self contains any characters or not.

Examples
use magnus::RString;

let s = RString::new("");
assert!(s.is_empty());

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 neve give Ruby a chance to free the string.
let s = unsafe { value.classname() }.into_owned();
assert_eq!(s, "Hash");

Convert self to the Rust type T.

See the types that TryConvert is implemented on for what this method can convert to.

Examples
use magnus::{eval, Value};

assert_eq!(eval::<Value>("42").unwrap().try_convert::<i64>().unwrap(), 42);
assert_eq!(eval::<Value>("1.23").unwrap().try_convert::<i64>().unwrap(), 1);
assert_eq!(eval::<Value>("1").unwrap().try_convert::<f64>().unwrap(), 1.0);
assert_eq!(eval::<Value>("nil").unwrap().try_convert::<Option<i64>>().unwrap(), None);
assert_eq!(eval::<Value>("42").unwrap().try_convert::<Option<i64>>().unwrap(), Some(42));

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

Get the encoding of self. Read more

Set self’s encoding. Read more

Set self’s encoding, along with performing additional fix-up self’s contents. Read more

Converts to this type from the input type.

Converts to this type from the input type.

Converts to this type from the input type.

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.

Write a buffer into this writer, returning how many bytes were written. Read more

Flush this output stream, ensuring that all intermediately buffered contents reach their destination. Read more

Like write, except that it writes from a slice of buffers. Read more

🔬 This is a nightly-only experimental API. (can_vector)

Determines if this Writer has an efficient write_vectored implementation. Read more

Attempts to write an entire buffer into this writer. Read more

🔬 This is a nightly-only experimental API. (write_all_vectored)

Attempts to write multiple buffers into this writer. Read more

Writes a formatted string into this writer, returning any error encountered. Read more

Creates a “by reference” adapter for this instance of Write. Read more

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

🔬 This is a nightly-only experimental API. (toowned_clone_into)

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.