use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SearchResult {
pub score: f32,
pub item_id: u32,
pub name: String,
pub path: String,
pub kind: String,
pub crate_name: String,
pub version: String,
pub visibility: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub doc_preview: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub member: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct SearchItemsFuzzyOutput {
pub results: Vec<SearchResult>,
pub query: String,
pub total_results: usize,
pub fuzzy_enabled: bool,
pub crate_name: String,
pub version: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub member: Option<String>,
}
impl SearchItemsFuzzyOutput {
pub fn to_json(&self) -> String {
serde_json::to_string(self)
.unwrap_or_else(|_| r#"{"error":"Failed to serialize response"}"#.to_string())
}
pub fn has_results(&self) -> bool {
!self.results.is_empty()
}
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct SearchErrorOutput {
pub error: String,
}
impl SearchErrorOutput {
pub fn new(message: impl Into<String>) -> Self {
Self {
error: message.into(),
}
}
pub fn to_json(&self) -> String {
serde_json::to_string(self)
.unwrap_or_else(|_| r#"{"error":"Failed to serialize error"}"#.to_string())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_search_fuzzy_output_serialization() {
let output = SearchItemsFuzzyOutput {
results: vec![SearchResult {
score: 0.95,
item_id: 42,
name: "deserialize".to_string(),
path: "serde::de".to_string(),
kind: "function".to_string(),
crate_name: "serde".to_string(),
version: "1.0.0".to_string(),
visibility: "public".to_string(),
doc_preview: Some("Deserialize a value".to_string()),
member: None,
}],
query: "deserialize".to_string(),
total_results: 1,
fuzzy_enabled: true,
crate_name: "serde".to_string(),
version: "1.0.0".to_string(),
member: None,
};
assert!(output.has_results());
let json = output.to_json();
let deserialized: SearchItemsFuzzyOutput = serde_json::from_str(&json).unwrap();
assert_eq!(output, deserialized);
}
#[test]
fn test_search_error_output() {
let output = SearchErrorOutput::new("Search failed");
let json = output.to_json();
let deserialized: SearchErrorOutput = serde_json::from_str(&json).unwrap();
assert_eq!(output, deserialized);
}
}