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
/*
==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--

Binn-IR

Copyright (C) 2018-2023  Anonymous

There are several releases over multiple years,
they are listed as ranges, such as: "2018-2023".

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.

::--::--::--::--::--::--::--::--::--::--::--::--::--::--::--::--
*/

//! # Shortcuts for `Value::Map`

use {
    core::iter::FromIterator,
    crate::{Error, Map, MapKey, Result, Value},
};

/// # Helper macro for Value::*_maybe_by()/*_maybe_mut_by()
macro_rules! maybe_by_or_mut_by { ($self: ident, $variant: tt, $keys: ident, $code: tt) => {{
    if $keys.is_empty() {
        return Err(err!("Keys must not be empty"));
    }

    let mut value = Some($self);
    for (nth, key) in $keys.iter().enumerate() {
        match value {
            Some(Value::$variant(variant)) => value = variant.$code(key),
            Some(_) => return Err(match nth {
                0 => err!("Value is not {}", stringify!($variant)),
                _ => err!("Value at {keys:?} is not {variant}", keys=&$keys[..nth], variant=stringify!($variant)),
            }),
            None => return Err(err!("There is no value at {:?}", &$keys[..nth])),
        };
    }

    Ok(value)
}}}

/// # Helper macro for Value::*_take_by()
macro_rules! maybe_take_by { ($self: ident, $variant: tt, $keys: ident) => {{
    let mut value = Some($self);
    for (nth, key) in $keys.iter().enumerate() {
        match value {
            Some(Value::$variant(variant)) => if nth + 1 == $keys.len() {
                return Ok(variant.remove(key));
            } else {
                value = variant.get_mut(key);
            },
            Some(_) => return Err(match nth {
                0 => err!("Value is not {}", stringify!($variant)),
                _ => err!("Value at {keys:?} is not {variant}", keys=&$keys[..nth], variant=stringify!($variant)),
            }),
            None => return Err(err!("There is no value at {:?}", &$keys[..nth])),
        };
    }

    Err(err!("Keys must not be empty"))
}}}

/// # Shortcuts for [`Map`](#variant.Map)
impl Value {

    /// # If the value is a map, inserts new item into it
    ///
    /// On success, returns previous value (if it existed).
    ///
    /// Returns an error if the value is not a map.
    pub fn map_insert<K, V>(&mut self, key: K, value: V) -> Result<Option<Self>> where K: Into<MapKey>, V: Into<Self> {
        match self {
            Self::Map(map) => Ok(crate::map_insert(map, key, value)),
            _ => Err(err!("Value is not a map")),
        }
    }

    /// # Gets an immutable item from this map and its sub maps
    ///
    /// The function returns an error on one of these conditions:
    ///
    /// - Keys are empty.
    /// - The value or any of its sub items is not a map.
    ///
    /// ## Examples
    ///
    /// ```
    /// let mut map = binn_ir::map();
    /// map.map_insert(0, true)?;
    /// map.map_insert(1, {
    ///     let mut map = binn_ir::Map::new();
    ///     binn_ir::map_insert(&mut map, 2, 99);
    ///     map
    /// })?;
    ///
    /// assert_eq!(bool::try_from(map.map_by(&[0])?)?, true);
    /// assert_eq!(u8::try_from(map.map_by(&[1, 2])?)?, 99);
    ///
    /// assert!(map.map_by(&[2]).is_err());
    /// assert!(map.map_maybe_by(&[2])?.is_none());
    ///
    /// assert!(map.map_by(&[]).is_err());
    /// assert!(map.map_by(&[0, 2]).is_err());
    /// assert!(map.map_by(&[1, 2, 3]).is_err());
    ///
    /// # Ok::<_, binn_ir::Error>(())
    /// ```
    pub fn map_by(&self, keys: &[MapKey]) -> Result<&Self> {
        self.map_maybe_by(keys)?.ok_or_else(|| err!("There is no value at: {:?}", keys))
    }

