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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
use crate::Id;
use derive_more::{From, TryInto};
use std::{
    collections::{BTreeSet, BinaryHeap, HashSet, LinkedList, VecDeque},
    convert::TryFrom,
};
use strum::{Display, EnumDiscriminants, EnumString};

/// Represents a definition of an edge, which is comprised of its name, type
/// of edge value, and the edge's deletion policy
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde-1", derive(serde::Serialize, serde::Deserialize))]
pub struct EdgeDefinition {
    pub(super) name: String,
    r#type: EdgeValueType,
    deletion_policy: EdgeDeletionPolicy,
}

impl EdgeDefinition {
    /// Creates a new definition for an edge with the given name, type of value,
    /// and deletion policy of nothing
    pub fn new<N: Into<String>, T: Into<EdgeValueType>>(name: N, r#type: T) -> Self {
        Self::new_with_deletion_policy(name, r#type, EdgeDeletionPolicy::default())
    }

    /// Creates a new definition for an edge with the given name, type of value,
    /// and deletion policy
    pub fn new_with_deletion_policy<N: Into<String>, T: Into<EdgeValueType>>(
        name: N,
        r#type: T,
        deletion_policy: EdgeDeletionPolicy,
    ) -> Self {
        Self {
            name: name.into(),
            r#type: r#type.into(),
            deletion_policy,
        }
    }

    /// The name of the edge tied to the definition
    #[inline]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// The type of value of the edge tied to the definition
    #[inline]
    pub fn r#type(&self) -> &EdgeValueType {
        &self.r#type
    }

    /// Returns the deletion policy of the edge tied to the definition
    #[inline]
    pub fn deletion_policy(&self) -> EdgeDeletionPolicy {
        self.deletion_policy
    }

    /// Returns true if the deletion policy is nothing
    #[inline]
    pub fn has_no_deletion_policy(&self) -> bool {
        matches!(self.deletion_policy(), EdgeDeletionPolicy::Nothing)
    }

    /// Returns true if the deletion policy is shallow
    #[inline]
    pub fn has_shallow_deletion_policy(&self) -> bool {
        matches!(self.deletion_policy(), EdgeDeletionPolicy::ShallowDelete)
    }

    /// Returns true if the deletion policy is deep
    #[inline]
    pub fn has_deep_deletion_policy(&self) -> bool {
        matches!(self.deletion_policy(), EdgeDeletionPolicy::DeepDelete)
    }
}

impl From<Edge> for EdgeDefinition {
    fn from(edge: Edge) -> Self {
        Self::new_with_deletion_policy(edge.name, edge.value, edge.deletion_policy)
    }
}

impl<'a> From<&'a Edge> for EdgeDefinition {
    fn from(edge: &'a Edge) -> Self {
        Self::new_with_deletion_policy(edge.name(), edge.value(), edge.deletion_policy())
    }
}

/// Represents a edge from an ent to one or more other ents
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde-1", derive(serde::Serialize, serde::Deserialize))]
pub struct Edge {
    name: String,
    value: EdgeValue,
    deletion_policy: EdgeDeletionPolicy,
}

impl Edge {
    /// Creates a new edge with the given name, value, and deletion policy
    /// of nothing
    ///
    /// ## Examples
    ///
    /// ```
    /// use entity::{Edge, EdgeDeletionPolicy};
    ///
    /// let edge = Edge::new("edge1", 999);
    /// assert_eq!(edge.name(), "edge1");
    /// assert_eq!(edge.to_ids(), vec![999]);
    /// assert_eq!(edge.deletion_policy(), EdgeDeletionPolicy::Nothing);
    /// ```
    pub fn new<N: Into<String>, V: Into<EdgeValue>>(name: N, value: V) -> Self {
        Self::new_with_deletion_policy(name, value, EdgeDeletionPolicy::default())
    }

