mwa_hyperdrive/srclist/hyperdrive/
write.rs1use std::collections::HashMap;
8
9use indexmap::IndexMap;
10
11use crate::{
12 cli::Warn,
13 srclist::{error::WriteSourceListError, SourceList},
14};
15
16pub(crate) fn source_list_to_yaml<T: std::io::Write>(
18 mut buf: &mut T,
19 sl: &SourceList,
20 num_sources: Option<usize>,
21) -> Result<(), WriteSourceListError> {
22 if let Some(num_sources) = num_sources {
23 let mut map = HashMap::with_capacity(1);
24 for (name, src) in sl.iter().take(num_sources) {
25 map.insert(name.as_str(), serde_yaml::to_value(src)?);
26 #[allow(clippy::needless_borrows_for_generic_args)]
28 serde_yaml::to_writer(&mut buf, &map)?;
29 map.clear();
30 }
31
32 if num_sources > sl.len() {
33 format!(
34 "Couldn't write the requested number of sources ({num_sources}): wrote {}",
35 sl.len()
36 )
37 .warn()
38 };
39 } else {
40 serde_yaml::to_writer(buf, &sl)?;
41 }
42 Ok(())
43}
44
45pub(crate) fn source_list_to_json<T: std::io::Write>(
47 buf: &mut T,
48 sl: &SourceList,
49 num_sources: Option<usize>,
50) -> Result<(), WriteSourceListError> {
51 if let Some(num_sources) = num_sources {
52 let mut map = IndexMap::with_capacity(sl.len().min(num_sources));
53 for (name, src) in sl.iter().take(num_sources) {
54 map.insert(name.as_str(), serde_json::to_value(src)?);
55 }
56 serde_json::to_writer_pretty(buf, &map)?;
57
58 if num_sources > sl.len() {
59 format!(
60 "Couldn't write the requested number of sources ({num_sources}): wrote {}",
61 sl.len()
62 )
63 .warn()
64 };
65 } else {
66 serde_json::to_writer_pretty(buf, &sl)?;
67 }
68 Ok(())
69}