Skip to main content

tower_http_cache_plus/cache/
weight.rs

1use kutil::{http::*, std::foster::*};
2
3//
4// CacheWeight
5//
6
7/// Cache weight.
8pub trait CacheWeight {
9    /// Cache weight as a byte count.
10    ///
11    /// It is *not* the amount of memory used, but rather an indicator of *potential* storage
12    /// requirements.
13    ///
14    /// Its intended use is for apples-to-apples comparisons, e.g. to find out which of two items
15    /// of the same type weighs more. But even then it may be misleading in some cases, e.g. if
16    /// storage involves compression then the "heavier" item might end up taking less storage then
17    /// the "lighter" item.
18    ///
19    /// Note that *sums* of weights can be especially misleading in terms of memory use because
20    /// there might be memory shared between items, e.g. via the use of
21    /// [ImmutableBytes](kutil::std::immutable::ImmutableBytes).
22    fn cache_weight(&self) -> usize;
23}
24
25impl CacheWeight for ETag {
26    fn cache_weight(&self) -> usize {
27        const SELF_SIZE: usize = size_of::<ETag>();
28        SELF_SIZE + self.tag.len()
29    }
30}
31
32impl CacheWeight for Language {
33    fn cache_weight(&self) -> usize {
34        const SELF_SIZE: usize = size_of::<Language>();
35        let mut size = SELF_SIZE;
36        for subtag in &self.0 {
37            size += subtag.len();
38        }
39        size
40    }
41}
42
43impl CacheWeight for MediaType {
44    fn cache_weight(&self) -> usize {
45        const SELF_SIZE: usize = size_of::<MediaType>();
46        SELF_SIZE + self.main.cache_weight() + self.subtype.cache_weight()
47    }
48}
49
50impl CacheWeight for MediaTypeSegment {
51    fn cache_weight(&self) -> usize {
52        const SELF_SIZE: usize = size_of::<MediaTypeSegment>();
53        SELF_SIZE + self.0.len()
54    }
55}
56
57impl CacheWeight for MediaTypeSelector {
58    fn cache_weight(&self) -> usize {
59        const SELF_SIZE: usize = size_of::<MediaTypeSelector>();
60        SELF_SIZE + self.main.cache_weight() + self.subtype.cache_weight()
61    }
62}
63
64impl<SelectionT> CacheWeight for Selector<SelectionT>
65where
66    SelectionT: CacheWeight,
67{
68    fn cache_weight(&self) -> usize {
69        let mut size = size_of::<Self>();
70        if let Self::Specific(selection) = self {
71            size += selection.cache_weight();
72        }
73        size
74    }
75}