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
use std::{collections::HashSet, hash::Hash};

pub trait Node<Id> {
    fn id(&self) -> &Id;
    fn parent(&self) -> Option<Id>;
    fn parent_set(&mut self, id: Id);
    fn parent_set_none(&mut self);
    fn children(&self) -> Vec<Id>;
    fn children_ref_mut(&mut self) -> &mut Vec<Id>;
}

/// provides basic node-reflection abiliy; no check
pub trait FlowBase {
    type Id: Default + Clone + Hash + Eq;
    type Node: Default + Clone + Node<Self::Id>;
    /// ensures root and returns it
    fn orphan(&self) -> Vec<Self::Id>;
    fn contains_node(&self, obj: &Self::Id) -> bool {
        self.node(obj).is_some()
    }
    fn node(&self, obj: &Self::Id) -> Option<&Self::Node>;
    fn node_mut(&mut self, obj: &Self::Id) -> Option<&mut Self::Node>;
    fn parent(&self, obj: &Self::Id) -> Option<Self::Id> {
        self.node(obj).map_or(None, |node| node.parent())
    }
    fn children(&self, obj: &Self::Id) -> Vec<Self::Id> {
        self.node(obj).map_or(Vec::new(), |node| node.children())
    }

    /// returns parent's children
    fn friends(&self, obj: &Self::Id) -> Vec<Self::Id> {
        self.parent(obj)
            .map_or(Vec::new(), |obj| self.children(&obj))
    }

    /// returns nth position in friends; None if not found in either way
    fn nth_friend(&self, obj: &Self::Id) -> Option<usize> {
        self.friends(obj).into_iter().position(|id| &id == obj)
    }

    /// returns owned children
    fn children_owned(&self, obj: &Self::Id) -> Vec<Self::Id> {
        self.children(obj)
            .into_iter()
            .filter_map(|id| {
                if self.parent(&id) == Some(obj.clone()) {
                    Some(id)
                } else {
                    None
                }
            })
            .collect()
    }

    /// judge whether the obj is owned by the owner
    fn is_owned(&self, obj: &Self::Id, owner: &Self::Id) -> bool {
        self.parent(obj).map_or(false, |id| &id == owner)
            && self.children(owner).contains(obj)
    }

    /// judge whether the obj is *purely* linked from the owner
    fn is_linked(&self, obj: &Self::Id, owner: &Self::Id) -> bool {
        self.parent(obj).map_or(true, |id| &id != owner)
            && self.children(owner).contains(obj)
    }

    /// returns all the offspring of a node, not including itself
    fn node_offspring_set(&self, obj: &Self::Id) -> HashSet<Self::Id> {
        let mut visit_set = HashSet::new();
        let mut final_set = HashSet::new();
        visit_set.insert(obj.clone());
        while !visit_set.is_empty() {
            let mut wait_set = HashSet::new();
            for obj in visit_set.iter() {
                let children =
                    self.node(&obj).map(|x| x.children()).unwrap_or_default();
                wait_set.extend(children);
            }
            final_set.extend(wait_set.iter().cloned());
            visit_set.clear();
            visit_set.extend(wait_set);
        }
        final_set
    }

    /// returns all the nodes owned by a node, including itself
    fn node_ownership_set(&self, obj: &Self::Id) -> HashSet<Self::Id> {
        let mut visit_set = HashSet::new();
        let mut final_set = HashSet::new();
        if self.contains_node(obj) {
            visit_set.insert(obj.clone());
            final_set.insert(obj.clone());
        }
        while !visit_set.is_empty() {
            let mut wait_set = HashSet::new();
            for obj in visit_set.iter() {
                let children =
                    self.node(&obj).map(|x| x.children()).unwrap_or_default();
                let set: Vec<Self::Id> = children
                    .into_iter()
                    .filter_map(|id| {
                        self.node(&id)
                            .map(|node| {
                                if node.parent() == Some(obj.clone()) {
                                    Some(id)
                                } else {
                                    None
                                }
                            })
                            .flatten()
                    })
                    .collect();
                wait_set.extend(set);
            }
            final_set.extend(wait_set.iter().cloned());
            visit_set.clear();
            visit_set.extend(wait_set);
        }
        final_set
    }
}

