use crate::clock;
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
pub const DEFAULT_LOG_EVERY: f64 = 30.0;
pub const SRC_LIVE: &str = "live";
pub const MERGED: &str = "merged";
#[allow(dead_code)]
pub const SRC_FLASH: &str = "flash";
pub fn g(v: f64) -> String {
if v == 0.0 {
return "0".to_string();
}
if !v.is_finite() {
return format!("{}", v);
}
let sci = format!("{:.*e}", 5, v);
let (mantissa, exp) = match sci.split_once('e') {
Some((m, e)) => (m.to_string(), e.parse::<i32>().unwrap_or(0)),
None => (sci, 0),
};
if exp < -4 || exp >= 6 {
format!(
"{}e{}{:02}",
trim(&mantissa),
if exp < 0 { '-' } else { '+' },
exp.abs()
)
} else {
let places = (5 - exp).max(0) as usize;
trim(&format!("{:.*}", places, v))
}
}
fn trim(s: &str) -> String {
if !s.contains('.') {
return s.to_string();
}
s.trim_end_matches('0').trim_end_matches('.').to_string()
}
pub fn header(spans: &[f64]) -> String {
let mut head: Vec<String> = ["time", "cps", "counts", "seconds"]
.iter()
.map(|s| s.to_string())
.collect();
head.extend(spans.iter().map(|s| format!("cpm_{}", g(*s))));
head.extend(spans.iter().map(|s| format!("peak_{}", g(*s))));
head.push("src".to_string());
head.push("site".to_string());
format!("#{}", head.join("\t"))
}
pub fn exact(v: f64) -> String {
if !v.is_finite() {
return String::new();
}
format!("{}", v)
}
pub fn merged_header(spans: &[f64]) -> String {
let mut head: Vec<String> = [
"time", "unix", "tubes", "interleave", "counts", "seconds",
"tube_seconds", "cps", "cps_raw",
]
.iter()
.map(|s| s.to_string())
.collect();
head.extend(spans.iter().map(|s| format!("cpm_{}", g(*s))));
head.push("sigma_30".to_string());
head.extend(spans.iter().map(|s| format!("peak_{}", g(*s))));
head.push("per_tube".to_string());
head.push("src".to_string());
head.push("site".to_string());
format!("#{}", head.join("\t"))
}
#[allow(clippy::too_many_arguments)]
pub fn merged_row(
when: f64,
tubes: usize,
interleave: Option<f64>,
counts: u64,
seconds: f64,
tube_seconds: f64,
averages: &[Option<f64>],
sigma: Option<f64>,
peaks: &[Option<f64>],
per_tube: &[(String, u64)],
src: &str,
site: &str,
) -> String {
let cps = if tube_seconds > 0.0 { counts as f64 / tube_seconds } else { 0.0 };
let cps_raw = if seconds > 0.0 { counts as f64 / seconds } else { 0.0 };
let mut cells = vec![
clock::stamp(when),
exact(when),
format!("{}", tubes),
interleave.map(exact).unwrap_or_default(),
format!("{}", counts),
exact(seconds),
exact(tube_seconds),
exact(cps),
exact(cps_raw),
];
let one = |v: &Option<f64>| v.map(exact).unwrap_or_default();
cells.extend(averages.iter().map(one));
cells.push(one(&sigma));
cells.extend(peaks.iter().map(one));
cells.push(
per_tube
.iter()
.map(|(serial, n)| format!("{}={}", serial, n))
.collect::<Vec<_>>()
.join(","),
);
cells.push(src.to_string());
cells.push(site.to_string());
cells.join("\t")
}
pub fn columns(header_line: &str) -> Vec<String> {
if !header_line.starts_with('#') {
return Vec::new();
}
header_line[1..]
.trim_end_matches('\n')
.split('\t')
.map(|s| s.to_string())
.collect()
}
#[allow(clippy::too_many_arguments)]
pub fn row(
when: f64,
cps: f64,
counts: u64,
seconds: f64,
averages: &[Option<f64>],
peaks: &[Option<f64>],
src: &str,
site: &str,
) -> String {
let mut cells = vec![
clock::stamp(when),
format!("{:.3}", cps),
format!("{}", counts),
g(seconds),
];
let one = |v: &Option<f64>| match v {
Some(x) => format!("{:.1}", x),
None => String::new(),
};
cells.extend(averages.iter().map(one));
cells.extend(peaks.iter().map(one));
cells.push(src.to_string());
cells.push(site.to_string());
cells.join("\t")
}
pub fn path(when: f64, directory: &Path, serial: Option<&str>) -> PathBuf {
directory.join(format!(
"cpm-{}-{}.tsv",
serial.unwrap_or("unknown"),
clock::format(when, "%Y-%m")
))
}
pub fn files(directory: &Path) -> Vec<(String, PathBuf)> {
let mut names: Vec<String> = match fs::read_dir(directory) {
Ok(entries) => entries
.filter_map(|e| e.ok())
.filter_map(|e| e.file_name().into_string().ok())
.collect(),
Err(_) => return Vec::new(),
};
names.sort();
let mut out = Vec::new();
for name in names {
if !name.starts_with("cpm-") || !name.ends_with(".tsv") {
continue;
}
let stem = &name[4..name.len() - 4];
let mut parts = stem.rsplitn(3, '-');
if parts.next().is_none() || parts.next().is_none() {
continue;
}
let serial = match parts.next() {
Some(s) if !s.is_empty() => s.to_string(),
_ => continue,
};
if serial == MERGED {
continue;
}
out.push((serial, directory.join(&name)));
}
out
}
pub fn merged_files(directory: &Path) -> Vec<PathBuf> {
let mut out: Vec<PathBuf> = match fs::read_dir(directory) {
Ok(entries) => entries
.filter_map(|e| e.ok())
.filter_map(|e| e.file_name().into_string().ok())
.filter(|n| {
n.starts_with(&format!("cpm-{}-", MERGED)) && n.ends_with(".tsv")
})
.map(|n| directory.join(n))
.collect(),
Err(_) => return Vec::new(),
};
out.sort();
out
}
pub fn row_time(line: &str) -> Option<f64> {
if line.is_empty() || line.starts_with('#') {
return None;
}
clock::parse_stamp(line.split('\t').next()?)
}
pub fn align_row(
cells: &[&str],
from_names: &[String],
to_names: &[String],
) -> Vec<String> {
to_names
.iter()
.map(|name| match from_names.iter().position(|f| f == name) {
Some(i) => cells.get(i).copied().unwrap_or("").to_string(),
None => String::new(),
})
.collect()
}
pub fn read_table(path: &Path, to_names: &[String]) -> Vec<(f64, Vec<String>)> {
let text = match fs::read_to_string(path) {
Ok(t) => t,
Err(_) => return Vec::new(),
};
let mut from_names: Vec<String> = to_names.to_vec();
let mut saw_header = false;
let mut out = Vec::new();
for line in text.lines() {
if line.starts_with('#') {
let names = columns(line);
if !names.is_empty() {
from_names = names;
saw_header = true;
}
continue;
}
let when = match row_time(line) {
Some(w) => w,
None => continue,
};
let cells: Vec<&str> = line.split('\t').collect();
let mut aligned = align_row(&cells, &from_names, to_names);
if saw_header && !from_names.iter().any(|n| n == "src") {
if let Some(i) = to_names.iter().position(|n| n == "src") {
aligned[i] = SRC_LIVE.to_string();
}
}
out.push((when, aligned));
}
out
}
pub fn slot_of(when: f64, every: f64) -> i64 {
(when / every).floor() as i64
}
pub fn merge(
path: &Path,
head: &str,
rows: &[(f64, String)],
every: f64,
) -> std::io::Result<(usize, usize)> {
let names = columns(head);
let existing: Vec<(f64, String)> = read_table(path, &names)
.into_iter()
.map(|(w, cells)| (w, cells.join("\t")))
.collect();
let mut taken: Vec<i64> =
existing.iter().map(|(w, _)| slot_of(*w, every)).collect();
taken.sort_unstable();
taken.dedup();
let mut keep = Vec::new();
let mut clashed = 0;
for (when, line) in rows {
let slot = slot_of(*when, every);
if taken.binary_search(&slot).is_ok() {
clashed += 1;
continue;
}
let at = taken.partition_point(|s| *s < slot);
taken.insert(at, slot);
keep.push((*when, line.clone()));
}
let added = keep.len();
if added == 0 {
return Ok((0, clashed));
}
let mut merged: Vec<(f64, String)> = existing;
merged.extend(keep);
merged.sort_by(|a, b| a.1.cmp(&b.1));
let tmp = path.with_extension("tsv.new");
{
let mut f = fs::File::create(&tmp)?;
writeln!(f, "{}", head)?;
for (_w, line) in &merged {
writeln!(f, "{}", line)?;
}
f.flush()?;
f.sync_all()?;
}
fs::rename(&tmp, path)?;
Ok((added, clashed))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_exact_number_parses_back_to_the_same_bits() {
let cases = [
0.0, 0.5, 1.0, 34.0, 1.0 / 3.0, 60.0 / 7.0, 1789832801.956088,
0.0001234567890123, 1.7976931348623157e308, 5e-324,
96.92307692307692, -12.5,
];
for v in cases {
let text = exact(v);
let back: f64 = text.parse().expect(&text);
assert_eq!(back.to_bits(), v.to_bits(), "{} -> {}", v, text);
}
assert_eq!(exact(0.5), "0.5");
assert_eq!(exact(34.0), "34");
assert_eq!(exact(f64::NAN), "");
assert_eq!(exact(f64::INFINITY), "");
}
#[test]
fn the_merged_header_is_a_second_format_and_not_a_change_to_the_first() {
let spans = [3.0, 30.0, 300.0, 3000.0, 30000.0];
assert_eq!(
header(&spans),
"#time\tcps\tcounts\tseconds\tcpm_3\tcpm_30\tcpm_300\tcpm_3000\tcpm_30000\t\
peak_3\tpeak_30\tpeak_300\tpeak_3000\tpeak_30000\tsrc\tsite"
);
let m = columns(&merged_header(&spans));
for want in ["counts", "tube_seconds", "per_tube", "cps", "cps_raw",
"tubes", "interleave", "cpm_30", "sigma_30", "unix"] {
assert!(m.contains(&want.to_string()), "no {} in {:?}", want, m);
}
let row = merged_row(
1_700_000_000.5, 2, Some(0.5413), 34, 30.0, 60.0,
&[Some(70.0), Some(34.0), None, None, None],
Some(4.2),
&[Some(90.0), Some(40.0), None, None, None],
&[("AAA".into(), 20), ("BBB".into(), 14)],
SRC_LIVE, "the desk",
);
assert_eq!(row.split('\t').count(), m.len(), "{}", row);
let cells: Vec<&str> = row.split('\t').collect();
let at = |name: &str| cells[m.iter().position(|c| c == name).unwrap()];
assert_eq!(at("cps"), exact(34.0 / 60.0));
assert_eq!(at("cps_raw"), exact(34.0 / 30.0));
assert_eq!(at("counts"), "34");
assert_eq!(at("tubes"), "2");
assert_eq!(at("per_tube"), "AAA=20,BBB=14");
assert_eq!(at("site"), "the desk");
assert_eq!(at("cpm_300"), "");
}
#[test]
fn the_merged_log_is_never_mistaken_for_a_counter() {
let dir = std::env::temp_dir()
.join(format!("radbeeper-merged-{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
for name in ["cpm-F48824B8207F7E-2026-09.tsv", "cpm-AA1122BB3344CC-2026-09.tsv",
"cpm-merged-2026-09.tsv", "cpm-merged-2026-10.tsv"] {
fs::write(dir.join(name), "").unwrap();
}
let serials: Vec<String> = files(&dir).into_iter().map(|(s, _)| s).collect();
assert_eq!(serials, vec!["AA1122BB3344CC", "F48824B8207F7E"]);
let merged: Vec<String> = merged_files(&dir)
.into_iter()
.map(|p| p.file_name().unwrap().to_string_lossy().into_owned())
.collect();
assert_eq!(merged, vec!["cpm-merged-2026-09.tsv", "cpm-merged-2026-10.tsv"]);
let _ = fs::remove_dir_all(&dir);
}
const G_CASES: &[(f64, &str)] = &[
(3.0, "3"),
(30.0, "30"),
(300.0, "300"),
(3000.0, "3000"),
(0.5, "0.5"),
(1.0, "1"),
(10.0, "10"),
(60.0, "60"),
(30.1666666666, "30.1667"),
(29.16111111, "29.1611"),
(27.15, "27.15"),
(4.0, "4"),
(0.0, "0"),
(2.5, "2.5"),
(0.1, "0.1"),
(100000.0, "100000"),
(1234567.0, "1.23457e+06"),
(1000000.0, "1e+06"),
(123456789.0, "1.23457e+08"),
(0.000123456789, "0.000123457"),
(0.00001, "1e-05"),
(999999.5, "1e+06"),
(999999.4, "999999"),
(0.00009999999, "0.0001"),
];
#[test]
fn g_agrees_with_python() {
for (v, want) in G_CASES {
assert_eq!(&g(*v), want, "%g of {}", v);
}
}
#[test]
fn the_header_names_a_column_per_window_twice() {
let h = header(&[3.0, 30.0, 300.0, 3000.0]);
assert_eq!(
h,
"#time\tcps\tcounts\tseconds\tcpm_3\tcpm_30\tcpm_300\tcpm_3000\t\
peak_3\tpeak_30\tpeak_300\tpeak_3000\tsrc\tsite"
);
assert!(h.starts_with('#'), "the header must sort above the rows");
assert_eq!(columns(&h).len(), 14);
assert_eq!(columns(&h)[0], "time");
}
#[test]
fn a_row_is_tabs_and_the_time_comes_first() {
let r = row(
1_788_600_000.0,
0.333,
10,
30.0,
&[Some(20.0), None],
&[Some(60.0), None],
SRC_LIVE,
"The bench",
);
let cells: Vec<&str> = r.split('\t').collect();
assert_eq!(cells.len(), 10);
assert_eq!(cells[0], clock::stamp(1_788_600_000.0));
assert_eq!(cells[1], "0.333");
assert_eq!(cells[2], "10");
assert_eq!(cells[3], "30");
assert_eq!(cells[4], "20.0");
assert_eq!(cells[5], "", "a window that was not full is empty");
assert_eq!(cells[6], "60.0");
assert_eq!(cells[7], "");
assert_eq!(cells[8], SRC_LIVE);
assert_eq!(cells[9], "The bench");
}
#[test]
fn an_empty_field_is_not_a_zero() {
let r = row(0.0, 0.0, 0, 30.0, &[None], &[None], SRC_LIVE, "");
assert!(r.contains("\t\t"), "{}", r);
let zero = row(0.0, 0.0, 0, 30.0, &[Some(0.0)], &[Some(0.0)], SRC_LIVE, "");
assert!(zero.contains("0.0"));
assert_ne!(r, zero);
}
#[test]
fn a_row_goes_in_the_file_for_its_own_month() {
let d = Path::new("/tmp");
let name = path(1_788_600_000.0, d, Some("A1"));
let stem = name.file_name().unwrap().to_str().unwrap();
assert!(stem.starts_with("cpm-A1-"), "{}", stem);
assert!(stem.ends_with(".tsv"));
assert_eq!(stem.len(), "cpm-A1-2026-09.tsv".len());
assert_ne!(name, path(1_791_600_000.0, d, Some("A1")));
assert_ne!(name, path(1_788_600_000.0, d, None));
}
#[test]
fn columns_are_matched_by_name_so_a_new_window_cannot_shift_a_row() {
let old: Vec<String> = columns(&header(&[3.0, 300.0]));
let new: Vec<String> = columns(&header(&[3.0, 300.0, 3000.0]));
let cells = vec![
"2026-09-04T12:00:00", "0.3", "9", "30",
"20.0", "33.0", "60.0", "40.0", "live", "The bench",
];
let out = align_row(&cells, &old, &new);
let at = |n: &str| out[new.iter().position(|x| x == n).unwrap()].clone();
assert_eq!(at("src"), "live", "src must not land in a peak column");
assert_eq!(at("site"), "The bench");
assert_eq!(at("cpm_300"), "33.0");
assert_eq!(at("cpm_3000"), "", "a column that did not exist is empty");
assert_eq!(at("peak_3000"), "");
}
#[test]
fn a_status_is_written_where_it_was_told_and_nowhere_else() {
let root = std::env::temp_dir().join(format!("rb-status-{}", std::process::id()));
let (real, other) = (root.join("real"), root.join("other"));
fs::create_dir_all(&real).unwrap();
fs::create_dir_all(&other).unwrap();
let p = write_status(&real, "monitoring /dev/ttyUSB0");
assert_eq!(p, real.join("status"));
write_status(&other, "stopped");
let said = fs::read_to_string(real.join("status")).unwrap();
assert!(said.contains("monitoring /dev/ttyUSB0"), "{}", said);
assert!(!said.contains("stopped"), "the other one answered for it: {}", said);
assert!(fs::read_to_string(other.join("status")).unwrap().contains("stopped"));
let _ = fs::remove_dir_all(&root);
}
#[test]
fn a_slot_is_a_rows_identity() {
assert_eq!(slot_of(0.0, 30.0), 0);
assert_eq!(slot_of(29.9, 30.0), 0);
assert_eq!(slot_of(30.0, 30.0), 1);
assert_eq!(slot_of(-1.0, 30.0), -1, "floor, not truncate");
}
}
pub fn state_dir() -> PathBuf {
let home = std::env::var("HOME").unwrap_or_default();
let candidates = [
PathBuf::from("/var/lib/radbeeper"),
PathBuf::from("/var/log/radbeeper"),
PathBuf::from(home).join(".local/share/radbeeper"),
];
for d in candidates {
if d.as_os_str().is_empty() {
continue;
}
if fs::create_dir_all(&d).is_err() {
continue;
}
let probe = d.join(".writable");
if fs::File::create(&probe).is_ok() {
let _ = fs::remove_file(&probe);
return d;
}
}
PathBuf::from(".")
}
pub fn write_status(directory: &Path, text: &str) -> PathBuf {
let path = directory.join("status");
if let Ok(mut f) = fs::File::create(&path) {
let _ = writeln!(f, "{} {}", clock::format(clock::now(), "%Y-%m-%d %H:%M:%S"), text);
}
path
}
pub struct Interval {
pub counts: u64,
pub seconds: f64,
pub peaks: Vec<Option<f64>>,
}
impl Interval {
pub fn new(spans: usize) -> Interval {
Interval { counts: 0, seconds: 0.0, peaks: vec![None; spans] }
}
pub fn reset(&mut self) {
self.counts = 0;
self.seconds = 0.0;
for p in self.peaks.iter_mut() {
*p = None;
}
}
pub fn add(&mut self, counts: u32, averages: &[Option<f64>], dt: f64) {
self.counts += counts as u64;
self.seconds += dt;
for (i, cpm) in averages.iter().enumerate() {
if let (Some(v), Some(slot)) = (cpm, self.peaks.get_mut(i)) {
if slot.is_none() || *v > slot.unwrap() {
*slot = Some(*v);
}
}
}
}
pub fn cps(&self) -> f64 {
if self.seconds == 0.0 {
0.0
} else {
self.counts as f64 / self.seconds
}
}
}
pub struct Writer {
head: String,
dir: PathBuf,
serial: Option<String>,
every: f64,
path: Option<PathBuf>,
file: Option<fs::File>,
ino: Option<u64>,
last_slot: Option<i64>,
}
impl Writer {
pub fn new(spans: &[f64], dir: PathBuf, serial: Option<String>, every: f64)
-> Writer
{
Writer::under(header(spans), dir, serial, every)
}
pub fn merged(spans: &[f64], dir: PathBuf, every: f64) -> Writer {
Writer::under(merged_header(spans), dir, Some(MERGED.to_string()), every)
}
fn under(head: String, dir: PathBuf, serial: Option<String>, every: f64)
-> Writer
{
Writer {
head,
dir,
serial,
every,
path: None,
file: None,
ino: None,
last_slot: None,
}
}
fn open(&mut self, path: &Path) -> std::io::Result<()> {
self.close();
let fresh = fs::metadata(path).map(|m| m.len() == 0).unwrap_or(true);
let mut f = fs::OpenOptions::new().create(true).append(true).open(path)?;
if fresh || last_header(path).as_deref() != Some(self.head.as_str()) {
writeln!(f, "{}", self.head)?;
f.flush()?;
}
let names = columns(&self.head);
self.last_slot = read_table(path, &names)
.last()
.map(|(w, _)| slot_of(*w, self.every));
self.ino = ino_of(path);
self.path = Some(path.to_path_buf());
self.file = Some(f);
Ok(())
}
fn replaced(&self) -> bool {
match (&self.path, self.ino) {
(Some(p), Some(i)) => ino_of(p) != Some(i),
_ => true,
}
}
pub fn write(&mut self, when: f64, text: &str) -> std::io::Result<bool> {
let want = path(when, &self.dir, self.serial.as_deref());
if self.path.as_deref() != Some(want.as_path())
|| self.file.is_none()
|| self.replaced()
{
self.open(&want)?;
}
let slot = slot_of(when, self.every);
if self.last_slot.map(|last| slot <= last).unwrap_or(false) {
return Ok(false);
}
if let Some(f) = self.file.as_mut() {
writeln!(f, "{}", text)?;
f.flush()?;
}
self.last_slot = Some(slot);
Ok(true)
}
pub fn close(&mut self) {
self.file = None;
}
}
fn last_header(path: &Path) -> Option<String> {
let text = fs::read_to_string(path).ok()?;
text.lines().rev().find(|l| l.starts_with('#')).map(str::to_string)
}
fn ino_of(path: &Path) -> Option<u64> {
use std::os::unix::fs::MetadataExt;
fs::metadata(path).ok().map(|m| m.ino())
}
#[derive(Clone, Debug, PartialEq)]
pub struct SiteRow {
pub serial: String,
pub from: f64,
pub name: String,
pub lat: Option<f64>,
pub lon: Option<f64>,
pub elevation: Option<f64>,
}
impl SiteRow {
pub fn fix(&self, _places: usize) -> String {
let (Some(lat), Some(lon)) = (self.lat, self.lon) else { return String::new() };
let mut out = format!("{}, {}", crate::log::exact(lat), crate::log::exact(lon));
if let Some(e) = self.elevation {
out.push_str(&format!(" ({}m)", crate::log::exact(e)));
}
out
}
}
pub const FIX_PRECISION: usize = 3;
pub fn read_site_rows(directory: &Path) -> Vec<SiteRow> {
let text = match fs::read_to_string(directory.join("sites.tsv")) {
Ok(t) => t,
Err(_) => return Vec::new(),
};
let mut out: Vec<SiteRow> = Vec::new();
for line in text.lines() {
if line.trim().is_empty() || line.starts_with('#') {
continue;
}
let cells: Vec<&str> = line.split('\t').collect();
if cells.len() < 3 {
continue;
}
let Some(when) = clock::parse_stamp(cells[1]) else { continue };
let cell = |i: usize| -> Option<f64> {
cells.get(i).map(|c| c.trim()).filter(|c| !c.is_empty() && *c != "--")
.and_then(|c| c.parse::<f64>().ok())
};
out.push(SiteRow {
serial: cells[0].to_string(),
from: when,
name: cells[2].to_string(),
lat: cell(3),
lon: cell(4),
elevation: cell(5),
});
}
out.sort_by(|a, b| {
(a.serial.as_str(), a.from)
.partial_cmp(&(b.serial.as_str(), b.from))
.unwrap_or(std::cmp::Ordering::Equal)
});
out
}
pub fn site_row_at(serial: &str, when: f64, rows: &[SiteRow]) -> Option<SiteRow> {
let mine: Vec<&SiteRow> = rows.iter().filter(|r| r.serial == serial).collect();
let first = mine.first()?;
let mut current = *first;
for row in &mine {
if row.from <= when {
current = row;
}
}
Some((*current).clone())
}
pub fn read_sites(directory: &Path) -> Vec<(String, f64, String)> {
let text = match fs::read_to_string(directory.join("sites.tsv")) {
Ok(t) => t,
Err(_) => return Vec::new(),
};
let mut out = Vec::new();
for line in text.lines() {
if line.trim().is_empty() || line.starts_with('#') {
continue;
}
let cells: Vec<&str> = line.split('\t').collect();
if cells.len() < 3 {
continue;
}
if let Some(when) = clock::parse_stamp(cells[1]) {
out.push((cells[0].to_string(), when, cells[2].to_string()));
}
}
out.sort_by(|a, b| (a.0.as_str(), a.1).partial_cmp(&(b.0.as_str(), b.1)).unwrap());
out
}
pub fn site_at(serial: &str, when: f64, sites: &[(String, f64, String)])
-> Option<String>
{
let mine: Vec<&(String, f64, String)> =
sites.iter().filter(|r| r.0 == serial).collect();
let first = mine.first()?;
let mut current = *first;
for row in &mine {
if row.1 <= when {
current = row;
}
}
Some(current.2.clone())
}
#[cfg(test)]
mod writer_tests {
use super::*;
#[test]
fn a_change_of_windows_mid_file_writes_a_new_header() {
let dir = std::env::temp_dir().join(format!("rb-hdr-{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
let when = 1_789_000_000.0;
let four = [3.0, 30.0, 300.0, 3000.0];
let five = [3.0, 30.0, 300.0, 3000.0, 30000.0];
let p = path(when, &dir, Some("A1"));
let mut w = Writer::new(&four, dir.clone(), Some("A1".into()), 30.0);
w.write(when, &format!("{}\tfour", clock::stamp(when))).unwrap();
w.close();
let mut w = Writer::new(&four, dir.clone(), Some("A1".into()), 30.0);
w.write(when + 30.0, &format!("{}\tfour", clock::stamp(when + 30.0))).unwrap();
w.close();
let mut w = Writer::new(&five, dir.clone(), Some("A1".into()), 30.0);
w.write(when + 60.0, &format!("{}\tfive", clock::stamp(when + 60.0))).unwrap();
w.close();
let text = fs::read_to_string(&p).unwrap();
let heads: Vec<&str> = text.lines().filter(|l| l.starts_with('#')).collect();
assert_eq!(heads, vec![header(&four).as_str(), header(&five).as_str()],
"a restart with the same windows must not repeat the header");
let _ = fs::remove_dir_all(&dir);
}
}