Skip to content

Commit

Permalink
Use Rc for better deduplication
Browse files Browse the repository at this point in the history
This massively reduces memory usage in the number_to_setver example.
  • Loading branch information
kleinesfilmroellchen committed Oct 2, 2022
1 parent ba729ef commit 8782c13
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 8 deletions.
9 changes: 5 additions & 4 deletions examples/number_to_setver.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use setver::SetVersion;
use std::env::args;
use std::rc::Rc;

fn main() {
let mut args = args();
Expand All @@ -11,14 +12,14 @@ fn main() {
// This is exactly how natural numbers (including zero) work in set theory.
// Some dynamic programming makes this ~ 1/2 O(n^2).
let mut previous_number_setvers = Vec::with_capacity(number);
previous_number_setvers.push(SetVersion::default());
previous_number_setvers.push(Rc::new(SetVersion::default()));

for n in 1..=number {
let mut n_version = SetVersion::default();
for child in previous_number_setvers.iter().take(n) {
n_version.add_child_version(child.clone());
for i in 0..n {
n_version.add_child_version(previous_number_setvers[i].clone());
}
previous_number_setvers.push(n_version);
previous_number_setvers.push(Rc::new(n_version));
}

let number_version = previous_number_setvers.last().unwrap();
Expand Down
9 changes: 5 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use std::collections::BTreeSet;
use std::fmt::Display;
use std::rc::Rc;
use std::str::FromStr;

/// A SetVer version specification.
Expand All @@ -13,7 +14,7 @@ use std::str::FromStr;
#[derive(Eq, PartialEq, Clone, Debug, Ord, PartialOrd, Default)]
pub struct SetVersion {
/// Making this an ordered set guarantees that all iterations are performed in order, which gives some nice guarantees for faster implementations.
versions: BTreeSet<SetVersion>,
versions: BTreeSet<Rc<SetVersion>>,
}

impl SetVersion {
Expand Down Expand Up @@ -58,7 +59,7 @@ impl SetVersion {
}

/// Adds the given version as a child version. This is useful when constructing a parent version for one or many previous child versions.
pub fn add_child_version(&mut self, child: SetVersion) -> &mut Self {
pub fn add_child_version(&mut self, child: Rc<SetVersion>) -> &mut Self {
self.versions.insert(child);
self
}
Expand Down Expand Up @@ -254,8 +255,8 @@ impl FromStr for SetVersion {

let versions = inner_sets
.iter()
.map(|string_set| string_set.parse())
.collect::<Result<BTreeSet<SetVersion>, SetVerParseError>>()?;
.map(|string_set| string_set.parse::<SetVersion>().map(Rc::new))
.collect::<Result<BTreeSet<Rc<SetVersion>>, SetVerParseError>>()?;
if versions.len() < inner_sets.len() {
return Err(SetVerParseError::NonUniqueElements);
}
Expand Down

0 comments on commit 8782c13

Please sign in to comment.