-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstr.rs
More file actions
209 lines (183 loc) · 6.77 KB
/
Copy pathstr.rs
File metadata and controls
209 lines (183 loc) · 6.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
use std::any::Any;
use std::fmt;
use std::sync::{Arc, RwLock};
use once_cell::sync::Lazy;
use crate::format::render_template;
use crate::vm::{RuntimeBoolResult, RuntimeErr, RuntimeObjResult};
use super::gen::{self, use_arg, use_arg_str, use_arg_usize};
use super::new;
use super::base::{ObjectRef, ObjectTrait, TypeRef, TypeTrait};
use super::class::TYPE_TYPE;
use super::ns::Namespace;
// Str Type ------------------------------------------------------------
gen::type_and_impls!(StrType, Str);
pub static STR_TYPE: Lazy<gen::obj_ref_t!(StrType)> = Lazy::new(|| {
let type_ref = gen::obj_ref!(StrType::new());
let mut type_obj = type_ref.write().unwrap();
type_obj.add_attrs(&[
// Class Methods -----------------------------------------------
gen::meth!("new", type_ref, &["value"], "", |_, args, _| {
let arg = use_arg!(args, 0);
Ok(if arg.is_str() { args[0].clone() } else { new::str(arg.to_string()) })
}),
// Instance Attributes -----------------------------------------
gen::prop!("length", type_ref, "", |this, _, _| {
let this = this.read().unwrap();
let value = this.get_str_val().unwrap();
Ok(new::int(value.len()))
}),
// Instance Methods --------------------------------------------
gen::meth!("starts_with", type_ref, &["prefix"], "", |this, args, _| {
let this = this.read().unwrap();
let value = this.get_str_val().unwrap();
let arg = use_arg!(args, 0);
let prefix = use_arg_str!(starts_with, prefix, arg);
Ok(new::bool(value.starts_with(prefix)))
}),
gen::meth!("ends_with", type_ref, &["suffix"], "", |this, args, _| {
let this = this.read().unwrap();
let value = this.get_str_val().unwrap();
let arg = use_arg!(args, 0);
let suffix = use_arg_str!(ends_with, suffix, arg);
Ok(new::bool(value.ends_with(suffix)))
}),
gen::meth!("upper", type_ref, &[], "", |this, _, _| {
let this = this.read().unwrap();
let value = this.get_str_val().unwrap();
Ok(new::str(value.to_uppercase()))
}),
gen::meth!("lower", type_ref, &[], "", |this, _, _| {
let this = this.read().unwrap();
let value = this.get_str_val().unwrap();
Ok(new::str(value.to_lowercase()))
}),
gen::meth!(
"render",
type_ref,
&["context"],
"Render string as template
Templates may contain `{{ name }}` vars which will be replaced with the
values provided in the context map.
# Args
- context: Map<Str, Str> A map containing values to be rendered into the
template.
",
|this, args, _| {
let context = args[0].clone();
let result = render_template(this.clone(), context)?;
Ok(result)
}
),
gen::meth!("repeat", type_ref, &["count"], "", |this, args, _| {
let this = this.read().unwrap();
let value = this.get_str_val().unwrap();
let count = use_arg_usize!(get, index, args, 0);
Ok(new::str(value.repeat(count)))
}),
gen::meth!("replace", type_ref, &["old", "new"], "", |this, args, _| {
let this = this.read().unwrap();
let value = this.get_str_val().unwrap();
let arg1 = use_arg!(args, 0);
let arg2 = use_arg!(args, 1);
let old = use_arg_str!(replace, old, arg1);
let new = use_arg_str!(replace, new, arg2);
let result = value.replace(old, new);
Ok(new::str(result))
}),
gen::meth!("remove_prefix", type_ref, &["prefix"], "", |this_ref, args, _| {
let this = this_ref.read().unwrap();
let val = this.get_str_val().unwrap();
let arg = use_arg!(args, 0);
let prefix = use_arg_str!(starts_with, prefix, arg);
Ok(if let Some(new_val) = val.strip_prefix(prefix) {
new::str(new_val)
} else {
drop(this);
this_ref
})
}),
]);
type_ref.clone()
});
// Str Object ----------------------------------------------------------
pub struct Str {
ns: Namespace,
value: String,
}
gen::standard_object_impls!(Str);
impl Str {
pub fn new(value: String) -> Self {
Self {
ns: Namespace::with_entries(&[
// Instance Attributes
("len", new::int(value.len())),
]),
value,
}
}
pub fn value(&self) -> &str {
self.value.as_str()
}
}
impl ObjectTrait for Str {
gen::object_trait_header!(STR_TYPE);
fn is_equal(&self, rhs: &dyn ObjectTrait) -> bool {
if self.is(rhs) || rhs.is_always() {
true
} else if let Some(rhs) = rhs.down_to_str() {
self.is(rhs) || self.value() == rhs.value()
} else {
false
}
}
fn add(&self, rhs: &dyn ObjectTrait) -> RuntimeObjResult {
if let Some(rhs) = rhs.down_to_str() {
let a = self.value();
let b = rhs.value();
let mut value = String::with_capacity(a.len() + b.len());
value.push_str(a);
value.push_str(b);
let value = new::str(value);
Ok(value)
} else {
Err(RuntimeErr::type_err(format!(
"Cannot concatenate {} to {}",
self.class().read().unwrap(),
rhs.class().read().unwrap(),
)))
}
}
fn less_than(&self, rhs: &dyn ObjectTrait) -> RuntimeBoolResult {
if let Some(rhs) = rhs.down_to_str() {
Ok(self.value() < rhs.value())
} else {
Err(RuntimeErr::type_err(format!(
"Cannot compare {} to {}: <",
self.class().read().unwrap(),
rhs.class().read().unwrap(),
)))
}
}
fn greater_than(&self, rhs: &dyn ObjectTrait) -> RuntimeBoolResult {
if let Some(rhs) = rhs.down_to_str() {
Ok(self.value() > rhs.value())
} else {
Err(RuntimeErr::type_err(format!(
"Cannot compare {} to {}: >",
self.class().read().unwrap(),
rhs.class().read().unwrap(),
)))
}
}
}
// Display -------------------------------------------------------------
impl fmt::Display for Str {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.value)
}
}
impl fmt::Debug for Str {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "\"{}\"", self.value)
}
}