sonic_channel2/commands/
count.rs

1use super::StreamCommand;
2use crate::misc::*;
3use crate::protocol;
4use crate::result::*;
5
6/// Parameters for the `count` command.
7#[derive(Debug)]
8pub struct CountRequest(OptDest);
9
10impl CountRequest {
11    /// Creates a new request to get the number of buckets in the collection.
12    pub fn buckets(collection: impl ToString) -> CountRequest {
13        Self(OptDest::col(collection))
14    }
15
16    /// Creates a new request to get the number of objects in the collection bucket.
17    pub fn objects(collection: impl ToString, bucket: impl ToString) -> CountRequest {
18        Self(OptDest::col_buc(collection, bucket))
19    }
20
21    /// Creates a new request to get the number of words in the collection bucket object.
22    pub fn words(
23        collection: impl ToString,
24        bucket: impl ToString,
25        object: impl ToString,
26    ) -> CountRequest {
27        Self(OptDest::col_buc_obj(collection, bucket, object))
28    }
29}
30
31impl From<Dest> for CountRequest {
32    fn from(d: Dest) -> Self {
33        Self(OptDest::from(d))
34    }
35}
36
37impl From<ObjDest> for CountRequest {
38    fn from(d: ObjDest) -> Self {
39        Self(OptDest::from(d))
40    }
41}
42
43#[derive(Debug)]
44pub struct CountCommand {
45    pub(crate) req: CountRequest,
46}
47
48impl StreamCommand for CountCommand {
49    type Response = usize;
50
51    fn request(&self) -> protocol::Request {
52        let dest = &self.req.0;
53        protocol::Request::Count {
54            collection: dest.collection.clone(),
55            bucket: dest.bucket.clone(),
56            object: dest.object.clone(),
57        }
58    }
59
60    fn receive(&self, res: protocol::Response) -> Result<Self::Response> {
61        if let protocol::Response::Result(count) = res {
62            Ok(count)
63        } else {
64            Err(Error::WrongResponse)
65        }
66    }
67}