Merge branch 'master' into plugins

This commit is contained in:
Stephen Chung
2020-07-22 13:33:24 +08:00
18 changed files with 455 additions and 234 deletions

View File

@@ -203,6 +203,7 @@ impl Dynamic {
}
/// Map the name of a standard type into a friendly form.
#[inline]
pub(crate) fn map_std_type_name(name: &str) -> &str {
if name == type_name::<String>() {
"string"
@@ -340,30 +341,47 @@ impl Dynamic {
/// assert_eq!(new_result.type_name(), "string");
/// assert_eq!(new_result.to_string(), "hello");
/// ```
#[inline(always)]
pub fn from<T: Variant + Clone>(value: T) -> Self {
if let Some(result) = <dyn Any>::downcast_ref::<()>(&value) {
return result.clone().into();
} else if let Some(result) = <dyn Any>::downcast_ref::<bool>(&value) {
return result.clone().into();
} else if let Some(result) = <dyn Any>::downcast_ref::<INT>(&value) {
return result.clone().into();
} else if let Some(result) = <dyn Any>::downcast_ref::<char>(&value) {
return result.clone().into();
} else if let Some(result) = <dyn Any>::downcast_ref::<ImmutableString>(&value) {
return result.clone().into();
}
let type_id = TypeId::of::<T>();
if type_id == TypeId::of::<INT>() {
return <dyn Any>::downcast_ref::<INT>(&value)
.unwrap()
.clone()
.into();
}
#[cfg(not(feature = "no_float"))]
if let Some(result) = <dyn Any>::downcast_ref::<FLOAT>(&value) {
return result.clone().into();
if type_id == TypeId::of::<FLOAT>() {
return <dyn Any>::downcast_ref::<FLOAT>(&value)
.unwrap()
.clone()
.into();
}
if type_id == TypeId::of::<bool>() {
return <dyn Any>::downcast_ref::<bool>(&value)
.unwrap()
.clone()
.into();
}
if type_id == TypeId::of::<char>() {
return <dyn Any>::downcast_ref::<char>(&value)
.unwrap()
.clone()
.into();
}
if type_id == TypeId::of::<ImmutableString>() {
return <dyn Any>::downcast_ref::<ImmutableString>(&value)
.unwrap()
.clone()
.into();
}
if type_id == TypeId::of::<()>() {
return ().into();
}
let mut boxed = Box::new(value);
boxed = match unsafe_cast_box::<_, Dynamic>(boxed) {
Ok(d) => return *d,
Err(val) => val,
};
boxed = match unsafe_cast_box::<_, String>(boxed) {
Ok(s) => return (*s).into(),
Err(val) => val,
@@ -384,6 +402,11 @@ impl Dynamic {
}
}
boxed = match unsafe_cast_box::<_, Dynamic>(boxed) {
Ok(d) => return *d,
Err(val) => val,
};
Self(Union::Variant(Box::new(boxed)))
}
@@ -401,30 +424,80 @@ impl Dynamic {
///
/// assert_eq!(x.try_cast::<u32>().unwrap(), 42);
/// ```
#[inline(always)]
pub fn try_cast<T: Variant>(self) -> Option<T> {
let type_id = TypeId::of::<T>();
if type_id == TypeId::of::<INT>() {
return match self.0 {
Union::Int(value) => unsafe_try_cast(value),
_ => None,
};
}
#[cfg(not(feature = "no_float"))]
if type_id == TypeId::of::<FLOAT>() {
return match self.0 {
Union::Float(value) => unsafe_try_cast(value),
_ => None,
};
}
if type_id == TypeId::of::<bool>() {
return match self.0 {
Union::Bool(value) => unsafe_try_cast(value),
_ => None,
};
}
if type_id == TypeId::of::<ImmutableString>() {
return match self.0 {
Union::Str(value) => unsafe_try_cast(value),
_ => None,
};
}
if type_id == TypeId::of::<String>() {
return match self.0 {
Union::Str(value) => unsafe_try_cast(value.into_owned()),
_ => None,
};
}
if type_id == TypeId::of::<char>() {
return match self.0 {
Union::Char(value) => unsafe_try_cast(value),
_ => None,
};
}
#[cfg(not(feature = "no_index"))]
if type_id == TypeId::of::<Array>() {
return match self.0 {
Union::Array(value) => unsafe_cast_box::<_, T>(value).ok().map(|v| *v),
_ => None,
};
}
#[cfg(not(feature = "no_object"))]
if type_id == TypeId::of::<Map>() {
return match self.0 {
Union::Map(value) => unsafe_cast_box::<_, T>(value).ok().map(|v| *v),
_ => None,
};
}
if type_id == TypeId::of::<FnPtr>() {
return match self.0 {
Union::FnPtr(value) => unsafe_try_cast(value),
_ => None,
};
}
if type_id == TypeId::of::<()>() {
return match self.0 {
Union::Unit(value) => unsafe_try_cast(value),
_ => None,
};
}
if type_id == TypeId::of::<Dynamic>() {
return unsafe_cast_box::<_, T>(Box::new(self)).ok().map(|v| *v);
}
match self.0 {
Union::Unit(value) => unsafe_try_cast(value),
Union::Bool(value) => unsafe_try_cast(value),
Union::Str(value) if type_id == TypeId::of::<ImmutableString>() => {
unsafe_try_cast(value)
}
Union::Str(value) => unsafe_try_cast(value.into_owned()),
Union::Char(value) => unsafe_try_cast(value),
Union::Int(value) => unsafe_try_cast(value),
#[cfg(not(feature = "no_float"))]
Union::Float(value) => unsafe_try_cast(value),
#[cfg(not(feature = "no_index"))]
Union::Array(value) => unsafe_cast_box::<_, T>(value).ok().map(|v| *v),
#[cfg(not(feature = "no_object"))]
Union::Map(value) => unsafe_cast_box::<_, T>(value).ok().map(|v| *v),
Union::FnPtr(value) => unsafe_try_cast(value),
Union::Variant(value) => (*value).as_box_any().downcast().map(|x| *x).ok(),
_ => None,
}
}
@@ -444,81 +517,162 @@ impl Dynamic {
///
/// assert_eq!(x.cast::<u32>(), 42);
/// ```
#[inline(always)]
pub fn cast<T: Variant + Clone>(self) -> T {
let type_id = TypeId::of::<T>();
if type_id == TypeId::of::<Dynamic>() {
return *unsafe_cast_box::<_, T>(Box::new(self)).unwrap();
}
match self.0 {
Union::Unit(value) => unsafe_try_cast(value).unwrap(),
Union::Bool(value) => unsafe_try_cast(value).unwrap(),
Union::Str(value) if type_id == TypeId::of::<ImmutableString>() => {
unsafe_try_cast(value).unwrap()
}
Union::Str(value) => unsafe_try_cast(value.into_owned()).unwrap(),
Union::Char(value) => unsafe_try_cast(value).unwrap(),
Union::Int(value) => unsafe_try_cast(value).unwrap(),
#[cfg(not(feature = "no_float"))]
Union::Float(value) => unsafe_try_cast(value).unwrap(),
#[cfg(not(feature = "no_index"))]
Union::Array(value) => *unsafe_cast_box::<_, T>(value).unwrap(),
#[cfg(not(feature = "no_object"))]
Union::Map(value) => *unsafe_cast_box::<_, T>(value).unwrap(),
Union::FnPtr(value) => unsafe_try_cast(value).unwrap(),
Union::Variant(value) => (*value).as_box_any().downcast().map(|x| *x).unwrap(),
}
self.try_cast::<T>().unwrap()
}
/// Get a reference of a specific type to the `Dynamic`.
/// Casting to `Dynamic` just returns a reference to it.
/// Returns `None` if the cast fails.
#[inline(always)]
pub fn downcast_ref<T: Variant + Clone>(&self) -> Option<&T> {
if TypeId::of::<T>() == TypeId::of::<Dynamic>() {
let type_id = TypeId::of::<T>();
if type_id == TypeId::of::<INT>() {
return match &self.0 {
Union::Int(value) => <dyn Any>::downcast_ref::<T>(value),
_ => None,
};
}
#[cfg(not(feature = "no_float"))]
if type_id == TypeId::of::<FLOAT>() {
return match &self.0 {
Union::Float(value) => <dyn Any>::downcast_ref::<T>(value),
_ => None,
};
}
if type_id == TypeId::of::<bool>() {
return match &self.0 {
Union::Bool(value) => <dyn Any>::downcast_ref::<T>(value),
_ => None,
};
}
if type_id == TypeId::of::<ImmutableString>() {
return match &self.0 {
Union::Str(value) => <dyn Any>::downcast_ref::<T>(value),
_ => None,
};
}
if type_id == TypeId::of::<String>() {
return match &self.0 {
Union::Str(value) => <dyn Any>::downcast_ref::<T>(value.as_ref()),
_ => None,
};
}
if type_id == TypeId::of::<char>() {
return match &self.0 {
Union::Char(value) => <dyn Any>::downcast_ref::<T>(value),
_ => None,
};
}
#[cfg(not(feature = "no_index"))]
if type_id == TypeId::of::<Array>() {
return match &self.0 {
Union::Array(value) => <dyn Any>::downcast_ref::<T>(value.as_ref()),
_ => None,
};
}
#[cfg(not(feature = "no_object"))]
if type_id == TypeId::of::<Map>() {
return match &self.0 {
Union::Map(value) => <dyn Any>::downcast_ref::<T>(value.as_ref()),
_ => None,
};
}
if type_id == TypeId::of::<FnPtr>() {
return match &self.0 {
Union::FnPtr(value) => <dyn Any>::downcast_ref::<T>(value),
_ => None,
};
}
if type_id == TypeId::of::<()>() {
return match &self.0 {
Union::Unit(value) => <dyn Any>::downcast_ref::<T>(value),
_ => None,
};
}
if type_id == TypeId::of::<Dynamic>() {
return <dyn Any>::downcast_ref::<T>(self);
}
match &self.0 {
Union::Unit(value) => <dyn Any>::downcast_ref::<T>(value),
Union::Bool(value) => <dyn Any>::downcast_ref::<T>(value),
Union::Str(value) => <dyn Any>::downcast_ref::<T>(value)
.or_else(|| <dyn Any>::downcast_ref::<T>(value.as_ref())),
Union::Char(value) => <dyn Any>::downcast_ref::<T>(value),
Union::Int(value) => <dyn Any>::downcast_ref::<T>(value),
#[cfg(not(feature = "no_float"))]
Union::Float(value) => <dyn Any>::downcast_ref::<T>(value),
#[cfg(not(feature = "no_index"))]
Union::Array(value) => <dyn Any>::downcast_ref::<T>(value.as_ref()),
#[cfg(not(feature = "no_object"))]
Union::Map(value) => <dyn Any>::downcast_ref::<T>(value.as_ref()),
Union::FnPtr(value) => <dyn Any>::downcast_ref::<T>(value),
Union::Variant(value) => value.as_ref().as_ref().as_any().downcast_ref::<T>(),
_ => None,
}
}
/// Get a mutable reference of a specific type to the `Dynamic`.
/// Casting to `Dynamic` just returns a mutable reference to it.
/// Returns `None` if the cast fails.
#[inline(always)]
pub fn downcast_mut<T: Variant + Clone>(&mut self) -> Option<&mut T> {
if TypeId::of::<T>() == TypeId::of::<Dynamic>() {
let type_id = TypeId::of::<T>();
if type_id == TypeId::of::<INT>() {
return match &mut self.0 {
Union::Int(value) => <dyn Any>::downcast_mut::<T>(value),
_ => None,
};
}
#[cfg(not(feature = "no_float"))]
if type_id == TypeId::of::<FLOAT>() {
return match &mut self.0 {
Union::Float(value) => <dyn Any>::downcast_mut::<T>(value),
_ => None,
};
}
if type_id == TypeId::of::<bool>() {
return match &mut self.0 {
Union::Bool(value) => <dyn Any>::downcast_mut::<T>(value),
_ => None,
};
}
if type_id == TypeId::of::<ImmutableString>() {
return match &mut self.0 {
Union::Str(value) => <dyn Any>::downcast_mut::<T>(value),
_ => None,
};
}
if type_id == TypeId::of::<char>() {
return match &mut self.0 {
Union::Char(value) => <dyn Any>::downcast_mut::<T>(value),
_ => None,
};
}
#[cfg(not(feature = "no_index"))]
if type_id == TypeId::of::<Array>() {
return match &mut self.0 {
Union::Array(value) => <dyn Any>::downcast_mut::<T>(value.as_mut()),
_ => None,
};
}
#[cfg(not(feature = "no_object"))]
if type_id == TypeId::of::<Map>() {
return match &mut self.0 {
Union::Map(value) => <dyn Any>::downcast_mut::<T>(value.as_mut()),
_ => None,
};
}
if type_id == TypeId::of::<FnPtr>() {
return match &mut self.0 {
Union::FnPtr(value) => <dyn Any>::downcast_mut::<T>(value),
_ => None,
};
}
if type_id == TypeId::of::<()>() {
return match &mut self.0 {
Union::Unit(value) => <dyn Any>::downcast_mut::<T>(value),
_ => None,
};
}
if type_id == TypeId::of::<Dynamic>() {
return <dyn Any>::downcast_mut::<T>(self);
}
match &mut self.0 {
Union::Unit(value) => <dyn Any>::downcast_mut::<T>(value),
Union::Bool(value) => <dyn Any>::downcast_mut::<T>(value),
Union::Str(value) => <dyn Any>::downcast_mut::<T>(value),
Union::Char(value) => <dyn Any>::downcast_mut::<T>(value),
Union::Int(value) => <dyn Any>::downcast_mut::<T>(value),
#[cfg(not(feature = "no_float"))]
Union::Float(value) => <dyn Any>::downcast_mut::<T>(value),
#[cfg(not(feature = "no_index"))]
Union::Array(value) => <dyn Any>::downcast_mut::<T>(value.as_mut()),
#[cfg(not(feature = "no_object"))]
Union::Map(value) => <dyn Any>::downcast_mut::<T>(value.as_mut()),
Union::FnPtr(value) => <dyn Any>::downcast_mut::<T>(value),
Union::Variant(value) => value.as_mut().as_mut_any().downcast_mut::<T>(),
_ => None,
}
}

View File

@@ -18,7 +18,7 @@ use crate::utils::StaticVec;
use crate::parser::FLOAT;
#[cfg(feature = "internals")]
use crate::syntax::CustomSyntax;
use crate::syntax::{CustomSyntax, EvalContext};
use crate::stdlib::{
any::{type_name, TypeId},
@@ -1738,15 +1738,19 @@ impl Engine {
#[deprecated(note = "this method is volatile and may change")]
pub fn eval_expression_tree(
&self,
context: &mut EvalContext,
scope: &mut Scope,
mods: &mut Imports,
state: &mut State,
lib: &Module,
this_ptr: &mut Option<&mut Dynamic>,
expr: &Expression,
level: usize,
) -> Result<Dynamic, Box<EvalAltResult>> {
self.eval_expr(scope, mods, state, lib, this_ptr, expr.expr(), level)
self.eval_expr(
scope,
context.mods,
context.state,
context.lib,
context.this_ptr,
expr.expr(),
context.level,
)
}
/// Evaluate an expression
@@ -1773,8 +1777,8 @@ impl Engine {
Expr::CharConstant(x) => Ok(x.0.into()),
Expr::FnPointer(x) => Ok(FnPtr::new_unchecked(x.0.clone()).into()),
Expr::Variable(x) if (x.0).0 == KEYWORD_THIS => {
if let Some(ref val) = this_ptr {
Ok((*val).clone())
if let Some(val) = this_ptr {
Ok(val.clone())
} else {
Err(Box::new(EvalAltResult::ErrorUnboundedThis((x.0).1)))
}
@@ -1829,15 +1833,16 @@ impl Engine {
// Not built in, map to `var = var op rhs`
let op = &op[..op.len() - 1]; // extract operator without =
let hash = calc_fn_hash(empty(), op, 2, empty());
// Clone the LHS value
let args = &mut [&mut lhs_ptr.clone(), &mut rhs_val];
// Set variable value
*lhs_ptr = self
// Run function
let (value, _) = self
.exec_fn_call(
state, lib, op, true, hash, args, false, false, None, level,
)
.map(|(v, _)| v)
.map_err(|err| err.new_position(*op_pos))?;
// Set value to LHS
*lhs_ptr = value;
}
Ok(Default::default())
}
@@ -2215,7 +2220,14 @@ impl Engine {
Expr::Custom(x) => {
let func = (x.0).1.as_ref();
let ep: StaticVec<_> = (x.0).0.iter().map(|e| e.into()).collect();
func(self, scope, mods, state, lib, this_ptr, ep.as_ref(), level)
let mut context = EvalContext {
mods,
state,
lib,
this_ptr,
level,
};
func(self, &mut context, scope, ep.as_ref())
}
_ => unreachable!(),
@@ -2492,12 +2504,8 @@ impl Engine {
for ((id, id_pos), rename) in list.iter() {
// Mark scope variables as public
if let Some(index) = scope.get_index(id).map(|(i, _)| i) {
let alias = rename
.as_ref()
.map(|(n, _)| n.clone())
.unwrap_or_else(|| id.clone());
scope.set_entry_alias(index, alias);
let alias = rename.as_ref().map(|(n, _)| n).unwrap_or_else(|| id);
scope.set_entry_alias(index, alias.clone());
} else {
return Err(Box::new(EvalAltResult::ErrorVariableNotFound(
id.into(),

View File

@@ -175,6 +175,10 @@ pub use parser::{CustomExpr, Expr, ReturnType, ScriptFnDef, Stmt};
#[deprecated(note = "this type is volatile and may change")]
pub use engine::{Expression, Imports, State as EvalState};
#[cfg(feature = "internals")]
#[deprecated(note = "this type is volatile and may change")]
pub use syntax::EvalContext;
#[cfg(feature = "internals")]
#[deprecated(note = "this type is volatile and may change")]
pub use module::ModuleRef;

View File

@@ -434,7 +434,7 @@ fn optimize_expr(expr: Expr, state: &mut State) -> Expr {
(Expr::StringConstant(s), Expr::IntegerConstant(i)) if i.0 >= 0 && (i.0 as usize) < s.0.chars().count() => {
// String literal indexing - get the character
state.set_dirty();
Expr::CharConstant(Box::new((s.0.chars().nth(i.0 as usize).expect("should get char"), s.1)))
Expr::CharConstant(Box::new((s.0.chars().nth(i.0 as usize).unwrap(), s.1)))
}
// lhs[rhs]
(lhs, rhs) => Expr::Index(Box::new((optimize_expr(lhs, state), optimize_expr(rhs, state), x.2))),
@@ -614,7 +614,7 @@ fn optimize_expr(expr: Expr, state: &mut State) -> Expr {
state.set_dirty();
// Replace constant with value
state.find_constant(&name).expect("should find constant in scope!").clone().set_position(pos)
state.find_constant(&name).unwrap().clone().set_position(pos)
}
// Custom syntax
@@ -655,10 +655,7 @@ fn optimize(
&& expr.as_ref().map(|v| v.is_constant()).unwrap_or(false)
})
.for_each(|ScopeEntry { name, expr, .. }| {
state.push_constant(
name.as_ref(),
(**expr.as_ref().expect("should be Some(expr)")).clone(),
)
state.push_constant(name.as_ref(), expr.as_ref().unwrap().as_ref().clone())
});
let orig_constants_len = state.constants.len();

View File

@@ -22,26 +22,13 @@ use crate::stdlib::{
#[cfg(not(feature = "sync"))]
pub type FnCustomSyntaxEval = dyn Fn(
&Engine,
&mut EvalContext,
&mut Scope,
&mut Imports,
&mut State,
&Module,
&mut Option<&mut Dynamic>,
&[Expression],
usize,
) -> Result<Dynamic, Box<EvalAltResult>>;
/// A general function trail object.
#[cfg(feature = "sync")]
pub type FnCustomSyntaxEval = dyn Fn(
&Engine,
&mut Scope,
&mut Imports,
&mut State,
&Module,
&mut Option<&mut Dynamic>,
&[Expression],
usize,
) -> Result<Dynamic, Box<EvalAltResult>>
pub type FnCustomSyntaxEval = dyn Fn(&Engine, &mut EvalContext, &mut Scope, &[Expression]) -> Result<Dynamic, Box<EvalAltResult>>
+ Send
+ Sync;
@@ -58,6 +45,14 @@ impl fmt::Debug for CustomSyntax {
}
}
pub struct EvalContext<'a, 'b: 'a, 's, 'm, 't, 'd: 't> {
pub(crate) mods: &'a mut Imports<'b>,
pub(crate) state: &'s mut State,
pub(crate) lib: &'m Module,
pub(crate) this_ptr: &'t mut Option<&'d mut Dynamic>,
pub(crate) level: usize,
}
impl Engine {
pub fn register_custom_syntax<S: AsRef<str> + ToString>(
&mut self,
@@ -65,13 +60,9 @@ impl Engine {
scope_delta: isize,
func: impl Fn(
&Engine,
&mut EvalContext,
&mut Scope,
&mut Imports,
&mut State,
&Module,
&mut Option<&mut Dynamic>,
&[Expression],
usize,
) -> Result<Dynamic, Box<EvalAltResult>>
+ SendSync
+ 'static,

View File

@@ -12,6 +12,7 @@ use crate::stdlib::{
};
/// Cast a type into another type.
#[inline(always)]
pub fn unsafe_try_cast<A: Any, B: Any>(a: A) -> Option<B> {
if TypeId::of::<B>() == a.type_id() {
// SAFETY: Just checked we have the right type. We explicitly forget the
@@ -28,6 +29,7 @@ pub fn unsafe_try_cast<A: Any, B: Any>(a: A) -> Option<B> {
}
/// Cast a Boxed type into another type.
#[inline(always)]
pub fn unsafe_cast_box<X: Variant, T: Variant>(item: Box<X>) -> Result<Box<T>, Box<X>> {
// Only allow casting to the exact same type
if TypeId::of::<X>() == TypeId::of::<T>() {
@@ -51,6 +53,7 @@ pub fn unsafe_cast_box<X: Variant, T: Variant>(item: Box<X>) -> Result<Box<T>, B
///
/// Force-casting a local variable's lifetime to the current `Scope`'s larger lifetime saves
/// on allocations and string cloning, thus avoids us having to maintain a chain of `Scope`'s.
#[inline]
pub fn unsafe_cast_var_name_to_lifetime<'s>(name: &str, state: &State) -> Cow<'s, str> {
// If not at global level, we can force-cast
if state.scope_level > 0 {

View File

@@ -36,11 +36,9 @@ use ahash::AHasher;
pub struct StraightHasher(u64);
impl Hasher for StraightHasher {
#[inline(always)]
fn finish(&self) -> u64 {
self.0
}
#[inline]
fn write(&mut self, bytes: &[u8]) {
let mut key = [0_u8; 8];
key.copy_from_slice(&bytes[..8]); // Panics if fewer than 8 bytes
@@ -50,7 +48,6 @@ impl Hasher for StraightHasher {
impl StraightHasher {
/// Create a `StraightHasher`.
#[inline(always)]
pub fn new() -> Self {
Self(0)
}
@@ -63,7 +60,6 @@ pub struct StraightHasherBuilder;
impl BuildHasher for StraightHasherBuilder {
type Hasher = StraightHasher;
#[inline(always)]
fn build_hasher(&self) -> Self::Hasher {
StraightHasher::new()
}
@@ -150,7 +146,6 @@ pub struct StaticVec<T> {
const MAX_STATIC_VEC: usize = 4;
impl<T> Drop for StaticVec<T> {
#[inline(always)]
fn drop(&mut self) {
self.clear();
}
@@ -233,7 +228,6 @@ impl<T: 'static> IntoIterator for StaticVec<T> {
impl<T> StaticVec<T> {
/// Create a new `StaticVec`.
#[inline(always)]
pub fn new() -> Self {
Default::default()
}
@@ -249,7 +243,6 @@ impl<T> StaticVec<T> {
self.len = 0;
}
/// Extract a `MaybeUninit` into a concrete initialized type.
#[inline(always)]
fn extract(value: MaybeUninit<T>) -> T {
unsafe { value.assume_init() }
}
@@ -311,7 +304,6 @@ impl<T> StaticVec<T> {
);
}
/// Is data stored in fixed-size storage?
#[inline(always)]
fn is_fixed_storage(&self) -> bool {
self.len <= MAX_STATIC_VEC
}
@@ -418,12 +410,10 @@ impl<T> StaticVec<T> {
}
}
/// Get the number of items in this `StaticVec`.
#[inline(always)]
pub fn len(&self) -> usize {
self.len
}
/// Is this `StaticVec` empty?
#[inline(always)]
pub fn is_empty(&self) -> bool {
self.len == 0
}
@@ -664,48 +654,41 @@ pub struct ImmutableString(Shared<String>);
impl Deref for ImmutableString {
type Target = String;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl AsRef<String> for ImmutableString {
#[inline(always)]
fn as_ref(&self) -> &String {
&self.0
}
}
impl Borrow<str> for ImmutableString {
#[inline(always)]
fn borrow(&self) -> &str {
self.0.as_str()
}
}
impl From<&str> for ImmutableString {
#[inline(always)]
fn from(value: &str) -> Self {
Self(value.to_string().into())
}
}
impl From<String> for ImmutableString {
#[inline(always)]
fn from(value: String) -> Self {
Self(value.into())
}
}
impl From<Box<String>> for ImmutableString {
#[inline(always)]
fn from(value: Box<String>) -> Self {
Self(value.into())
}
}
impl From<ImmutableString> for String {
#[inline(always)]
fn from(value: ImmutableString) -> Self {
value.into_owned()
}
@@ -714,49 +697,42 @@ impl From<ImmutableString> for String {
impl FromStr for ImmutableString {
type Err = ();
#[inline(always)]
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Self(s.to_string().into()))
}
}
impl FromIterator<char> for ImmutableString {
#[inline(always)]
fn from_iter<T: IntoIterator<Item = char>>(iter: T) -> Self {
Self(iter.into_iter().collect::<String>().into())
}
}
impl<'a> FromIterator<&'a char> for ImmutableString {
#[inline(always)]
fn from_iter<T: IntoIterator<Item = &'a char>>(iter: T) -> Self {
Self(iter.into_iter().cloned().collect::<String>().into())
}
}
impl<'a> FromIterator<&'a str> for ImmutableString {
#[inline(always)]
fn from_iter<T: IntoIterator<Item = &'a str>>(iter: T) -> Self {
Self(iter.into_iter().collect::<String>().into())
}
}
impl<'a> FromIterator<String> for ImmutableString {
#[inline(always)]
fn from_iter<T: IntoIterator<Item = String>>(iter: T) -> Self {
Self(iter.into_iter().collect::<String>().into())
}
}
impl fmt::Display for ImmutableString {
#[inline(always)]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self.0.as_str(), f)
}
}
impl fmt::Debug for ImmutableString {
#[inline(always)]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(self.0.as_str(), f)
}
@@ -891,7 +867,6 @@ impl Add<char> for &ImmutableString {
}
impl AddAssign<char> for ImmutableString {
#[inline(always)]
fn add_assign(&mut self, rhs: char) {
self.make_mut().push(rhs);
}
@@ -906,7 +881,6 @@ impl ImmutableString {
}
/// Make sure that the `ImmutableString` is unique (i.e. no other outstanding references).
/// Then return a mutable reference to the `String`.
#[inline(always)]
pub fn make_mut(&mut self) -> &mut String {
shared_make_mut(&mut self.0)
}