rune_core/item/
item.rs

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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
use core::fmt;

#[cfg(feature = "alloc")]
use crate::alloc::borrow::TryToOwned;
#[cfg(feature = "alloc")]
use crate::alloc::iter::IteratorExt;
#[cfg(feature = "alloc")]
use crate::alloc::{self, Vec};

#[cfg(feature = "alloc")]
use crate::item::Component;
use crate::item::{ComponentRef, IntoComponent, ItemBuf, Iter};

/// The reference to an [ItemBuf].
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
pub struct Item {
    content: [u8],
}

impl Item {
    /// Construct an [Item] corresponding to the root item.
    ///
    /// # Examples
    ///
    /// ```
    /// use rune::{Item, ItemBuf};
    ///
    /// assert_eq!(Item::new(), &*ItemBuf::new());
    /// ```
    #[inline]
    pub const fn new() -> &'static Self {
        // SAFETY: an empty slice is a valid bit pattern for the root.
        unsafe { Self::from_bytes(&[]) }
    }

    /// Construct an [Item] from an [ItemBuf].
    ///
    /// # Safety
    ///
    /// Caller must ensure that content has a valid [ItemBuf] representation.
    /// The easiest way to accomplish this is to use the `rune::item!` macro.
    ///
    /// # Examples
    ///
    /// ```
    /// use rune::{Item, ItemBuf};
    ///
    /// let item = ItemBuf::with_item(["foo", "bar"])?;
    ///
    /// // SAFETY: item is constructed from a valid buffer.
    /// let item = unsafe { Item::from_bytes(item.as_bytes()) };
    /// # Ok::<_, rune::alloc::Error>(())
    /// ```
    pub const unsafe fn from_bytes(content: &[u8]) -> &Self {
        &*(content as *const _ as *const _)
    }

    /// Return the underlying byte representation of the [Item].
    ///
    /// # Examples
    ///
    /// ```
    /// use rune::{Item, ItemBuf};
    ///
    /// assert_eq!(Item::new().as_bytes(), b"");
    ///
    /// let item = ItemBuf::with_item(["foo", "bar"])?;
    /// assert_eq!(item.as_bytes(), b"\x0d\0foo\x0d\0\x0d\0bar\x0d\0");
    /// # Ok::<_, rune::alloc::Error>(())
    /// ```
    #[inline]
    pub fn as_bytes(&self) -> &[u8] {
        &self.content
    }

    /// Get the crate corresponding to the item.
    ///
    /// # Examples
    ///
    /// ```
    /// use rune::ItemBuf;
    ///
    /// let item = ItemBuf::with_crate("std")?;
    /// assert_eq!(item.as_crate(), Some("std"));
    ///
    /// let item = ItemBuf::with_item(["local"])?;
    /// assert_eq!(item.as_crate(), None);
    /// # Ok::<_, rune::alloc::Error>(())
    /// ```
    pub fn as_crate(&self) -> Option<&str> {
        if let Some(ComponentRef::Crate(s)) = self.iter().next() {
            Some(s)
        } else {
            None
        }
    }

    /// Access the first component of this item.
    ///
    /// # Examples
    ///
    /// ```
    /// use rune::ItemBuf;
    /// use rune::item::ComponentRef;
    ///
    /// let item = ItemBuf::with_item(["foo", "bar"])?;
    /// assert_eq!(item.first(), Some(ComponentRef::Str("foo")));
    /// # Ok::<_, rune::alloc::Error>(())
    /// ```
    #[inline]
    pub fn first(&self) -> Option<ComponentRef<'_>> {
        self.iter().next()
    }

    /// Check if the item is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use rune::ItemBuf;
    ///
    /// let item = ItemBuf::new();
    /// assert!(item.is_empty());
    ///
    /// let item = ItemBuf::with_crate("std")?;
    /// assert!(!item.is_empty());
    /// # Ok::<_, rune::alloc::Error>(())
    /// ```
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.content.is_empty()
    }

    /// Construct a new vector from the current item.
    #[cfg(feature = "alloc")]
    pub fn as_vec(&self) -> alloc::Result<Vec<Component>> {
        self.iter()
            .map(ComponentRef::into_component)
            .try_collect::<Result<Vec<_>, _>>()?
    }

    /// If the item only contains one element, return that element.
    pub fn as_local(&self) -> Option<&str> {
        let mut it = self.iter();

        match it.next_back_str() {
            Some(last) if it.is_empty() => Some(last),
            _ => None,
        }
    }

    /// Return an owned and joined variant of this item.
    ///
    /// # Examples
    ///
    /// ```
    /// use rune::Item;
    /// use rune::item::ComponentRef;
    ///
    /// let item = Item::new();
    /// assert!(item.is_empty());
    ///
    /// let item2 = item.join(["hello", "world"])?;
    /// assert_eq!(item2.first(), Some(ComponentRef::Str("hello")));
    /// assert_eq!(item2.last(), Some(ComponentRef::Str("world")));
    /// # Ok::<(), rune::support::Error>(())
    /// ```
    pub fn join(&self, other: impl IntoIterator<Item: IntoComponent>) -> alloc::Result<ItemBuf> {
        let mut content = self.content.try_to_owned()?;

        for c in other {
            c.write_component(&mut content)?;
        }

        // SAFETY: construction through write_component ensures valid
        // construction of buffer.
        Ok(unsafe { ItemBuf::from_raw(content) })
    }

    /// Return an owned and extended variant of this item.
    ///
    /// # Examples
    ///
    /// ```
    /// use rune::Item;
    /// use rune::item::ComponentRef;
    ///
    /// let item = Item::new();
    /// assert!(item.is_empty());
    ///
    /// let item2 = item.extended("hello")?;
    /// assert_eq!(item2.first(), Some(ComponentRef::Str("hello")));
    /// # Ok::<(), rune::support::Error>(())
    /// ```
    pub fn extended<C>(&self, part: C) -> alloc::Result<ItemBuf>
    where
        C: IntoComponent,
    {
        let mut content = self.content.try_to_owned()?;
        part.write_component(&mut content)?;

        // SAFETY: construction through write_component ensures valid
        // construction of buffer.
        Ok(unsafe { ItemBuf::from_raw(content) })
    }

    /// Access the last component in the path.
    #[inline]
    pub fn last(&self) -> Option<ComponentRef<'_>> {
        self.iter().next_back()
    }

    /// Access the base name of the item if available.
    ///
    /// The base name is the last string component of the item.
    #[inline]
    pub fn base_name(&self) -> Option<&str> {
        self.iter().next_back()?.as_str()
    }

    /// An iterator over the [Component]s that constitute this item.
    ///
    /// # Examples
    ///
    /// ```
    /// use rune::ItemBuf;
    /// use rune::item::{ComponentRef, IntoComponent};
    ///
    /// let mut item = ItemBuf::new();
    ///
    /// item.push("start")?;
    /// item.push(ComponentRef::Id(1))?;
    /// item.push(ComponentRef::Id(2))?;
    /// item.push("middle")?;
    /// item.push(ComponentRef::Id(3))?;
    /// item.push("end")?;
    ///
    /// let mut it = item.iter();
    ///
    /// assert_eq!(it.next(), Some("start".as_component_ref()));
    /// assert_eq!(it.next(), Some(ComponentRef::Id(1)));
    /// assert_eq!(it.next(), Some(ComponentRef::Id(2)));
    /// assert_eq!(it.next(), Some("middle".as_component_ref()));
    /// assert_eq!(it.next(), Some(ComponentRef::Id(3)));
    /// assert_eq!(it.next(), Some("end".as_component_ref()));
    /// assert_eq!(it.next(), None);
    ///
    /// assert!(!item.is_empty());
    /// # Ok::<(), rune::support::Error>(())
    /// ```
    #[inline]
    pub fn iter(&self) -> Iter<'_> {
        Iter::new(&self.content)
    }

    /// Test if current item starts with another.
    #[inline]
    pub fn starts_with<U>(&self, other: U) -> bool
    where
        U: AsRef<Item>,
    {
        self.content.starts_with(&other.as_ref().content)
    }

    /// Test if current is immediate super of `other`.
    ///
    /// # Examples
    ///
    /// ```
    /// use rune::{Item, ItemBuf};
    ///
    /// assert!(Item::new().is_super_of(Item::new(), 1));
    /// assert!(!ItemBuf::with_item(["a"])?.is_super_of(Item::new(), 1));
    ///
    /// assert!(!ItemBuf::with_item(["a", "b"])?.is_super_of(ItemBuf::with_item(["a"])?, 1));
    /// assert!(ItemBuf::with_item(["a", "b"])?.is_super_of(ItemBuf::with_item(["a", "b"])?, 1));
    /// assert!(!ItemBuf::with_item(["a"])?.is_super_of(ItemBuf::with_item(["a", "b", "c"])?, 1));
    /// # Ok::<_, rune::alloc::Error>(())
    /// ```
    pub fn is_super_of<U>(&self, other: U, n: usize) -> bool
    where
        U: AsRef<Item>,
    {
        let other = other.as_ref();

        if self == other {
            return true;
        }

        let mut it = other.iter();

        for _ in 0..n {
            if it.next_back().is_none() {
                return false;
            }

            if self == it {
                return true;
            }
        }

        false
    }

    /// Get the ancestry of one module to another.
    ///
    /// This returns three things:
    /// * The shared prefix between the current and the `other` path.
    /// * The suffix to get to the `other` path from the shared prefix.
    ///
    /// # Examples
    ///
    /// ```
    /// use rune::{Item, ItemBuf};
    ///
    /// assert_eq!(
    ///     (ItemBuf::new(), ItemBuf::new()),
    ///     Item::new().ancestry(Item::new())?
    /// );
    ///
    /// assert_eq!(
    ///     (ItemBuf::new(), ItemBuf::with_item(["a"])?),
    ///     Item::new().ancestry(ItemBuf::with_item(["a"])?)?
    /// );
    ///
    /// assert_eq!(
    ///     (ItemBuf::new(), ItemBuf::with_item(["a", "b"])?),
    ///     Item::new().ancestry(ItemBuf::with_item(["a", "b"])?)?
    /// );
    ///
    /// assert_eq!(
    ///     (ItemBuf::with_item(["a"])?, ItemBuf::with_item(["b"])?),
    ///     ItemBuf::with_item(["a", "c"])?.ancestry(ItemBuf::with_item(["a", "b"])?)?
    /// );
    ///
    /// assert_eq!(
    ///     (ItemBuf::with_item(["a", "b"])?, ItemBuf::with_item(["d", "e"])?),
    ///     ItemBuf::with_item(["a", "b", "c"])?.ancestry(ItemBuf::with_item(["a", "b", "d", "e"])?)?
    /// );
    /// # Ok::<_, rune::alloc::Error>(())
    /// ```
    pub fn ancestry<U>(&self, other: U) -> alloc::Result<(ItemBuf, ItemBuf)>
    where
        U: AsRef<Item>,
    {
        let mut a = self.iter();
        let other = other.as_ref();
        let mut b = other.iter();

        let mut shared = ItemBuf::new();
        let mut suffix = ItemBuf::new();

        while let Some(v) = b.next() {
            if let Some(u) = a.next() {
                if u == v {
                    shared.push(v)?;
                    continue;
                } else {
                    suffix.push(v)?;
                    suffix.extend(b)?;
                    return Ok((shared, suffix));
                }
            }

            suffix.push(v)?;
            break;
        }

        suffix.extend(b)?;
        Ok((shared, suffix))
    }

    /// Get the parent item for the current item.
    ///
    /// # Examples
    ///
    /// ```
    /// use rune::ItemBuf;
    ///
    /// let item = ItemBuf::with_item(["foo", "bar", "baz"])?;
    /// let item2 = ItemBuf::with_item(["foo", "bar"])?;
    ///
    /// assert_eq!(item.parent(), Some(&*item2));
    /// # Ok::<_, rune::alloc::Error>(())
    /// ```
    pub fn parent(&self) -> Option<&Item> {
        let mut it = self.iter();
        it.next_back()?;
        Some(it.into_item())
    }

    /// Display an unqalified variant of the item which does not include `::` if
    /// a crate is present.
    pub fn unqalified(&self) -> Unqalified {
        Unqalified::new(self)
    }
}

