pl_lens/
path.rs

1//
2// Copyright (c) 2015 Plausible Labs Cooperative, Inc.
3// All rights reserved.
4//
5
6use std::fmt;
7
8/// An element in a `LensPath`.
9#[derive(PartialEq, Eq, PartialOrd, Ord, Debug, Clone, Copy)]
10pub struct LensPathElement {
11    id: u64,
12}
13
14impl LensPathElement {
15    pub fn new(id: u64) -> LensPathElement {
16        LensPathElement { id }
17    }
18}
19
20/// Describes a lens relative to a source data structure.
21#[derive(PartialEq, Eq, PartialOrd, Ord, Clone)]
22pub struct LensPath {
23    /// The path elements.
24    pub elements: Vec<LensPathElement>,
25}
26
27impl LensPath {
28    /// Creates a new `LensPath` with no elements.
29    pub fn empty() -> LensPath {
30        LensPath { elements: vec![] }
31    }
32
33    /// Creates a new `LensPath` with a single element.
34    pub fn new(id: u64) -> LensPath {
35        LensPath {
36            elements: vec![LensPathElement { id }],
37        }
38    }
39
40    /// Creates a new `LensPath` with a single index (for an indexed type such as `Vec`).
41    pub fn from_index(index: usize) -> LensPath {
42        LensPath {
43            elements: vec![LensPathElement { id: index as u64 }],
44        }
45    }
46
47    /// Creates a new `LensPath` with two elements.
48    pub fn from_pair(id0: u64, id1: u64) -> LensPath {
49        LensPath {
50            elements: vec![LensPathElement { id: id0 }, LensPathElement { id: id1 }],
51        }
52    }
53
54    /// Creates a new `LensPath` from a vector of element identifiers.
55    pub fn from_vec(ids: Vec<u64>) -> LensPath {
56        LensPath {
57            elements: ids.iter().map(|id| LensPathElement { id: *id }).collect(),
58        }
59    }
60
61    /// Creates a new `LensPath` that is the concatenation of the two paths.
62    pub fn concat(lhs: LensPath, rhs: LensPath) -> LensPath {
63        let mut elements = lhs.elements;
64        elements.extend(&rhs.elements);
65        LensPath { elements }
66    }
67}
68
69impl fmt::Debug for LensPath {
70    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
71        write!(
72            f,
73            "[{}]",
74            self.elements
75                .iter()
76                .map(|elem| elem.id.to_string())
77                .collect::<Vec<String>>()
78                .join(", ")
79        )
80    }
81}
82
83#[test]
84fn test_lens_path_concat() {
85    let p0 = LensPath::from_vec(vec![1, 2, 3]);
86    let p1 = LensPath::from_vec(vec![4, 5]);
87    let p2 = LensPath::concat(p0, p1);
88    assert_eq!(p2, LensPath::from_vec(vec![1, 2, 3, 4, 5]));
89}
90
91#[test]
92fn test_lens_path_debug() {
93    let path = LensPath::from_vec(vec![1, 2, 3, 4, 5]);
94    assert_eq!(format!("{:?}", path), "[1, 2, 3, 4, 5]".to_string());
95}