    /// Creates a new edge with the given name, value, and deletion policy
    ///
    /// ## Examples
    ///
    /// ```
    /// use entity::{Edge, EdgeDeletionPolicy};
    ///
    /// let edge = Edge::new_with_deletion_policy(
    ///     "edge1",
    ///     999,
    ///     EdgeDeletionPolicy::DeepDelete,
    /// );
    /// assert_eq!(edge.name(), "edge1");
    /// assert_eq!(edge.to_ids(), vec![999]);
    /// assert_eq!(edge.deletion_policy(), EdgeDeletionPolicy::DeepDelete);
    /// ```
    pub fn new_with_deletion_policy<N: Into<String>, V: Into<EdgeValue>>(
        name: N,
        value: V,
        deletion_policy: EdgeDeletionPolicy,
    ) -> Self {
        Self {
            name: name.into(),
            value: value.into(),
            deletion_policy,
        }
    }

    /// The name of the edge
    #[inline]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// The value of the edge
    #[inline]
    pub fn value(&self) -> &EdgeValue {
        &self.value
    }

    /// The mutable value of the edge
    #[inline]
    pub fn value_mut(&mut self) -> &mut EdgeValue {
        &mut self.value
    }

    /// Converts edge into its value
    #[inline]
    pub fn into_value(self) -> EdgeValue {
        self.value
    }

    /// Converts to the ids of the ents referenced by this edge
    pub fn to_ids(&self) -> Vec<Id> {
        self.value.to_ids()
    }

    /// Converts to the edge's value type
    pub fn to_type(&self) -> EdgeValueType {
        self.value().into()
    }

    /// Returns the policy to perform for this edge when its ent is deleted
    #[inline]
    pub fn deletion_policy(&self) -> EdgeDeletionPolicy {
        self.deletion_policy
    }

    /// Returns true if the deletion policy is nothing
    #[inline]
    pub fn has_no_deletion_policy(&self) -> bool {
        matches!(self.deletion_policy(), EdgeDeletionPolicy::Nothing)
    }

    /// Returns true if the deletion policy is shallow
    #[inline]
    pub fn has_shallow_deletion_policy(&self) -> bool {
        matches!(self.deletion_policy(), EdgeDeletionPolicy::ShallowDelete)
    }

    /// Returns true if the deletion policy is deep
    #[inline]
    pub fn has_deep_deletion_policy(&self) -> bool {
        matches!(self.deletion_policy(), EdgeDeletionPolicy::DeepDelete)
    }
}

/// Represents the policy to apply to an edge when its ent is deleted
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
#[cfg_attr(feature = "serde-1", derive(serde::Serialize, serde::Deserialize))]
pub enum EdgeDeletionPolicy {
    /// When this ent instance is deleted, nothing else will be done
    Nothing,

    /// When this ent instance is deleted, delete the reverse edge connections
    /// of all ents connected by this edge
    ShallowDelete,

    /// When this ent instance is deleted, fully delete all ents connected
    /// by this edge
    DeepDelete,
}

impl Default for EdgeDeletionPolicy {
    /// By default, the deletion policy does nothing
    fn default() -> Self {
        Self::Nothing
    }
}

/// Represents the value of an edge, which is some collection of ent ids
#[derive(Clone, Debug, From, PartialEq, Eq, EnumDiscriminants, TryInto)]
#[cfg_attr(feature = "serde-1", derive(serde::Serialize, serde::Deserialize))]
#[strum_discriminants(derive(Display, EnumString))]
#[strum_discriminants(name(EdgeValueType), strum(serialize_all = "snake_case"))]
#[cfg_attr(
    feature = "serde-1",
    strum_discriminants(derive(serde::Serialize, serde::Deserialize))
)]
#[cfg_attr(
    feature = "async-graphql",
    strum_discriminants(derive(async_graphql::Enum))
)]
pub enum EdgeValue {
    /// Edge can potentially have one outward connection
    MaybeOne(Option<Id>),
    /// Edge can have exactly one outward connection
    One(Id),
    /// Edge can have many outward connections
    Many(Vec<Id>),
}

