1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
use std::fmt::{self, Debug};

use linked_hash_map::LinkedHashMap;

use base::crypto::Hash;
use base::RefCnt;
use error::Result;
use trans::Eid;

/// Data chunk
#[derive(Clone, Deserialize, Serialize)]
pub struct Chunk {
    pub(super) pos: usize, // chunk start position in segment data
    pub(super) len: usize, // chunk length, in bytes
    refcnt: RefCnt,
}

impl Chunk {
    pub fn new(pos: usize, len: usize) -> Self {
        Chunk {
            pos,
            len,
            refcnt: RefCnt::new(),
        }
    }

    #[inline]
    pub fn inc_ref(&mut self) -> Result<u32> {
        self.refcnt.inc_ref()
    }

    #[inline]
    pub fn dec_ref(&mut self) -> Result<u32> {
        self.refcnt.dec_ref()
    }

    #[inline]
    pub fn end_pos(&self) -> usize {
        self.pos + self.len
    }

    #[inline]
    pub fn is_orphan(&self) -> bool {
        self.refcnt.val() == 0
    }
}

impl Debug for Chunk {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "Chunk(pos: {}, len: {}, refcnt: {})",
            self.pos,
            self.len,
            self.refcnt.val()
        )
    }
}

/// Chunk location
#[derive(Debug, Hash, Eq, PartialEq, Deserialize, Serialize)]
pub struct ChunkLoc {
    pub(super) seg_id: Eid,
    pub(super) idx: usize, // index in segment chunk list
}

#[derive(Default, Clone, Deserialize, Serialize)]
struct ChunkIdx {
    seg_idx: usize, // index in segment id list
    chk_idx: usize, // index in segment chunk list
}

/// Chunk map, used for chunk dedup in a file
#[derive(Default, Clone, Deserialize, Serialize)]
pub struct ChunkMap {
    seg_ids: Vec<Eid>, // segment id array

    // key: chunk hash
    // val: (index in segment id array, index in segment chunk list)
    map: LinkedHashMap<Hash, ChunkIdx>,

    is_enabled: bool,
}

impl ChunkMap {
    // max number of index in the map, this is a trade-off to save memory as
    // large file will have too many chunks
    const INDEX_MAP_CAPACITY: usize = 256;

    pub fn new(is_enabled: bool) -> Self {
        ChunkMap {
            seg_ids: Vec::new(),
            map: LinkedHashMap::with_capacity(if is_enabled {
                Self::INDEX_MAP_CAPACITY
            } else {
                0
            }),
            is_enabled,
        }
    }

    pub fn get_refresh(&mut self, hash: &Hash) -> Option<ChunkLoc> {
        if !self.is_enabled {
            return None;
        }
        let seg_ids = &self.seg_ids;
        self.map.get_refresh(hash).map(|ci| ChunkLoc {
            seg_id: seg_ids[ci.seg_idx as usize].clone(),
            idx: ci.chk_idx,
        })
    }

    pub fn insert(&mut self, chk_hash: &Hash, seg_id: &Eid, chk_idx: usize) {
        if !self.is_enabled {
            return;
        }
        let idx = self
            .seg_ids
            .iter()
            .position(|s| s == seg_id)
            .unwrap_or_else(|| {
                self.seg_ids.push(seg_id.clone());
                self.seg_ids.len() - 1
            });
        self.map.insert(
            chk_hash.clone(),
            ChunkIdx {
                seg_idx: idx,
                chk_idx,
            },
        );
        if self.map.len() >= Self::INDEX_MAP_CAPACITY {
            self.map.pop_front();
        }
    }

    fn retain<F>(&mut self, mut f: F)
    where
        F: FnMut(&Hash, &ChunkIdx) -> bool,
    {
        for ent in self.map.entries() {
            if !f(ent.key(), ent.get()) {
                ent.remove();
            }
        }
    }

    pub fn remove_chunks(&mut self, seg_id: &Eid, chk_indices: &[usize]) {
        if !self.is_enabled {
            return;
        }
        self.seg_ids.iter().position(|s| s == seg_id).and_then(
            |seg_idx| -> Option<()> {
                self.retain(|_, val| {
                    val.seg_idx != seg_idx
                        || !chk_indices.contains(&val.chk_idx)
                });
                None
            },
        );
    }

    pub fn remove_segment(&mut self, seg_id: &Eid) {
        if !self.is_enabled {
            return;
        }
        self.seg_ids.iter().position(|s| s == seg_id).and_then(
            |seg_idx| -> Option<()> {
                self.retain(|_, val| val.seg_idx != seg_idx);
                None
            },
        );
    }
}

impl Debug for ChunkMap {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("ChunkMap")
            .field("seg_ids", &self.seg_ids)
            .field("map_len", &self.map.len())
            .field("is_enabled", &self.is_enabled)
            .finish()
    }
}