/// checks the Flow's properties and see whether they hold
pub trait FlowCheck {
    fn check(&self) -> Result<(), (FlowError, String)>;
    /// panics if anything went wrong. Iff in debug state.
    fn check_assert(&self) {
        if cfg!(debug_assertions) {
            if let Err((err, current)) = self.check() {
                panic!("{:?}{}", err, current)
            }
        }
    }
}

/// provides hashmap functionality
pub trait FlowMap: FlowBase + FlowCheck {
    /// inserts a node; returns err if id exists.
    fn grow(&mut self, obj: Self::Node) -> Result<Self::Id, FlowError>;

    /// removes a node; returns err if id not found under root
    fn erase(&mut self, obj: &Self::Id) -> Result<Self::Node, FlowError>;
}

/// provides ability to link nodes; graph-ish
pub trait FlowLink: FlowBase + FlowCheck {
    /// randomly ensures the link of a node to another; won't change if aleady has the node as child
    fn link(
        &mut self,
        obj: &Self::Id,
        owner: &Self::Id,
        nth: usize,
    ) -> Result<(), FlowError> {
        if !self.contains_node(obj) {
            Err(FlowError::NotExistObj)?
        }
        let res = self
            .node_mut(owner)
            .map(|owner| {
                if owner.children().contains(obj) {
                    return Ok(());
                    // owner.children_ref_mut().retain(|id| id != obj)
                }
                if nth > owner.children().len() {
                    Err(FlowError::InvalidLen)?
                }
                owner.children_ref_mut().insert(nth, obj.clone());
                Ok(())
            })
            .unwrap_or(Err(FlowError::NotExistOwner));
        self.check_assert();
        res
    }

    fn link_push(
        &mut self,
        obj: &Self::Id,
        owner: &Self::Id,
    ) -> Result<(), FlowError> {
        let nth = self.node(owner).map_or(0, |node| node.children().len());
        let res = self.link(obj, owner, nth);
        self.check_assert();
        res
    }
    /// detaches a node from a non-owner link
    fn detach(
        &mut self,
        obj: &Self::Id,
        owner: &Self::Id,
    ) -> Result<(), FlowError> {
        if !self.contains_node(obj) {
            Err(FlowError::NotExistObj)?
        }
        let res = self
            .node_mut(owner)
            .map(|owner| {
                if !owner.children().contains(obj) {
                    Err(FlowError::AbandonedChild)?
                }
                owner.children_ref_mut().retain(|x| x != obj);
                Ok(())
            })
            .unwrap_or(Err(FlowError::NotExistOwner));
        self.check_assert();
        res
    }
}

/// provides ability to devote / own nodes; tree-ish
pub trait FlowDevote: FlowBase + FlowLink + FlowCheck {
    /// appoints and ensures an owner; also links to owner; won't do anything if aleady has the node as child
    fn devote(
        &mut self,
        obj: &Self::Id,
        owner: &Self::Id,
        nth: usize,
    ) -> Result<(), FlowError> {
        let res = self.link(obj, owner, nth).and_then(|_| {
            self.node_mut(obj)
                .map(|obj| {
                    obj.parent_set(owner.clone());
                    Ok(())
                })
                .unwrap_or(Err(FlowError::NotExistObj))
        });
        self.check_assert();
        res
    }

    fn devote_push(
        &mut self,
        obj: &Self::Id,
        owner: &Self::Id,
    ) -> Result<(), FlowError> {
        let res = self.link_push(obj, owner).and_then(|_| {
            self.node_mut(obj)
                .map_or(Err(FlowError::NotExistObj), |obj| {
                    obj.parent_set(owner.clone());
                    Ok(())
                })
        });
        self.check_assert();
        res
    }

