| 4 | use tokio::io::{AsyncBufReadExt, BufReader}; |
| 5 | |
| 6 | pub async fn read_jsonl<T>(path: impl AsRef<Path>) -> Result<Vec<T>> |
| 7 | where |
| 8 | T: DeserializeOwned, |
| 9 | { |
| 10 | let path = path.as_ref(); |
| 11 | if !path.exists() { |
| 12 | return Err(Error::FileNotFound(path.display().to_string())); |
| 13 | } |
| 14 | |
| 15 | let file = tokio::fs::File::open(path).await?; |
| 16 | let reader = BufReader::new(file); |
| 17 | let mut lines = reader.lines(); |
| 18 | let mut entries = Vec::new(); |
| 19 | |
| 20 | while let Some(line) = lines.next_line().await? { |
| 21 | if line.trim().is_empty() { |
| 22 | continue; |
| 23 | } |
| 24 | match serde_json::from_str::<T>(&line) { |
| 25 | Ok(entry) => entries.push(entry), |
| 26 | Err(e) => { |
| 27 | tracing::debug!("Failed to parse line: {}", e); |
| 28 | continue; |
| 29 | } |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | Ok(entries) |
| 34 | } |
| 35 | |
| 36 | pub async fn read_jsonl_raw(path: impl AsRef<Path>) -> Result<Vec<serde_json::Value>> { |
| 37 | read_jsonl::<serde_json::Value>(path).await |