Created
January 15, 2019 23:34
-
-
Save rust-play/8f2a2316dd93a2ddbac873064bbde344 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// test3.rs | |
//! test of using an arena for managing info | |
use typed_arena::Arena; | |
use std::collections::HashMap; | |
pub type StringArena = Arena<String>; | |
pub type Map<'a> = HashMap<&'a str, PackageVersion<'a>>; | |
pub struct PackMap<'a> { | |
arena: StringArena, | |
map: Map<'a>, | |
} | |
impl<'a> PackMap<'a> { | |
fn new() -> Self { | |
Self { | |
arena: StringArena::new(), | |
map: Map::new(), | |
} | |
} | |
pub fn add< I: Into<String>>(&mut self, package: I) { | |
let v1: &'a str = self.arena.alloc(package.into()); | |
// ^ problem here with lifetime | |
let p1 = PackageVersion::new(v1); | |
self.map.insert(v1, p1); | |
} | |
pub fn get(&self, name: &str) -> Option<&PackageVersion<'a>> { | |
self.map.get(name) | |
} | |
} | |
pub struct PackageVersion<'a> { | |
item: &'a str, | |
} | |
impl<'a> PackageVersion<'a> { | |
pub fn name(&self) -> &str { | |
let pieces: Vec<&'a str> = self.item.split("-").collect(); | |
pieces[0] | |
} | |
pub fn version(&self) -> &str { | |
let pieces: Vec<&'a str> = self.item.split("-").collect(); | |
pieces[1] | |
} | |
pub fn fullname(&self) -> &str { | |
self.item | |
} | |
pub fn new<'b: 'a>(item: &'b str) -> Self { | |
Self { | |
item | |
} | |
} | |
} | |
//type Map = HashMap<String, Option<IdString>>; | |
pub fn test3() { | |
let arena = StringArena::new(); | |
let mut map = Map::new(); | |
let v1 = arena.alloc("foo-0.1.0".into()); | |
let val1 = PackageVersion::new(v1) ; | |
let v2 = arena.alloc("foo-0.2.0".into()); | |
let val2 = PackageVersion::new(v1) ; | |
map.insert(v1, val1); | |
map.insert(v2, val2); | |
let v = map.get("foo-0.2.0").unwrap(); | |
println!("fullname:{} base:{} version:{}", v.fullname(), v.name(), v.version()); | |
let mut pm = PackMap::new(); | |
pm.add("foo-1.0.0"); | |
pm.add("foo-2.0.0"); | |
let p = pm.get("foo-2.0.0").unwrap(); | |
println!("{}", p.fullname()); | |
} | |
// main.rs | |
mod test3; | |
use self::test3::test3; | |
fn main() { | |
test3(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment