wasm_ast/model/values.rs
1//! Model for values in the WebAssembly syntax.
2
3/// Names are sequences of characters, which are scalar values as defined by Unicode (Section 2.4).
4/// Due to the limitations of the binary format,
5/// the length of a name is bounded by the length of its UTF-8 encoding.
6///
7/// See <https://webassembly.github.io/spec/core/syntax/values.html#names>
8///
9/// # Examples
10/// ```rust
11/// use wasm_ast::Name;
12///
13/// let text = "test";
14/// let name = Name::new(String::from(text));
15///
16/// assert_eq!(name, Name::from(text));
17/// assert_eq!(name, Name::from(text.to_string()));
18/// assert_eq!(name.as_bytes(), text.as_bytes());
19/// assert_eq!(name.len(), text.len());
20/// assert_eq!(name.is_empty(), false);
21/// ```
22#[derive(Clone, Debug, Eq, PartialEq)]
23pub struct Name {
24 value: String,
25}
26
27impl Name {
28 /// Creates a new name with the given Unicode text.
29 pub fn new(value: String) -> Self {
30 Name { value }
31 }
32
33 /// Returns a byte slice of this `Name`’s contents.
34 pub fn as_bytes(&self) -> &[u8] {
35 self.value.as_bytes()
36 }
37
38 /// Returns the length of this `Name`, in bytes, not chars or graphemes.
39 /// In other words, it may not be what a human considers the length of the name.
40 pub fn len(&self) -> usize {
41 self.value.len()
42 }
43
44 /// Returns true if this `Name` has a length of zero, false otherwise.
45 pub fn is_empty(&self) -> bool {
46 self.value.is_empty()
47 }
48}
49
50impl From<&str> for Name {
51 fn from(name: &str) -> Self {
52 Name {
53 value: name.to_string(),
54 }
55 }
56}
57
58impl From<String> for Name {
59 fn from(name: String) -> Self {
60 Name { value: name }
61 }
62}