    /// removes ownership; also detaches
    fn decay(&mut self, obj: &Self::Id) -> Result<(), FlowError> {
        let owner = self.node(obj).map(|x| x.parent());
        // Not owned by anyone
        if let Some(None) = owner {
            return Ok(());
        }
        let owner = owner.flatten();
        let res = self
            .node_mut(obj)
            .map_or(Err(FlowError::NotExistObj), |obj| {
                obj.parent_set_none();
                Ok(())
            })
            .and_then(|_| {
                owner.map_or(Err(FlowError::NotExistOwner), |owner| {
                    self.detach(obj, &owner)
                })
            });
        self.check_assert();
        res
    }

    /// decay before devote
    fn devote_loyal(
        &mut self,
        obj: &Self::Id,
        owner: &Self::Id,
        nth: usize,
    ) -> Result<(), FlowError> {
        self.decay(&obj)?;
        self.devote(&obj, &owner, nth)
    }

    /// decay before devote
    fn devote_loyal_push(
        &mut self,
        obj: &Self::Id,
        owner: &Self::Id,
    ) -> Result<(), FlowError> {
        self.decay(&obj)?;
        self.devote_push(&obj, &owner)
    }
}

/// provides ability to cut (undock) and copy (snap) a flow from a node and paste it to another node (dock)
pub trait FlowDock: FlowDevote + FlowCheck + Sized {
    /// adds all the nodes in another flow to self and mounts all orphan nodes to the designated node
    ///
    /// Err if:
    /// 1. Owner not found.
    /// 2. Node exists in current flow.
    fn dock_unordered(
        &mut self,
        owner: &Self::Id,
        flow: Self,
    ) -> Result<(), FlowError> {
        self.dock(owner, flow.orphan(), flow)
    }
    fn dock(
        &mut self,
        owner: &Self::Id,
        vec: Vec<Self::Id>,
        flow: Self,
    ) -> Result<(), FlowError>;
    /// moves all the nodes under the designated node out of the current flow and unmounts them
    ///
    /// Err if:
    /// 1. Obj not found.
    /// 2. Node linked by other nodes.
    fn undock_impl(
        &mut self,
        obj: &Self::Id,
        owned: bool,
    ) -> Result<(Self, Vec<Self::Id>), FlowError>;
    fn undock(
        &mut self,
        obj: &Self::Id,
    ) -> Result<(Self, Vec<Self::Id>), FlowError> {
        self.undock_impl(obj, false)
    }
    fn undock_owned(
        &mut self,
        obj: &Self::Id,
    ) -> Result<(Self, Vec<Self::Id>), FlowError> {
        self.undock_impl(obj, true)
    }
    /// clones all the nodes linked under the designated node and unmounts the clone
    ///
    /// Err if:
    /// 1. Obj not found.
    fn snap(&self, obj: &Self::Id) -> Result<(Self, Vec<Self::Id>), FlowError>;
    /// clones all the nodes owned under the designated node and unmounts the clone
    ///
    /// Err if:
    /// 1. Obj not found.
    fn snap_owned(
        &self,
        obj: &Self::Id,
    ) -> Result<(Self, Vec<Self::Id>), FlowError>;
}

/// Direction under FlowView:
///
/// - Forward - Down
/// - Backward - Up
/// - Ascend - Left
/// - Descend - Right
#[derive(Debug, Copy, Clone)]
pub enum Direction {
    Forward,
    Backward,
    Ascend,
    Descend,
}

impl Direction {
    /// shift isize according to dir
    fn shift(&self) -> isize {
        use Direction::*;
        match self {
            Forward => 1,
            Backward => -1,
            _ => 0,
        }
    }

    /// bounded in [0, len)
    fn walk(&self, nth: usize, len: usize) -> Result<usize, ()> {
        let pos = nth as isize + self.shift();
        if pos < 0 {
            Err(())
        } else if (pos as usize) < len {
            Ok(pos as usize)
        } else {
            Err(())
        }
    }
}

