Skip to content

Commit d9c03ff

Browse files
committed
feat: in mem kv store with rust
1 parent 40d85eb commit d9c03ff

File tree

3 files changed

+117
-0
lines changed

3 files changed

+117
-0
lines changed

rust/kv_store/.gitignore

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# Cargo
2+
/target/
3+
**/*.rs.bk
4+
5+
# Artifacts
6+
/debug/
7+
release/
8+
9+
# Binaries
10+
*.exe
11+
*.exe.*
12+
*.dll
13+
*.dylib
14+
*.so
15+
16+
# Runtime files
17+
*.log
18+
*.out
19+
*.pid
20+
21+
# Other
22+
*.swp
23+
*.bak
24+
*.tmp
25+
*.old
26+
*.orig
27+
28+
# MacOS
29+
.DS_Store
30+
31+
# Linux
32+
*~
33+
34+
# Node
35+
node_modules/
36+
37+
# IDEs
38+
.idea/
39+
.vscode/
40+
*.sublime-workspace
41+
42+
# Rust
43+
Cargo.lock

rust/kv_store/Cargo.toml

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
[package]
2+
name = "kv_store"
3+
version = "0.1.0"
4+
edition = "2021"
5+
6+
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7+
8+
[dependencies]

rust/kv_store/src/main.rs

+66
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
use std::collections::HashMap;
2+
use std::sync::{Arc, Mutex};
3+
use std::io::{self, Write};
4+
5+
type Db = Arc<Mutex<HashMap<String, String>>>;
6+
7+
struct KvStore {
8+
db: Db,
9+
}
10+
11+
impl KvStore {
12+
fn new() -> Self {
13+
KvStore {
14+
db: Arc::new(Mutex::new(HashMap::new())),
15+
}
16+
}
17+
18+
fn set(&self, key: String, value: String) {
19+
let mut db = self.db.lock().unwrap();
20+
db.insert(key, value);
21+
}
22+
23+
fn get(&self, key: String) -> Option<String> {
24+
let db = self.db.lock().unwrap();
25+
db.get(&key).cloned()
26+
}
27+
28+
fn delete(&self, key: String) -> Option<String> {
29+
let mut db = self.db.lock().unwrap();
30+
db.remove(&key)
31+
}
32+
}
33+
34+
fn main() {
35+
let store = KvStore::new();
36+
loop {
37+
print!("> ");
38+
io::stdout().flush().unwrap();
39+
let mut input = String::new();
40+
io::stdin().read_line(&mut input).unwrap();
41+
let parts: Vec<&str> = input.trim().split_whitespace().collect();
42+
if parts.is_empty() {
43+
continue;
44+
}
45+
match parts[0] {
46+
"set" if parts.len() == 3 => {
47+
store.set(parts[1].to_string(), parts[2].to_string());
48+
println!("OK");
49+
}
50+
"get" if parts.len() == 2 => {
51+
match store.get(parts[1].to_string()) {
52+
Some(value) => println!("{}", value),
53+
None => println!("Key not found"),
54+
}
55+
}
56+
"delete" if parts.len() == 2 => {
57+
match store.delete(parts[1].to_string()) {
58+
Some(_) => println!("OK"),
59+
None => println!("Key not found"),
60+
}
61+
}
62+
"exit" => break,
63+
_ => println!("Unknown command"),
64+
}
65+
}
66+
}

0 commit comments

Comments
 (0)