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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
use crate::*;
use generic_array::typenum::{marker_traits::Unsigned, U32};
use generic_array::GenericArray;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::{
convert::{Into, TryFrom},
str::FromStr,
};
use base58::{FromBase58, ToBase58};
use serde::{Serialize, Deserialize};
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd)]
pub struct ChunkId(GenericArray<u8, U32>);
impl Default for ChunkId {
fn default() -> Self {
Self(GenericArray::default())
}
}
impl Hash for ChunkId {
fn hash<H: Hasher>(&self, state: &mut H) {
let mut buff = [0 as u8; 32];
let _ = self.raw_encode(buff.as_mut(), &None).unwrap();
state.write(buff.as_ref());
}
}
impl std::fmt::Debug for ChunkId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "ChunkId: {:?}", self.0.as_slice().to_base58())
}
}
impl std::fmt::Display for ChunkId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0.as_slice().to_base58())
}
}
impl FromStr for ChunkId {
type Err = BuckyError;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
let buf = s.from_base58().map_err(|_e| {
log::error!("convert base58 str to object id failed, str:{}", s);
let msg = format!("convert base58 str to object id failed, str:{}", s);
BuckyError::new(BuckyErrorCode::ParseError, msg)
})?;
if buf.len() != 32 {
let msg = format!(
"convert base58 str to chunk id failed, str is too long:{}, len:{}",
s,
buf.len()
);
return Err(BuckyError::new(BuckyErrorCode::ParseError, msg));
}
let mut id = Self::default();
unsafe {
std::ptr::copy(buf.as_ptr(), id.as_mut_slice().as_mut_ptr(), buf.len());
}
Ok(id)
}
}
impl TryFrom<&ObjectId> for ChunkId {
type Error = BuckyError;
fn try_from(id: &ObjectId) -> Result<Self, Self::Error> {
let obj_type_code = id.obj_type_code();
if obj_type_code == ObjectTypeCode::Chunk {
Ok(Self(id.as_ref().clone()))
} else {
Err(
BuckyError::new(
BuckyErrorCode::InvalidParam,
format!("try convert from object id to named object id failed, mismatch obj_type_code, expect obj_type_code is: {}, current obj_type_code is:{}", ObjectTypeCode::Chunk.to_string(), obj_type_code.to_string())
)
)
}
}
}
impl ProtobufTransform<ChunkId> for Vec<u8> {
fn transform(value: ChunkId) -> BuckyResult<Self> {
Ok(Vec::from(value.0.as_slice()))
}
}
impl ProtobufTransform<&ChunkId> for Vec<u8> {
fn transform(value: &ChunkId) -> BuckyResult<Self> {
Ok(Vec::from(value.0.as_slice()))
}
}
impl ProtobufTransform<Vec<u8>> for ChunkId {
fn transform(value: Vec<u8>) -> BuckyResult<Self> {
if value.len() != 32 {
return Err(BuckyError::new(
BuckyErrorCode::InvalidParam,
format!("try convert from vec<u8> to chunk id failed, invalid len {}", value.len())
));
}
let mut id = Self::default();
unsafe {
std::ptr::copy(value.as_ptr(), id.as_mut_slice().as_mut_ptr(), value.len());
}
Ok(id)
}
}
impl From<GenericArray<u8, U32>> for ChunkId {
fn from(chunk_id: GenericArray<u8, U32>) -> Self {
Self(chunk_id)
}
}
impl From<ChunkId> for GenericArray<u8, U32> {
fn from(hash: ChunkId) -> Self {
hash.0
}
}
impl AsRef<GenericArray<u8, U32>> for ChunkId {
fn as_ref(&self) -> &GenericArray<u8, U32> {
&self.0
}
}
impl ChunkId {
pub fn as_slice(&self) -> &[u8] {
self.0.as_slice()
}
pub fn obj_type_code(&self) -> Option<ObjectTypeCode> {
Some(ObjectTypeCode::Chunk)
}
pub fn object_id(&self) -> ObjectId {
ObjectId::clone_from_slice(self.as_slice())
}
pub fn as_object_id(&self) -> &ObjectId {
unsafe { std::mem::transmute::<&ChunkId, &ObjectId>(&self) }
}
fn as_mut_slice(&mut self) -> &mut [u8] {
self.0.as_mut_slice()
}
pub fn to_string(&self) -> String {
self.0.as_slice().to_base58()
}
pub async fn calculate(data: &[u8]) -> BuckyResult<Self> {
let hash = hash_data(data);
Ok(ChunkId::new(&hash, data.len() as u32))
}
pub fn calculate_sync(data: &[u8]) -> BuckyResult<Self> {
let hash = hash_data(data);
Ok(ChunkId::new(&hash, data.len() as u32))
}
pub fn new(hash_value: &HashValue, len: u32) -> Self {
let hash = hash_value.as_slice();
let mut id = Self::default();
let chunkid = id.as_mut_slice();
chunkid[0] = 0b_01000000 | (ObjectTypeCode::Chunk.to_u16() as u8) << 4 >> 2;
unsafe {
*(chunkid[1..5].as_mut_ptr() as *mut u32) = len;
}
chunkid[5..].copy_from_slice(&hash[0..27]);
id
}
pub fn hash(&self) -> &[u8] {
let chunkid = self.as_slice();
&chunkid[5..]
}
pub fn len(&self) -> usize {
let chunkid = self.as_slice();
return unsafe { *(chunkid[1..5].as_ptr() as *const u32) } as usize;
}
}
impl RawFixedBytes for ChunkId {
fn raw_bytes() -> Option<usize> {
Some(U32::to_usize())
}
}
impl RawEncode for ChunkId {
fn raw_measure(&self, _purpose: &Option<RawEncodePurpose>) -> Result<usize, BuckyError> {
Ok(U32::to_usize())
}
fn raw_encode<'a>(
&self,
buf: &'a mut [u8],
_purpose: &Option<RawEncodePurpose>,
) -> Result<&'a mut [u8], BuckyError> {
let bytes = Self::raw_bytes().unwrap();
if buf.len() < bytes {
let msg = format!(
"not enough buffer for encode ChunkId, except={}, got={}",
bytes,
buf.len()
);
error!("{}", msg);
return Err(BuckyError::new(BuckyErrorCode::OutOfLimit, msg));
}
unsafe {
std::ptr::copy(self.0.as_slice().as_ptr(), buf.as_mut_ptr(), bytes);
}
Ok(&mut buf[bytes..])
}
}
impl<'de> RawDecode<'de> for ChunkId {
fn raw_decode(buf: &'de [u8]) -> Result<(Self, &'de [u8]), BuckyError> {
let bytes = Self::raw_bytes().unwrap();
if buf.len() < bytes {
let msg = format!(
"not enough buffer for decode ChunkId, except={}, got={}",
bytes,
buf.len()
);
error!("{}", msg);
return Err(BuckyError::new(BuckyErrorCode::OutOfLimit, msg));
}
let mut _id = Self::default();
unsafe {
std::ptr::copy(buf.as_ptr(), _id.0.as_mut_slice().as_mut_ptr(), bytes);
}
Ok((_id, &buf[bytes..]))
}
}
use super::raw_diff::{RawDiff, RawPatch};
impl RawDiff for ChunkId {
fn diff_measure(&self, right: &Self) -> BuckyResult<usize> {
let data = self.as_ref();
let r = right.as_ref();
data.diff_measure(r)
}
fn diff<'d>(&self, right: &Self, buf: &'d mut [u8]) -> BuckyResult<&'d mut [u8]> {
let size = self.diff_measure(right).map_err(|e| {
log::error!("ChunkId::diff error:{}", e);
e
})?;
if buf.len() < size {
return Err(BuckyError::new(
BuckyErrorCode::OutOfLimit,
"[raw_diff] not enough buffer for chunk_id",
));
}
self.as_ref().diff(right.as_ref(), buf)
}
}
impl<'de> RawPatch<'de> for ChunkId {
fn patch(self, buf: &'de [u8]) -> BuckyResult<(Self, &'de [u8])> {
let data: GenericArray<u8, U32> = self.into();
let (data, buf) = data.patch(buf).map_err(|e| {
log::error!("ChunkId::patch error:{}", e);
e
})?;
Ok((ChunkId::from(data), buf))
}
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone, Serialize, Deserialize)]
pub enum ChunkState {
Unknown = 0,
NotFound = 1,
Pending = 2,
OnAir = 3,
Ready = 4,
Ignore = 5,
}
impl TryFrom<u8> for ChunkState {
type Error = BuckyError;
fn try_from(value: u8) -> Result<Self, Self::Error> {
match value {
0 => Ok(ChunkState::Unknown),
1 => Ok(ChunkState::NotFound),
2 => Ok(ChunkState::Pending),
3 => Ok(ChunkState::OnAir),
4 => Ok(ChunkState::Ready),
5 => Ok(ChunkState::Ignore),
_ => {
let msg = format!("unknown chunk-state: {}", value);
error!("{}", msg);
Err(BuckyError::new(BuckyErrorCode::InvalidData, msg))
}
}
}
}
impl From<ChunkState> for u8 {
fn from(value: ChunkState) -> Self {
let r = &value;
r.into()
}
}
impl From<&ChunkState> for u8 {
fn from(value: &ChunkState) -> Self {
match value {
ChunkState::Unknown => 0,
ChunkState::NotFound => 1,
ChunkState::Pending => 2,
ChunkState::OnAir => 3,
ChunkState::Ready => 4,
ChunkState::Ignore => 5,
}
}
}
#[cfg(test)]
mod test {
use super::ChunkId;
use crate::*;
use std::convert::TryFrom;
use std::str::FromStr;
#[test]
fn chunk() {
let hash = HashValue::default();
let chunk_id = ChunkId::new(&hash, 100);
let chunk_id_str = chunk_id.to_string();
let chunk_id_str2 = chunk_id.as_object_id().to_string();
assert_eq!(chunk_id_str, chunk_id_str2);
println!("chunk_id_str:{}", chunk_id_str);
let chunk_id_from_str = ChunkId::from_str(&chunk_id_str).unwrap();
println!("chunk_id_from_str:{:?}", chunk_id_from_str);
assert_eq!(chunk_id.obj_type_code().unwrap(), ObjectTypeCode::Chunk);
let obj_id = chunk_id.object_id();
assert_eq!(obj_id.obj_type_code(), ObjectTypeCode::Chunk);
{
let new_chunk_id = ChunkId::try_from(&obj_id).unwrap();
assert_eq!(new_chunk_id, chunk_id);
}
}
}