Skip to main content

nanvm_lib/vm/string/
partial_eq.rs

1use crate::vm::{IContainer, IVm, String};
2
3impl<A: IVm> PartialEq for String<A> {
4    fn eq(&self, other: &Self) -> bool {
5        self.0.items_eq(&other.0)
6    }
7}
8
9impl<A: IVm> String<A> {
10    /// Whether `self` is `s`, code unit by code unit against its UTF-16
11    /// encoding, without building a VM string from the literal โ€” the
12    /// question every built-in name lookup asks.
13    ///
14    /// An inherent method, not `PartialEq<str>`: a second `PartialEq`
15    /// impl would leave every `s == "x".into()` in the crate without a
16    /// target type for `into`.
17    pub(crate) fn is_str(&self, s: &str) -> bool {
18        self.clone().into_iter().eq(s.encode_utf16())
19    }
20}
21
22#[cfg(test)]
23mod tests {
24    use crate::{
25        naive::Naive,
26        vm::{String, ToString},
27    };
28
29    type A = Naive;
30
31    #[test]
32    fn is_str() {
33        let s: String<A> = "length".into();
34        assert!(s.is_str("length"));
35        assert!(!s.is_str("lengt"));
36        assert!(!s.is_str("lengths"));
37        assert!(!s.is_str(""));
38        let empty: String<A> = "".into();
39        assert!(empty.is_str(""));
40        assert!(!empty.is_str("a"));
41    }
42
43    /// The literal is compared as UTF-16, as the VM string holds it: a
44    /// character outside the BMP is its surrogate pair, and a lone
45    /// surrogate, which no `&str` spells, equals nothing.
46    #[test]
47    fn is_str_utf16() {
48        let pair: String<A> = "๐Ÿ˜€".into();
49        assert!(pair.is_str("๐Ÿ˜€"));
50        let lone: String<A> = [0xD83D].to_string();
51        assert!(!lone.is_str("๐Ÿ˜€"));
52        assert!(!lone.is_str("\u{FFFD}"));
53    }
54}