1use core::{cmp::Ordering, convert::Infallible, fmt::Debug};
2
3use super::{
4 env::internal::{Env as _, EnvBase as _, StringObject},
5 ConversionError, Env, TryFromVal, TryIntoVal, Val,
6};
7
8use crate::unwrap::{UnwrapInfallible, UnwrapOptimized};
9#[cfg(doc)]
10use crate::{storage::Storage, Map, Vec};
11
12#[cfg(not(target_family = "wasm"))]
13use super::xdr::{ScString, ScVal};
14
15#[derive(Clone)]
37pub struct String {
38 env: Env,
39 obj: StringObject,
40}
41
42impl Debug for String {
43 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
44 #[cfg(target_family = "wasm")]
45 write!(f, "String(..)")?;
46 #[cfg(not(target_family = "wasm"))]
47 write!(f, "String({})", self.to_string())?;
48 Ok(())
49 }
50}
51
52impl Eq for String {}
53
54impl PartialEq for String {
55 fn eq(&self, other: &Self) -> bool {
56 self.partial_cmp(other) == Some(Ordering::Equal)
57 }
58}
59
60impl PartialOrd for String {
61 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
62 Some(Ord::cmp(self, other))
63 }
64}
65
66impl Ord for String {
67 fn cmp(&self, other: &Self) -> core::cmp::Ordering {
68 #[cfg(not(target_family = "wasm"))]
69 if !self.env.is_same_env(&other.env) {
70 return ScVal::from(self).cmp(&ScVal::from(other));
71 }
72 let v = self
73 .env
74 .obj_cmp(self.obj.to_val(), other.obj.to_val())
75 .unwrap_infallible();
76 v.cmp(&0)
77 }
78}
79
80impl TryFromVal<Env, String> for String {
81 type Error = ConversionError;
82
83 fn try_from_val(_env: &Env, v: &String) -> Result<Self, Self::Error> {
84 Ok(v.clone())
85 }
86}
87
88impl TryFromVal<Env, StringObject> for String {
89 type Error = Infallible;
90
91 fn try_from_val(env: &Env, val: &StringObject) -> Result<Self, Self::Error> {
92 Ok(unsafe { String::unchecked_new(env.clone(), *val) })
93 }
94}
95
96impl TryFromVal<Env, Val> for String {
97 type Error = ConversionError;
98
99 fn try_from_val(env: &Env, val: &Val) -> Result<Self, Self::Error> {
100 Ok(StringObject::try_from_val(env, val)?
101 .try_into_val(env)
102 .unwrap_infallible())
103 }
104}
105
106impl TryFromVal<Env, String> for Val {
107 type Error = ConversionError;
108
109 fn try_from_val(_env: &Env, v: &String) -> Result<Self, Self::Error> {
110 Ok(v.to_val())
111 }
112}
113
114impl TryFromVal<Env, &String> for Val {
115 type Error = ConversionError;
116
117 fn try_from_val(_env: &Env, v: &&String) -> Result<Self, Self::Error> {
118 Ok(v.to_val())
119 }
120}
121
122impl From<String> for Val {
123 #[inline(always)]
124 fn from(v: String) -> Self {
125 v.obj.into()
126 }
127}
128
129impl From<String> for StringObject {
130 #[inline(always)]
131 fn from(v: String) -> Self {
132 v.obj
133 }
134}
135
136impl From<&String> for StringObject {
137 #[inline(always)]
138 fn from(v: &String) -> Self {
139 v.obj
140 }
141}
142
143impl From<&String> for String {
144 #[inline(always)]
145 fn from(v: &String) -> Self {
146 v.clone()
147 }
148}
149
150#[cfg(not(target_family = "wasm"))]
151impl From<&String> for ScVal {
152 fn from(v: &String) -> Self {
153 ScVal::try_from_val(&v.env, &v.obj.to_val()).unwrap()
159 }
160}
161
162#[cfg(not(target_family = "wasm"))]
163impl From<String> for ScVal {
164 fn from(v: String) -> Self {
165 (&v).into()
166 }
167}
168
169#[cfg(not(target_family = "wasm"))]
170impl TryFromVal<Env, ScVal> for String {
171 type Error = ConversionError;
172 fn try_from_val(env: &Env, val: &ScVal) -> Result<Self, Self::Error> {
173 Ok(
174 StringObject::try_from_val(env, &Val::try_from_val(env, val)?)?
175 .try_into_val(env)
176 .unwrap_infallible(),
177 )
178 }
179}
180
181impl TryFromVal<Env, &str> for String {
182 type Error = ConversionError;
183
184 fn try_from_val(env: &Env, v: &&str) -> Result<Self, Self::Error> {
185 Ok(String::from_str(env, v))
186 }
187}
188
189#[cfg(not(target_family = "wasm"))]
190impl ToString for String {
191 fn to_string(&self) -> std::string::String {
192 let sc_val: ScVal = self.try_into().unwrap();
193 if let ScVal::String(ScString(s)) = sc_val {
194 s.to_utf8_string().unwrap()
195 } else {
196 panic!("value is not a string");
197 }
198 }
199}
200
201impl String {
202 #[inline(always)]
203 pub(crate) unsafe fn unchecked_new(env: Env, obj: StringObject) -> Self {
204 Self { env, obj }
205 }
206
207 #[inline(always)]
208 pub fn env(&self) -> &Env {
209 &self.env
210 }
211
212 pub fn as_val(&self) -> &Val {
213 self.obj.as_val()
214 }
215
216 pub fn to_val(&self) -> Val {
217 self.obj.to_val()
218 }
219
220 pub fn as_object(&self) -> &StringObject {
221 &self.obj
222 }
223
224 pub fn to_object(&self) -> StringObject {
225 self.obj
226 }
227
228 #[inline(always)]
229 #[doc(hidden)]
230 #[deprecated(note = "use from_str")]
231 pub fn from_slice(env: &Env, slice: &str) -> String {
232 Self::from_str(env, slice)
233 }
234
235 #[inline(always)]
236 pub fn from_bytes(env: &Env, b: &[u8]) -> String {
237 String {
238 env: env.clone(),
239 obj: env.string_new_from_slice(b).unwrap_optimized(),
240 }
241 }
242
243 #[inline(always)]
244 pub fn from_str(env: &Env, s: &str) -> String {
245 String {
246 env: env.clone(),
247 obj: env.string_new_from_slice(s.as_bytes()).unwrap_optimized(),
248 }
249 }
250
251 #[inline(always)]
252 pub fn len(&self) -> u32 {
253 self.env().string_len(self.obj).unwrap_infallible().into()
254 }
255
256 #[inline(always)]
257 pub fn is_empty(&self) -> bool {
258 self.len() == 0
259 }
260
261 #[inline(always)]
267 pub fn copy_into_slice(&self, slice: &mut [u8]) {
268 let env = self.env();
269 if self.len() as usize != slice.len() {
270 sdk_panic!("String::copy_into_slice with mismatched slice length")
271 }
272 env.string_copy_to_slice(self.to_object(), Val::U32_ZERO, slice)
273 .unwrap_optimized();
274 }
275}
276
277#[cfg(test)]
278mod test {
279 use super::*;
280 use crate::IntoVal;
281
282 #[test]
283 fn string_from_and_to_slices() {
284 let env = Env::default();
285
286 let msg = "a message";
287 let s = String::from_str(&env, msg);
288 let mut out = [0u8; 9];
289 s.copy_into_slice(&mut out);
290 assert_eq!(msg.as_bytes(), out)
291 }
292
293 #[test]
294 fn string_from_and_to_bytes() {
295 let env = Env::default();
296
297 let msg = b"a message";
298 let s = String::from_bytes(&env, msg);
299 let mut out = [0u8; 9];
300 s.copy_into_slice(&mut out);
301 assert_eq!(msg, &out)
302 }
303
304 #[test]
305 #[should_panic]
306 fn string_to_short_slice() {
307 let env = Env::default();
308 let msg = "a message";
309 let s = String::from_str(&env, msg);
310 let mut out = [0u8; 8];
311 s.copy_into_slice(&mut out);
312 }
313
314 #[test]
315 #[should_panic]
316 fn string_to_long_slice() {
317 let env = Env::default();
318 let msg = "a message";
319 let s = String::from_str(&env, msg);
320 let mut out = [0u8; 10];
321 s.copy_into_slice(&mut out);
322 }
323
324 #[test]
325 fn string_to_val() {
326 let env = Env::default();
327
328 let s = String::from_str(&env, "abcdef");
329 let val: Val = s.clone().into_val(&env);
330 let rt: String = val.into_val(&env);
331
332 assert_eq!(s, rt);
333 }
334
335 #[test]
336 fn ref_string_to_val() {
337 let env = Env::default();
338
339 let s = String::from_str(&env, "abcdef");
340 let val: Val = (&s).into_val(&env);
341 let rt: String = val.into_val(&env);
342
343 assert_eq!(s, rt);
344 }
345
346 #[test]
347 fn double_ref_string_to_val() {
348 let env = Env::default();
349
350 let s = String::from_str(&env, "abcdef");
351 let val: Val = (&&s).into_val(&env);
352 let rt: String = val.into_val(&env);
353
354 assert_eq!(s, rt);
355 }
356}