/// Represents some error the can occur when mutating an edge's value
#[derive(Debug, derive_more::Display, derive_more::Error)]
pub enum EdgeValueMutationError {
    #[display(fmt = "Too many ids for edge of type {}: {}", r#type, cnt)]
    TooManyIds { r#type: EdgeValueType, cnt: usize },

    #[display(fmt = "Too ids ents for edge of type {}: {}", r#type, cnt)]
    TooFewIds { r#type: EdgeValueType, cnt: usize },

    #[display(fmt = "Change invalidates edge of type {}", r#type)]
    InvalidatesEdge { r#type: EdgeValueType },
}

impl EdgeValue {
    /// Produces all ids of ents referenced by this edge's value
    ///
    /// ## Examples
    ///
    /// For an optional edge, this can produce a vec of size 0 or 1:
    ///
    /// ```
    /// use entity::EdgeValue;
    ///
    /// let v = EdgeValue::MaybeOne(None);
    /// assert!(v.to_ids().is_empty());
    ///
    /// let v = EdgeValue::MaybeOne(Some(999));
    /// assert_eq!(v.to_ids(), vec![999]);
    /// ```
    ///
    /// For a guaranteed edge of 1, this will always produce a vec of size 1:
    ///
    /// ```
    /// use entity::EdgeValue;
    ///
    /// let v = EdgeValue::One(999);
    /// assert_eq!(v.to_ids(), vec![999]);
    /// ```
    ///
    /// For an edge of many ids, this will produce a vec of equal size:
    ///
    /// ```
    /// use entity::EdgeValue;
    ///
    /// let v = EdgeValue::Many(vec![1, 2, 3, 4]);
    /// assert_eq!(v.to_ids(), vec![1, 2, 3, 4]);
    /// ```
    pub fn to_ids(&self) -> Vec<Id> {
        match self {
            Self::MaybeOne(x) => x.iter().copied().collect(),
            Self::One(x) => vec![*x],
            Self::Many(x) => x.clone(),
        }
    }

    /// Converts the value to its associated type
    ///
    /// ## Examples
    ///
    /// ```
    /// use entity::{EdgeValue, EdgeValueType};
    ///
    /// let v = EdgeValue::MaybeOne(None);
    /// assert_eq!(v.to_type(), EdgeValueType::MaybeOne);
    ///
    /// let v = EdgeValue::One(999);
    /// assert_eq!(v.to_type(), EdgeValueType::One);
    ///
    /// let v = EdgeValue::Many(vec![1, 2, 3]);
    /// assert_eq!(v.to_type(), EdgeValueType::Many);
    /// ```
    pub fn to_type(&self) -> EdgeValueType {
        self.into()
    }

    /// Adds the provided ids to the edge value, failing if the ids would
    /// exceed the maximum allowed by the edge with current ids included
    ///
    /// ## Examples
    ///
    /// If edge is an optional, single value, this will fail if the edge
    /// already has a value or is provided more than one id. Otherwise,
    /// it will succeed.
    ///
    /// ```
    /// use entity::EdgeValue;
    ///
    /// let mut v = EdgeValue::MaybeOne(Some(1));
    /// assert!(v.add_ids(vec![2]).is_err());
    /// assert!(v.add_ids(vec![]).is_ok());
    /// assert_eq!(v, EdgeValue::MaybeOne(Some(1)));
    ///
    /// let mut v = EdgeValue::MaybeOne(None);
    /// assert!(v.add_ids(vec![2, 3]).is_err());
    /// assert_eq!(v, EdgeValue::MaybeOne(None));
    ///
    /// let mut v = EdgeValue::MaybeOne(None);
    /// assert!(v.add_ids(vec![]).is_ok());
    /// assert_eq!(v, EdgeValue::MaybeOne(None));
    ///
    /// let mut v = EdgeValue::MaybeOne(None);
    /// assert!(v.add_ids(vec![1]).is_ok());
    /// assert_eq!(v, EdgeValue::MaybeOne(Some(1)));
    /// ```
    ///
    /// If an edge is exactly one value, this will fail unless an empty
    /// list of ids is given as we cannot add any more edge ids.
    ///
    /// ```
    /// use entity::EdgeValue;
    ///
    /// let mut v = EdgeValue::One(999);
    /// assert!(v.add_ids(vec![1]).is_err());
    /// assert_eq!(v, EdgeValue::One(999));
    ///
    /// let mut v = EdgeValue::One(999);
    /// assert!(v.add_ids(vec![]).is_ok());
    /// assert_eq!(v, EdgeValue::One(999));
    /// ```
    ///
    /// If an edge can have many ids, this will succeed and append those
    /// ids to the end of the list.
    ///
    /// ```
    /// use entity::EdgeValue;
    ///
    /// let mut v = EdgeValue::Many(vec![]);
    /// assert!(v.add_ids(vec![1, 2, 3]).is_ok());
    /// assert_eq!(v, EdgeValue::Many(vec![1, 2, 3]));
    ///
    /// let mut v = EdgeValue::Many(vec![1, 2, 3]);
    /// assert!(v.add_ids(vec![4, 5, 6]).is_ok());
    /// assert_eq!(v, EdgeValue::Many(vec![1, 2, 3, 4, 5, 6]));
    /// ```
    pub fn add_ids(
        &mut self,
        into_ids: impl IntoIterator<Item = Id>,
    ) -> Result<(), EdgeValueMutationError> {
        let mut ids = into_ids.into_iter().collect::<Vec<Id>>();
        ids.sort_unstable();
        ids.dedup();

        // If no ids to add, will always succeed and do nothing
        if ids.is_empty() {
            return Ok(());
        }

        let cnt = self.id_count();

        // Fails if adding these ids would exceed the maximum allowed ids
        if cnt + ids.len() > self.max_ids_allowed() {
            return Err(EdgeValueMutationError::TooManyIds {
                r#type: self.to_type(),
                cnt: ids.len(),
            });
        }

        // Update our optional id as we know it should be None and that we
        // only were given a single id
        if let Self::MaybeOne(maybe_id) = self {
            maybe_id.replace(ids.into_iter().next().unwrap());

        // Otherwise, add our ids to our many
        } else if let Self::Many(existing_ids) = self {
            existing_ids.extend(ids);
        }

        Ok(())
    }

    /// Removes the provided ids from the edge value, failing if the ids would
    /// exceed the minimum allowed by the edge with current ids possibly
    /// removed
    ///
    /// ## Examples
    ///
    /// If edge is an optional, single value, this will never fail as this
    /// can either result in the value retaining its id or becoming none.
    ///
    /// ```
    /// use entity::EdgeValue;
    ///
    /// let mut v = EdgeValue::MaybeOne(Some(1));
    /// assert!(v.remove_ids(vec![2, 3]).is_ok());
    /// assert_eq!(v, EdgeValue::MaybeOne(Some(1)));
    ///
    /// let mut v = EdgeValue::MaybeOne(Some(1));
    /// assert!(v.remove_ids(vec![1, 2, 3]).is_ok());
    /// assert_eq!(v, EdgeValue::MaybeOne(None));
    ///
    /// let mut v = EdgeValue::MaybeOne(None);
    /// assert!(v.remove_ids(vec![2, 3]).is_ok());
    /// assert_eq!(v, EdgeValue::MaybeOne(None));
    ///
    /// let mut v = EdgeValue::MaybeOne(None);
    /// assert!(v.remove_ids(vec![]).is_ok());
    /// assert_eq!(v, EdgeValue::MaybeOne(None));
    /// ```
    ///
    /// If an edge is exactly one value, this will fail if it would cause
    /// the value to lose its id.
    ///
    /// ```
    /// use entity::EdgeValue;
    ///
    /// let mut v = EdgeValue::One(999);
    /// assert!(v.remove_ids(vec![999]).is_err());
    /// assert_eq!(v, EdgeValue::One(999));
    ///
    /// let mut v = EdgeValue::One(999);
    /// assert!(v.remove_ids(vec![1, 2, 3]).is_ok());
    /// assert_eq!(v, EdgeValue::One(999));
    ///
    /// let mut v = EdgeValue::One(999);
    /// assert!(v.remove_ids(vec![]).is_ok());
    /// assert_eq!(v, EdgeValue::One(999));
    /// ```
    ///
    /// If an edge can have many ids, this will succeed and remove all ids
    /// found within the value.
    ///
    /// ```
    /// use entity::EdgeValue;
    ///
    /// let mut v = EdgeValue::Many(vec![]);
    /// assert!(v.remove_ids(vec![1, 2, 3]).is_ok());
    /// assert_eq!(v, EdgeValue::Many(vec![]));
    ///
    /// let mut v = EdgeValue::Many(vec![1, 2, 3]);
    /// assert!(v.remove_ids(vec![4, 5, 6]).is_ok());
    /// assert_eq!(v, EdgeValue::Many(vec![1, 2, 3]));
    ///
    /// let mut v = EdgeValue::Many(vec![1, 2, 3]);
    /// assert!(v.remove_ids(vec![1, 3]).is_ok());
    /// assert_eq!(v, EdgeValue::Many(vec![2]));
    /// ```
    pub fn remove_ids(
        &mut self,
        into_ids: impl IntoIterator<Item = Id>,
    ) -> Result<(), EdgeValueMutationError> {
        let ids = into_ids.into_iter().collect::<HashSet<Id>>();

        // If no ids to remove, will always succeed and do nothing
        if ids.is_empty() {
            return Ok(());
        }

        // Fails if we are not allowed to remove our id and we're given
        // some selection that would cause that issue
        if let Self::One(id) = self {
            if ids.contains(&id) {
                return Err(EdgeValueMutationError::InvalidatesEdge {
                    r#type: self.to_type(),
                });
            }
        }

        // Remove the id from our optional id if it is in our selection
        if let Self::MaybeOne(maybe_id) = self {
            if maybe_id.is_some() && ids.contains(&maybe_id.unwrap()) {
                maybe_id.take();
            }
        // Remove all ids provided from our many
        } else if let Self::Many(existing_ids) = self {
            existing_ids.retain(|id| !ids.contains(id));
        }

        Ok(())
    }

    /// Returns the total ids contained within this value
    #[inline]
    fn id_count(&self) -> usize {
        match self {
            Self::MaybeOne(None) => 0,
            Self::MaybeOne(Some(_)) | Self::One(_) => 1,
            Self::Many(ids) => ids.len(),
        }
    }

    /// Returns the maximum ids possible to contain within this value
    #[inline]
    fn max_ids_allowed(&self) -> usize {
        match self {
            Self::MaybeOne(_) | Self::One(_) => 1,
            Self::Many(_) => usize::MAX,
        }
    }
}

impl From<VecDeque<Id>> for EdgeValue {
    fn from(x: VecDeque<Id>) -> Self {
        Self::Many(x.into_iter().collect())
    }
}

impl TryFrom<EdgeValue> for VecDeque<Id> {
    type Error = &'static str;

    fn try_from(x: EdgeValue) -> Result<Self, Self::Error> {
        match x {
            EdgeValue::Many(x) => Ok(x.into_iter().collect()),
            _ => Err("Only edge type of many may become a VecDeque"),
        }
    }
}

impl From<LinkedList<Id>> for EdgeValue {
    fn from(x: LinkedList<Id>) -> Self {
        Self::Many(x.into_iter().collect())
    }
}

impl TryFrom<EdgeValue> for LinkedList<Id> {
    type Error = &'static str;

    fn try_from(x: EdgeValue) -> Result<Self, Self::Error> {
        match x {
            EdgeValue::Many(x) => Ok(x.into_iter().collect()),
            _ => Err("Only edge type of many may become a LinkedList"),
        }
    }
}

impl From<BinaryHeap<Id>> for EdgeValue {
    fn from(x: BinaryHeap<Id>) -> Self {
        Self::Many(x.into_iter().collect())
    }
}

impl TryFrom<EdgeValue> for BinaryHeap<Id> {
    type Error = &'static str;

    fn try_from(x: EdgeValue) -> Result<Self, Self::Error> {
        match x {
            EdgeValue::Many(x) => Ok(x.into_iter().collect()),
            _ => Err("Only edge type of many may become a BinaryHeap"),
        }
    }
}

impl From<HashSet<Id>> for EdgeValue {
    fn from(x: HashSet<Id>) -> Self {
        Self::Many(x.into_iter().collect())
    }
}

impl TryFrom<EdgeValue> for HashSet<Id> {
    type Error = &'static str;

    fn try_from(x: EdgeValue) -> Result<Self, Self::Error> {
        match x {
            EdgeValue::Many(x) => Ok(x.into_iter().collect()),
            _ => Err("Only edge type of many may become a HashSet"),
        }
    }
}

impl From<BTreeSet<Id>> for EdgeValue {
    fn from(x: BTreeSet<Id>) -> Self {
        Self::Many(x.into_iter().collect())
    }
}

impl TryFrom<EdgeValue> for BTreeSet<Id> {
    type Error = &'static str;

    fn try_from(x: EdgeValue) -> Result<Self, Self::Error> {
        match x {
            EdgeValue::Many(x) => Ok(x.into_iter().collect()),
            _ => Err("Only edge type of many may become a BTreeSet"),
        }
    }
}