oxedyne/fe2o3/fe2o3_text/tests/detect_corpus/rust/async_tokio.txt
1.3 KiB, 1 run
created by r1870400018:12036, which is this file's identity for as long as the history lasts, whatever it is later renamed to
download · who wrote it · its history
| 1 | use std::collections::HashMap; |
| 2 | use std::sync::Arc; |
| 3 | |
| 4 | /// Shared application state behind an RwLock. |
| 5 | pub struct AppState { |
| 6 | cache: HashMap<String, Vec<u8>>, |
| 7 | hit_count: u64, |
| 8 | } |
| 9 | |
| 10 | impl AppState { |
| 11 | pub fn new() -> Self { |
| 12 | Self { |
| 13 | cache: HashMap::new(), |
| 14 | hit_count: 0, |
| 15 | } |
| 16 | } |
| 17 | |
| 18 | pub fn lookup(&mut self, key: &str) -> Option<&Vec<u8>> { |
| 19 | self.hit_count += 1; |
| 20 | self.cache.get(key) |
| 21 | } |
| 22 | |
| 23 | pub fn store(&mut self, key: String, data: Vec<u8>) { |
| 24 | self.cache.insert(key, data); |
| 25 | } |
| 26 | } |
| 27 | |
| 28 | /// A request handler that reads from shared state. |
| 29 | pub async fn handle_get( |
| 30 | state: Arc<std::sync::RwLock<AppState>>, |
| 31 | key: String, |
| 32 | ) |
| 33 | -> Result<Vec<u8>, String> |
| 34 | { |
| 35 | let mut guard = state.write().map_err(|e| format!("lock: {}", e))?; |
| 36 | match guard.lookup(&key) { |
| 37 | Some(data) => Ok(data.clone()), |
| 38 | None => Err(format!("key not found: {}", key)), |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | /// Process a batch of keys concurrently. |
| 43 | pub async fn batch_lookup( |
| 44 | state: Arc<std::sync::RwLock<AppState>>, |
| 45 | keys: Vec<String>, |
| 46 | ) |
| 47 | -> Vec<Result<Vec<u8>, String>> |
| 48 | { |
| 49 | let mut results = Vec::with_capacity(keys.len()); |
| 50 | for key in keys { |
| 51 | let result = handle_get(Arc::clone(&state), key).await; |
| 52 | results.push(result); |
| 53 | } |
| 54 | results |
| 55 | } |