Skip to content

Commit

Permalink
Merge pull request #294 from CosmWasm/primary-key-string
Browse files Browse the repository at this point in the history
Implement PrimaryKey and Prefixer for String
  • Loading branch information
ethanfrey committed Jun 2, 2021
2 parents 5310525 + 4c8fc23 commit 65649f7
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions packages/storage-plus/src/keys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,21 @@ impl<'a> Prefixer<'a> for Vec<u8> {
}
}

impl<'a> PrimaryKey<'a> for String {
type Prefix = ();
type SubPrefix = ();

fn key(&self) -> Vec<&[u8]> {
vec![self.as_bytes()]
}
}

impl<'a> Prefixer<'a> for String {
fn prefix(&self) -> Vec<&[u8]> {
vec![self.as_bytes()]
}
}

/// type safe version to ensure address was validated before use.
impl<'a> PrimaryKey<'a> for &'a Addr {
type Prefix = ();
Expand Down Expand Up @@ -255,6 +270,19 @@ mod test {
assert_eq!(joined, b"hello")
}

#[test]
fn string_key_works() {
type K = String;

let k: K = "hello".to_string();
let path = k.key();
assert_eq!(1, path.len());
assert_eq!("hello".as_bytes(), path[0]);

let joined = k.joined_key();
assert_eq!(joined, b"hello")
}

#[test]
fn nested_str_key_works() {
type K<'a> = (&'a str, &'a [u8]);
Expand Down Expand Up @@ -321,5 +349,13 @@ mod test {
triple.prefix(),
vec![one.as_slice(), two.as_slice(), three.as_slice()]
);

// same works with owned variants (&str -> String, &[u8] -> Vec<u8>)
let owned_triple: (String, U32Key, Vec<u8>) =
("begin".to_string(), 12345.into(), b"end".to_vec());
assert_eq!(
owned_triple.prefix(),
vec![one.as_slice(), two.as_slice(), three.as_slice()]
);
}
}

0 comments on commit 65649f7

Please sign in to comment.