store_api/storage/
file.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::fmt;
16use std::fmt::Debug;
17use std::str::FromStr;
18
19use serde::{Deserialize, Serialize};
20use snafu::{ResultExt, Snafu};
21use uuid::Uuid;
22
23#[derive(Debug, Snafu, PartialEq)]
24pub struct ParseIdError {
25    source: uuid::Error,
26}
27
28/// Unique id for [SST File].
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
30pub struct FileId(Uuid);
31
32impl FileId {
33    /// Returns a new unique [FileId] randomly.
34    pub fn random() -> FileId {
35        FileId(Uuid::new_v4())
36    }
37
38    /// Parses id from string.
39    pub fn parse_str(input: &str) -> std::result::Result<FileId, ParseIdError> {
40        Uuid::parse_str(input).map(FileId).context(ParseIdSnafu)
41    }
42
43    /// Converts [FileId] as byte slice.
44    pub fn as_bytes(&self) -> &[u8] {
45        self.0.as_bytes()
46    }
47}
48
49impl From<FileId> for Uuid {
50    fn from(value: FileId) -> Self {
51        value.0
52    }
53}
54
55impl fmt::Display for FileId {
56    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57        write!(f, "{}", self.0)
58    }
59}
60
61impl FromStr for FileId {
62    type Err = ParseIdError;
63
64    fn from_str(s: &str) -> std::result::Result<FileId, ParseIdError> {
65        FileId::parse_str(s)
66    }
67}
68
69#[cfg(test)]
70mod tests {
71
72    use super::*;
73
74    #[test]
75    fn test_file_id() {
76        let id = FileId::random();
77        let uuid_str = id.to_string();
78        assert_eq!(id.0.to_string(), uuid_str);
79
80        let parsed = FileId::parse_str(&uuid_str).unwrap();
81        assert_eq!(id, parsed);
82        let parsed = uuid_str.parse().unwrap();
83        assert_eq!(id, parsed);
84    }
85
86    #[test]
87    fn test_file_id_serialization() {
88        let id = FileId::random();
89        let json = serde_json::to_string(&id).unwrap();
90        assert_eq!(format!("\"{id}\""), json);
91
92        let parsed = serde_json::from_str(&json).unwrap();
93        assert_eq!(id, parsed);
94    }
95}