Advertisement
Guest User

Untitled

a guest
Apr 18th, 2019
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 KB | None | 0 0
  1. #![allow(dead_code)]
  2. use std::collections::HashMap;
  3.  
  4. struct KVDB {
  5. entries: HashMap<String, String>,
  6. }
  7.  
  8. impl KVDB {
  9. /// Creates a new instance of the key-value store.
  10. pub fn new() -> KVDB {
  11. KVDB {
  12. entries: HashMap::new(),
  13. }
  14. }
  15.  
  16. /// Retrieves a value given a key.
  17. pub fn get(&self, key: &str) -> Option<String> {
  18. self.entries
  19. .get(&key.to_string()).cloned()
  20. }
  21.  
  22. /// Stores a value into its given key.
  23. pub fn put(&mut self, key: &str, value: &str) -> Result<String, String> {
  24. let action = self.entries.insert(key.to_string(), value.to_string());
  25. {
  26. match action {
  27. None => Ok("added".to_string()),
  28. _ => Ok("modified".to_string()),
  29. }
  30. }
  31. }
  32. }
  33.  
  34. #[cfg(test)]
  35. mod tests {
  36. // Note this useful idiom: importing names from outer (for mod tests) scope.
  37. use super::*;
  38.  
  39. #[test]
  40. fn test_basics() {
  41. let mut kvdb = KVDB::new();
  42. assert_eq!(kvdb.put("a", "b"), Ok("added".to_string()));
  43. assert_eq!(kvdb.get("a"), Some("b".to_string()));
  44. assert_eq!(kvdb.put("a", "c"), Ok("modified".to_string()));
  45. assert_eq!(kvdb.get("b"), None);
  46. }
  47.  
  48. #[test]
  49. fn test_inserting_types() {
  50. let mut kvdb = KVDB::new();
  51. assert_eq!(kvdb.put("a", "b"), Ok("added".to_string()));
  52. assert_eq!(kvdb.put(&"b".to_string(), "b"), Ok("added".to_string()));
  53. }
  54. }
  55.  
  56. fn main() {}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement