xabc_lib/
source.rs

1use std::{
2    clone::Clone,
3    convert::AsRef,
4    ops::{Deref, Index},
5    sync::Arc,
6};
7
8/// 存放 ABC 文件的原始数据,用于浅拷贝。
9pub struct Source<T> {
10    // Rc<T> 是一个引用计数的智能指针,用于在多个所有权之间共享不可变访问权。
11    // 当你调用 Rc<T> 实例的 clone() 方法时,它不会创建 T 的数据的副本,而是增加引用计数,从而允许新的 Rc<T> 实例共享相同的数据。
12    // inner: Rc<T>,
13    // 线程安全,Python 接口需要。
14    inner: Arc<T>,
15}
16
17impl<T> Source<T>
18where
19    T: AsRef<[u8]>,
20{
21    /// 创建一个新的 `Source`
22    pub(crate) fn new(inner: T) -> Self {
23        Self {
24            // inner: Rc::new(inner),
25            inner: Arc::new(inner),
26        }
27    }
28}
29
30impl<T> Clone for Source<T> {
31    /// 浅拷贝
32    fn clone(&self) -> Self {
33        Self {
34            // 不会创建 T 的数据副本
35            inner: self.inner.clone(),
36        }
37    }
38}
39
40// scroll::Pread 必须实现这个
41// `Deref` 用于重载 * 运算符,可以通过 * 运算符访问 Source 的内部数据。
42impl<T: AsRef<[u8]>> Deref for Source<T> {
43    type Target = [u8];
44
45    #[inline]
46    fn deref(&self) -> &[u8] {
47        self.as_ref()
48    }
49}
50
51// `AsRef<T>` 允许将一个类型的引用转换为类型 T 的引用,而不需要进行显式的转换或复制。
52// 重载 & 运算符; 将 Source 转换为 &[u8]
53impl<T: AsRef<[u8]>> AsRef<[u8]> for Source<T> {
54    /// 获取内部数据的引用
55    fn as_ref(&self) -> &[u8] {
56        self.inner.as_ref().as_ref()
57    }
58}
59
60/// Index 用于重载 [] 运算符
61impl<T> Index<usize> for Source<T>
62where
63    T: AsRef<[u8]>,
64{
65    type Output = u8;
66
67    fn index(&self, index: usize) -> &Self::Output {
68        &self.as_ref()[index]
69    }
70}
71
72/// Index 用于重载 [m..n] 运算符
73impl<T> Index<std::ops::Range<usize>> for Source<T>
74where
75    T: AsRef<[u8]>,
76{
77    type Output = [u8];
78
79    fn index(&self, index: std::ops::Range<usize>) -> &Self::Output {
80        &self.as_ref()[index]
81    }
82}
83
84/// Index 用于重载 [m..] 运算符
85impl<T> Index<std::ops::RangeFrom<usize>> for Source<T>
86where
87    T: AsRef<[u8]>,
88{
89    type Output = [u8];
90
91    fn index(&self, index: std::ops::RangeFrom<usize>) -> &Self::Output {
92        &self.as_ref()[index]
93    }
94}