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
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
use crate::{
    errors::Error,
    uuid::{
        UuidManager,
        Uuid
    }
};

use std::collections::BTreeMap;

enum PruneBy {
    Group,
    Store
}
pub enum Deleted {
    True,
    False
}

pub struct StoreDefaults {
    pub max_byte_size: Option<u32>
}

#[derive(Debug, Clone, Copy)]
pub struct GroupDefaults {
    pub max_byte_size: Option<u32>,
}

pub struct Group {
    pub max_byte_size: Option<u32>,
    pub byte_size: u32,
    pub msgs_map: BTreeMap<Uuid, u32>,
}
impl Group {
    pub fn new(max_byte_size: Option<u32>) -> Group {
        Group { 
            max_byte_size,
            byte_size: 0, 
            msgs_map: BTreeMap::new() 
        }
    }
    pub fn update_from_config(&mut self, defaults: GroupDefaults) {
        self.max_byte_size = defaults.max_byte_size;
    }
}

struct RemovedMsgs {
    priority: u32,
    msgs: Vec<Uuid>
}
impl RemovedMsgs {
    pub fn new(priority: u32) -> RemovedMsgs {
        RemovedMsgs {
            priority,
            msgs: vec![]
        }
    }
    pub fn add(&mut self, uuid: Uuid) {
        self.msgs.push(uuid);
    }
}

#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
pub struct PacketMetaData {
    pub uuid: Uuid,
    pub priority: u32,
    pub byte_size: u32
}

pub struct AddResult {
    pub uuid: Uuid,
    pub bytes_removed: u32,
    pub groups_removed: Vec<u32>,
    pub msgs_removed: Vec<Uuid>
} 

/// The base unit which stores information about inserted messages and priority groups
/// to determine which messages should be forwarded or burned first.
/// 
/// The store can contain 4,294,967,295 priorities.
/// Messages are forwarded on a highest priority then oldest status basis.
/// Messages are burned/pruned on a lowest priority then oldest status basis.
/// Messages are only burned once the store has reached the max bytesize limit.
/// The store as a whole contains a max bytesize limit option as does each individule priority
/// group. For example, a developer can limit the size of the store to 1,000 bytes, while restricting
/// priority group 1 to only 500 bytes, and leave higher priorities free with no restriction (except that of the store.)
/// 
/// The store keeps track of basic statistics such as counting the messages that have been inserted, deleted, or burned.
/// Messages that have been deleted have been so on instructions of the developer using the del method.
/// Messages that have been burned have been so automatically on insert or store/group defaults update once the
/// max bytesize limit has been reached.
pub struct Store {
    pub max_byte_size: Option<u32>,
    pub byte_size: u32,
    pub group_defaults: BTreeMap<u32, GroupDefaults>,
    pub uuid_manager: UuidManager,
    pub id_to_group_map: BTreeMap<Uuid, u32>,
    pub groups_map: BTreeMap<u32, Group>
}

impl Store {

    pub fn new() -> Store {
        Store {
            max_byte_size: None,
            byte_size: 0,
            group_defaults: BTreeMap::new(),
            uuid_manager: UuidManager::default(),
            id_to_group_map: BTreeMap::new(),
            groups_map: BTreeMap::new()
        }
    }

    fn msg_excedes_max_byte_size(byte_size: &u32, max_byte_size: &u32, msg_byte_size: &u32) -> bool {
        &(byte_size + msg_byte_size) > max_byte_size
    }

    fn remove_msg(&mut self, uuid: &Uuid, group: &mut Group) -> Result<(), Error> {
        let byte_size = match group.msgs_map.remove(&uuid) {
            Some(byte_size) => Ok(byte_size),
            None => Err(Error::SyncError)
        }?;
        self.id_to_group_map.remove(&uuid);
        self.byte_size -= byte_size;
        group.byte_size -= byte_size;
        Ok(())
    }
    