    /// # Gets an optional immutable item from this map and its sub maps
    ///
    /// The function returns an error on one of these conditions:
    ///
    /// - Keys are empty.
    /// - The value or any of its sub items is not a map.
    pub fn map_maybe_by(&self, keys: &[MapKey]) -> Result<Option<&Self>> {
        maybe_by_or_mut_by!(self, Map, keys, get)
    }

    /// # Gets a mutable item from this map and its sub maps
    ///
    /// The function returns an error on one of these conditions:
    ///
    /// - Keys are empty.
    /// - The value or any of its sub items is not a map.
    pub fn map_mut_by(&mut self, keys: &[MapKey]) -> Result<&mut Self> {
        self.map_maybe_mut_by(keys)?.ok_or_else(|| err!("There is no value at: {:?}", keys))
    }

    /// # Gets an optional mutable item from this map and its sub maps
    ///
    /// The function returns an error on one of these conditions:
    ///
    /// - Keys are empty.
    /// - The value or any of its sub items is not a map.
    pub fn map_maybe_mut_by(&mut self, keys: &[MapKey]) -> Result<Option<&mut Self>> {
        maybe_by_or_mut_by!(self, Map, keys, get_mut)
    }

    /// # Takes an item from this map and its sub maps
    ///
    /// The function returns an error on one of these conditions:
    ///
    /// - Keys are empty.
    /// - The value or any of its sub items is not a map.
    ///
    /// ## Examples
    ///
    /// ```
    /// let mut map = binn_ir::map();
    /// map.map_insert(0, "zero")?;
    /// map.map_insert(1, {
    ///     let mut map = binn_ir::Map::new();
    ///     binn_ir::map_insert(&mut map, 2, "two");
    ///     map
    /// })?;
    ///
    /// assert_eq!(map.map_take_by(&[0])?.as_text()?, "zero");
    /// assert_eq!(map.map_take_by(&[1, 2])?.as_text()?, "two");
    ///
    /// assert!(map.map_take_by(&[0]).is_err());
    /// assert!(map.map_maybe_take_by(&[0])?.is_none());
    /// assert!(map.map_maybe_take_by(&[1, 2])?.is_none());
    ///
    /// assert!(map.map_take_by(&[]).is_err());
    /// assert!(map.map_take_by(&[3, 4]).is_err());
    ///
    /// # Ok::<_, binn_ir::Error>(())
    /// ```
    pub fn map_take_by(&mut self, keys: &[MapKey]) -> Result<Self> {
        self.map_maybe_take_by(keys)?.ok_or_else(|| err!("There is no value at: {:?}", keys))
    }

    /// # Takes an optional item from this map and its sub maps
    ///
    /// The function returns an error on one of these conditions:
    ///
    /// - Keys are empty.
    /// - The value or any of its sub items is not a map.
    pub fn map_maybe_take_by(&mut self, keys: &[MapKey]) -> Result<Option<Self>> {
        maybe_take_by!(self, Map, keys)
    }

    /// # If the value is a map, returns an immutable reference of it
    ///
    /// Returns an error if the value is not a map.
    pub fn as_map(&self) -> Result<&Map> {
        match self {
            Self::Map(map) => Ok(map),
            _ => Err(err!("Value is not a Map")),
        }
    }

    /// # If the value is a map, returns a mutable reference of it
    ///
    /// Returns an error if the value is not a map.
    pub fn as_mut_map(&mut self) -> Result<&mut Map> {
        match self {
            Self::Map(map) => Ok(map),
            _ => Err(err!("Value is not a Map")),
        }
    }

}

impl From<Map> for Value {

    fn from(map: Map) -> Self {
        Self::Map(map)
    }

}

impl FromIterator<(MapKey, Value)> for Value {

    fn from_iter<T>(iter: T) -> Self where T: IntoIterator<Item=(MapKey, Self)> {
        Self::Map(iter.into_iter().collect())
    }

}

impl TryFrom<Value> for Map {

    type Error = Error;

    fn try_from(v: Value) -> core::result::Result<Self, Self::Error> {
        match v {
            Value::Map(map) => Ok(map),
            _ => Err(err!("Value is not a Map")),
        }
    }

}