impl AsRef<Item> for &Item {
    #[inline]
    fn as_ref(&self) -> &Item {
        self
    }
}

impl Default for &Item {
    #[inline]
    fn default() -> Self {
        Item::new()
    }
}

#[cfg(feature = "alloc")]
impl TryToOwned for Item {
    type Owned = ItemBuf;

    #[inline]
    fn try_to_owned(&self) -> alloc::Result<Self::Owned> {
        // SAFETY: item ensures that content is valid.
        Ok(unsafe { ItemBuf::from_raw(self.content.try_to_owned()?) })
    }
}

/// Format implementation for an [ItemBuf].
///
/// An empty item is formatted as `{root}`, because it refers to the topmost
/// root module.
///
/// # Examples
///
/// ```
/// use rune::alloc::prelude::*;
/// use rune::ItemBuf;
/// use rune::item::ComponentRef;
///
/// let root = ItemBuf::new().try_to_string()?;
/// assert_eq!("{root}", root);
///
/// let hello = ItemBuf::with_item(&[ComponentRef::Str("hello"), ComponentRef::Id(0)])?;
/// assert_eq!("hello::$0", hello.try_to_string()?);
/// # Ok::<_, rune::alloc::Error>(())
/// ```
impl fmt::Display for Item {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut it = self.iter();