    fn get_group(&mut self, priority: u32) -> Group {
        match self.groups_map.remove(&priority) {
            Some(group) => group,
            None => {
                let max_byte_size = match self.group_defaults.get(&priority) {
                    Some(defaults) => defaults.max_byte_size.clone(),
                    None => None
                };
                Group::new(max_byte_size)
            }
        }
    }

    fn check_msg_size_agains_store(&self, msg_byte_size: u32) -> Result<(), Error> {
        if let Some(store_max_byte_size) = self.max_byte_size {
            if msg_byte_size > store_max_byte_size {
                return Err(Error::ExceedesStoreMax)
            }
        }
        Ok(())
    }

    fn check_msg_size_against_group(&mut self, group: Group, msg_priority: u32, msg_byte_size: u32) -> Result<Group, Error> {
        // check if the msg is too large for the target group
        if let Some(group_max_byte_size) = &group.max_byte_size {
            if &msg_byte_size > group_max_byte_size {
                self.groups_map.insert(msg_priority, group);
                return Err(Error::ExceedesGroupMax);
            }
        }

        // get the total byte count of all msgs that are higher priority
        // in order to know how free bytes are remaining for the new message
        let higher_priority_msg_total = {
            let mut total = 0;
            for (priority, group) in self.groups_map.iter().rev() {
                if &msg_priority > priority {
                    break;
                }
                total += group.byte_size;
            }
            total
        };

        // check if there is enough free space for the message
        if let Some(store_max_byte_size) = self.max_byte_size {
            if Self::msg_excedes_max_byte_size(&higher_priority_msg_total, &store_max_byte_size, &msg_byte_size) {
                self.groups_map.insert(msg_priority, group);
                return Err(Error::LacksPriority);
            }
        }
        Ok(group)
    }

    fn prune_group(&mut self, group: &mut Group, msg_byte_size: u32, prune_type: PruneBy) -> Result<(u32, Vec<Uuid>), Error> {
        let (byte_size, max_byte_size) = match prune_type {
            PruneBy::Group => (group.byte_size, group.max_byte_size),
            PruneBy::Store => (self.byte_size, self.max_byte_size)
        };
        let mut removed_msgs = vec![];
        let mut bytes_removed = 0;
        if let Some(max_byte_size) = &max_byte_size {            
            if Self::msg_excedes_max_byte_size(&byte_size, max_byte_size, &msg_byte_size) {
                // prune group
                for (uuid, group_msg_byte_size) in group.msgs_map.iter() {
                    if !Self::msg_excedes_max_byte_size(&(byte_size - bytes_removed), max_byte_size, &msg_byte_size) {
                        break;
                    }
                    bytes_removed += group_msg_byte_size;
                    removed_msgs.push(uuid.clone());
                }
                for uuid in removed_msgs.iter() {
                    self.remove_msg(&uuid, group)?;
                }
            }
        }
        Ok((bytes_removed, removed_msgs))
    }

