From aa3dd026c9a8c8407bccea0f1345f777afe0090c Mon Sep 17 00:00:00 2001 From: Lars Wirzenius Date: Fri, 18 Sep 2020 19:29:40 +0300 Subject: feat: representations of responses for server operations --- src/lib.rs | 1 + src/server.rs | 78 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 79 insertions(+) create mode 100644 src/server.rs (limited to 'src') diff --git a/src/lib.rs b/src/lib.rs index 6955243..d96fd2b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -2,4 +2,5 @@ pub mod chunk; pub mod chunkid; pub mod chunkmeta; pub mod index; +pub mod server; pub mod store; diff --git a/src/server.rs b/src/server.rs new file mode 100644 index 0000000..6b8a064 --- /dev/null +++ b/src/server.rs @@ -0,0 +1,78 @@ +use crate::chunkid::ChunkId; +use crate::chunkmeta::ChunkMeta; +use serde::{Deserialize, Serialize}; +use std::collections::HashMap; +use std::default::Default; + +/// Result of creating a chunk. +#[derive(Debug, Serialize)] +pub struct Created { + id: ChunkId, +} + +impl Created { + pub fn new(id: ChunkId) -> Self { + Created { id } + } + + pub fn to_json(&self) -> String { + serde_json::to_string(&self).unwrap() + } +} + +/// Result of retrieving a chunk. +#[derive(Debug, Serialize)] +pub struct Fetched { + id: ChunkId, + meta: ChunkMeta, +} + +impl Fetched { + pub fn new(id: ChunkId, meta: ChunkMeta) -> Self { + Fetched { id, meta } + } +} + +/// Result of a search. +#[derive(Debug, Default, PartialEq, Deserialize, Serialize)] +pub struct SearchHits { + map: HashMap, +} + +impl SearchHits { + pub fn insert(&mut self, id: ChunkId, meta: ChunkMeta) { + self.map.insert(format!("{}", id), meta); + } + + pub fn from_json(s: &str) -> anyhow::Result { + let map = serde_json::from_str(s)?; + Ok(SearchHits { map }) + } + + pub fn to_json(&self) -> String { + serde_json::to_string(&self.map).unwrap() + } +} + +#[cfg(test)] +mod test_search_hits { + use super::{ChunkMeta, SearchHits}; + + #[test] + fn no_search_hits() { + let hits = SearchHits::default(); + assert_eq!(hits.to_json(), "{}"); + } + + #[test] + fn one_search_hit() { + let id = "abc".parse().unwrap(); + let meta = ChunkMeta::new("123"); + let mut hits = SearchHits::default(); + hits.insert(id, meta); + eprintln!("hits: {:?}", hits); + let json = hits.to_json(); + let hits2 = SearchHits::from_json(&json).unwrap(); + assert_eq!(hits, hits2); + } +} -- cgit v1.2.1