        if let Some(last) = it.next_back() {
            for p in it {
                write!(f, "{}::", p)?;
            }

            write!(f, "{}", last)?;
        } else {
            f.write_str("{root}")?;
        }

        Ok(())
    }
}

impl fmt::Debug for Item {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self)
    }
}

impl<'a> IntoIterator for &'a Item {
    type IntoIter = Iter<'a>;
    type Item = ComponentRef<'a>;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl PartialEq<ItemBuf> for Item {
    fn eq(&self, other: &ItemBuf) -> bool {
        self.content == other.content
    }
}

impl PartialEq<ItemBuf> for &Item {
    fn eq(&self, other: &ItemBuf) -> bool {
        self.content == other.content
    }
}

impl PartialEq<Iter<'_>> for Item {
    fn eq(&self, other: &Iter<'_>) -> bool {
        self == other.as_item()
    }
}

impl PartialEq<Iter<'_>> for &Item {
    fn eq(&self, other: &Iter<'_>) -> bool {
        *self == other.as_item()
    }
}

/// Display an unqalified path.
pub struct Unqalified<'a> {
    item: &'a Item,
}

impl<'a> Unqalified<'a> {
    fn new(item: &'a Item) -> Self {
        Self { item }
    }
}

impl fmt::Display for Unqalified<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut it = self.item.iter();

        if let Some(last) = it.next_back() {
            for c in it {
                match c {
                    ComponentRef::Crate(name) => {
                        write!(f, "{name}::")?;
                    }
                    ComponentRef::Str(name) => {
                        write!(f, "{name}::")?;
                    }
                    c => {
                        write!(f, "{c}::")?;
                    }
                }
            }

            write!(f, "{}", last)?;
        } else {
            f.write_str("{root}")?;
        }

        Ok(())
    }
}