/// provides ability to move around in flow
pub trait FlowShift: FlowBase + FlowDevote {
    /// returns the obj in the corresponding relative position
    fn shuttle(
        &self,
        obj: &Self::Id,
        dir: Direction,
    ) -> Result<Self::Id, FlowError> {
        use Direction::*;
        match dir {
            Forward | Backward => {
                let friends = self.friends(obj);
                let nth = if let Some(nth) =
                    friends.iter().position(|id| id == obj)
                {
                    nth
                } else {
                    Err(FlowError::AbandonedChild)?
                };
                let len = friends.len();
                let walk =
                    dir.walk(nth, len).map_err(|_| FlowError::InvalidLen)?;
                Ok(friends[walk].clone())
            }
            Ascend => {
                let candidate = self.parent(obj);
                let res = candidate.map_or(obj.clone(), |id| id);
                Ok(res)
            }
            Descend => {
                let candidate = self.children(obj).get(0).cloned();
                let res = candidate.map_or(obj.clone(), |id| id);
                Ok(res)
            }
        }
    }

    /// iteratively shuttles within the flow
    fn shuttle_iter(
        &self,
        obj: &Self::Id,
        dir: Direction,
    ) -> Result<Self::Id, FlowError> {
        use Direction::*;
        match dir {
            Forward | Backward => self.shuttle(obj, dir).map_or_else(
                |_| Ok(self.parent(obj).unwrap_or(obj.clone())),
                |id| Ok(id),
            ),
            Ascend | Descend => self.shuttle(obj, dir),
        }
    }

    /// alters the node position by the corresponding relative position, within a single node
    fn migrate(
        &mut self,
        obj: &Self::Id,
        dir: Direction,
    ) -> Result<(), FlowError> {
        use Direction::*;
        if !self.contains_node(obj) {
            Err(FlowError::NotExistObj)?
        }
        match dir {
            Forward | Backward => {
                let owner = self.parent(obj).ok_or(FlowError::NotExistObj)?;
                let nth =
                    self.nth_friend(obj).ok_or(FlowError::AbandonedChild)?;
                let len = self.friends(&owner).len();
                let walk =
                    dir.walk(nth, len).map_err(|_| FlowError::InvalidLen)?;
                self.decay(obj)?;
                self.devote(obj, &owner, walk)?
            }
            Ascend => {
                let parent = self.parent(obj).ok_or(FlowError::NotExistObj)?;
                let owner =
                    self.parent(&parent).ok_or(FlowError::IsOrphaned)?;
                let nth = self
                    .nth_friend(&parent)
                    .ok_or(FlowError::AbandonedChild)?
                    + 1;
                self.decay(obj)?;
                self.devote(obj, &owner, nth)?
            }
            Descend => Err(FlowError::InvalidDir)?,
        }
        self.check_assert();
        Ok(())
    }

    /// alters the node position by the corresponding relative position, iteratively within the flow
    fn migrate_iter(
        &mut self,
        obj: &Self::Id,
        dir: Direction,
    ) -> Result<(), FlowError> {
        use Direction::*;
        match dir {
            Forward | Backward => self.migrate(obj, dir).map_or_else(
                |e| {
                    if let FlowError::InvalidLen = e {
                        self.migrate(obj, Ascend)
                    } else {
                        Err(e)
                    }
                },
                |v| Ok(v),
            ),
            Ascend | Descend => self.migrate(obj, dir),
        }
    }
}

/// Represents all possible Errors in Flow Operations
#[derive(Debug)]
pub enum FlowError {
    NotExistObj,
    NotExistOwner,
    InvalidLen,
    ExistGrow,
    ExistDock,
    OwnerDetach,
    LinkedUndock,
    InvalidDir,
    /// certain operations requires node to be orphaned
    NotOrphaned,
    /// certain operations requires node to be unorphaned
    IsOrphaned,

    NodeIdNotMatch,
    NotExistParent,
    NotExistChild,
    /// potential parent doesn't have the child
    AbandonedChild,
}

/// The overall `Flow` trait, checking whether anything is missing.
pub trait Flow:
    FlowBase + FlowCheck + FlowMap + FlowLink + FlowDevote + FlowDock + FlowShift
{
}