use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct CodeChunk {
pub id: Option<i64>,
pub file_path: String,
pub byte_start: usize,
pub byte_end: usize,
pub content: String,
pub content_hash: String,
pub symbol_name: Option<String>,
pub symbol_kind: Option<String>,
pub created_at: i64,
}
impl CodeChunk {
pub fn new(
file_path: String,
byte_start: usize,
byte_end: usize,
content: String,
symbol_name: Option<String>,
symbol_kind: Option<String>,
) -> Self {
let content_hash = Self::compute_hash(&content);
let created_at = Self::now();
Self {
id: None,
file_path,
byte_start,
byte_end,
content,
content_hash,
symbol_name,
symbol_kind,
created_at,
}
}
fn compute_hash(content: &str) -> String {
use sha2::{Digest, Sha256};
let mut hasher = Sha256::new();
hasher.update(content.as_bytes());
let hash = hasher.finalize();
hex::encode(hash)
}
fn now() -> i64 {
use std::time::{SystemTime, UNIX_EPOCH};
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0)
}
pub fn byte_len(&self) -> usize {
self.byte_end - self.byte_start
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_code_chunk_hash() {
let chunk1 = CodeChunk::new(
"test.rs".to_string(),
0,
10,
"fn main() {}".to_string(),
Some("main".to_string()),
Some("fn".to_string()),
);
let chunk2 = CodeChunk::new(
"test.rs".to_string(),
0,
10,
"fn main() {}".to_string(),
Some("main".to_string()),
Some("fn".to_string()),
);
assert_eq!(chunk1.content_hash, chunk2.content_hash);
}
#[test]
fn test_code_chunk_byte_len() {
let chunk = CodeChunk::new("test.rs".to_string(), 100, 200, "x".repeat(100), None, None);
assert_eq!(chunk.byte_len(), 100);
}
#[test]
fn test_code_chunk_with_symbols() {
let chunk = CodeChunk::new(
"src/main.rs".to_string(),
42,
100,
"fn my_function() {}".to_string(),
Some("my_function".to_string()),
Some("fn".to_string()),
);
assert_eq!(chunk.symbol_name, Some("my_function".to_string()));
assert_eq!(chunk.symbol_kind, Some("fn".to_string()));
assert_eq!(chunk.byte_start, 42);
assert_eq!(chunk.byte_end, 100);
}
}