Skip to main content

rune/modules/
string.rs

1//! Strings.
2
3use core::char;
4use core::cmp::Ordering;
5use core::num::{ParseFloatError, ParseIntError};
6
7use crate as rune;
8use crate::alloc;
9use crate::alloc::fmt::TryWrite;
10use crate::alloc::prelude::*;
11use crate::alloc::string::FromUtf8Error;
12use crate::compile::Named;
13use crate::runtime::{
14    Bytes, Dismantle, Formatter, FromValue, Function, Handover, Hasher, Inline, MaybeTypeOf, Range,
15    RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive, Ref, Repr, ToValue, TypeOf,
16    Value, VmError, VmErrorKind,
17};
18use crate::{Any, ContextError, Module, TypeHash};
19
20/// Strings.
21///
22/// Strings in Rune are declared with the literal `"string"` syntax, but can also be
23/// interacted with through the fundamental [`String`] type.
24///
25/// ```rune
26/// let string1 = "Hello";
27/// let string2 = String::new();
28/// string2.push_str("Hello");
29///
30/// assert_eq!(string1, string2);
31/// ```
32#[rune::module(::std::string)]
33pub fn module() -> Result<Module, ContextError> {
34    let mut m = Module::from_meta(self::module__meta)?;
35
36    m.ty::<String>()?;
37
38    m.function_meta(string_from)?;
39    m.function_meta(string_from_str)?;
40    m.function_meta(string_new)?;
41    m.function_meta(string_with_capacity)?;
42    m.function_meta(len)?;
43    m.function_meta(starts_with)?;
44    m.function_meta(ends_with)?;
45    m.function_meta(capacity)?;
46    m.function_meta(clear)?;
47    m.function_meta(contains)?;
48    m.function_meta(push)?;
49    m.function_meta(push_str)?;
50    m.function_meta(reserve)?;
51    m.function_meta(reserve_exact)?;
52    m.function_meta(from_utf8)?;
53    m.function_meta(as_bytes)?;
54    m.function_meta(into_bytes)?;
55    m.function_meta(shrink_to_fit)?;
56    m.function_meta(char_at)?;
57    m.function_meta(split)?;
58    m.function_meta(split_once)?;
59    m.associated_function("split_str", __rune_fn__split)?;
60    m.function_meta(trim)?;
61    m.function_meta(trim_end)?;
62    m.function_meta(replace)?;
63    m.function_meta(is_empty)?;
64    m.function_meta(chars)?;
65    m.function_meta(get__meta)?;
66    m.function_meta(parse_int)?;
67    m.function_meta(parse_float)?;
68    m.function_meta(parse_char)?;
69    m.function_meta(to_lowercase)?;
70    m.function_meta(to_uppercase)?;
71
72    m.function_meta(add)?;
73    m.function_meta(add_assign)?;
74    m.function_meta(index_get)?;
75
76    m.function_meta(clone__meta)?;
77    m.implement_trait::<String>(rune::item!(::std::clone::Clone))?;
78
79    m.function_meta(partial_eq__meta)?;
80    m.implement_trait::<String>(rune::item!(::std::cmp::PartialEq))?;
81
82    m.function_meta(eq__meta)?;
83    m.implement_trait::<String>(rune::item!(::std::cmp::Eq))?;
84
85    m.function_meta(partial_cmp__meta)?;
86    m.implement_trait::<String>(rune::item!(::std::cmp::PartialOrd))?;
87
88    m.function_meta(cmp__meta)?;
89    m.implement_trait::<String>(rune::item!(::std::cmp::Ord))?;
90
91    m.function_meta(hash__meta)?;
92
93    m.function_meta(display_fmt__meta)?;
94    m.function_meta(debug_fmt__meta)?;
95
96    m.ty::<Chars>()?;
97    m.function_meta(Chars::next__meta)?;
98    m.function_meta(Chars::next_back__meta)?;
99    m.implement_trait::<Chars>(rune::item!(::std::iter::Iterator))?;
100    m.implement_trait::<Chars>(rune::item!(::std::iter::DoubleEndedIterator))?;
101
102    macro_rules! split {
103        ($ty:ty) => {
104            m.ty::<Split<$ty>>()?;
105            m.function_meta(Split::<$ty>::next__meta)?;
106            m.implement_trait::<Split<$ty>>(rune::item!(::std::iter::Iterator))?;
107        };
108    }
109
110    split!(Function);
111    split!(String);
112    split!(char);
113    Ok(m)
114}
115
116/// Converts a vector of bytes to a [`String`].
117///
118/// A string ([`String`]) is made of bytes (`u8`), and a vector of bytes
119/// ([`Vec<u8>`]) is made of bytes, so this function converts between the two.
120/// Not all byte slices are valid [`String`]s, however: [`String`] requires that it
121/// is valid UTF-8. `from_utf8()` checks to ensure that the bytes are valid
122/// UTF-8, and then does the conversion.
123///
124/// If you are sure that the byte slice is valid UTF-8, and you don't want to
125/// incur the overhead of the validity check, there is an unsafe version of this
126/// function, `from_utf8_unchecked`, which has the same behavior but skips the
127/// check.
128///
129/// The inverse of this method is [`into_bytes`].
130///
131/// # Errors
132///
133/// Returns [`Err`] if the slice is not UTF-8 with a description as to why the
134/// provided bytes are not UTF-8. The vector you moved in is also included.
135///
136/// # Examples
137///
138/// Basic usage:
139///
140/// ```rune
141/// // some bytes, in a vector
142/// let sparkle_heart = Bytes::from_vec([240u8, 159u8, 146u8, 150u8]);
143///
144/// // We know these bytes are valid, so we'll use `unwrap()`.
145/// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
146///
147/// assert_eq!("💖", sparkle_heart);
148/// ```
149///
150/// Incorrect bytes:
151///
152/// ```rune
153/// // some invalid bytes, in a vector
154/// let sparkle_heart = Bytes::from_vec([0u8, 159u8, 146u8, 150u8]);
155///
156/// assert!(String::from_utf8(sparkle_heart).is_err());
157/// ```
158///
159/// See the docs for `FromUtf8Error` for more details on what you can do with
160/// this error.
161///
162/// [`Vec<u8>`]: crate::vec::Vec "Vec"
163/// [`&str`]: prim@str "&str"
164/// [`into_bytes`]: String::into_bytes
165#[rune::function(free, path = String::from_utf8)]
166fn from_utf8(bytes: &[u8]) -> Result<Result<String, FromUtf8Error>, VmError> {
167    let vec = Vec::try_from(bytes)?;
168    Ok(String::from_utf8(vec))
169}
170
171/// Returns a byte slice of this [`String`]'s contents.
172///
173/// The inverse of this method is [`from_utf8`].
174///
175/// [`from_utf8`]: String::from_utf8
176///
177/// # Examples
178///
179/// Basic usage:
180///
181/// ```rune
182/// let s = "hello";
183/// assert_eq!(b"hello", s.as_bytes());
184/// assert!(is_readable(s));
185/// ```
186#[rune::function(instance)]
187fn as_bytes(s: &str) -> Result<Bytes, VmError> {
188    Ok(Bytes::from_vec(Vec::try_from(s.as_bytes())?))
189}
190
191/// Constructs a string from another string.
192///
193/// # Examples
194///
195/// Basic usage:
196///
197/// ```rune
198/// let s = String::from("hello");
199/// assert_eq!(s, "hello");
200/// ```
201#[rune::function(free, path = String::from)]
202fn string_from(value: &str) -> Result<String, VmError> {
203    Ok(String::try_from(value)?)
204}
205
206#[rune::function(free, path = String::from_str, deprecated = "Use String::from instead")]
207fn string_from_str(value: &str) -> Result<String, VmError> {
208    Ok(String::try_from(value)?)
209}
210
211/// Creates a new empty [`String`].
212///
213/// Given that the [`String`] is empty, this will not allocate any initial buffer.
214/// While that means that this initial operation is very inexpensive, it may
215/// cause excessive allocation later when you add data. If you have an idea of
216/// how much data the [`String`] will hold, consider the [`with_capacity`] method
217/// to prevent excessive re-allocation.
218///
219/// [`with_capacity`]: String::with_capacity
220///
221/// # Examples
222///
223/// Basic usage:
224///
225/// ```rune
226/// let s = String::new();
227/// ```
228#[rune::function(free, path = String::new)]
229fn string_new() -> String {
230    String::new()
231}
232
233/// Creates a new empty [`String`] with at least the specified capacity.
234///
235/// [`String`]s have an internal buffer to hold their data. The capacity is the
236/// length of that buffer, and can be queried with the [`capacity`] method. This
237/// method creates an empty [`String`], but one with an initial buffer that can
238/// hold at least `capacity` bytes. This is useful when you may be appending a
239/// bunch of data to the [`String`], reducing the number of reallocations it needs
240/// to do.
241///
242/// [`capacity`]: String::capacity
243///
244/// If the given capacity is `0`, no allocation will occur, and this method is
245/// identical to the [`new`] method.
246///
247/// [`new`]: String::new
248///
249/// # Examples
250///
251/// Basic usage:
252///
253/// ```rune
254/// let s = String::with_capacity(10);
255///
256/// // The String contains no chars, even though it has capacity for more
257/// assert_eq!(s.len(), 0);
258///
259/// // These are all done without reallocating...
260/// let cap = s.capacity();
261///
262/// for _ in 0..10 {
263///     s.push('a');
264/// }
265///
266/// assert_eq!(s.capacity(), cap);
267///
268/// // ...but this may make the string reallocate
269/// s.push('a');
270/// ```
271#[rune::function(free, path = String::with_capacity)]
272fn string_with_capacity(capacity: usize) -> Result<String, VmError> {
273    Ok(String::try_with_capacity(capacity)?)
274}
275
276/// Returns the length of `self`.
277///
278/// This length is in bytes, not [`char`]s or graphemes. In other words, it
279/// might not be what a human considers the length of the string.
280///
281/// [`char`]: prim@char
282///
283/// # Examples
284///
285/// Basic usage:
286///
287/// ```rune
288/// let len = "foo".len();
289/// assert_eq!(3, len);
290///
291/// assert_eq!("ƒoo".len(), 4); // fancy f!
292/// assert_eq!("ƒoo".chars().count(), 3);
293/// ```
294#[rune::function(instance)]
295fn len(this: &str) -> usize {
296    this.len()
297}
298
299/// Returns `true` if the given pattern matches a prefix of this string slice.
300///
301/// Returns `false` if it does not.
302///
303/// The pattern can be a `&str`, [`char`], a slice of [`char`]s, or a function
304/// or closure that determines if a character matches.
305///
306/// [`char`]: prim@char
307///
308/// # Examples
309///
310/// Basic usage:
311///
312/// ```rune
313/// let bananas = "bananas";
314///
315/// assert!(bananas.starts_with("bana"));
316/// assert!(!bananas.starts_with("nana"));
317/// ```
318#[rune::function(instance)]
319fn starts_with(this: &str, other: &str) -> bool {
320    this.starts_with(other)
321}
322
323/// Returns `true` if the given pattern matches a suffix of this string slice.
324///
325/// Returns `false` if it does not.
326///
327/// The pattern can be a `&str`, [`char`], a slice of [`char`]s, or a function
328/// or closure that determines if a character matches.
329///
330/// [`char`]: prim@char
331///
332/// # Examples
333///
334/// Basic usage:
335///
336/// ```rune
337/// let bananas = "bananas";
338///
339/// assert!(bananas.ends_with("anas"));
340/// assert!(!bananas.ends_with("nana"));
341/// ```
342#[rune::function(instance)]
343fn ends_with(this: &str, other: &str) -> bool {
344    this.ends_with(other)
345}
346
347/// Returns this [`String`]'s capacity, in bytes.
348///
349/// # Examples
350///
351/// Basic usage:
352///
353/// ```rune
354/// let s = String::with_capacity(10);
355///
356/// assert!(s.capacity() >= 10);
357/// ```
358#[rune::function(instance)]
359fn capacity(this: &String) -> usize {
360    this.capacity()
361}
362
363/// Truncates this [`String`], removing all contents.
364///
365/// While this means the [`String`] will have a length of zero, it does not touch
366/// its capacity.
367///
368/// # Examples
369///
370/// Basic usage:
371///
372/// ```rune
373/// let s = "foo";
374///
375/// s.clear();
376///
377/// assert!(s.is_empty());
378/// assert_eq!(0, s.len());
379/// assert_eq!(3, s.capacity());
380/// ```
381#[rune::function(instance)]
382fn clear(this: &mut String) {
383    this.clear();
384}
385
386/// Returns `true` if the given pattern matches a sub-slice of this string
387/// slice.
388///
389/// Returns `false` if it does not.
390///
391/// The pattern can be a [`String`], [`char`], or a function or closure that
392/// determines if a character matches.
393///
394/// [`char`]: prim@char
395///
396/// # Examples
397///
398/// Basic usage:
399///
400/// ```rune
401/// let bananas = "bananas";
402///
403/// assert!(bananas.contains("nana"));
404/// assert!(!bananas.contains("apples"));
405/// ```
406#[rune::function(instance)]
407fn contains(this: &str, other: &str) -> bool {
408    this.contains(other)
409}
410
411/// Appends the given [`char`] to the end of this [`String`].
412///
413/// # Examples
414///
415/// Basic usage:
416///
417/// ```rune
418/// let s = "abc";
419///
420/// s.push('1');
421/// s.push('2');
422/// s.push('3');
423///
424/// assert_eq!("abc123", s);
425/// ```
426#[rune::function(instance)]
427fn push(this: &mut String, c: char) -> Result<(), VmError> {
428    this.try_push(c)?;
429    Ok(())
430}
431
432/// Appends a given string slice onto the end of this [`String`].
433///
434/// # Examples
435///
436/// Basic usage:
437///
438/// ```rune
439/// let s = "foo";
440///
441/// s.push_str("bar");
442///
443/// assert_eq!("foobar", s);
444/// ```
445#[rune::function(instance)]
446fn push_str(this: &mut String, other: &str) -> Result<(), VmError> {
447    this.try_push_str(other)?;
448    Ok(())
449}
450
451/// Reserves capacity for at least `additional` bytes more than the current
452/// length. The allocator may reserve more space to speculatively avoid frequent
453/// allocations. After calling `reserve`, capacity will be greater than or equal
454/// to `self.len() + additional`. Does nothing if capacity is already
455/// sufficient.
456///
457/// # Panics
458///
459/// Panics if the new capacity overflows `usize`.
460///
461/// # Examples
462///
463/// Basic usage:
464///
465/// ```rune
466/// let s = String::new();
467///
468/// s.reserve(10);
469///
470/// assert!(s.capacity() >= 10);
471/// ```
472///
473/// This might not actually increase the capacity:
474///
475/// ```rune
476/// let s = String::with_capacity(10);
477/// s.push('a');
478/// s.push('b');
479///
480/// // s now has a length of 2 and a capacity of at least 10
481/// let capacity = s.capacity();
482/// assert_eq!(2, s.len());
483/// assert!(capacity >= 10);
484///
485/// // Since we already have at least an extra 8 capacity, calling this...
486/// s.reserve(8);
487///
488/// // ... doesn't actually increase.
489/// assert_eq!(capacity, s.capacity());
490/// ```
491#[rune::function(instance)]
492fn reserve(this: &mut String, additional: usize) -> Result<(), VmError> {
493    this.try_reserve(additional)?;
494    Ok(())
495}
496
497/// Reserves the minimum capacity for at least `additional` bytes more than the
498/// current length. Unlike [`reserve`], this will not deliberately over-allocate
499/// to speculatively avoid frequent allocations. After calling `reserve_exact`,
500/// capacity will be greater than or equal to `self.len() + additional`. Does
501/// nothing if the capacity is already sufficient.
502///
503/// [`reserve`]: String::reserve
504///
505/// # Panics
506///
507/// Panics if the new capacity overflows `usize`.
508///
509/// # Examples
510///
511/// Basic usage:
512///
513/// ```rune
514/// let s = String::new();
515///
516/// s.reserve_exact(10);
517///
518/// assert!(s.capacity() >= 10);
519/// ```
520///
521/// This might not actually increase the capacity:
522///
523/// ```rune
524/// let s = String::with_capacity(10);
525/// s.push('a');
526/// s.push('b');
527///
528/// // s now has a length of 2 and a capacity of at least 10
529/// let capacity = s.capacity();
530/// assert_eq!(2, s.len());
531/// assert!(capacity >= 10);
532///
533/// // Since we already have at least an extra 8 capacity, calling this...
534/// s.reserve_exact(8);
535///
536/// // ... doesn't actually increase.
537/// assert_eq!(capacity, s.capacity());
538/// ```
539#[rune::function(instance)]
540fn reserve_exact(this: &mut String, additional: usize) -> alloc::Result<()> {
541    this.try_reserve_exact(additional)
542}
543
544/// Returns a byte slice of this [`String`]'s contents while moving the string.
545///
546/// The inverse of this method is [`from_utf8`].
547///
548/// [`from_utf8`]: String::from_utf8
549///
550/// # Examples
551///
552/// Basic usage:
553///
554/// ```rune
555/// let s = "hello";
556/// assert_eq!(b"hello", s.into_bytes());
557/// assert!(!is_readable(s));
558/// ```
559#[rune::function(instance)]
560fn into_bytes(s: String) -> Bytes {
561    Bytes::from_vec(s.into_bytes())
562}
563
564/// Checks that `index`-th byte is the first byte in a UTF-8 code point sequence
565/// or the end of the string.
566///
567/// The start and end of the string (when `index == self.len()`) are considered
568/// to be boundaries.
569///
570/// Returns `false` if `index` is greater than `self.len()`.
571///
572/// # Examples
573///
574/// ```rune
575/// let s = "Löwe 老虎 Léopard";
576/// assert!(s.is_char_boundary(0));
577/// // start of `老`
578/// assert!(s.is_char_boundary(6));
579/// assert!(s.is_char_boundary(s.len()));
580///
581/// // second byte of `ö`
582/// assert!(!s.is_char_boundary(2));
583///
584/// // third byte of `老`
585/// assert!(!s.is_char_boundary(8));
586/// ```
587#[rune::function(instance)]
588fn is_char_boundary(s: &str, index: usize) -> bool {
589    s.is_char_boundary(index)
590}
591
592/// Access the character at the given byte index.
593///
594/// Returns [`None`] if the index is out of bounds or not a character boundary.
595///
596/// # Examples
597///
598/// ```rune
599/// let s = "おはよう";
600/// assert_eq!(s.char_at(0), Some('お'));
601/// assert_eq!(s.char_at(1), None);
602/// assert_eq!(s.char_at(2), None);
603/// assert_eq!(s.char_at(3), Some('は'));
604/// ```
605#[rune::function(instance)]
606fn char_at(s: &str, index: usize) -> Option<char> {
607    if !s.is_char_boundary(index) {
608        return None;
609    }
610
611    s[index..].chars().next()
612}
613
614/// Clones the string and its underlying storage.
615///
616/// # Examples
617///
618/// Basic usage:
619///
620/// ```rune
621/// let a = "h";
622/// let b = a;
623/// b.push('i');
624///
625/// // `a` and `b` refer to the same underlying string.
626/// assert_eq!(a, b);
627///
628/// let c = b.clone();
629/// c.push('!');
630/// assert_ne!(a, c);
631/// ```
632#[rune::function(keep, instance, protocol = CLONE)]
633fn clone(this: &String) -> alloc::Result<String> {
634    this.try_clone()
635}
636
637/// Test two strings for partial equality.
638///
639/// # Examples
640///
641/// ```rune
642/// use std::ops::partial_eq;
643///
644/// assert_eq!(partial_eq("a", "a"), true);
645/// assert_eq!(partial_eq("a", "ab"), false);
646/// assert_eq!(partial_eq("ab", "a"), false);
647/// ```
648#[rune::function(keep, instance, protocol = PARTIAL_EQ)]
649#[inline]
650fn partial_eq(this: &str, rhs: &str) -> bool {
651    this.eq(rhs)
652}
653
654/// Test two strings for total equality.
655///
656/// # Examples
657///
658/// ```rune
659/// use std::ops::eq;
660///
661/// assert_eq!(eq("a", "a"), true);
662/// assert_eq!(eq("a", "ab"), false);
663/// assert_eq!(eq("ab", "a"), false);
664/// ```
665#[rune::function(keep, instance, protocol = EQ)]
666#[inline]
667fn eq(this: &str, rhs: &str) -> bool {
668    this.eq(rhs)
669}
670
671/// Perform a partial ordered comparison between two strings.
672///
673/// # Examples
674///
675/// ```rune
676/// assert!("a" < "ab");
677/// assert!("ab" > "a");
678/// assert!("a" == "a");
679/// ```
680///
681/// Using explicit functions:
682///
683/// ```rune
684/// use std::cmp::Ordering;
685/// use std::ops::partial_cmp;
686///
687/// assert_eq!(partial_cmp("a", "ab"), Some(Ordering::Less));
688/// assert_eq!(partial_cmp("ab", "a"), Some(Ordering::Greater));
689/// assert_eq!(partial_cmp("a", "a"), Some(Ordering::Equal));
690/// ```
691#[rune::function(keep, instance, protocol = PARTIAL_CMP)]
692#[inline]
693fn partial_cmp(this: &str, rhs: &str) -> Option<Ordering> {
694    this.partial_cmp(rhs)
695}
696
697/// Perform a totally ordered comparison between two strings.
698///
699/// # Examples
700///
701/// ```rune
702/// use std::cmp::Ordering;
703/// use std::ops::cmp;
704///
705/// assert_eq!(cmp("a", "ab"), Ordering::Less);
706/// assert_eq!(cmp("ab", "a"), Ordering::Greater);
707/// assert_eq!(cmp("a", "a"), Ordering::Equal);
708/// ```
709#[rune::function(keep, instance, protocol = CMP)]
710#[inline]
711fn cmp(this: &str, rhs: &str) -> Ordering {
712    this.cmp(rhs)
713}
714
715/// Hash the string.
716///
717/// # Examples
718///
719/// ```rune
720/// use std::ops::hash;
721///
722/// let a = "hello";
723/// let b = "hello";
724///
725/// assert_eq!(hash(a), hash(b));
726/// ```
727#[rune::function(keep, instance, protocol = HASH)]
728fn hash(this: &str, hasher: &mut Hasher) {
729    hasher.write_str(this);
730}
731
732/// Write a display representation of a string.
733///
734/// # Examples
735///
736/// ```rune
737/// println!("{}", "Hello");
738/// ```
739#[rune::function(keep, instance, protocol = DISPLAY_FMT)]
740#[inline]
741fn display_fmt(this: &str, f: &mut Formatter) -> alloc::Result<()> {
742    write!(f, "{this}")
743}
744
745/// Write a debug representation of a string.
746///
747/// # Examples
748///
749/// ```rune
750/// println!("{:?}", "Hello");
751/// ```
752#[rune::function(keep, instance, protocol = DEBUG_FMT)]
753#[inline]
754fn debug_fmt(this: &str, f: &mut Formatter) -> alloc::Result<()> {
755    write!(f, "{this:?}")
756}
757
758/// Shrinks the capacity of this [`String`] to match its length.
759///
760/// # Examples
761///
762/// Basic usage:
763///
764/// ```rune
765/// let s = "foo";
766///
767/// s.reserve(100);
768/// assert!(s.capacity() >= 100);
769///
770/// s.shrink_to_fit();
771/// assert_eq!(3, s.capacity());
772/// ```
773#[rune::function(instance)]
774fn shrink_to_fit(s: &mut String) -> alloc::Result<()> {
775    s.try_shrink_to_fit()
776}
777
778/// An iterator over substrings of this string slice, separated by
779/// characters matched by a pattern.
780///
781/// The pattern can be a `&str`, [`char`], a slice of [`char`]s, or a
782/// function or closure that determines if a character matches.
783///
784/// [`char`]: prim@char
785///
786/// # Iterator behavior
787///
788/// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
789/// allows a reverse search and forward/reverse search yields the same
790/// elements. This is true for, e.g., [`char`], but not for `&str`.
791///
792/// [`DoubleEndedIterator`]: std::iter::DoubleEndedIterator
793///
794/// If the pattern allows a reverse search but its results might differ
795/// from a forward search, the `rsplit` method can be used.
796///
797/// # Examples
798///
799/// Simple patterns:
800///
801/// ```rune
802/// let v = "Mary had a little lamb".split(' ').collect::<Vec>();
803/// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
804///
805/// let v = "".split('X').collect::<Vec>();
806/// assert_eq!(v, [""]);
807///
808/// let v = "lionXXtigerXleopard".split('X').collect::<Vec>();
809/// assert_eq!(v, ["lion", "", "tiger", "leopard"]);
810///
811/// let v = "lion::tiger::leopard".split("::").collect::<Vec>();
812/// assert_eq!(v, ["lion", "tiger", "leopard"]);
813///
814/// let v = "abc1def2ghi".split(char::is_numeric).collect::<Vec>();
815/// assert_eq!(v, ["abc", "def", "ghi"]);
816///
817/// let v = "lionXtigerXleopard".split(char::is_uppercase).collect::<Vec>();
818/// assert_eq!(v, ["lion", "tiger", "leopard"]);
819/// ```
820///
821/// A more complex pattern, using a closure:
822///
823/// ```rune
824/// let v = "abc1defXghi".split(|c| c == '1' || c == 'X').collect::<Vec>();
825/// assert_eq!(v, ["abc", "def", "ghi"]);
826/// ```
827///
828/// If a string contains multiple contiguous separators, you will end up
829/// with empty strings in the output:
830///
831/// ```rune
832/// let x = "||||a||b|c";
833/// let d = x.split('|').collect::<Vec>();
834///
835/// assert_eq!(d, ["", "", "", "", "a", "", "b", "c"]);
836/// ```
837///
838/// Contiguous separators are separated by the empty string.
839///
840/// ```rune
841/// let x = "(///)";
842/// let d = x.split('/').collect::<Vec>();
843///
844/// assert_eq!(d, ["(", "", "", ")"]);
845/// ```
846///
847/// Separators at the start or end of a string are neighbored
848/// by empty strings.
849///
850/// ```rune
851/// let d = "010".split("0").collect::<Vec>();
852/// assert_eq!(d, ["", "1", ""]);
853/// ```
854///
855/// When the empty string is used as a separator, it separates
856/// every character in the string, along with the beginning
857/// and end of the string.
858///
859/// ```rune
860/// let f = "rust".split("").collect::<Vec>();
861/// assert_eq!(f, ["", "r", "u", "s", "t", ""]);
862/// ```
863///
864/// Contiguous separators can lead to possibly surprising behavior
865/// when whitespace is used as the separator. This code is correct:
866///
867/// ```rune
868/// let x = "    a  b c";
869/// let d = x.split(' ').collect::<Vec>();
870///
871/// assert_eq!(d, ["", "", "", "", "a", "", "b", "c"]);
872/// ```
873///
874/// It does _not_ give you:
875///
876/// ```rune,ignore
877/// assert_eq!(d, ["a", "b", "c"]);
878/// ```
879///
880/// Use `split_whitespace` for this behavior.
881#[rune::function(instance, deprecated = "Use String::split instead")]
882fn split(this: Ref<str>, value: Value) -> Result<Value, VmError> {
883    match value.as_ref() {
884        Repr::Inline(Inline::Char(c)) => Ok(rune::to_value(Split::new(this, *c))?),
885        Repr::Inline(value) => Err(VmError::from([
886            VmErrorKind::expected::<String>(value.type_info()),
887            VmErrorKind::bad_argument(0),
888        ])),
889        Repr::Dynamic(value) => Err(VmError::from([
890            VmErrorKind::expected::<String>(value.type_info()),
891            VmErrorKind::bad_argument(0),
892        ])),
893        Repr::Any(value) => match value.type_hash() {
894            String::HASH => {
895                let s = value.borrow_ref::<String>()?;
896
897                let split = rune::to_value(Split::new(this, String::try_from(s.as_str())?))?;
898
899                Ok(split)
900            }
901            Function::HASH => {
902                let f = value.borrow_ref::<Function>()?;
903                let split = rune::to_value(Split::new(this, f.try_clone()?))?;
904                Ok(split)
905            }
906            _ => Err(VmError::from([
907                VmErrorKind::expected::<String>(value.type_info()),
908                VmErrorKind::bad_argument(0),
909            ])),
910        },
911    }
912}
913
914/// Splits the string on the first occurrence of the specified delimiter and
915/// returns prefix before delimiter and suffix after delimiter.
916///
917/// # Examples
918///
919/// ```rune
920/// assert_eq!("cfg".split_once('='), None);
921/// assert_eq!("cfg=".split_once('='), Some(("cfg", "")));
922/// assert_eq!("cfg=foo".split_once('='), Some(("cfg", "foo")));
923/// assert_eq!("cfg=foo=bar".split_once('='), Some(("cfg", "foo=bar")));
924/// ```
925#[rune::function(instance)]
926fn split_once(this: &str, value: Value) -> Result<Option<(String, String)>, VmError> {
927    let outcome = match value.as_ref() {
928        Repr::Inline(Inline::Char(pat)) => this.split_once(*pat),
929        Repr::Inline(value) => {
930            return Err(VmError::from([
931                VmErrorKind::expected::<String>(value.type_info()),
932                VmErrorKind::bad_argument(0),
933            ]));
934        }
935        Repr::Dynamic(value) => {
936            return Err(VmError::from([
937                VmErrorKind::expected::<String>(value.type_info()),
938                VmErrorKind::bad_argument(0),
939            ]));
940        }
941        Repr::Any(value) => match value.type_hash() {
942            String::HASH => {
943                let s = value.borrow_ref::<String>()?;
944                this.split_once(s.as_str())
945            }
946            Function::HASH => {
947                let f = value.borrow_ref::<Function>()?;
948                let mut err = None;
949
950                let outcome = this.split_once(|c: char| match f.call::<bool>((c,)) {
951                    Ok(b) => b,
952                    Err(e) => {
953                        if err.is_none() {
954                            err = Some(e);
955                        }
956
957                        false
958                    }
959                });
960
961                if let Some(e) = err.take() {
962                    return Err(e);
963                }
964
965                outcome
966            }
967            _ => {
968                return Err(VmError::from([
969                    VmErrorKind::expected::<String>(value.type_info()),
970                    VmErrorKind::bad_argument(0),
971                ]));
972            }
973        },
974    };
975
976    let Some((a, b)) = outcome else {
977        return Ok(None);
978    };
979
980    Ok(Some((a.try_to_owned()?, b.try_to_owned()?)))
981}
982
983/// Returns a string slice with leading and trailing whitespace removed.
984///
985/// 'Whitespace' is defined according to the terms of the Unicode Derived Core
986/// Property `White_Space`, which includes newlines.
987///
988/// # Examples
989///
990/// Basic usage:
991///
992/// ```rune
993/// let s = "\n Hello\tworld\t\n";
994///
995/// assert_eq!("Hello\tworld", s.trim());
996/// ```
997#[rune::function(instance)]
998fn trim(this: &str) -> alloc::Result<String> {
999    this.trim().try_to_owned()
1000}
1001
1002/// Returns a string slice with trailing whitespace removed.
1003///
1004/// 'Whitespace' is defined according to the terms of the Unicode Derived Core
1005/// Property `White_Space`, which includes newlines.
1006///
1007/// # Text directionality
1008///
1009/// A string is a sequence of bytes. `end` in this context means the last
1010/// position of that byte string; for a left-to-right language like English or
1011/// Russian, this will be right side, and for right-to-left languages like
1012/// Arabic or Hebrew, this will be the left side.
1013///
1014/// # Examples
1015///
1016/// Basic usage:
1017///
1018/// ```rune
1019/// let s = "\n Hello\tworld\t\n";
1020/// assert_eq!("\n Hello\tworld", s.trim_end());
1021/// ```
1022///
1023/// Directionality:
1024///
1025/// ```rune
1026/// let s = "  English  ";
1027/// assert!(Some('h') == s.trim_end().chars().rev().next());
1028///
1029/// let s = "  עברית  ";
1030/// assert!(Some('ת') == s.trim_end().chars().rev().next());
1031/// ```
1032#[rune::function(instance)]
1033fn trim_end(this: &str) -> alloc::Result<String> {
1034    this.trim_end().try_to_owned()
1035}
1036
1037/// Returns `true` if `self` has a length of zero bytes.
1038///
1039/// # Examples
1040///
1041/// Basic usage:
1042///
1043/// ```rune
1044/// let s = "";
1045/// assert!(s.is_empty());
1046///
1047/// let s = "not empty";
1048/// assert!(!s.is_empty());
1049/// ```
1050#[rune::function(instance)]
1051fn is_empty(this: &str) -> bool {
1052    this.is_empty()
1053}
1054
1055/// Replaces all matches of a pattern with another string.
1056///
1057/// `replace` creates a new [`String`], and copies the data from this string
1058/// slice into it. While doing so, it attempts to find matches of a pattern. If
1059/// it finds any, it replaces them with the replacement string slice.
1060///
1061/// # Examples
1062///
1063/// Basic usage:
1064///
1065/// ```rune
1066/// let s = "this is old";
1067///
1068/// assert_eq!("this is new", s.replace("old", "new"));
1069/// assert_eq!("than an old", s.replace("is", "an"));
1070/// ```
1071///
1072/// When the pattern doesn't match, it returns this string slice as [`String`]:
1073///
1074/// ```rune
1075/// let s = "this is old";
1076/// assert_eq!(s, s.replace("cookie monster", "little lamb"));
1077/// ```
1078#[rune::function(instance)]
1079fn replace(this: &str, from: &str, to: &str) -> alloc::Result<String> {
1080    alloc::str::replace(this, from, to)
1081}
1082
1083/// Returns an iterator over the [`char`]s of a string slice.
1084///
1085/// As a string slice consists of valid UTF-8, we can iterate through a string
1086/// slice by [`char`]. This method returns such an iterator.
1087///
1088/// It's important to remember that [`char`] represents a Unicode Scalar Value,
1089/// and might not match your idea of what a 'character' is. Iteration over
1090/// grapheme clusters may be what you actually want. This functionality is not
1091/// provided by Rust's standard library, check crates.io instead.
1092///
1093/// # Examples
1094///
1095/// Basic usage:
1096///
1097/// ```rune
1098/// let word = "goodbye";
1099///
1100/// let count = word.chars().count();
1101/// assert_eq!(7, count);
1102///
1103/// let chars = word.chars();
1104///
1105/// assert_eq!(Some('g'), chars.next());
1106/// assert_eq!(Some('o'), chars.next());
1107/// assert_eq!(Some('o'), chars.next());
1108/// assert_eq!(Some('d'), chars.next());
1109/// assert_eq!(Some('b'), chars.next());
1110/// assert_eq!(Some('y'), chars.next());
1111/// assert_eq!(Some('e'), chars.next());
1112///
1113/// assert_eq!(None, chars.next());
1114/// ```
1115///
1116/// Remember, [`char`]s might not match your intuition about characters:
1117///
1118/// [`char`]: prim@char
1119///
1120/// ```rune
1121/// let y = "y̆";
1122///
1123/// let chars = y.chars();
1124///
1125/// assert_eq!(Some('y'), chars.next()); // not 'y̆'
1126/// assert_eq!(Some('\u{0306}'), chars.next());
1127///
1128/// assert_eq!(None, chars.next());
1129/// ```
1130#[rune::function(instance)]
1131fn chars(s: Ref<str>) -> Chars {
1132    Chars::new(s)
1133}
1134
1135/// Returns a subslice of `str`.
1136///
1137/// This is the non-panicking alternative to indexing the `str`. Returns
1138/// [`None`] whenever equivalent indexing operation would panic.
1139///
1140/// # Examples
1141///
1142/// ```rune
1143/// let v = "🗻∈🌏";
1144///
1145/// assert_eq!(Some("🗻"), v.get(0..4));
1146///
1147/// // indices not on UTF-8 sequence boundaries
1148/// assert!(v.get(1..).is_none());
1149/// assert!(v.get(..8).is_none());
1150///
1151/// // out of bounds
1152/// assert!(v.get(..42).is_none());
1153/// ```
1154#[rune::function(keep, instance)]
1155fn get(this: &str, key: Value) -> Result<Option<String>, VmError> {
1156    use crate::runtime::TypeOf;
1157
1158    let slice = match key.as_any() {
1159        Some(value) => match value.type_hash() {
1160            RangeFrom::HASH => {
1161                let range = value.borrow_ref::<RangeFrom>()?;
1162                let start = range.start.as_usize()?;
1163                this.get(start..)
1164            }
1165            RangeFull::HASH => {
1166                _ = value.borrow_ref::<RangeFull>()?;
1167                this.get(..)
1168            }
1169            RangeInclusive::HASH => {
1170                let range = value.borrow_ref::<RangeInclusive>()?;
1171                let start = range.start.as_usize()?;
1172                let end = range.end.as_usize()?;
1173                this.get(start..=end)
1174            }
1175            RangeToInclusive::HASH => {
1176                let range = value.borrow_ref::<RangeToInclusive>()?;
1177                let end = range.end.as_usize()?;
1178                this.get(..=end)
1179            }
1180            RangeTo::HASH => {
1181                let range = value.borrow_ref::<RangeTo>()?;
1182                let end = range.end.as_usize()?;
1183                this.get(..end)
1184            }
1185            Range::HASH => {
1186                let range = value.borrow_ref::<Range>()?;
1187                let start = range.start.as_usize()?;
1188                let end = range.end.as_usize()?;
1189                this.get(start..end)
1190            }
1191            _ => {
1192                return Err(VmError::from(VmErrorKind::UnsupportedIndexGet {
1193                    target: String::type_info(),
1194                    index: value.type_info(),
1195                }))
1196            }
1197        },
1198        _ => {
1199            return Err(VmError::from(VmErrorKind::UnsupportedIndexGet {
1200                target: String::type_info(),
1201                index: key.type_info(),
1202            }))
1203        }
1204    };
1205
1206    let Some(slice) = slice else {
1207        return Ok(None);
1208    };
1209
1210    Ok(Some(slice.try_to_owned()?))
1211}
1212
1213/// The add operation for strings.
1214#[rune::function(instance, protocol = ADD)]
1215fn add(a: &str, b: &str) -> Result<String, VmError> {
1216    let mut string = String::try_with_capacity(a.len() + b.len())?;
1217    string.try_push_str(a)?;
1218    string.try_push_str(b)?;
1219    Ok(string)
1220}
1221
1222/// The add assign operation for strings.
1223#[rune::function(instance, protocol = ADD_ASSIGN)]
1224fn add_assign(this: &mut String, other: &str) -> Result<(), VmError> {
1225    this.try_push_str(other)?;
1226    Ok(())
1227}
1228
1229/// Get a specific string index.
1230#[rune::function(instance, protocol = INDEX_GET)]
1231fn index_get(s: &str, key: Value) -> Result<String, VmError> {
1232    match get(s, key)? {
1233        Some(slice) => Ok(slice),
1234        None => Err(VmError::panic("missing string slice")),
1235    }
1236}
1237
1238/// Parses this string into an integer.
1239///
1240/// # Errors
1241///
1242/// Will return [`Err`] if it's not possible to parse this string slice into an
1243/// integer.
1244///
1245/// # Examples
1246///
1247/// Basic usage
1248///
1249/// ```rune
1250/// let four = "4".parse::<i64>()?;
1251/// assert_eq!(4, four);
1252/// ```
1253#[rune::function(instance, path = parse::<i64>)]
1254fn parse_int(s: &str) -> Result<i64, ParseIntError> {
1255    str::parse::<i64>(s)
1256}
1257
1258/// Parses this string into a float.
1259///
1260/// # Errors
1261///
1262/// Will return [`Err`] if it's not possible to parse this string slice into an
1263/// float.
1264///
1265/// # Examples
1266///
1267/// Basic usage
1268///
1269/// ```rune
1270/// let pi = "3.1415".parse::<f64>()?;
1271/// assert_eq!(3.1415, pi);
1272/// ```
1273#[rune::function(instance, path = parse::<f64>)]
1274fn parse_float(s: &str) -> Result<f64, ParseFloatError> {
1275    str::parse::<f64>(s)
1276}
1277
1278/// Parses this string into a character.
1279///
1280/// # Errors
1281///
1282/// Will return [`Err`] if it's not possible to parse this string slice into an
1283/// integer.
1284///
1285/// # Examples
1286///
1287/// Basic usage
1288///
1289/// ```rune
1290/// let a = "a".parse::<char>()?;
1291/// assert_eq!('a', a);
1292/// ```
1293#[rune::function(instance, path = parse::<char>)]
1294fn parse_char(s: &str) -> Result<char, char::ParseCharError> {
1295    str::parse::<char>(s)
1296}
1297
1298/// Returns the lowercase equivalent of this string slice, as a new [`String`].
1299///
1300/// 'Lowercase' is defined according to the terms of the Unicode Derived Core Property
1301/// `Lowercase`.
1302///
1303/// Since some characters can expand into multiple characters when changing
1304/// the case, this function returns a [`String`] instead of modifying the
1305/// parameter in-place.
1306///
1307/// # Examples
1308///
1309/// Basic usage:
1310///
1311/// ```rune
1312/// let s = "HELLO";
1313///
1314/// assert_eq!("hello", s.to_lowercase());
1315/// ```
1316///
1317/// A tricky example, with sigma:
1318///
1319/// ```rune
1320/// let sigma = "Σ";
1321///
1322/// assert_eq!("σ", sigma.to_lowercase());
1323///
1324/// // but at the end of a word, it's ς, not σ:
1325/// let odysseus = "ὈΔΥΣΣΕΎΣ";
1326///
1327/// assert_eq!("ὀδυσσεύς", odysseus.to_lowercase());
1328/// ```
1329///
1330/// Languages without case are not changed:
1331///
1332/// ```rune
1333/// let new_year = "农历新年";
1334///
1335/// assert_eq!(new_year, new_year.to_lowercase());
1336/// ```
1337#[rune::function(instance)]
1338fn to_lowercase(s: &str) -> Result<String, VmError> {
1339    let mut lowercase = String::try_with_capacity(s.len())?;
1340
1341    for (i, c) in s.char_indices() {
1342        // Inlined code to from std::str to handle upper-case sigma,
1343        // since it is the only Unicode character that is context-dependent
1344        // See https://github.com/rust-lang/rust/issues/26035 for more context
1345        if c == 'Σ' {
1346            lowercase.try_push_str(map_uppercase_sigma(s, i))?;
1347        } else {
1348            lowercase.try_extend(c.to_lowercase())?;
1349        }
1350    }
1351
1352    return Ok(lowercase);
1353
1354    fn map_uppercase_sigma(from: &str, i: usize) -> &'static str {
1355        // See https://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G33992
1356        // for the definition of `Final_Sigma`.
1357        debug_assert!('Σ'.len_utf8() == 2);
1358        let is_word_final = case_ignorable_then_cased(from[..i].chars().rev())
1359            && !case_ignorable_then_cased(from[i + 2..].chars());
1360        if is_word_final {
1361            "ς"
1362        } else {
1363            "σ"
1364        }
1365    }
1366
1367    fn case_ignorable_then_cased<I: core::iter::Iterator<Item = char>>(mut iter: I) -> bool {
1368        match iter.find(|&c| !unicode::case_ignorable::lookup(c)) {
1369            Some(c) => unicode::cased::lookup(c),
1370            None => false,
1371        }
1372    }
1373}
1374
1375/// Returns the uppercase equivalent of this string slice, as a new [`String`].
1376///
1377/// 'Uppercase' is defined according to the terms of the Unicode Derived Core Property
1378/// `Uppercase`.
1379///
1380/// Since some characters can expand into multiple characters when changing
1381/// the case, this function returns a [`String`] instead of modifying the
1382/// parameter in-place.
1383///
1384/// # Examples
1385///
1386/// Basic usage:
1387///
1388/// ```rune
1389/// let s = "hello";
1390///
1391/// assert_eq!("HELLO", s.to_uppercase());
1392/// ```
1393///
1394/// Scripts without case are not changed:
1395///
1396/// ```rune
1397/// let new_year = "农历新年";
1398///
1399/// assert_eq!(new_year, new_year.to_uppercase());
1400/// ```
1401///
1402/// One character can become multiple:
1403/// ```rune
1404/// let s = "tschüß";
1405///
1406/// assert_eq!("TSCHÜSS", s.to_uppercase());
1407/// ```
1408#[rune::function(instance)]
1409fn to_uppercase(s: &str) -> Result<String, VmError> {
1410    let mut uppercase = String::try_with_capacity(s.len())?;
1411    uppercase.try_extend(s.chars().flat_map(|c| c.to_uppercase()))?;
1412    Ok(uppercase)
1413}
1414
1415#[derive(Any)]
1416#[rune(item = ::std::string)]
1417struct Chars {
1418    string: Ref<str>,
1419    start: usize,
1420    end: usize,
1421}
1422
1423impl Chars {
1424    fn new(string: Ref<str>) -> Self {
1425        let end = string.len();
1426        Self {
1427            string,
1428            start: 0,
1429            end,
1430        }
1431    }
1432
1433    #[rune::function(keep, protocol = NEXT)]
1434    fn next(&mut self) -> Option<char> {
1435        let string = self.string.get(self.start..self.end)?;
1436        let c = string.chars().next()?;
1437        self.start += c.len_utf8();
1438        Some(c)
1439    }
1440
1441    #[rune::function(keep, protocol = NEXT_BACK)]
1442    fn next_back(&mut self) -> Option<char> {
1443        let string = self.string.get(self.start..self.end)?;
1444        let c = string.chars().next_back()?;
1445        self.end -= c.len_utf8();
1446        Some(c)
1447    }
1448}
1449
1450pub(crate) trait Pattern:
1451    'static + TryClone + Named + FromValue + ToValue + MaybeTypeOf + TypeOf
1452{
1453    fn test(&self, tail: &str) -> Result<(bool, usize), VmError>;
1454
1455    fn is_empty(&self) -> bool;
1456
1457    /// Hand over the values the pattern is made of, if it is made of any.
1458    ///
1459    /// A pattern which is a function carries what the closure captured, and a
1460    /// script can nest one split inside the next by capturing it, so what a
1461    /// pattern holds has to be handed over rather than dropped in place.
1462    fn dismantle(&mut self, _: &mut Handover<'_>) {}
1463}
1464
1465impl Pattern for String {
1466    fn test(&self, tail: &str) -> Result<(bool, usize), VmError> {
1467        if tail.starts_with(self.as_str()) {
1468            Ok((true, self.len()))
1469        } else {
1470            let Some(c) = tail.chars().next() else {
1471                return Ok((false, 0));
1472            };
1473
1474            Ok((false, c.len_utf8()))
1475        }
1476    }
1477
1478    #[inline]
1479    fn is_empty(&self) -> bool {
1480        String::is_empty(self)
1481    }
1482}
1483
1484impl Pattern for char {
1485    fn test(&self, tail: &str) -> Result<(bool, usize), VmError> {
1486        let Some(c) = tail.chars().next() else {
1487            return Ok((false, 0));
1488        };
1489
1490        Ok((c == *self, c.len_utf8()))
1491    }
1492
1493    #[inline]
1494    fn is_empty(&self) -> bool {
1495        false
1496    }
1497}
1498
1499impl Pattern for Function {
1500    fn dismantle(&mut self, out: &mut Handover<'_>) {
1501        Dismantle::dismantle(self, out)
1502    }
1503
1504    fn test(&self, tail: &str) -> Result<(bool, usize), VmError> {
1505        let Some(c) = tail.chars().next() else {
1506            return Ok((false, 0));
1507        };
1508
1509        Ok((self.call((c,))?, c.len_utf8()))
1510    }
1511
1512    #[inline]
1513    fn is_empty(&self) -> bool {
1514        false
1515    }
1516}
1517
1518#[derive(Any)]
1519#[rune(item = ::std::string, dismantle)]
1520pub(crate) struct Split<T>
1521where
1522    T: Pattern,
1523{
1524    string: Option<Ref<str>>,
1525    pattern: T,
1526    from: usize,
1527    to: usize,
1528}
1529
1530impl<T> Split<T>
1531where
1532    T: Pattern,
1533{
1534    fn new(string: Ref<str>, pattern: T) -> Self {
1535        Self {
1536            string: Some(string),
1537            pattern,
1538            from: 0,
1539            to: 0,
1540        }
1541    }
1542
1543    #[rune::function(keep, protocol = NEXT)]
1544    fn next(&mut self) -> Result<Option<String>, VmError> {
1545        let Some(string) = &self.string else {
1546            return Ok(None);
1547        };
1548
1549        if self.from == string.len() && self.from == self.to {
1550            self.string = None;
1551            let out = "".try_to_owned()?;
1552            return Ok(Some(out));
1553        }
1554
1555        while self.to < string.len() {
1556            let Some(tail) = string.get(self.to..) else {
1557                return Ok(None);
1558            };
1559
1560            let (m, len) = self.pattern.test(tail)?;
1561
1562            if m {
1563                let head = string.get(self.from..self.to).unwrap_or_default();
1564                let out = head.try_to_owned()?;
1565
1566                if len == 0 {
1567                    self.from = self.to;
1568                    self.to += tail.chars().next().map_or(0, |c| c.len_utf8());
1569                } else {
1570                    self.to += len;
1571                    self.from = self.to;
1572                }
1573
1574                return Ok(Some(out));
1575            } else {
1576                self.to += len;
1577            }
1578        }
1579
1580        let tail = string.get(self.from..self.to).unwrap_or_default();
1581        self.from = self.to;
1582        let out = tail.try_to_owned()?;
1583
1584        if !self.pattern.is_empty() {
1585            self.string = None;
1586        }
1587
1588        Ok(Some(out))
1589    }
1590
1591    #[rune::function(keep, protocol = INTO_ITER)]
1592    fn into_iter(self) -> Self {
1593        self
1594    }
1595}
1596
1597// Inlined code from core::unicode, since using it directly is marked as using an
1598// unstable library feature
1599mod unicode {
1600    fn decode_prefix_sum(short_offset_run_header: u32) -> u32 {
1601        short_offset_run_header & ((1 << 21) - 1)
1602    }
1603
1604    fn decode_length(short_offset_run_header: u32) -> usize {
1605        (short_offset_run_header >> 21) as usize
1606    }
1607
1608    #[inline(always)]
1609    fn skip_search<const SOR: usize, const OFFSETS: usize>(
1610        needle: u32,
1611        short_offset_runs: &[u32; SOR],
1612        offsets: &[u8; OFFSETS],
1613    ) -> bool {
1614        // Note that this *cannot* be past the end of the array, as the last
1615        // element is greater than std::char::MAX (the largest possible needle).
1616        //
1617        // So, we cannot have found it (i.e. Ok(idx) + 1 != length) and the correct
1618        // location cannot be past it, so Err(idx) != length either.
1619        //
1620        // This means that we can avoid bounds checking for the accesses below, too.
1621        let last_idx =
1622            match short_offset_runs.binary_search_by_key(&(needle << 11), |header| header << 11) {
1623                Ok(idx) => idx + 1,
1624                Err(idx) => idx,
1625            };
1626
1627        let mut offset_idx = decode_length(short_offset_runs[last_idx]);
1628        let length = if let Some(next) = short_offset_runs.get(last_idx + 1) {
1629            decode_length(*next) - offset_idx
1630        } else {
1631            offsets.len() - offset_idx
1632        };
1633        let prev = last_idx
1634            .checked_sub(1)
1635            .map(|prev| decode_prefix_sum(short_offset_runs[prev]))
1636            .unwrap_or(0);
1637
1638        let total = needle - prev;
1639        let mut prefix_sum = 0;
1640        for _ in 0..(length - 1) {
1641            let offset = offsets[offset_idx];
1642            prefix_sum += offset as u32;
1643            if prefix_sum > total {
1644                break;
1645            }
1646            offset_idx += 1;
1647        }
1648        offset_idx % 2 == 1
1649    }
1650
1651    #[rustfmt::skip]
1652    pub mod case_ignorable {
1653        static SHORT_OFFSET_RUNS: [u32; 35] = [
1654            688, 44045149, 572528402, 576724925, 807414908, 878718981, 903913493, 929080568, 933275148,
1655            937491230, 1138818560, 1147208189, 1210124160, 1222707713, 1235291428, 1260457643,
1656            1264654383, 1499535675, 1507925040, 1566646003, 1629566000, 1650551536, 1658941263,
1657            1671540720, 1688321181, 1700908800, 1709298023, 1717688832, 1738661888, 1763828398,
1658            1797383403, 1805773008, 1809970171, 1819148289, 1824457200,
1659        ];
1660        static OFFSETS: [u8; 875] = [
1661            39, 1, 6, 1, 11, 1, 35, 1, 1, 1, 71, 1, 4, 1, 1, 1, 4, 1, 2, 2, 0, 192, 4, 2, 4, 1, 9, 2,
1662            1, 1, 251, 7, 207, 1, 5, 1, 49, 45, 1, 1, 1, 2, 1, 2, 1, 1, 44, 1, 11, 6, 10, 11, 1, 1, 35,
1663            1, 10, 21, 16, 1, 101, 8, 1, 10, 1, 4, 33, 1, 1, 1, 30, 27, 91, 11, 58, 11, 4, 1, 2, 1, 24,
1664            24, 43, 3, 44, 1, 7, 2, 6, 8, 41, 58, 55, 1, 1, 1, 4, 8, 4, 1, 3, 7, 10, 2, 13, 1, 15, 1,
1665            58, 1, 4, 4, 8, 1, 20, 2, 26, 1, 2, 2, 57, 1, 4, 2, 4, 2, 2, 3, 3, 1, 30, 2, 3, 1, 11, 2,
1666            57, 1, 4, 5, 1, 2, 4, 1, 20, 2, 22, 6, 1, 1, 58, 1, 2, 1, 1, 4, 8, 1, 7, 2, 11, 2, 30, 1,
1667            61, 1, 12, 1, 50, 1, 3, 1, 55, 1, 1, 3, 5, 3, 1, 4, 7, 2, 11, 2, 29, 1, 58, 1, 2, 1, 6, 1,
1668            5, 2, 20, 2, 28, 2, 57, 2, 4, 4, 8, 1, 20, 2, 29, 1, 72, 1, 7, 3, 1, 1, 90, 1, 2, 7, 11, 9,
1669            98, 1, 2, 9, 9, 1, 1, 7, 73, 2, 27, 1, 1, 1, 1, 1, 55, 14, 1, 5, 1, 2, 5, 11, 1, 36, 9, 1,
1670            102, 4, 1, 6, 1, 2, 2, 2, 25, 2, 4, 3, 16, 4, 13, 1, 2, 2, 6, 1, 15, 1, 94, 1, 0, 3, 0, 3,
1671            29, 2, 30, 2, 30, 2, 64, 2, 1, 7, 8, 1, 2, 11, 3, 1, 5, 1, 45, 5, 51, 1, 65, 2, 34, 1, 118,
1672            3, 4, 2, 9, 1, 6, 3, 219, 2, 2, 1, 58, 1, 1, 7, 1, 1, 1, 1, 2, 8, 6, 10, 2, 1, 39, 1, 8, 31,
1673            49, 4, 48, 1, 1, 5, 1, 1, 5, 1, 40, 9, 12, 2, 32, 4, 2, 2, 1, 3, 56, 1, 1, 2, 3, 1, 1, 3,
1674            58, 8, 2, 2, 64, 6, 82, 3, 1, 13, 1, 7, 4, 1, 6, 1, 3, 2, 50, 63, 13, 1, 34, 101, 0, 1, 1,
1675            3, 11, 3, 13, 3, 13, 3, 13, 2, 12, 5, 8, 2, 10, 1, 2, 1, 2, 5, 49, 5, 1, 10, 1, 1, 13, 1,
1676            16, 13, 51, 33, 0, 2, 113, 3, 125, 1, 15, 1, 96, 32, 47, 1, 0, 1, 36, 4, 3, 5, 5, 1, 93, 6,
1677            93, 3, 0, 1, 0, 6, 0, 1, 98, 4, 1, 10, 1, 1, 28, 4, 80, 2, 14, 34, 78, 1, 23, 3, 103, 3, 3,
1678            2, 8, 1, 3, 1, 4, 1, 25, 2, 5, 1, 151, 2, 26, 18, 13, 1, 38, 8, 25, 11, 46, 3, 48, 1, 2, 4,
1679            2, 2, 17, 1, 21, 2, 66, 6, 2, 2, 2, 2, 12, 1, 8, 1, 35, 1, 11, 1, 51, 1, 1, 3, 2, 2, 5, 2,
1680            1, 1, 27, 1, 14, 2, 5, 2, 1, 1, 100, 5, 9, 3, 121, 1, 2, 1, 4, 1, 0, 1, 147, 17, 0, 16, 3,
1681            1, 12, 16, 34, 1, 2, 1, 169, 1, 7, 1, 6, 1, 11, 1, 35, 1, 1, 1, 47, 1, 45, 2, 67, 1, 21, 3,
1682            0, 1, 226, 1, 149, 5, 0, 6, 1, 42, 1, 9, 0, 3, 1, 2, 5, 4, 40, 3, 4, 1, 165, 2, 0, 4, 0, 2,
1683            80, 3, 70, 11, 49, 4, 123, 1, 54, 15, 41, 1, 2, 2, 10, 3, 49, 4, 2, 2, 2, 1, 4, 1, 10, 1,
1684            50, 3, 36, 5, 1, 8, 62, 1, 12, 2, 52, 9, 10, 4, 2, 1, 95, 3, 2, 1, 1, 2, 6, 1, 2, 1, 157, 1,
1685            3, 8, 21, 2, 57, 2, 3, 1, 37, 7, 3, 5, 195, 8, 2, 3, 1, 1, 23, 1, 84, 6, 1, 1, 4, 2, 1, 2,
1686            238, 4, 6, 2, 1, 2, 27, 2, 85, 8, 2, 1, 1, 2, 106, 1, 1, 1, 2, 6, 1, 1, 101, 3, 2, 4, 1, 5,
1687            0, 9, 1, 2, 0, 2, 1, 1, 4, 1, 144, 4, 2, 2, 4, 1, 32, 10, 40, 6, 2, 4, 8, 1, 9, 6, 2, 3, 46,
1688            13, 1, 2, 0, 7, 1, 6, 1, 1, 82, 22, 2, 7, 1, 2, 1, 2, 122, 6, 3, 1, 1, 2, 1, 7, 1, 1, 72, 2,
1689            3, 1, 1, 1, 0, 2, 11, 2, 52, 5, 5, 1, 1, 1, 0, 17, 6, 15, 0, 5, 59, 7, 9, 4, 0, 1, 63, 17,
1690            64, 2, 1, 2, 0, 4, 1, 7, 1, 2, 0, 2, 1, 4, 0, 46, 2, 23, 0, 3, 9, 16, 2, 7, 30, 4, 148, 3,
1691            0, 55, 4, 50, 8, 1, 14, 1, 22, 5, 1, 15, 0, 7, 1, 17, 2, 7, 1, 2, 1, 5, 5, 62, 33, 1, 160,
1692            14, 0, 1, 61, 4, 0, 5, 0, 7, 109, 8, 0, 5, 0, 1, 30, 96, 128, 240, 0,
1693        ];
1694        pub fn lookup(c: char) -> bool {
1695            super::skip_search(
1696                c as u32,
1697                &SHORT_OFFSET_RUNS,
1698                &OFFSETS,
1699            )
1700        }
1701    }
1702
1703    #[rustfmt::skip]
1704    pub mod cased {
1705        static SHORT_OFFSET_RUNS: [u32; 22] = [
1706            4256, 115348384, 136322176, 144711446, 163587254, 320875520, 325101120, 350268208,
1707            392231680, 404815649, 413205504, 421595008, 467733632, 484513952, 492924480, 497144832,
1708            501339814, 578936576, 627171376, 639756544, 643952944, 649261450,
1709        ];
1710        static OFFSETS: [u8; 315] = [
1711            65, 26, 6, 26, 47, 1, 10, 1, 4, 1, 5, 23, 1, 31, 1, 195, 1, 4, 4, 208, 1, 36, 7, 2, 30, 5,
1712            96, 1, 42, 4, 2, 2, 2, 4, 1, 1, 6, 1, 1, 3, 1, 1, 1, 20, 1, 83, 1, 139, 8, 166, 1, 38, 9,
1713            41, 0, 38, 1, 1, 5, 1, 2, 43, 1, 4, 0, 86, 2, 6, 0, 9, 7, 43, 2, 3, 64, 192, 64, 0, 2, 6, 2,
1714            38, 2, 6, 2, 8, 1, 1, 1, 1, 1, 1, 1, 31, 2, 53, 1, 7, 1, 1, 3, 3, 1, 7, 3, 4, 2, 6, 4, 13,
1715            5, 3, 1, 7, 116, 1, 13, 1, 16, 13, 101, 1, 4, 1, 2, 10, 1, 1, 3, 5, 6, 1, 1, 1, 1, 1, 1, 4,
1716            1, 6, 4, 1, 2, 4, 5, 5, 4, 1, 17, 32, 3, 2, 0, 52, 0, 229, 6, 4, 3, 2, 12, 38, 1, 1, 5, 1,
1717            0, 46, 18, 30, 132, 102, 3, 4, 1, 59, 5, 2, 1, 1, 1, 5, 24, 5, 1, 3, 0, 43, 1, 14, 6, 80, 0,
1718            7, 12, 5, 0, 26, 6, 26, 0, 80, 96, 36, 4, 36, 116, 11, 1, 15, 1, 7, 1, 2, 1, 11, 1, 15, 1,
1719            7, 1, 2, 0, 1, 2, 3, 1, 42, 1, 9, 0, 51, 13, 51, 0, 64, 0, 64, 0, 85, 1, 71, 1, 2, 2, 1, 2,
1720            2, 2, 4, 1, 12, 1, 1, 1, 7, 1, 65, 1, 4, 2, 8, 1, 7, 1, 28, 1, 4, 1, 5, 1, 1, 3, 7, 1, 0, 2,
1721            25, 1, 25, 1, 31, 1, 25, 1, 31, 1, 25, 1, 31, 1, 25, 1, 31, 1, 25, 1, 8, 0, 10, 1, 20, 6, 6,
1722            0, 62, 0, 68, 0, 26, 6, 26, 6, 26, 0,
1723        ];
1724        pub fn lookup(c: char) -> bool {
1725            super::skip_search(
1726                c as u32,
1727                &SHORT_OFFSET_RUNS,
1728                &OFFSETS,
1729            )
1730        }
1731    }
1732}
1733
1734/// A split carries the pattern it was handed, which is a value made of values
1735/// when it is a function, so it hands it over rather than being dropped in
1736/// place.
1737impl<T> Dismantle for Split<T>
1738where
1739    T: Pattern,
1740{
1741    fn dismantle(&mut self, out: &mut Handover<'_>) {
1742        Pattern::dismantle(&mut self.pattern, out)
1743    }
1744}