remdb/
types.rs

1use core::fmt;
2use core::mem::size_of;
3
4/// 基本数据类型枚举
5#[repr(u8)]
6#[derive(Copy, Clone, PartialEq)]
7pub enum DataType {
8    /// 8位无符号整数
9    UInt8 = 0,
10    /// 16位无符号整数
11    UInt16 = 1,
12    /// 32位无符号整数
13    UInt32 = 2,
14    /// 64位无符号整数
15    UInt64 = 3,
16    /// 8位有符号整数
17    Int8 = 4,
18    /// 16位有符号整数
19    Int16 = 5,
20    /// 32位有符号整数
21    Int32 = 6,
22    /// 64位有符号整数
23    Int64 = 7,
24    /// 32位浮点数
25    Float32 = 8,
26    /// 64位浮点数
27    Float64 = 9,
28    /// 布尔值
29    Bool = 10,
30    /// 时间戳(毫秒)
31    Timestamp = 11,
32    /// 定长字符串
33    String = 12,
34}
35
36impl DataType {
37    /// 获取数据类型的大小(字节)
38    pub const fn size(&self) -> usize {
39        match self {
40            DataType::UInt8 => 1,
41            DataType::UInt16 => 2,
42            DataType::UInt32 => 4,
43            DataType::UInt64 => 8,
44            DataType::Int8 => 1,
45            DataType::Int16 => 2,
46            DataType::Int32 => 4,
47            DataType::Int64 => 8,
48            DataType::Float32 => 4,
49            DataType::Float64 => 8,
50            DataType::Bool => 1,
51            DataType::Timestamp => 8,
52            DataType::String => panic!("String size is variable at compile time"),
53        }
54    }
55    
56    /// 将数据类型转换为SQL类型字符串(SQLite3兼容)
57    pub fn to_sql_type(&self, size: usize) -> &'static str {
58        match self {
59            // SQLite3使用INTEGER存储所有整数类型
60            DataType::UInt8 => "INTEGER",
61            DataType::UInt16 => "INTEGER",
62            DataType::UInt32 => "INTEGER",
63            DataType::UInt64 => "INTEGER",
64            DataType::Int8 => "INTEGER",
65            DataType::Int16 => "INTEGER",
66            DataType::Int32 => "INTEGER",
67            DataType::Int64 => "INTEGER",
68            // SQLite3使用REAL存储浮点数
69            DataType::Float32 => "REAL",
70            DataType::Float64 => "REAL",
71            // SQLite3使用INTEGER(0/1)存储布尔值
72            DataType::Bool => "INTEGER",
73            // SQLite3使用INTEGER存储时间戳(毫秒)
74            DataType::Timestamp => "INTEGER",
75            // SQLite3使用TEXT存储字符串
76            DataType::String => "TEXT",
77        }
78    }
79}
80
81impl Default for DataType {
82    fn default() -> Self {
83        DataType::Int32
84    }
85}
86
87/// 时间相关辅助方法
88pub mod time_utils {
89    /// 将秒转换为毫秒
90    pub const fn seconds_to_millis(seconds: u64) -> u64 {
91        seconds * 1000
92    }
93    
94    /// 将毫秒转换为秒
95    pub const fn millis_to_seconds(millis: u64) -> u64 {
96        millis / 1000
97    }
98    
99    /// 将微秒转换为毫秒
100    pub const fn micros_to_millis(micros: u64) -> u64 {
101        micros / 1000
102    }
103    
104    /// 将毫秒转换为微秒
105    pub const fn millis_to_micros(millis: u64) -> u64 {
106        millis * 1000
107    }
108    
109    /// 将纳秒转换为毫秒
110    pub const fn nanos_to_millis(nanos: u64) -> u64 {
111        nanos / 1000000
112    }
113    
114    /// 将毫秒转换为纳秒
115    pub const fn millis_to_nanos(millis: u64) -> u64 {
116        millis * 1000000
117    }
118    
119    /// 计算两个时间戳之间的时间差(毫秒)
120    pub fn time_diff(start: u64, end: u64) -> u64 {
121        if end > start {
122            end - start
123        } else {
124            start - end
125        }
126    }
127    
128    /// 检查时间戳是否在指定范围内
129    pub fn is_in_time_range(timestamp: u64, start: u64, end: u64) -> bool {
130        timestamp >= start && timestamp <= end
131    }
132    
133    /// 获取当前时间戳(毫秒)
134    /// 注意:在no_std环境中,此函数需要平台支持
135    #[cfg(feature = "std")]
136    pub fn now_millis() -> u64 {
137        use std::time::{SystemTime, UNIX_EPOCH};
138        SystemTime::now()
139            .duration_since(UNIX_EPOCH)
140            .expect("Time went backwards")
141            .as_millis() as u64
142    }
143    
144    /// 获取当前时间戳(微秒)
145    /// 注意:在no_std环境中,此函数需要平台支持
146    #[cfg(feature = "std")]
147    pub fn now_micros() -> u64 {
148        use std::time::{SystemTime, UNIX_EPOCH};
149        SystemTime::now()
150            .duration_since(UNIX_EPOCH)
151            .expect("Time went backwards")
152            .as_micros() as u64
153    }
154}
155
156/// 通用值类型
157#[repr(C)]
158#[derive(Copy, Clone)]
159pub union Value {
160    pub u8: u8,
161    pub u16: u16,
162    pub u32: u32,
163    pub u64: u64,
164    pub i8: i8,
165    pub i16: i16,
166    pub i32: i32,
167    pub i64: i64,
168    pub float32: f32,
169    pub float64: f64,
170    pub bool: bool,
171    pub timestamp: u64,
172    pub string: [u8; MAX_STRING_LEN],
173}
174
175/// 手动实现PartialEq trait,因为Rust不支持为union类型自动派生PartialEq
176impl PartialEq for Value {
177    fn eq(&self, other: &Self) -> bool {
178        // 注意:这里的实现假设我们知道要比较的是哪种类型
179        // 但实际上在约束验证中,我们是比较相同字段的值,所以类型是相同的
180        // 因此我们需要根据字段类型来比较对应的union变体
181        // 由于我们无法在这里知道字段类型,所以这个实现是不完整的
182        // 我们需要修改约束验证逻辑,不直接比较Value,而是比较具体的字段值
183        false
184    }
185}
186
187/// 定长字符串最大长度
188pub const MAX_STRING_LEN: usize = 64;
189
190/// 字段定义
191#[repr(C)]
192#[derive(Copy, Clone)]
193pub struct FieldDef {
194    /// 字段名称(编译时固定)
195    pub name: &'static str,
196    /// 数据类型
197    pub data_type: DataType,
198    /// 字段大小(字节)
199    pub size: usize,
200    /// 偏移量(在记录中的位置)
201    pub offset: usize,
202    /// 是否为主键
203    pub primary_key: bool,
204    /// 是否非空
205    pub not_null: bool,
206    /// 是否唯一
207    pub unique: bool,
208    /// 是否自增
209    pub auto_increment: bool,
210}
211
212impl FieldDef {
213    /// 生成字段的SQL约束字符串
214    pub fn constraints_to_sql(&self) -> alloc::string::String {
215        let mut constraints = alloc::string::String::new();
216        
217        if self.primary_key {
218            constraints.push_str(" PRIMARY KEY");
219        }
220        
221        if self.auto_increment {
222            constraints.push_str(" AUTO_INCREMENT");
223        }
224        
225        if self.not_null {
226            constraints.push_str(" NOT NULL");
227        }
228        
229        if self.unique && !self.primary_key {
230            constraints.push_str(" UNIQUE");
231        }
232        
233        constraints
234    }
235}
236
237/// 索引类型枚举
238#[repr(u8)]
239#[derive(Copy, Clone, PartialEq, Debug)]
240pub enum IndexType {
241    /// 哈希索引(仅用于主键)
242    Hash = 0,
243    /// 有序数组索引
244    SortedArray = 1,
245    /// B-Tree索引
246    BTree = 2,
247    /// T-Tree索引
248    TTree = 3,
249}
250
251/// 表定义
252#[derive(Copy, Clone)]
253pub struct TableDef {
254    /// 表ID
255    pub id: u8,
256    /// 表名称
257    pub name: &'static str,
258    /// 字段定义
259    pub fields: &'static [FieldDef],
260    /// 主键字段索引
261    pub primary_key: usize,
262    /// 辅助索引字段索引(可选)
263    pub secondary_index: Option<usize>,
264    /// 辅助索引类型
265    pub secondary_index_type: IndexType,
266    /// 单条记录大小
267    pub record_size: usize,
268    /// 最大记录数
269    pub max_records: usize,
270}
271
272/// 记录状态
273#[derive(Debug, PartialEq, Copy, Clone)]
274#[repr(u8)]
275pub enum RecordStatus {
276    /// 空闲
277    Free = 0,
278    /// 已占用
279    Used = 1,
280    /// 已删除(标记)
281    Deleted = 2,
282}
283
284/// 锁类型
285#[repr(u8)]
286pub enum LockType {
287    /// 无锁
288    None = 0,
289    /// 共享锁(读锁)
290    Shared = 1,
291    /// 排他锁(写锁)
292    Exclusive = 2,
293}
294
295/// 记录头
296#[repr(C)]
297pub struct RecordHeader {
298    /// 记录状态
299    pub status: RecordStatus,
300    /// 版本号(用于事务)
301    pub version: u16,
302    /// 锁类型
303    pub lock_type: LockType,
304    /// 持有锁的事务ID
305    pub lock_owner: u32,
306    /// 锁计数器(用于共享锁)
307    pub lock_count: u8,
308}
309
310impl RecordHeader {
311    /// 记录头大小
312    pub const SIZE: usize = size_of::<Self>();
313}
314
315/// 确保所有类型大小正确
316const _: () = {
317    assert!(size_of::<RecordStatus>() == 1);
318    assert!(size_of::<DataType>() == 1);
319};
320
321/// 错误类型
322#[derive(Debug, PartialEq, Eq)]
323pub enum RemDbError {
324    /// 内存不足
325    OutOfMemory,
326    /// 记录未找到
327    RecordNotFound,
328    /// 主键重复
329    DuplicateKey,
330    /// 字段不存在
331    FieldNotFound,
332    /// 类型不匹配
333    TypeMismatch,
334    /// 事务错误
335    TransactionError,
336    /// 配置错误
337    ConfigError,
338    /// 操作不支持
339    UnsupportedOperation,
340    /// 文件I/O错误
341    FileIoError,
342    /// 快照格式错误
343    SnapshotFormatError,
344    /// CRC校验失败
345    Crc32Error,
346    /// 日志格式错误
347    LogFormatError,
348    /// 日志记录未找到
349    LogRecordNotFound,
350    /// 日志校验和错误
351    LogChecksumError,
352    /// 锁冲突
353    LockConflict,
354    /// 锁超时
355    LockTimeout,
356    /// 表未找到
357    TableNotFound,
358    /// 记录大小无效
359    InvalidRecordSize,
360    /// 无效的SQL查询
361    InvalidSqlQuery,
362    /// 内部错误
363    InternalError,
364}
365
366impl fmt::Display for RemDbError {
367    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
368        match self {
369            RemDbError::OutOfMemory => write!(f, "Out of memory"),
370            RemDbError::RecordNotFound => write!(f, "Record not found"),
371            RemDbError::DuplicateKey => write!(f, "Duplicate key"),
372            RemDbError::FieldNotFound => write!(f, "Field not found"),
373            RemDbError::TypeMismatch => write!(f, "Type mismatch"),
374            RemDbError::TransactionError => write!(f, "Transaction error"),
375            RemDbError::ConfigError => write!(f, "Config error"),
376            RemDbError::UnsupportedOperation => write!(f, "Unsupported operation"),
377            RemDbError::FileIoError => write!(f, "File I/O error"),
378            RemDbError::SnapshotFormatError => write!(f, "Snapshot format error"),
379            RemDbError::Crc32Error => write!(f, "CRC32 checksum error"),
380            RemDbError::LogFormatError => write!(f, "Log format error"),
381            RemDbError::LogRecordNotFound => write!(f, "Log record not found"),
382            RemDbError::LogChecksumError => write!(f, "Log checksum error"),
383            RemDbError::LockConflict => write!(f, "Lock conflict"),
384            RemDbError::LockTimeout => write!(f, "Lock timeout"),
385            RemDbError::TableNotFound => write!(f, "Table not found"),
386            RemDbError::InvalidRecordSize => write!(f, "Invalid record size"),
387            RemDbError::InvalidSqlQuery => write!(f, "Invalid SQL query"),
388            RemDbError::InternalError => write!(f, "Internal error"),
389        }
390    }
391}
392
393/// 结果类型
394pub type Result<T> = core::result::Result<T, RemDbError>;