    fn prune_store(&mut self, group: Option<&mut Group>, msg_priority: u32, msg_byte_size: u32) -> Result<(u32, Vec<u32>, Vec<Uuid>), Error> {
        let mut groups_removed = vec![];
        let mut all_removed_msgs = vec![];
        let mut bytes_removed = 0;
        {
            if let Some(store_max_byte_size) = self.max_byte_size.clone() {
                if Self::msg_excedes_max_byte_size(&self.byte_size, &store_max_byte_size, &msg_byte_size) {
                    'groups: for (priority, group) in self.groups_map.iter_mut() {
                        if &msg_priority < priority {
                            break 'groups;
                        }
                        if !Self::msg_excedes_max_byte_size(&(self.byte_size - bytes_removed), &store_max_byte_size, &msg_byte_size) {
                            break 'groups;
                        }
                        let mut removed_msgs = RemovedMsgs::new(*priority);
                        'messages: for (uuid, group_msg_byte_size) in group.msgs_map.iter() {
                            if !Self::msg_excedes_max_byte_size(&(self.byte_size - bytes_removed), &store_max_byte_size, &msg_byte_size) {
                                break 'messages;
                            }
                            bytes_removed += group_msg_byte_size;
                            removed_msgs.add(uuid.clone());
                        }
                        if group.byte_size == 0 {
                            groups_removed.push(*priority);
                        }
                        all_removed_msgs.push(removed_msgs);
                    }
                    // get groups of msgs that where removed
                    for group_data in &all_removed_msgs {
                        let mut group = match self.groups_map.remove(&group_data.priority) {
                            Some(group) => Ok(group),
                            None => Err(Error::SyncError)
                        }?;
                        for uuid in &group_data.msgs {
                            self.remove_msg(&uuid, &mut group)?;
                        }
                        self.groups_map.insert(group_data.priority, group);
                    }
                    for priority in &groups_removed {
                        self.groups_map.remove(&priority);
                    }
    
                    // prune group again
                    if let Some(group) = group {
                        self.prune_group(group, msg_byte_size, PruneBy::Store)?;
                    }
                }            
            }
        }
        
        let msgs_removed: Vec<Uuid> = all_removed_msgs.into_iter().map(|removed_msgs| removed_msgs.msgs).flatten().collect();
        Ok((bytes_removed, groups_removed, msgs_removed))
    }

    fn insert_msg(&mut self, mut group: Group, uuid: Uuid, priority: u32, msg_byte_size: u32) {
        self.byte_size += msg_byte_size;                                          // increase store byte size
        self.id_to_group_map.insert(uuid.clone(), priority);            // insert the uuid into the uuid->priority map
        group.byte_size += msg_byte_size;                                         // increase the group byte size
        group.msgs_map.insert(uuid.clone(), msg_byte_size);             // insert the uuid into the uuid->byte size map
        self.groups_map.insert(priority, group);
    }

    // fn insert_data(&mut self, data: &PacketMetaData) -> Result<(), Error> {

    //     // check if the msg is too large for the store
    //     self.check_msg_size_agains_store(data.byte_size)?;

    //     // check if the target group exists
    //     // create if id does not
    //     let group = self.get_group(data.priority);

    //     // check if the msg is too large for the target group
    //     let mut group = self.check_msg_size_against_group(group, data.priority, data.byte_size)?;

    //     // prune group if needed
    //     self.prune_group(&mut group, data.byte_size, PruneBy::Group)?;

    //     // prune store
    //     self.prune_store(Some(&mut group), data.priority, data.byte_size)?;

    //     // insert msg
    //     self.insert_msg(group, data.uuid, data.priority, data.byte_size);

    //     Ok(())
    // }

    /// Adds a msg to the store when no uuid is provided
    /// see also: add_with_uuid
    /// 
    /// # Example
    /// ```
    /// use msg_store::Store;
    /// 
    /// let mut store = Store::new();
    /// let uuid = store.add(1, "my message".len() as u32).unwrap().uuid;
    /// 
    /// ```
    /// 
    pub fn add(&mut self, priority: u32, msg_byte_size: u32) -> Result<AddResult, Error> {
        let uuid = self.uuid_manager.next(priority);
        self.add_with_uuid(uuid, msg_byte_size)        
    }

    /// Adds a msg to the store
    /// 
    /// The message itself is written to disk as well as metadata about the message
    /// such as its bytesize and priority. The priority and bytesize will
    /// also be held in memory for quick access. A unique uuid will be returned
    /// on success.
    /// 
    /// The store's inserted message count will also be incremented by one.
    /// 
    /// # Errors
    /// The method will return an error when:
    /// * the message byte size exceeds the store's max byte size limit.
    /// * the message byte size exceeds the priority group's max byte size limit.
    /// * the message byte size does not exceed either the store's or group's max limit, but
    ///    where the the store does not have enough space for it after accounting for
    ///    higher priority messages i.e., higher priority messages will not be removed to make
    ///    space for lower priority ones.
    /// * the database implimentation encounters an error. Please read the database plugin's documentation for details.
    /// 
    /// The error wiil be returned as a string.
    /// 
    /// # Example
    /// ```
    /// use msg_store::Store;
    /// 
    /// let mut store = Store::new();
    /// let uuid = store.uuid(1);
    /// let add_result = store.add_with_uuid(uuid, "my message".len() as u32).unwrap();
    /// 
    /// ```
    ///
    pub fn add_with_uuid(&mut self, uuid: Uuid, msg_byte_size: u32) -> Result<AddResult, Error> {
        // let msg_byte_size = msg.len() as u32;
        let priority = uuid.priority;

        // check if the msg is too large for the store
        self.check_msg_size_agains_store(msg_byte_size)?;

        // check if the target group exists
        // create if id does not
        let group = self.get_group(priority);

        // check if the msg is too large for the target group
        let mut group = self.check_msg_size_against_group(group, priority, msg_byte_size)?;

        let mut bytes_removed = 0;
        let mut groups_removed = vec![];
        let mut msgs_removed = vec![];

        // prune group if needed
        let (bytes_removed_from_group, mut msgs_removed_from_group) = self.prune_group(&mut group, msg_byte_size, PruneBy::Group)?;

        bytes_removed += bytes_removed_from_group;
        msgs_removed.append(&mut msgs_removed_from_group);

        // prune store
        let (bytes_removed_from_groups, mut groups_removed_from_store, mut msgs_removed_from_groups) = self.prune_store(Some(&mut group), priority, msg_byte_size)?;
        bytes_removed += bytes_removed_from_groups;
        msgs_removed.append(&mut msgs_removed_from_groups);
        groups_removed.append(&mut groups_removed_from_store);

        // insert msg
        self.insert_msg(group, uuid, priority, msg_byte_size);
        
        Ok(AddResult{ uuid, bytes_removed, msgs_removed, groups_removed })
    }
    
    /// Deletes a message from the store
    /// 
    /// A message will be removed from the store and disk once given the
    /// the message's uuid number.
    /// 
    /// The message store's msgs_deleted member will also be incremented by one.
    /// 
    /// # Errors
    /// An error will be returned if the database encounters an error, read the database plugin documention for specifics.
    /// 
    /// # Example
    /// ```
    /// use msg_store::Store;
    /// 
    /// let mut store = Store::new();
    /// let uuid = store.add(1, "my message".len() as u32).unwrap().uuid;
    /// store.del(&uuid).unwrap();
    /// 
    /// ```
    pub fn del(&mut self, uuid: &Uuid) -> Result<(), Error> {
        let mut remove_group = false;
        let priority = match self.id_to_group_map.get(&uuid) {
            Some(priority) => priority,
            None => {
                return Ok(());
            }
        };
        let mut group = match self.groups_map.get_mut(&priority) {
            Some(group) => group,
            None => {
                return Ok(());
            }
        };
        let bytes_removed = match group.msgs_map.remove(&uuid) {
            Some(bytes_removed) => bytes_removed,
            None => {
                return Ok(());
            }
        };
        group.byte_size -= bytes_removed;
        self.byte_size -= bytes_removed;
        if group.msgs_map.is_empty() {
            remove_group = true;
        }
        if remove_group {
            self.groups_map.remove(&priority);
        }
        self.id_to_group_map.remove(&uuid);
        Ok(())
    }

    /// Deletes a group and its messages from the store
    /// 
    /// A group's metadata and messages will be removed from the store and disk once given the
    /// the group's priority number.
    /// 
    /// The message store's msgs_deleted member will also be incremented by one.
    /// 
    /// # Errors
    /// An error will be returned if the database encounters an error, read the database plugin documention for specifics.
    /// 
    /// # Example
    /// ```
    /// use msg_store::Store;
    /// 
    /// let mut store = Store::new();
    /// store.add(1, "my message".len() as u32).unwrap();
    /// store.del_group(&1).unwrap();
    /// 
    /// assert!(store.get(None, None, false).unwrap().is_none());
    /// 
    /// ```
    pub fn del_group(&mut self, priority: &u32) -> Result<(), Error> {
        if let Some(group) = self.groups_map.remove(priority) {
            for (uuid, _msg_byte_size) in group.msgs_map.iter() {
                self.id_to_group_map.remove(uuid);
            }
            self.byte_size -= group.byte_size;            
        }        
        Ok(())
    }

    /// Gets a message from the store, either the next in line, the next in a specified priority group, or a specific message
    /// specified by the uuid option.
    /// 
    /// If the uuid option is present, it will search for that uuid only. If the priority option is present, it will retrieve the next
    /// message in line for that priority only. If neither options are present, the store will retrieve the next message in line store wide. 
    /// If no message is found, None is returned.
    /// 
    /// # Errors
    /// This method will return an error if the database encounters an error or if the store realizes that the state is out of sync.
    /// 
    /// # Example
    /// ```
    /// use msg_store::Store;
    /// 
    /// let mut store = Store::new();
    /// let uuid = store.add(1, "my message".len() as u32).unwrap().uuid;
    /// let my_message = store.get(Some(uuid), None, false).unwrap();
    /// assert!(my_message.is_some());
    /// 
    /// let my_message = store.get(None, Some(1), false).unwrap();
    /// assert!(my_message.is_some());
    /// 
    /// let my_message = store.get(None, None, false).unwrap();
    /// assert!(my_message.is_some());
    /// 
    /// ```
    pub fn get(&self, uuid: Option<Uuid>, priority: Option<u32>, reverse: bool) -> Result<Option<Uuid>, Error> {

        if let Some(uuid) = uuid {

            match self.id_to_group_map.contains_key(&uuid) {
                true => Ok(Some(uuid)),
                false => Ok(None)
            }

        } else if let Some(priority) = priority {

            let group = match self.groups_map.get(&priority) {
                Some(group) => group,
                None => { return Ok(None) }
            };

            let uuid_option = match !reverse {
                true => group.msgs_map.keys().rev().next(),
                false => group.msgs_map.keys().next()
            };

            match uuid_option {
                Some(uuid) => Ok(Some(uuid.clone())),
                None => { return Ok(None) }
            }
            

        } else {

            let next_group_option = match !reverse {
                true => self.groups_map.values().rev().next(),
                false => self.groups_map.values().next()
            };

            let group = match next_group_option {
                Some(group) => group,
                None => { return Ok(None) }
            };

            let next_uuid_option = match !reverse {
                true => group.msgs_map.keys().rev().next(),
                false => group.msgs_map.keys().next()
            };

            match next_uuid_option {
                Some(uuid) => Ok(Some(uuid.clone())),
                None => Err(Error::SyncError)
            }

        }
    }

    pub fn get_n(&self, n: usize, starting_priority: Option<u32>, after_uuid: Option<Uuid>, reverse: bool) -> Vec<Uuid> {
        if let Some(starting_priority) = starting_priority {
            if let Some(after_uuid) = after_uuid {
                if !reverse {
                    self.id_to_group_map.iter()
                        .rev() // start with highest uuid
                        .filter(|(uuid, _group)| uuid.priority <= starting_priority && uuid < &&after_uuid)
                        .map(|(uuid, _group)| uuid.clone())
                        .take(n)
                        .collect::<Vec<Uuid>>()
                } else {
                    self.id_to_group_map.iter()
                        .filter(|(uuid, _group)| uuid.priority <= starting_priority && uuid < &&after_uuid)
                        .map(|(uuid, _group)| uuid.clone())
                        .take(n)
                        .collect::<Vec<Uuid>>()
                }
            } else {
                if !reverse {
                    self.id_to_group_map.iter()
                        .rev() // start with highest uuid
                        .filter(|(uuid, _group)| uuid.priority <= starting_priority)
                        .map(|(uuid, _group)| uuid.clone())
                        .take(n)
                        .collect::<Vec<Uuid>>()
                } else {
                    self.id_to_group_map.iter()
                        .filter(|(uuid, _group)| uuid.priority <= starting_priority)
                        .map(|(uuid, _group)| uuid.clone())
                        .take(n)
                        .collect::<Vec<Uuid>>()
                }
            }
        } else {
            if let Some(after_uuid) = after_uuid {
                if !reverse {
                    self.id_to_group_map.iter()
                        .rev() // start with highest uuid
                        .filter(|(uuid, _group)| uuid < &&after_uuid)
                        .map(|(uuid, _group)| uuid.clone())
                        .take(n)
                        .collect::<Vec<Uuid>>()
                } else {
                    self.id_to_group_map.iter()
                        .filter(|(uuid, _group)| uuid < &&after_uuid)
                        .map(|(uuid, _group)| uuid.clone())
                        .take(n)
                        .collect::<Vec<Uuid>>()
                }
            } else {
                if !reverse {
                    self.id_to_group_map.iter()
                        .rev() // start with highest uuid
                        .map(|(uuid, _group)| uuid.clone())
                        .take(n)
                        .collect::<Vec<Uuid>>()
                } else {
                    self.id_to_group_map.iter()
                        .map(|(uuid, _group)| uuid.clone())
                        .take(n)
                        .collect::<Vec<Uuid>>()
                }
            }
        }
    }

    /// Get x number of message metadata within a given range and/or priority. This can be useful in a larger application 
    /// context where more than one message retrieval may be required, like in a multithreaded app.
    /// 
    /// The range argument is a tulple consisting of two members. The first member is the starting index, and the second is the last index. 
    /// As always, indexes start with zero. If the priority argument is passed a integer the function will only return a vec containing metadata from that priority.
    /// 
    /// # Example
    /// 
    /// let mut store = open();
    /// let uuid1 = store.add(1, "my message".len() as u32).unwrap().uuid;
    /// let uuid2 = store.add(1, "my second message".len() as u32).unwrap().uuid;
    /// let uuid3 = store.add(1, "my thrid message".len() as u32).unwrap().uuid;
    /// 
    /// let range = (0,2);
    /// let priority = Some(1);
    /// let set = store.get_metadata(range, priority);
    /// assert_eq!(uuid1, set[0].uuid);
    /// assert_eq!(uuid2, set[1].uuid);
    /// assert_eq!(uuid3, set[2].uuid);
    /// 
    pub fn get_metadata(&mut self, range: (u32, u32), priority: Option<u32>) -> Vec<PacketMetaData> {
        let mut uuids = vec![];
        let mut iter_count: u32 = 0;
        let (start, end) = range;
        let mut primer_iter = 0;
        if let Some(priority) = priority {
            if let Some(group) = self.groups_map.get(&priority) {                
                for (uuid, msg_byte_size) in group.msgs_map.iter() {
                    if primer_iter < start {
                        primer_iter += 1;
                        continue;
                    }
                    uuids.push(PacketMetaData{
                        uuid: uuid.clone(),
                        priority: priority.clone(),
                        byte_size: msg_byte_size.clone()
                    });
                    if iter_count == end {
                        break;
                    }
                    iter_count += 1;
                }
            }
        } else {
            'group: for (priority, group) in self.groups_map.iter() {
                'msg: for (uuid, msg_byte_size) in group.msgs_map.iter().rev() {
                    if primer_iter < start {
                        primer_iter += 1;
                        continue 'msg;
                    }
                    uuids.push(PacketMetaData{
                        uuid: uuid.clone(),
                        priority: priority.clone(),
                        byte_size: msg_byte_size.clone()
                    });
                    if iter_count == end {
                        break 'group;
                    }
                    iter_count += 1;
                }
            }
        }
        uuids
    }

    /// Updates the defaults for a priority group
    /// 
    /// The method takes a GroupDefaults struct which contains a member: max_byte_size.
    /// The max_byte_size member type is Option<u32>. This method will auto prune the group
    /// if the group's current bytesize is greater than the new max bytesize default.
    /// 
    /// # Errors
    /// The method will return an error if the database encounters an error
    /// 
    /// # Example
    /// ```
    /// use msg_store::store::{Store,GroupDefaults};
    /// 
    /// let mut store = Store::new();
    /// store.add(1, "foo".len() as u32).unwrap();
    /// store.add(1, "bar".len() as u32).unwrap();
    /// assert_eq!(6, store.byte_size); // The store should contain 6 bytes of data, 3 for each message.
    /// 
    /// store.update_group_defaults(1, &GroupDefaults{ max_byte_size: Some(3) });
    /// 
    /// // The store should have removed 3 bytes in order to abide by the new requirement
    /// assert_eq!(3, store.byte_size); 
    /// 
    /// ```
    pub fn update_group_defaults(&mut self, priority: u32, defaults: &GroupDefaults) -> Result<(u32, Vec<Uuid>), Error> {
        let mut bytes_removed = 0;
        let mut msgs_removed = vec![];
        self.group_defaults.insert(priority, defaults.clone());
        if let Some(mut group) = self.groups_map.remove(&priority) {
            group.update_from_config(defaults.clone());
            let (bytes_removed_from_group, mut msgs_removed_from_group) = self.prune_group(&mut group, 0, PruneBy::Group)?;
            bytes_removed += bytes_removed_from_group;
            msgs_removed.append(&mut msgs_removed_from_group);
            self.groups_map.insert(priority, group);
        }
        Ok((bytes_removed, msgs_removed))
    }

    /// Removes the defaults for a priority group
    /// 
    /// # Example
    /// ```
    /// use msg_store::store::{Store,GroupDefaults};
    /// 
    /// let mut store = Store::new();
    /// store.update_group_defaults(1, &GroupDefaults{ max_byte_size: Some(6) });
    /// store.add(1, "foo".len() as u32).unwrap();
    /// store.add(1, "bar".len() as u32).unwrap();
    /// 
    /// let group_1 = store.groups_map.get(&1).expect("Could not find group");
    /// assert_eq!(Some(6), group_1.max_byte_size);
    /// 
    /// // Now for the removal of the defaults
    /// store.delete_group_defaults(1);
    /// 
    /// let group_1 = store.groups_map.get(&1).expect("Could not find group");
    /// 
    /// assert_eq!(None, group_1.max_byte_size);
    /// assert!(store.group_defaults.get(&1).is_none()); 
    /// 
    /// ```
    pub fn delete_group_defaults(&mut self, priority: u32) {
        self.group_defaults.remove(&priority);
        if let Some(group) = self.groups_map.get_mut(&priority) {
            group.max_byte_size = None;
        }
    }

    /// Updates the defaults for the store
    /// 
    /// The method takes a StoreDefaults struct which contains a member: max_byte_size.
    /// The max_byte_size member type is Option<u32>. This method will auto prune the store
    /// if the store's current bytesize is greater than the new max bytesize default.
    /// 
    /// # Errors
    /// The method will return an error if the database encounters an error
    /// 
    /// # Example
    /// ```
    /// use msg_store::store::{Store, StoreDefaults};
    /// 
    /// let mut store = Store::new();
    /// store.add(1, "foo".len() as u32).unwrap();
    /// store.add(1, "bar".len() as u32).unwrap();
    /// assert_eq!(6, store.byte_size); // The store should contain 6 bytes of data, 3 for each message.
    /// 
    /// store.update_store_defaults(&StoreDefaults{ max_byte_size: Some(3) }).unwrap();
    /// 
    /// // The store should have removed 3 bytes in order to abide by the new requirement
    /// assert_eq!(3, store.byte_size); 
    /// 
    /// ```
    pub fn update_store_defaults(&mut self, defaults: &StoreDefaults) -> Result<(u32, Vec<u32>, Vec<Uuid>), Error> {
        self.max_byte_size = defaults.max_byte_size;
        self.prune_store(None, u32::MAX, 0)
    }

    pub fn uuid(&mut self, priority: u32) -> Uuid {
        self.uuid_manager.next(priority)
    }

}