#[repr(transparent)]pub struct RString(_);
Expand description
Implementations
sourceimpl RString
impl RString
sourcepub fn from_value(val: Value) -> Option<Self>
pub fn from_value(val: Value) -> Option<Self>
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());
sourcepub fn new(s: &str) -> Self
pub fn new(s: &str) -> Self
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);
sourcepub fn buf_new(n: usize) -> Self
pub fn buf_new(n: usize) -> Self
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);
sourcepub fn with_capacity(n: usize) -> Self
pub fn with_capacity(n: usize) -> Self
sourcepub fn from_slice(s: &[u8]) -> Self
pub fn from_slice(s: &[u8]) -> Self
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);
sourcepub fn enc_new<T, E>(s: T, enc: E) -> Self where
T: AsRef<[u8]>,
E: Into<RbEncoding>,
pub fn enc_new<T, E>(s: T, enc: E) -> Self where
T: AsRef<[u8]>,
E: Into<RbEncoding>,
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);
sourcepub fn from_char(c: char) -> Self
pub fn from_char(c: char) -> Self
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);
sourcepub fn chr<T>(code: u32, enc: T) -> Result<Self, Error> where
T: Into<RbEncoding>,
pub fn chr<T>(code: u32, enc: T) -> Result<Self, Error> where
T: Into<RbEncoding>,
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);
sourcepub fn new_frozen(s: Self) -> Self
pub fn new_frozen(s: Self) -> Self
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);
sourcepub unsafe fn as_slice(&self) -> &[u8]ⓘNotable traits for &'_ [u8]impl<'_> Read for &'_ [u8]impl<'_> Write for &'_ mut [u8]
pub unsafe fn as_slice(&self) -> &[u8]ⓘNotable traits for &'_ [u8]impl<'_> Read for &'_ [u8]impl<'_> Write for &'_ mut [u8]
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]) };
sourcepub unsafe fn codepoints(&self) -> Codepoints<'_>ⓘNotable traits for Codepoints<'a>impl<'a> Iterator for Codepoints<'a> type Item = Result<u32, Error>;
pub unsafe fn codepoints(&self) -> Codepoints<'_>ⓘNotable traits for Codepoints<'a>impl<'a> Iterator for Codepoints<'a> type Item = Result<u32, Error>;
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]);
sourcepub unsafe fn char_bytes(&self) -> CharBytes<'_>ⓘNotable traits for CharBytes<'a>impl<'a> Iterator for CharBytes<'a> type Item = &'a [u8];
pub unsafe fn char_bytes(&self) -> CharBytes<'_>ⓘNotable traits for CharBytes<'a>impl<'a> Iterator for CharBytes<'a> type Item = &'a [u8];
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]]);
sourcepub fn is_utf8_compatible_encoding(self) -> bool
pub fn is_utf8_compatible_encoding(self) -> bool
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());
sourcepub fn encode_utf8(self) -> Result<Self, Error>
👎 Deprecated since 0.3.0: please use r_string.conv_enc(RbEncoding::utf8())
instead
pub fn encode_utf8(self) -> Result<Self, Error>
please use r_string.conv_enc(RbEncoding::utf8())
instead
Returns a new string by reencoding self
from its current encoding to
UTF-8.
sourcepub fn conv_enc<T>(self, enc: T) -> Result<Self, Error> where
T: Into<RbEncoding>,
pub fn conv_enc<T>(self, enc: T) -> Result<Self, Error> where
T: Into<RbEncoding>,
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]) };
sourcepub fn enc_coderange(self) -> Coderange
pub fn enc_coderange(self) -> Coderange
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);
sourcepub fn enc_coderange_scan(self) -> Coderange
pub fn enc_coderange_scan(self) -> Coderange
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);
sourcepub fn enc_coderange_clear(self)
pub fn enc_coderange_clear(self)
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);
sourcepub unsafe fn enc_coderange_set(self, cr: Coderange)
pub unsafe fn enc_coderange_set(self, cr: Coderange)
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);
sourcepub unsafe fn test_as_str(&self) -> Option<&str>
pub unsafe fn test_as_str(&self) -> Option<&str>
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") };
sourcepub unsafe fn as_str(&self) -> Result<&str, Error>
pub unsafe fn as_str(&self) -> Result<&str, Error>
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") };
sourcepub unsafe fn to_string_lossy(&self) -> Cow<'_, str>
pub unsafe fn to_string_lossy(&self) -> Cow<'_, str>
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") };
sourcepub fn to_string(self) -> Result<String, Error>
pub fn to_string(self) -> Result<String, Error>
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");
sourcepub fn is_interned(self) -> bool
pub fn is_interned(self) -> bool
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());
sourcepub fn as_interned_str(self) -> Option<FString>
pub fn as_interned_str(self) -> Option<FString>
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());
sourcepub fn append(self, other: Self) -> Result<(), Error>
pub fn append(self, other: Self) -> Result<(), Error>
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");
sourcepub fn cat<T: AsRef<[u8]>>(self, buf: T)
pub fn cat<T: AsRef<[u8]>>(self, buf: T)
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");
Methods from Deref<Target = Value>
sourcepub unsafe fn to_s(&self) -> Result<Cow<'_, str>, Error>
pub unsafe fn to_s(&self) -> Result<Cow<'_, str>, Error>
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");
sourcepub unsafe fn classname(&self) -> Cow<'_, str>
pub unsafe fn classname(&self) -> Cow<'_, str>
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");
sourcepub fn try_convert<T>(&self) -> Result<T, Error> where
T: TryConvert,
pub fn try_convert<T>(&self) -> Result<T, Error> where
T: TryConvert,
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
sourceimpl EncodingCapable for RString
impl EncodingCapable for RString
sourceimpl Object for RString
impl Object for RString
sourcefn define_singleton_method<M>(self, name: &str, func: M) -> Result<(), Error> where
M: Method,
fn define_singleton_method<M>(self, name: &str, func: M) -> Result<(), Error> where
M: Method,
Define a singleton method in self
’s scope. Read more
sourcefn ivar_get<T, U>(self, name: T) -> Result<U, Error> where
T: Into<Id>,
U: TryConvert,
fn ivar_get<T, U>(self, name: T) -> Result<U, Error> where
T: Into<Id>,
U: TryConvert,
Get the value for the instance variable name
within self
’s scope. Read more
sourcefn ivar_set<T, U>(self, name: T, value: U) -> Result<(), Error> where
T: Into<Id>,
U: Into<Value>,
fn ivar_set<T, U>(self, name: T, value: U) -> Result<(), Error> where
T: Into<Id>,
U: Into<Value>,
Set the value for the instance variable name
within self
’s scope. Read more
sourceimpl TryConvert for RString
impl TryConvert for RString
sourcefn try_convert(val: &Value) -> Result<Self, Error>
fn try_convert(val: &Value) -> Result<Self, Error>
Convert val
into Self
.
sourceimpl Write for RString
impl Write for RString
sourcefn write(&mut self, buf: &[u8]) -> Result<usize>
fn write(&mut self, buf: &[u8]) -> Result<usize>
Write a buffer into this writer, returning how many bytes were written. Read more
sourcefn flush(&mut self) -> Result<()>
fn flush(&mut self) -> Result<()>
Flush this output stream, ensuring that all intermediately buffered contents reach their destination. Read more
sourcefn is_write_vectored(&self) -> bool
fn is_write_vectored(&self) -> bool
can_vector
)Determines if this Write
r has an efficient write_vectored
implementation. Read more
1.0.0 · sourcefn write_all(&mut self, buf: &[u8]) -> Result<(), Error>
fn write_all(&mut self, buf: &[u8]) -> Result<(), Error>
Attempts to write an entire buffer into this writer. Read more
sourcefn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<(), Error>
fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<(), Error>
write_all_vectored
)Attempts to write multiple buffers into this writer. Read more
impl Copy for RString
impl ReprValue for RString
Auto Trait Implementations
impl RefUnwindSafe for RString
impl Send for RString
impl Sync for RString
impl Unpin for RString
impl UnwindSafe for RString
Blanket Implementations
sourceimpl<T> BorrowMut<T> for T where
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
const: unstable · sourcefn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
sourceimpl<T> ToOwned for T where
T: Clone,
impl<T> ToOwned for T where
T: Clone,
type Owned = T
type Owned = T
The resulting type after obtaining ownership.
sourcefn clone_into(&self, target: &mut T)
fn clone_into(&self, target: &mut T)
toowned_clone_into
)Uses borrowed data to replace owned data, usually by cloning. Read more