1use serde::{Deserialize, Serialize};
8use crate::api::mdf::Mdf;
9use crate::blocks::common::{DataType, BlockHeader, BlockParse};
10use crate::blocks::conversion::{ConversionBlock, ConversionType};
11use crate::error::MdfError;
12#[cfg(feature = "http")]
13use crate::fragments::{merge_ranges_bridging, FragmentStore, RecordingRangeReader};
14use crate::parsing::decoder::{check_value_validity, decode_channel_value, decode_channel_value_with_validity, decode_f64_from_record, vlsd_offset, DecodedValue};
15use crate::parsing::record_stream::RecordCarry;
16use crate::signal::Signal;
17use crate::types::{
18 logical_group_members, merge_group_infos, resolve_records, search_time_window, ChannelInfo, ConversionInfo,
19 GroupInfo, ReadOptions, TimeRange, Window,
20};
21use std::borrow::Cow;
22use std::collections::HashMap;
23
24const MAX_COALESCED_READ: u64 = 64 * 1024 * 1024;
26
27#[derive(Debug, Clone, Serialize, Deserialize)]
29pub struct DataBlockInfo {
30 pub file_offset: u64,
32 pub size: u64,
34 pub is_compressed: bool,
36}
37
38#[derive(Debug, Clone, Serialize, Deserialize)]
40pub struct IndexedChannel {
41 pub name: Option<String>,
43 pub unit: Option<String>,
45 #[serde(default, skip_serializing_if = "Option::is_none")]
47 pub comment: Option<String>,
48 pub data_type: DataType,
50 pub byte_offset: u32,
52 pub bit_offset: u8,
54 pub bit_count: u32,
56 pub channel_type: u8,
58 pub flags: u32,
60 pub pos_invalidation_bit: u32,
62 pub conversion: Option<ConversionBlock>,
74 #[serde(default)]
81 pub conversion_addr: u64,
82 pub vlsd_data_address: Option<u64>,
84 #[serde(default, skip_serializing_if = "Vec::is_empty")]
86 pub vlsd_data_blocks: Vec<DataBlockInfo>,
87}
88
89impl IndexedChannel {
90 pub fn is_master(&self) -> bool {
93 self.channel_type == 2 || self.channel_type == 3
94 }
95
96 pub fn is_virtual(&self) -> bool {
99 self.channel_type == 3 || self.channel_type == 6
100 }
101
102 pub fn info(&self) -> ChannelInfo {
104 ChannelInfo {
105 name: self.name.clone(),
106 unit: self.unit.clone(),
107 comment: self.comment.clone(),
108 data_type: self.data_type.name().to_string(),
109 bit_count: self.bit_count,
110 is_master: self.is_master(),
111 is_vlsd: self.is_vlsd(),
112 has_conversion: self.conversion.is_some() || self.conversion_addr != 0,
113 }
114 }
115
116 pub fn is_vlsd(&self) -> bool {
118 self.channel_type == 1 && self.vlsd_data_address.is_some()
119 }
120
121 fn to_decode_only_channel_block(&self) -> crate::blocks::channel_block::ChannelBlock {
125 Self::build_channel_block(
126 self.channel_type,
127 self.data_type.clone(),
128 self.bit_offset,
129 self.byte_offset,
130 self.bit_count,
131 self.flags,
132 self.pos_invalidation_bit,
133 None,
134 None,
135 )
136 }
137
138 fn build_channel_block(
139 channel_type: u8,
140 data_type: DataType,
141 bit_offset: u8,
142 byte_offset: u32,
143 bit_count: u32,
144 flags: u32,
145 pos_invalidation_bit: u32,
146 name: Option<String>,
147 conversion: Option<ConversionBlock>,
148 ) -> crate::blocks::channel_block::ChannelBlock {
149 crate::blocks::channel_block::ChannelBlock {
150 header: crate::blocks::common::BlockHeader {
151 id: "##CN".to_string(),
152 reserved0: 0,
153 block_len: 160,
154 links_nr: 8,
155 },
156 next_ch_addr: 0,
157 component_addr: 0,
158 name_addr: 0,
159 source_addr: 0,
160 conversion_addr: 0,
161 data: 0,
162 unit_addr: 0,
163 comment_addr: 0,
164 channel_type,
165 sync_type: 0,
166 data_type,
167 bit_offset,
168 byte_offset,
169 bit_count,
170 flags,
171 pos_invalidation_bit,
172 precision: 0,
173 reserved1: 0,
174 attachment_nr: 0,
175 min_raw_value: 0.0,
176 max_raw_value: 0.0,
177 lower_limit: 0.0,
178 upper_limit: 0.0,
179 lower_ext_limit: 0.0,
180 upper_ext_limit: 0.0,
181 name,
182 conversion,
183 }
184 }
185}
186
187#[derive(Debug, Clone, Serialize, Deserialize)]
189pub struct IndexedChannelGroup {
190 pub name: Option<String>,
192 pub comment: Option<String>,
194 pub record_id_len: u8,
196 pub record_size: u32,
198 pub invalidation_bytes: u32,
200 pub record_count: u64,
202 pub channels: Vec<IndexedChannel>,
204 pub data_blocks: Vec<DataBlockInfo>,
206 #[serde(default, skip_serializing_if = "Option::is_none")]
212 pub master_group: Option<usize>,
213}
214
215impl IndexedChannelGroup {
216 pub fn channel(&self, name: &str) -> Option<&IndexedChannel> {
218 self.channels
219 .iter()
220 .find(|c| c.name.as_deref() == Some(name))
221 }
222
223 pub fn channel_names(&self) -> Vec<&str> {
225 self.channels
226 .iter()
227 .filter_map(|c| c.name.as_deref())
228 .collect()
229 }
230
231 pub fn master_channel(&self) -> Option<&IndexedChannel> {
233 self.channels.iter().find(|c| c.is_master())
234 }
235}
236
237#[derive(Debug, Clone)]
244pub enum Source {
245 File(String),
247 #[cfg(feature = "http")]
249 Url(String),
250}
251
252impl Source {
253 pub fn as_str(&self) -> &str {
255 match self {
256 Source::File(p) => p,
257 #[cfg(feature = "http")]
258 Source::Url(u) => u,
259 }
260 }
261}
262
263fn url_scheme(value: &str) -> Option<&str> {
268 let (scheme, _) = value.split_once("://")?;
269 let mut chars = scheme.chars();
270 let valid = chars.next().is_some_and(|c| c.is_ascii_alphabetic())
271 && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'));
272 (valid && scheme.len() > 1).then_some(scheme)
273}
274
275fn is_http_url(value: &str) -> bool {
277 url_scheme(value).is_some_and(|s| s.eq_ignore_ascii_case("http") || s.eq_ignore_ascii_case("https"))
278}
279
280impl From<&str> for Source {
281 fn from(value: &str) -> Self {
282 #[cfg(feature = "http")]
283 if is_http_url(value) {
284 return Source::Url(value.to_string());
285 }
286 Source::File(value.to_string())
287 }
288}
289
290impl From<String> for Source {
291 fn from(value: String) -> Self {
292 Source::from(value.as_str())
293 }
294}
295
296#[cfg(feature = "http")]
299const BATCH_BRIDGE_BYTES: u64 = 4 * 1024;
300
301#[cfg(feature = "http")]
303const MAX_BATCH_ROUNDS: usize = 1_000;
304
305#[cfg(feature = "http")]
309const PARALLEL_CHUNK_BYTES: u64 = 8 * 1024 * 1024;
310
311#[cfg(feature = "http")]
315const BATCH_MEMORY_LIMIT: u64 = 256 * 1024 * 1024;
316
317#[cfg(feature = "http")]
321struct ChunkedUrlReader {
322 http: HttpRangeReader,
323 store: FragmentStore,
324}
325
326#[cfg(feature = "http")]
327impl ByteRangeReader for ChunkedUrlReader {
328 type Error = MdfError;
329
330 fn read_range(&mut self, offset: u64, length: u64) -> Result<Vec<u8>, MdfError> {
331 if let crate::fragments::Coverage::Full(bytes) = self.store.assemble(offset, length)? {
332 return Ok(bytes);
333 }
334 if length <= PARALLEL_CHUNK_BYTES {
335 return self.http.read_range(offset, length);
336 }
337 let parts = self.http.read_ranges_parallel(&split_spans(vec![(offset, length)], PARALLEL_CHUNK_BYTES))?;
338 let mut out = Vec::with_capacity(usize::try_from(length).unwrap_or(0));
339 for part in parts {
340 out.extend_from_slice(&part);
341 }
342 Ok(out)
343 }
344}
345
346#[cfg(feature = "http")]
349fn split_spans(spans: Vec<(u64, u64)>, chunk: u64) -> Vec<(u64, u64)> {
350 let mut out = Vec::with_capacity(spans.len());
351 for (offset, length) in spans {
352 let mut at = 0;
353 while at < length {
354 let take = chunk.min(length - at);
355 out.push((offset + at, take));
356 at += take;
357 }
358 }
359 out
360}
361
362enum SourceReader {
364 #[cfg(not(target_arch = "wasm32"))]
365 File(MmapRangeReader),
366 #[cfg(feature = "http")]
367 Url(CachingRangeReader<HttpRangeReader>),
368}
369
370impl ByteRangeReader for SourceReader {
371 type Error = MdfError;
372
373 #[allow(unused_variables)]
374 fn read_range(&mut self, offset: u64, length: u64) -> Result<Vec<u8>, MdfError> {
375 match *self {
376 #[cfg(not(target_arch = "wasm32"))]
377 SourceReader::File(ref mut r) => r.read_range(offset, length),
378 #[cfg(feature = "http")]
379 SourceReader::Url(ref mut r) => r.read_range(offset, length),
380 }
381 }
382}
383
384type WindowCache = HashMap<(Option<(usize, usize)>, u64), (u64, u64)>;
387
388type AxisCache = HashMap<(usize, usize, u64, u64), Vec<f64>>;
391
392#[derive(Debug, Clone, Serialize, Deserialize)]
394pub struct MdfIndex {
395 pub file_size: u64,
397 pub start_time_ns: Option<u64>,
400 pub channel_groups: Vec<IndexedChannelGroup>,
402 #[serde(skip)]
406 pub source: Option<Source>,
407}
408
409pub trait ByteRangeReader {
411 type Error;
412
413 fn read_range(&mut self, offset: u64, length: u64) -> Result<Vec<u8>, Self::Error>;
416
417 fn read_range_optional(
431 &mut self,
432 offset: u64,
433 length: u64,
434 ) -> Result<Option<Vec<u8>>, Self::Error> {
435 self.read_range(offset, length).map(Some)
436 }
437
438 fn is_probing(&self) -> bool {
446 false
447 }
448}
449
450#[cfg(not(target_arch = "wasm32"))]
455pub struct FileRangeReader {
456 file: std::fs::File,
457}
458
459#[cfg(not(target_arch = "wasm32"))]
460impl FileRangeReader {
461 pub fn new(file_path: &str) -> Result<Self, MdfError> {
462 let file = std::fs::File::open(file_path)
463 .map_err(MdfError::IOError)?;
464 Ok(Self { file })
465 }
466}
467
468#[cfg(not(target_arch = "wasm32"))]
469impl ByteRangeReader for FileRangeReader {
470 type Error = MdfError;
471
472 fn read_range(&mut self, offset: u64, length: u64) -> Result<Vec<u8>, Self::Error> {
473 use std::io::{Read, Seek, SeekFrom};
474
475 let file_len = self.file.metadata().map_err(MdfError::IOError)?.len();
479 match offset.checked_add(length) {
480 Some(end) if end <= file_len => {}
481 _ => {
482 return Err(MdfError::TooShortBuffer {
483 actual: file_len as usize,
484 expected: offset.saturating_add(length) as usize,
485 file: file!(),
486 line: line!(),
487 });
488 }
489 }
490
491 self.file.seek(SeekFrom::Start(offset))
492 .map_err(MdfError::IOError)?;
493
494 let mut buffer = vec![0u8; length as usize];
495 self.file.read_exact(&mut buffer)
496 .map_err(MdfError::IOError)?;
497
498 Ok(buffer)
499 }
500}
501
502#[cfg(not(target_arch = "wasm32"))]
506pub struct MmapRangeReader {
507 mmap: memmap2::Mmap,
508}
509
510#[cfg(not(target_arch = "wasm32"))]
511impl MmapRangeReader {
512 pub fn new(file_path: &str) -> Result<Self, MdfError> {
513 let file = std::fs::File::open(file_path).map_err(MdfError::IOError)?;
514 let mmap = unsafe { memmap2::Mmap::map(&file) }.map_err(MdfError::IOError)?;
515 Ok(Self { mmap })
516 }
517}
518
519#[cfg(not(target_arch = "wasm32"))]
520impl ByteRangeReader for MmapRangeReader {
521 type Error = MdfError;
522
523 fn read_range(&mut self, offset: u64, length: u64) -> Result<Vec<u8>, Self::Error> {
524 let end = match offset
526 .checked_add(length)
527 .and_then(|e| usize::try_from(e).ok())
528 {
529 Some(end) if end <= self.mmap.len() => end,
530 _ => {
531 return Err(MdfError::TooShortBuffer {
532 actual: self.mmap.len(),
533 expected: offset.saturating_add(length).min(usize::MAX as u64) as usize,
534 file: file!(),
535 line: line!(),
536 });
537 }
538 };
539 Ok(self.mmap[offset as usize..end].to_vec())
540 }
541}
542
543pub struct SliceRangeReader {
549 data: Vec<u8>,
550}
551
552impl SliceRangeReader {
553 pub fn new(data: Vec<u8>) -> Self {
554 Self { data }
555 }
556}
557
558impl ByteRangeReader for SliceRangeReader {
559 type Error = MdfError;
560
561 fn read_range(&mut self, offset: u64, length: u64) -> Result<Vec<u8>, Self::Error> {
562 let end = match offset
564 .checked_add(length)
565 .and_then(|e| usize::try_from(e).ok())
566 {
567 Some(end) if end <= self.data.len() => end,
568 _ => {
569 return Err(MdfError::TooShortBuffer {
570 actual: self.data.len(),
571 expected: offset.saturating_add(length).min(usize::MAX as u64) as usize,
572 file: file!(),
573 line: line!(),
574 });
575 }
576 };
577 Ok(self.data[offset as usize..end].to_vec())
578 }
579}
580
581struct BorrowedSliceReader<'a> {
585 data: &'a [u8],
586}
587
588impl<'a> ByteRangeReader for BorrowedSliceReader<'a> {
589 type Error = MdfError;
590
591 fn read_range(&mut self, offset: u64, length: u64) -> Result<Vec<u8>, Self::Error> {
592 let end = match offset
594 .checked_add(length)
595 .and_then(|e| usize::try_from(e).ok())
596 {
597 Some(end) if end <= self.data.len() => end,
598 _ => {
599 return Err(MdfError::TooShortBuffer {
600 actual: self.data.len(),
601 expected: offset.saturating_add(length).min(usize::MAX as u64) as usize,
602 file: file!(),
603 line: line!(),
604 });
605 }
606 };
607 Ok(self.data[offset as usize..end].to_vec())
608 }
609}
610
611pub struct CachingRangeReader<R: ByteRangeReader<Error = MdfError>> {
624 inner: R,
625 chunks: std::collections::BTreeMap<u64, Vec<u8>>,
626 chunk_size: u64,
627 bypass: bool,
628 underlying_requests: u64,
629 cache_hits: u64,
630 known_size: Option<u64>,
635}
636
637impl<R: ByteRangeReader<Error = MdfError>> CachingRangeReader<R> {
638 #[allow(dead_code)]
640 pub(crate) fn inner_mut(&mut self) -> &mut R {
641 &mut self.inner
642 }
643
644 #[allow(dead_code)]
646 pub(crate) fn into_parts(self) -> (R, Vec<(u64, Vec<u8>)>) {
647 let chunk_size = self.chunk_size;
648 let chunks = self
649 .chunks
650 .into_iter()
651 .filter(|(_, bytes)| !bytes.is_empty())
652 .map(|(i, bytes)| (i * chunk_size, bytes))
653 .collect();
654 (self.inner, chunks)
655 }
656
657 pub fn new(inner: R) -> Self {
659 Self::with_chunk_size(inner, 1 << 20)
660 }
661
662 pub fn with_chunk_size(inner: R, chunk_size: u64) -> Self {
664 assert!(chunk_size > 0, "chunk_size must be > 0");
665 Self {
666 inner,
667 chunks: std::collections::BTreeMap::new(),
668 chunk_size,
669 bypass: false,
670 underlying_requests: 0,
671 cache_hits: 0,
672 known_size: None,
673 }
674 }
675
676 pub fn set_known_size(&mut self, size: u64) {
680 self.known_size = Some(size);
681 }
682
683 pub fn set_bypass(&mut self, bypass: bool) {
690 self.bypass = bypass;
691 }
692
693 pub fn underlying_requests(&self) -> u64 {
695 self.underlying_requests
696 }
697
698 pub fn cache_hits(&self) -> u64 {
700 self.cache_hits
701 }
702
703 pub fn prefetch(&mut self, offset: u64, length: u64) -> Result<(), MdfError> {
705 if length == 0 {
706 return Ok(());
707 }
708 self.read_range(offset, length).map(|_| ())
709 }
710
711 fn try_serve_from_cache(&self, offset: u64, length: u64) -> Option<Vec<u8>> {
719 let first = offset / self.chunk_size;
720 let last = (offset + length - 1) / self.chunk_size;
721 let read_end = offset + length;
722 for i in first..=last {
723 let chunk = self.chunks.get(&i)?;
724 let chunk_start = i * self.chunk_size;
725 let cached_end = chunk_start + chunk.len() as u64;
726 let needed_end = read_end.min(chunk_start + self.chunk_size);
727 if cached_end < needed_end {
728 return None;
729 }
730 }
731 let mut out = Vec::with_capacity(length.min(1 << 24) as usize);
732 let mut remaining = length as usize;
733 let mut cursor = offset;
734 while remaining > 0 {
735 let chunk_index = cursor / self.chunk_size;
736 let chunk_offset = (cursor % self.chunk_size) as usize;
737 let chunk = self.chunks.get(&chunk_index)?;
738 if chunk_offset >= chunk.len() {
739 return None;
740 }
741 let take = std::cmp::min(remaining, chunk.len() - chunk_offset);
742 out.extend_from_slice(&chunk[chunk_offset..chunk_offset + take]);
743 cursor += take as u64;
744 remaining -= take;
745 if take == 0 {
746 return None;
747 }
748 }
749 Some(out)
750 }
751
752 fn ensure_chunks(&mut self, first: u64, last: u64, requested_end: u64) -> Result<(), MdfError> {
753 let mut idx = first;
756 while idx <= last {
757 if self.chunks.contains_key(&idx) {
758 idx += 1;
759 continue;
760 }
761 let run_start = idx;
762 while idx <= last && !self.chunks.contains_key(&idx) {
763 idx += 1;
764 }
765 let run_end = idx - 1;
766 let read_offset = run_start * self.chunk_size;
767 let mut read_len = (run_end - run_start + 1) * self.chunk_size;
768
769 if let Some(size) = self.known_size {
773 if read_offset >= size {
774 for slot in run_start..=run_end {
775 self.chunks.insert(slot, Vec::new());
776 }
777 continue;
778 }
779 read_len = read_len.min(size - read_offset);
780 }
781
782 let bytes = match self.inner.read_range(read_offset, read_len) {
783 Ok(b) => {
784 self.underlying_requests += 1;
785 b
786 }
787 Err(e) => {
788 self.underlying_requests += 1;
789 let clamp_to = match &e {
795 MdfError::TooShortBuffer { actual, .. }
796 if (*actual as u64) > read_offset
797 && (*actual as u64) < read_offset + read_len =>
798 {
799 self.known_size = Some(*actual as u64);
800 *actual as u64
801 }
802 _ if requested_end > read_offset
803 && requested_end < read_offset + read_len =>
804 {
805 requested_end
806 }
807 _ => return Err(e),
808 };
809 let b = self.inner.read_range(read_offset, clamp_to - read_offset)?;
810 self.underlying_requests += 1;
811 b
812 }
813 };
814
815 for (i, slot) in (run_start..=run_end).enumerate() {
818 let start = i * self.chunk_size as usize;
819 if start >= bytes.len() {
820 self.chunks.insert(slot, Vec::new());
821 continue;
822 }
823 let end = std::cmp::min(start + self.chunk_size as usize, bytes.len());
824 self.chunks.insert(slot, bytes[start..end].to_vec());
825 }
826 }
827 Ok(())
828 }
829}
830
831impl<R: ByteRangeReader<Error = MdfError>> ByteRangeReader for CachingRangeReader<R> {
832 type Error = MdfError;
833
834 fn read_range(&mut self, offset: u64, length: u64) -> Result<Vec<u8>, MdfError> {
835 if length == 0 {
836 return Ok(Vec::new());
837 }
838 if self.bypass {
839 if let Some(bytes) = self.try_serve_from_cache(offset, length) {
844 self.cache_hits += 1;
845 return Ok(bytes);
846 }
847 let bytes = self.inner.read_range(offset, length)?;
848 self.underlying_requests += 1;
849 return Ok(bytes);
850 }
851
852 let first = offset / self.chunk_size;
853 let last = (offset + length - 1) / self.chunk_size;
854 let read_end = offset + length;
855
856 for i in first..=last {
860 if let Some(chunk) = self.chunks.get(&i) {
861 let chunk_start = i * self.chunk_size;
862 let cached_end = chunk_start + chunk.len() as u64;
863 let mut needed_end = read_end.min(chunk_start + self.chunk_size);
864 if let Some(size) = self.known_size {
865 needed_end = needed_end.min(size);
866 }
867 if cached_end < needed_end {
868 self.chunks.remove(&i);
869 }
870 }
871 }
872
873 let need_fetch = (first..=last).any(|i| !self.chunks.contains_key(&i));
875 self.ensure_chunks(first, last, read_end)?;
876 if !need_fetch {
877 self.cache_hits += 1;
878 }
879
880 let mut out = Vec::with_capacity(length.min(1 << 24) as usize);
882 let mut remaining = length as usize;
883 let mut cursor = offset;
884 while remaining > 0 {
885 let chunk_index = cursor / self.chunk_size;
886 let chunk_offset = (cursor % self.chunk_size) as usize;
887 let chunk = self.chunks.get(&chunk_index).expect("chunk fetched above");
888 if chunk_offset >= chunk.len() {
889 return Err(MdfError::TooShortBuffer {
890 actual: chunk.len(),
891 expected: chunk_offset + 1,
892 file: file!(),
893 line: line!(),
894 });
895 }
896 let take = std::cmp::min(remaining, chunk.len() - chunk_offset);
897 out.extend_from_slice(&chunk[chunk_offset..chunk_offset + take]);
898 cursor += take as u64;
899 remaining -= take;
900 if take == 0 {
901 break;
902 }
903 }
904
905 if out.len() != length as usize {
906 return Err(MdfError::TooShortBuffer {
907 actual: out.len(),
908 expected: length as usize,
909 file: file!(),
910 line: line!(),
911 });
912 }
913
914 Ok(out)
915 }
916}
917
918#[cfg(feature = "http")]
927pub struct HttpRangeReader {
928 agent: ureq::Agent,
929 url: String,
930 request_count: u64,
931 expected_size: Option<u64>,
936}
937
938#[cfg(feature = "http")]
939impl HttpRangeReader {
940 pub fn new(url: impl Into<String>) -> Result<Self, MdfError> {
941 Ok(Self {
942 agent: shared_http_agent()?,
943 url: url.into(),
944 request_count: 0,
945 expected_size: None,
946 })
947 }
948
949 pub fn expect_size(&mut self, size: u64) {
952 self.expected_size = Some(size);
953 }
954
955 pub(crate) fn read_ranges_parallel(&mut self, spans: &[(u64, u64)]) -> Result<Vec<Vec<u8>>, MdfError> {
962 if spans.len() <= 1 {
963 return spans.iter().map(|&(o, l)| self.read_range(o, l)).collect();
964 }
965 let (agent, url, expected) = (&self.agent, self.url.as_str(), self.expected_size);
966 let mut out: Vec<Vec<u8>> = Vec::with_capacity(spans.len());
967 for chunk in spans.chunks(MAX_PARALLEL_REQUESTS) {
968 let results: Vec<Result<Vec<u8>, MdfError>> = std::thread::scope(|scope| {
969 let handles: Vec<_> = chunk
970 .iter()
971 .map(|&(offset, length)| scope.spawn(move || http_get_range(agent, url, offset, length, expected)))
972 .collect();
973 handles
974 .into_iter()
975 .map(|h| {
976 h.join().unwrap_or_else(|_| {
977 Err(MdfError::BlockSerializationError("HTTP fetch thread panicked".to_string()))
978 })
979 })
980 .collect()
981 });
982 self.request_count += chunk.len() as u64;
983 for r in results {
984 out.push(r?);
985 }
986 }
987 Ok(out)
988 }
989
990 pub(crate) fn fetch_all(&mut self) -> Result<Vec<u8>, MdfError> {
992 use std::io::Read;
993 self.request_count += 1;
994 let (agent, url) = (&self.agent, self.url.as_str());
995 with_retries(|| {
996 let response = agent.get(url).call().map_err(classify_call_error)?;
997 let mut body = Vec::new();
998 response
999 .into_reader()
1000 .read_to_end(&mut body)
1001 .map_err(|e| HttpFailure::Transient(MdfError::IOError(e), None))?;
1002 Ok(body)
1003 })
1004 }
1005
1006 pub fn probe_size(&mut self) -> Result<u64, MdfError> {
1014 use std::io::Read;
1015
1016 let (agent, url) = (&self.agent, self.url.as_str());
1017 let resp = with_retries(|| agent.get(url).set("Range", "bytes=0-0").call().map_err(classify_call_error))?;
1018 self.request_count += 1;
1019
1020 let total = resp
1022 .header("Content-Range")
1023 .and_then(|cr| cr.rsplit('/').next().map(|s| s.trim().to_string()))
1024 .filter(|s| s != "*")
1025 .and_then(|s| s.parse::<u64>().ok());
1026
1027 let content_length = resp
1031 .header("Content-Length")
1032 .and_then(|s| s.parse::<u64>().ok());
1033 let status = resp.status();
1034 let mut sink = Vec::new();
1035 let _ = resp.into_reader().take(1).read_to_end(&mut sink);
1036
1037 if let Some(len) = total {
1038 Ok(len)
1039 } else if status == 200 {
1040 content_length.ok_or_else(|| {
1041 MdfError::BlockSerializationError(
1042 "size probe: server ignored Range and sent no Content-Length".into(),
1043 )
1044 })
1045 } else {
1046 Err(MdfError::BlockSerializationError(
1047 "size probe: 206 response missing Content-Range total".into(),
1048 ))
1049 }
1050 }
1051
1052 pub fn request_count(&self) -> u64 {
1054 self.request_count
1055 }
1056}
1057
1058#[cfg(feature = "http")]
1059impl ByteRangeReader for HttpRangeReader {
1060 type Error = MdfError;
1061
1062 fn read_range(&mut self, offset: u64, length: u64) -> Result<Vec<u8>, MdfError> {
1063 let bytes = http_get_range(&self.agent, &self.url, offset, length, self.expected_size);
1064 if length > 0 {
1065 self.request_count += 1;
1066 }
1067 bytes
1068 }
1069}
1070
1071#[cfg(feature = "http")]
1074pub(crate) const MAX_PARALLEL_REQUESTS: usize = 8;
1075
1076#[cfg(feature = "http")]
1083fn shared_http_agent() -> Result<ureq::Agent, MdfError> {
1084 static AGENT: std::sync::Mutex<Option<(u32, ureq::Agent)>> = std::sync::Mutex::new(None);
1088 let pid = std::process::id();
1089 let mut slot = AGENT.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
1090 if let Some((owner, agent)) = slot.as_ref()
1091 && *owner == pid
1092 {
1093 return Ok(agent.clone());
1094 }
1095 let connector = native_tls::TlsConnector::new().map_err(|e| {
1099 MdfError::BlockSerializationError(format!("failed to init TLS backend: {e}"))
1100 })?;
1101 let agent = ureq::AgentBuilder::new()
1102 .tls_connector(std::sync::Arc::new(connector))
1103 .max_idle_connections_per_host(MAX_PARALLEL_REQUESTS)
1104 .timeout_connect(HTTP_CONNECT_TIMEOUT)
1107 .timeout_read(HTTP_READ_TIMEOUT)
1108 .timeout_write(HTTP_READ_TIMEOUT)
1109 .build();
1110 *slot = Some((pid, agent.clone()));
1111 Ok(agent)
1112}
1113
1114#[cfg(feature = "http")]
1116const HTTP_CONNECT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
1117
1118#[cfg(feature = "http")]
1121const HTTP_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60);
1122
1123#[cfg(feature = "http")]
1126const HTTP_MAX_RETRIES: u32 = 3;
1127
1128#[cfg(feature = "http")]
1130const HTTP_RETRY_BASE_DELAY: std::time::Duration = std::time::Duration::from_millis(200);
1131
1132#[cfg(feature = "http")]
1134const HTTP_MAX_RETRY_DELAY: std::time::Duration = std::time::Duration::from_secs(10);
1135
1136#[cfg(feature = "http")]
1138enum HttpFailure {
1139 Transient(MdfError, Option<std::time::Duration>),
1142 Fatal(MdfError),
1144}
1145
1146#[cfg(feature = "http")]
1149fn is_transient_status(status: u16) -> bool {
1150 matches!(status, 408 | 429 | 500 | 502 | 503 | 504)
1151}
1152
1153#[cfg(feature = "http")]
1155fn retry_after(resp: &ureq::Response) -> Option<std::time::Duration> {
1156 resp.header("Retry-After")?.trim().parse::<u64>().ok().map(std::time::Duration::from_secs)
1157}
1158
1159#[cfg(feature = "http")]
1162fn classify_call_error(error: ureq::Error) -> HttpFailure {
1163 match error {
1164 ureq::Error::Status(status, resp) if is_transient_status(status) => {
1165 let after = retry_after(&resp);
1166 HttpFailure::Transient(
1167 MdfError::BlockSerializationError(format!("HTTP request failed with status {status}")),
1168 after,
1169 )
1170 }
1171 ureq::Error::Status(status, _) => {
1172 HttpFailure::Fatal(MdfError::BlockSerializationError(format!("HTTP request failed with status {status}")))
1173 }
1174 ureq::Error::Transport(transport) => {
1175 let error = MdfError::BlockSerializationError(format!("HTTP request failed: {transport}"));
1176 match transport.kind() {
1179 ureq::ErrorKind::ConnectionFailed | ureq::ErrorKind::Io | ureq::ErrorKind::ProxyConnect => {
1180 HttpFailure::Transient(error, None)
1181 }
1182 _ => HttpFailure::Fatal(error),
1183 }
1184 }
1185 }
1186}
1187
1188#[cfg(feature = "http")]
1192fn with_retries<T>(mut attempt: impl FnMut() -> Result<T, HttpFailure>) -> Result<T, MdfError> {
1193 let mut delay = HTTP_RETRY_BASE_DELAY;
1194 let mut retries = 0;
1195 loop {
1196 match attempt() {
1197 Ok(value) => return Ok(value),
1198 Err(HttpFailure::Fatal(e)) => return Err(e),
1199 Err(HttpFailure::Transient(e, after)) => {
1200 if retries == HTTP_MAX_RETRIES {
1201 return Err(match e {
1202 MdfError::BlockSerializationError(msg) => MdfError::BlockSerializationError(format!(
1203 "{msg} (gave up after {} attempts)",
1204 HTTP_MAX_RETRIES + 1
1205 )),
1206 other => other,
1207 });
1208 }
1209 std::thread::sleep(after.unwrap_or(delay).min(HTTP_MAX_RETRY_DELAY));
1210 delay *= 2;
1211 retries += 1;
1212 }
1213 }
1214 }
1215}
1216
1217#[cfg(feature = "http")]
1220fn content_range_total(header: Option<&str>) -> Option<u64> {
1221 header?.rsplit_once('/')?.1.trim().parse().ok()
1222}
1223
1224#[cfg(feature = "http")]
1226fn content_range_span(header: Option<&str>) -> Option<(u64, u64)> {
1227 let spec = header?.trim().strip_prefix("bytes")?.trim();
1228 let (a, b) = spec.split_once('/')?.0.split_once('-')?;
1229 Some((a.trim().parse().ok()?, b.trim().parse().ok()?))
1230}
1231
1232#[cfg(any(feature = "http", not(target_arch = "wasm32")))]
1234fn check_resource_size(source: &str, expected: u64, actual: u64) -> Result<(), MdfError> {
1235 if expected != 0 && actual != expected {
1236 return Err(MdfError::InvalidArgument(format!(
1237 "the source does not match the index: the index was built from a {expected}-byte \
1238 file but '{source}' is {actual} bytes — attach the file the index was built \
1239 from, or rebuild the index"
1240 )));
1241 }
1242 Ok(())
1243}
1244
1245#[cfg(feature = "http")]
1248fn http_get_range(
1249 agent: &ureq::Agent,
1250 url: &str,
1251 offset: u64,
1252 length: u64,
1253 expected_size: Option<u64>,
1254) -> Result<Vec<u8>, MdfError> {
1255 if length == 0 {
1256 return Ok(Vec::new());
1257 }
1258 with_retries(|| http_get_range_once(agent, url, offset, length, expected_size))
1259}
1260
1261#[cfg(feature = "http")]
1263fn http_get_range_once(
1264 agent: &ureq::Agent,
1265 url: &str,
1266 offset: u64,
1267 length: u64,
1268 expected_size: Option<u64>,
1269) -> Result<Vec<u8>, HttpFailure> {
1270 use std::io::Read;
1271 use HttpFailure::Fatal;
1272
1273 let range_header = format!("bytes={}-{}", offset, offset + length - 1);
1274 let resp = match agent.get(url).set("Range", &range_header).call() {
1275 Ok(resp) => resp,
1276 Err(ureq::Error::Status(416, resp)) => {
1279 let total = content_range_total(resp.header("Content-Range"));
1280 if let (Some(expected), Some(actual)) = (expected_size, total) {
1281 check_resource_size(url, expected, actual).map_err(Fatal)?;
1282 }
1283 return Err(Fatal(MdfError::BlockSerializationError(format!(
1284 "HTTP range {offset}..{} is past the end of {url}{}",
1285 offset + length,
1286 total.map(|t| format!(" ({t} bytes)")).unwrap_or_default()
1287 ))));
1288 }
1289 Err(e) => return Err(classify_call_error(e)),
1290 };
1291 if let (Some(expected), Some(actual)) = (expected_size, content_range_total(resp.header("Content-Range"))) {
1292 check_resource_size(url, expected, actual).map_err(Fatal)?;
1293 }
1294 if resp.status() == 206 {
1298 if let Some((start, end)) = content_range_span(resp.header("Content-Range")) {
1299 let want_end = offset + length - 1;
1300 if start != offset || end > want_end {
1302 return Err(Fatal(MdfError::BlockSerializationError(format!(
1303 "HTTP server returned bytes {start}-{end} for requested range {offset}-{want_end}"
1304 ))));
1305 }
1306 }
1307 }
1308
1309 let status = resp.status();
1315 match status {
1316 206 => {}
1317 200 => {
1318 if offset != 0 {
1319 return Err(Fatal(MdfError::BlockSerializationError(format!(
1320 "HTTP server ignored Range request (status 200) for offset {}; \
1321 refusing to return bytes from the wrong position",
1322 offset
1323 ))));
1324 }
1325 }
1326 other => {
1327 return Err(Fatal(MdfError::BlockSerializationError(format!(
1328 "HTTP range request returned unexpected status {other}"
1329 ))));
1330 }
1331 }
1332
1333 let mut buf = Vec::with_capacity(length.min(1 << 20) as usize);
1339 resp.into_reader()
1341 .take(length)
1342 .read_to_end(&mut buf)
1343 .map_err(|e| HttpFailure::Transient(MdfError::IOError(e), None))?;
1344 if (buf.len() as u64) < length {
1345 return Err(Fatal(MdfError::TooShortBuffer {
1348 actual: (offset + buf.len() as u64) as usize,
1349 expected: (offset + length) as usize,
1350 file: file!(),
1351 line: line!(),
1352 }));
1353 }
1354 Ok(buf)
1355}
1356
1357impl MdfIndex {
1358 #[cfg(not(target_arch = "wasm32"))]
1362 pub fn from_file(file_path: &str) -> Result<Self, MdfError> {
1363 let mdf = Mdf::from_file(file_path)?;
1364 let file_size = std::fs::metadata(file_path)
1365 .map_err(MdfError::IOError)?
1366 .len();
1367 let mut index = Self::build_index(mdf, file_size)?;
1368 index.source = Some(Source::File(file_path.to_string()));
1369 Ok(index)
1370 }
1371
1372 #[cfg(feature = "http")]
1378 pub fn from_url(url: &str) -> Result<Self, MdfError> {
1379 Self::from_url_with_chunk_size(url, 1 << 20)
1380 }
1381
1382 #[cfg(feature = "http")]
1384 pub fn from_url_with_chunk_size(url: &str, chunk_size: u64) -> Result<Self, MdfError> {
1385 let mut http = HttpRangeReader::new(url)?;
1386 let file_size = http.probe_size()?;
1387 let mut cached = CachingRangeReader::with_chunk_size(http, chunk_size);
1388 cached.set_known_size(file_size);
1389 let mut index = Self::from_range_reader(&mut cached, file_size)?;
1390 index.source = Some(Source::Url(url.to_string()));
1391 Ok(index)
1392 }
1393
1394 fn build_index(mdf: Mdf, file_size: u64) -> Result<Self, MdfError> {
1396 let start_time_ns = mdf.start_time_ns();
1397 let mut indexed_groups = Vec::new();
1398 let mut cg_links: Vec<(u64, u64)> = Vec::new();
1400
1401 for group in mdf.channel_groups() {
1402 let raw_cg = group.raw_channel_group();
1403 cg_links.push((raw_cg.addr, raw_cg.block.master_cg_addr));
1404 let raw_dg = group.raw_data_group();
1408 if raw_dg.block.record_id_len > 0 && raw_dg.channel_groups.len() > 1 {
1409 return Err(MdfError::BlockSerializationError(
1410 "unsorted data groups (record IDs with multiple channel groups) \
1411 are not supported by the index"
1412 .to_string(),
1413 ));
1414 }
1415
1416 let mut indexed_channels = Vec::new();
1417 let mmap = group.mmap();
1418
1419 for channel in group.channels() {
1420 let block = channel.block();
1421
1422 let resolved_conversion = if let Some(mut conversion) = block.conversion.clone() {
1423 if let Err(e) = conversion.resolve_all_dependencies(mmap) {
1424 eprintln!("Warning: Failed to resolve conversion dependencies for channel '{}': {}",
1425 block.name.as_deref().unwrap_or("<unnamed>"), e);
1426 }
1427 Some(conversion)
1428 } else {
1429 None
1430 };
1431
1432 let vlsd_data_blocks = if block.channel_type == 1 && block.data != 0 {
1433 let mut slice_reader = BorrowedSliceReader { data: mmap };
1434 Self::extract_vlsd_data_blocks(&mut slice_reader, block.data)?
1435 } else {
1436 Vec::new()
1437 };
1438
1439 indexed_channels.push(IndexedChannel {
1440 name: channel.name()?,
1441 unit: channel.unit()?,
1442 comment: channel.comment()?,
1443 data_type: block.data_type.clone(),
1444 byte_offset: block.byte_offset,
1445 bit_offset: block.bit_offset,
1446 bit_count: block.bit_count,
1447 channel_type: block.channel_type,
1448 flags: block.flags,
1449 pos_invalidation_bit: block.pos_invalidation_bit,
1450 conversion: resolved_conversion,
1451 conversion_addr: block.conversion_addr,
1452 vlsd_data_address: if block.channel_type == 1 && block.data != 0 {
1453 Some(block.data)
1454 } else {
1455 None
1456 },
1457 vlsd_data_blocks,
1458 });
1459 }
1460
1461 let data_blocks = Self::extract_data_blocks(&group)?;
1462
1463 indexed_groups.push(IndexedChannelGroup {
1464 name: group.name()?,
1465 comment: group.comment()?,
1466 record_id_len: group.raw_data_group().block.record_id_len,
1467 record_size: group.raw_channel_group().block.samples_byte_nr,
1468 invalidation_bytes: group.raw_channel_group().block.invalidation_bytes_nr,
1469 record_count: group.raw_channel_group().block.cycles_nr,
1470 channels: indexed_channels,
1471 data_blocks,
1472 master_group: None,
1473 });
1474 }
1475 Self::link_remote_masters(&mut indexed_groups, &cg_links);
1476
1477 Ok(MdfIndex { file_size, start_time_ns, channel_groups: indexed_groups, source: None })
1478 }
1479
1480 fn link_remote_masters(groups: &mut [IndexedChannelGroup], cg_links: &[(u64, u64)]) {
1483 for g in 0..groups.len() {
1484 let target = cg_links[g].1;
1485 if target == 0 || groups[g].master_channel().is_some() {
1486 continue;
1487 }
1488 groups[g].master_group = cg_links
1489 .iter()
1490 .position(|&(addr, _)| addr == target)
1491 .filter(|&m| m != g && groups[m].master_channel().is_some());
1492 }
1493 }
1494
1495 fn extract_data_blocks(group: &crate::api::channel_group::ChannelGroup) -> Result<Vec<DataBlockInfo>, MdfError> {
1501 let mut reader = BorrowedSliceReader { data: group.mmap() };
1502 Self::extract_data_blocks_via_reader(&mut reader, group.raw_data_group().block.data_block_addr, None, 0)
1503 }
1504
1505 pub fn from_bytes(data: Vec<u8>) -> Result<Self, MdfError> {
1509 let file_size = data.len() as u64;
1510 let mdf = Mdf::from_bytes(data)?;
1511 Self::build_index(mdf, file_size)
1512 }
1513
1514 pub fn from_range_reader<R>(
1527 reader: &mut R,
1528 file_size: u64,
1529 ) -> Result<Self, MdfError>
1530 where
1531 R: ByteRangeReader<Error = MdfError>,
1532 {
1533 use crate::parsing::reader_walk;
1534
1535 let walk = reader_walk::walk(reader)?;
1536
1537 let start_time_ns = if walk.header.abs_time == 0 {
1538 None
1539 } else {
1540 Some(walk.header.abs_time)
1541 };
1542
1543 let mut indexed_groups = Vec::with_capacity(walk.groups.len());
1544 let cg_links: Vec<(u64, u64)> =
1545 walk.groups.iter().map(|g| (g.cg_addr, g.cg.master_cg_addr)).collect();
1546 for group in walk.groups {
1547 let mut indexed_channels = Vec::with_capacity(group.channels.len());
1548 for ch in group.channels {
1549 let block = ch.block;
1550 let vlsd_data_blocks = if block.channel_type == 1 && block.data != 0 {
1551 Self::extract_vlsd_data_blocks(reader, block.data)?
1552 } else {
1553 Vec::new()
1554 };
1555 indexed_channels.push(IndexedChannel {
1556 name: ch.name,
1557 unit: ch.unit,
1558 comment: ch.comment,
1559 data_type: block.data_type.clone(),
1560 byte_offset: block.byte_offset,
1561 bit_offset: block.bit_offset,
1562 bit_count: block.bit_count,
1563 channel_type: block.channel_type,
1564 flags: block.flags,
1565 pos_invalidation_bit: block.pos_invalidation_bit,
1566 conversion: None,
1570 conversion_addr: ch.conversion_addr,
1571 vlsd_data_address: if block.channel_type == 1 && block.data != 0 {
1572 Some(block.data)
1573 } else {
1574 None
1575 },
1576 vlsd_data_blocks,
1577 });
1578 }
1579
1580 let expected_bytes = group.cg.cycles_nr.checked_mul(
1583 group.record_id_len as u64
1584 + group.cg.samples_byte_nr as u64
1585 + group.cg.invalidation_bytes_nr as u64,
1586 );
1587 let data_blocks = Self::extract_data_blocks_via_reader(
1588 reader,
1589 group.data_block_addr,
1590 expected_bytes,
1591 file_size,
1592 )?;
1593
1594 indexed_groups.push(IndexedChannelGroup {
1595 name: group.cg_name,
1596 comment: group.cg_comment,
1597 record_id_len: group.record_id_len,
1598 record_size: group.cg.samples_byte_nr,
1599 invalidation_bytes: group.cg.invalidation_bytes_nr,
1600 record_count: group.cg.cycles_nr,
1601 channels: indexed_channels,
1602 data_blocks,
1603 master_group: None,
1604 });
1605 }
1606 Self::link_remote_masters(&mut indexed_groups, &cg_links);
1607
1608 Ok(MdfIndex {
1609 file_size,
1610 start_time_ns,
1611 channel_groups: indexed_groups,
1612 source: None,
1613 })
1614 }
1615
1616 fn extract_data_blocks_via_reader<R>(
1642 reader: &mut R,
1643 data_block_addr: u64,
1644 expected_bytes: Option<u64>,
1645 file_size: u64,
1646 ) -> Result<Vec<DataBlockInfo>, MdfError>
1647 where
1648 R: ByteRangeReader<Error = MdfError>,
1649 {
1650 let mut data_blocks = Vec::new();
1651
1652 macro_rules! probe_read {
1656 ($offset:expr, $len:expr) => {
1657 match reader.read_range($offset, $len) {
1658 Ok(b) => b,
1659 Err(e) => {
1660 if reader.is_probing() {
1661 return Ok(data_blocks);
1662 }
1663 return Err(e);
1664 }
1665 }
1666 };
1667 }
1668
1669 let mut current_block_address = data_block_addr;
1670 let mut visited = std::collections::HashSet::new();
1671
1672 while current_block_address != 0 {
1673 if !visited.insert(current_block_address) {
1674 return Err(MdfError::BlockLinkError(format!(
1675 "cycle detected in data block chain at address {:#x}",
1676 current_block_address
1677 )));
1678 }
1679 let header_bytes = probe_read!(current_block_address, 24);
1680 let block_header =
1681 crate::blocks::common::BlockHeader::from_bytes(&header_bytes)?;
1682
1683 match block_header.id.as_str() {
1684 "##DT" | "##DV" => {
1685 data_blocks.push(DataBlockInfo {
1686 file_offset: current_block_address,
1687 size: block_header.block_len,
1688 is_compressed: false,
1689 });
1690 current_block_address = 0;
1691 }
1692 "##DZ" => {
1693 data_blocks.push(DataBlockInfo {
1694 file_offset: current_block_address,
1695 size: block_header.block_len,
1696 is_compressed: true,
1697 });
1698 current_block_address = 0;
1699 }
1700 "##DL" => {
1701 let dl_bytes = probe_read!(current_block_address, block_header.block_len);
1702 let data_list_block =
1703 crate::blocks::data_list_block::DataListBlock::from_bytes(&dl_bytes)?;
1704
1705 if current_block_address == data_block_addr && data_list_block.next == 0
1706 && let Some(derived) = Self::derive_equal_length_fragments(
1707 &data_list_block,
1708 expected_bytes,
1709 file_size,
1710 ) {
1711 data_blocks.extend(derived);
1712 break;
1713 }
1714
1715 for &fragment_address in &data_list_block.data_links {
1716 if fragment_address == 0 {
1717 continue; }
1719 let frag_header_bytes = probe_read!(fragment_address, 24);
1720 let fragment_header = crate::blocks::common::BlockHeader::from_bytes(
1721 &frag_header_bytes,
1722 )?;
1723 let is_compressed = fragment_header.id == "##DZ";
1724 data_blocks.push(DataBlockInfo {
1725 file_offset: fragment_address,
1726 size: fragment_header.block_len,
1727 is_compressed,
1728 });
1729 }
1730
1731 current_block_address = data_list_block.next;
1732 }
1733 unexpected_id => {
1734 return Err(MdfError::BlockIDError {
1735 actual: unexpected_id.to_string(),
1736 expected: "##DT / ##DV / ##DL / ##DZ".to_string(),
1737 });
1738 }
1739 }
1740 }
1741
1742 Ok(data_blocks)
1743 }
1744
1745 fn derive_equal_length_fragments(
1749 dl: &crate::blocks::data_list_block::DataListBlock,
1750 expected_bytes: Option<u64>,
1751 file_size: u64,
1752 ) -> Option<Vec<DataBlockInfo>> {
1753 let equal = dl.data_block_len.filter(|_| dl.flags & 1 != 0)?;
1754 let total = expected_bytes?;
1755 let n = dl.data_links.len() as u64;
1756 if equal == 0 || n == 0 || total == 0 || dl.data_links.contains(&0) {
1757 return None;
1758 }
1759 let full = (n - 1).checked_mul(equal)?;
1761 if total <= full || total > full.checked_add(equal)? {
1762 return None;
1763 }
1764 let last = total - full;
1765 let mut out: Vec<DataBlockInfo> = Vec::with_capacity(n as usize);
1766 for (i, &addr) in dl.data_links.iter().enumerate() {
1767 let data = if i as u64 + 1 == n { last } else { equal };
1768 let size = data.checked_add(24)?;
1769 if file_size > 0 && addr.checked_add(size)? > file_size {
1770 return None;
1771 }
1772 if let Some(prev) = out.last()
1775 && addr < prev.file_offset.checked_add(prev.size)?
1776 {
1777 return None;
1778 }
1779 out.push(DataBlockInfo { file_offset: addr, size, is_compressed: false });
1780 }
1781 Some(out)
1782 }
1783
1784 fn for_each_data_section<R, F>(
1798 reader: &mut R,
1799 blocks: &[DataBlockInfo],
1800 mut f: F,
1801 ) -> Result<(), MdfError>
1802 where
1803 R: ByteRangeReader<Error = MdfError>,
1804 F: FnMut(&[u8]) -> Result<(), MdfError>,
1805 {
1806 let mut first_err = None;
1810 let mut i = 0;
1811 while i < blocks.len() {
1812 let start = blocks[i].file_offset;
1813 Self::data_section_size(&blocks[i])?;
1814 let mut end = start.checked_add(blocks[i].size).ok_or_else(|| {
1815 MdfError::BlockSerializationError("data block offset overflows".to_string())
1816 })?;
1817 let mut j = i + 1;
1818 while j < blocks.len() {
1819 let b = &blocks[j];
1820 let b_end = b.file_offset.saturating_add(b.size);
1821 if b.file_offset < end
1822 || b.file_offset - end > 7
1823 || b.size < 24
1824 || b_end - start > MAX_COALESCED_READ
1825 {
1826 break;
1827 }
1828 end = b_end;
1829 j += 1;
1830 }
1831 let buf = match reader.read_range(start, end - start) {
1832 Ok(buf) if first_err.is_none() => buf,
1833 Ok(_) => {
1834 i = j;
1835 continue;
1836 }
1837 Err(e) if reader.is_probing() => {
1838 first_err.get_or_insert(e);
1839 i = j;
1840 continue;
1841 }
1842 Err(e) => return Err(e),
1843 };
1844 for b in &blocks[i..j] {
1845 let header_start = (b.file_offset - start) as usize;
1846 let data_start = header_start + 24;
1847 let len = Self::verified_data_len(buf.get(header_start..data_start), b)?;
1848 match usize::try_from(len).ok().and_then(|l| buf.get(data_start..data_start.checked_add(l)?)) {
1849 Some(data) => f(data)?,
1850 None => f(&reader.read_range(b.file_offset + 24, len)?)?,
1851 }
1852 }
1853 i = j;
1854 }
1855 match first_err {
1856 Some(e) => Err(e),
1857 None => Ok(()),
1858 }
1859 }
1860
1861 fn verified_data_len(header: Option<&[u8]>, block: &DataBlockInfo) -> Result<u64, MdfError> {
1865 let h = BlockHeader::from_bytes(header.unwrap_or(&[]))?;
1866 if (h.id == "##DT" || h.id == "##DV") && h.block_len >= 24 {
1867 return Ok(h.block_len - 24);
1868 }
1869 Err(MdfError::BlockSerializationError(format!(
1870 "data block at offset {} is {} with length {} but the index expects an \
1871 uncompressed ##DT/##DV block of {} bytes (compressed or inconsistent \
1872 file; rebuild the index)",
1873 block.file_offset, h.id, h.block_len, block.size
1874 )))
1875 }
1876
1877 fn extract_vlsd_data_blocks<R>(
1894 reader: &mut R,
1895 data_addr: u64,
1896 ) -> Result<Vec<DataBlockInfo>, MdfError>
1897 where
1898 R: ByteRangeReader<Error = MdfError>,
1899 {
1900 let mut data_blocks: Vec<DataBlockInfo> = Vec::new();
1901
1902 macro_rules! probe_read {
1906 ($offset:expr, $len:expr) => {
1907 match reader.read_range($offset, $len) {
1908 Ok(b) => b,
1909 Err(e) => {
1910 if reader.is_probing() {
1911 return Ok(data_blocks);
1912 }
1913 return Err(e);
1914 }
1915 }
1916 };
1917 }
1918
1919 let mut visited: std::collections::HashSet<u64> = std::collections::HashSet::new();
1920 let mut running_offset: u64 = 0;
1923 let mut current = data_addr;
1924
1925 while current != 0 {
1926 let header_bytes = probe_read!(current, 24);
1927 let header = crate::blocks::common::BlockHeader::from_bytes(&header_bytes)?;
1928
1929 match header.id.as_str() {
1930 "##SD" => {
1931 data_blocks.push(DataBlockInfo {
1932 file_offset: current,
1933 size: header.block_len,
1934 is_compressed: false,
1935 });
1936 current = 0;
1937 }
1938 "##DZ" => {
1939 data_blocks.push(DataBlockInfo {
1940 file_offset: current,
1941 size: header.block_len,
1942 is_compressed: true,
1943 });
1944 current = 0;
1945 }
1946 "##DL" => {
1947 if !visited.insert(current) {
1950 return Err(MdfError::BlockLinkError(format!(
1951 "cycle detected in VLSD data list chain at address {:#x}",
1952 current
1953 )));
1954 }
1955 let dl_bytes = probe_read!(current, header.block_len);
1956 let dl = crate::blocks::data_list_block::DataListBlock::from_bytes(&dl_bytes)?;
1957
1958 for (i, &fragment_address) in dl.data_links.iter().enumerate() {
1959 if fragment_address == 0 {
1960 continue;
1961 }
1962 let frag_header_bytes = probe_read!(fragment_address, 24);
1963 let frag_header =
1964 crate::blocks::common::BlockHeader::from_bytes(&frag_header_bytes)?;
1965 let is_compressed = match frag_header.id.as_str() {
1966 "##SD" => false,
1967 "##DZ" => true,
1968 other => {
1969 return Err(MdfError::BlockIDError {
1970 actual: other.to_string(),
1971 expected: "##SD / ##DZ".to_string(),
1972 });
1973 }
1974 };
1975
1976 if let Some(offsets) = &dl.offsets
1982 && let Some(&declared) = offsets.get(i)
1983 && declared != running_offset {
1984 return Err(MdfError::BlockSerializationError(format!(
1985 "non-contiguous VLSD ##SD chain is unsupported: \
1986 fragment at offset {} declares virtual start {} \
1987 but the running data-section sum is {}",
1988 fragment_address, declared, running_offset
1989 )));
1990 }
1991
1992 let data_section = frag_header.block_len.checked_sub(24).ok_or_else(|| {
1993 MdfError::BlockSerializationError(format!(
1994 "VLSD fragment at offset {} has size {} \
1995 (smaller than the 24-byte block header)",
1996 fragment_address, frag_header.block_len
1997 ))
1998 })?;
1999 running_offset = running_offset.checked_add(data_section).ok_or_else(|| {
2000 MdfError::BlockSerializationError(
2001 "VLSD ##SD chain total size overflows the address space"
2002 .to_string(),
2003 )
2004 })?;
2005
2006 data_blocks.push(DataBlockInfo {
2007 file_offset: fragment_address,
2008 size: frag_header.block_len,
2009 is_compressed,
2010 });
2011 }
2012
2013 current = dl.next;
2014 }
2015 other => {
2016 return Err(MdfError::BlockIDError {
2017 actual: other.to_string(),
2018 expected: "##SD / ##DL / ##DZ".to_string(),
2019 });
2020 }
2021 }
2022 }
2023
2024 Ok(data_blocks)
2025 }
2026
2027 #[cfg(not(target_arch = "wasm32"))]
2031 pub fn save(&self, index_path: &str) -> Result<(), MdfError> {
2032 let json = self.to_json()?;
2033 std::fs::write(index_path, json)
2034 .map_err(MdfError::IOError)?;
2035 Ok(())
2036 }
2037
2038 #[cfg(not(target_arch = "wasm32"))]
2042 pub fn load(index_path: &str) -> Result<Self, MdfError> {
2043 let json = std::fs::read_to_string(index_path)
2044 .map_err(MdfError::IOError)?;
2045 Self::from_json(&json)
2046 }
2047
2048 pub fn to_json(&self) -> Result<String, MdfError> {
2050 serde_json::to_string_pretty(self)
2051 .map_err(|e| MdfError::BlockSerializationError(format!("JSON serialization failed: {}", e)))
2052 }
2053
2054 pub fn from_json(json: &str) -> Result<Self, MdfError> {
2059 let index: Self = serde_json::from_str(json)
2060 .map_err(|e| MdfError::BlockSerializationError(format!("JSON deserialization failed: {}", e)))?;
2061 index.validate()?;
2062 Ok(index)
2063 }
2064
2065 pub fn validate(&self) -> Result<(), MdfError> {
2071 for group in &self.channel_groups {
2072 let group_name = group.name.as_deref().unwrap_or("<unnamed>");
2073 for db in &group.data_blocks {
2074 if db.size < 24 {
2075 return Err(MdfError::BlockSerializationError(format!(
2076 "invalid index: group '{}' data block at offset {} has size {} \
2077 (smaller than the 24-byte block header)",
2078 group_name, db.file_offset, db.size
2079 )));
2080 }
2081 if db.file_offset.checked_add(db.size).is_none() {
2082 return Err(MdfError::BlockSerializationError(format!(
2083 "invalid index: group '{}' data block at offset {} with size {} \
2084 overflows the file address space",
2085 group_name, db.file_offset, db.size
2086 )));
2087 }
2088 }
2089 if !group.data_blocks.is_empty() {
2090 Self::checked_record_size(group)?;
2091 }
2092 for channel in &group.channels {
2093 for db in &channel.vlsd_data_blocks {
2094 if db.size < 24 {
2095 return Err(MdfError::BlockSerializationError(format!(
2096 "invalid index: group '{}' VLSD data block at offset {} has size {} \
2097 (smaller than the 24-byte block header)",
2098 group_name, db.file_offset, db.size
2099 )));
2100 }
2101 if db.file_offset.checked_add(db.size).is_none() {
2102 return Err(MdfError::BlockSerializationError(format!(
2103 "invalid index: group '{}' VLSD data block at offset {} with size {} \
2104 overflows the file address space",
2105 group_name, db.file_offset, db.size
2106 )));
2107 }
2108 }
2109 }
2110 }
2111 Ok(())
2112 }
2113
2114 fn checked_record_size(group: &IndexedChannelGroup) -> Result<usize, MdfError> {
2117 let size = group.record_id_len as usize
2118 + group.record_size as usize
2119 + group.invalidation_bytes as usize;
2120 if size == 0 {
2121 return Err(MdfError::BlockSerializationError(format!(
2122 "invalid index: channel group '{}' has record size 0",
2123 group.name.as_deref().unwrap_or("<unnamed>")
2124 )));
2125 }
2126 Ok(size)
2127 }
2128
2129 fn data_section_size(data_block: &DataBlockInfo) -> Result<u64, MdfError> {
2132 data_block.size.checked_sub(24).ok_or_else(|| {
2133 MdfError::BlockSerializationError(format!(
2134 "invalid index: data block at offset {} has size {} \
2135 (smaller than the 24-byte block header)",
2136 data_block.file_offset, data_block.size
2137 ))
2138 })
2139 }
2140
2141 fn ensure_not_vlsd(channel: &IndexedChannel) -> Result<(), MdfError> {
2149 if channel.channel_type == 1 {
2150 return Err(MdfError::BlockSerializationError(format!(
2151 "byte ranges cannot represent offset-indirected VLSD channel '{}'; \
2152 use read()/values() instead",
2153 channel.name.as_deref().unwrap_or("<unnamed>")
2154 )));
2155 }
2156 Ok(())
2157 }
2158
2159 pub(crate) fn read_channel_values<R: ByteRangeReader<Error = MdfError>>(
2169 &self,
2170 group_index: usize,
2171 channel_index: usize,
2172 raw: bool,
2173 reader: &mut R
2174 ) -> Result<Vec<Option<DecodedValue>>, MdfError> {
2175 let group = self.channel_groups.get(group_index)
2176 .ok_or_else(|| MdfError::BlockSerializationError("Invalid group index".to_string()))?;
2177
2178 let channel = group.channels.get(channel_index)
2179 .ok_or_else(|| MdfError::BlockSerializationError("Invalid channel index".to_string()))?;
2180
2181 let conversion = Self::read_conversion(channel, reader, raw)?;
2182
2183 if channel.is_virtual() {
2184 return self.virtual_values(group, 0, group.record_count, conversion.as_deref());
2185 }
2186 if channel.channel_type == 1 {
2187 return self.read_vlsd_channel_values(group, channel, conversion.as_deref(), reader);
2188 }
2189
2190 self.read_regular_channel_values(group, channel, conversion.as_deref(), reader)
2192 }
2193
2194 fn virtual_values(
2198 &self,
2199 group: &IndexedChannelGroup,
2200 start: u64,
2201 count: u64,
2202 conversion: Option<&ConversionBlock>,
2203 ) -> Result<Vec<Option<DecodedValue>>, MdfError> {
2204 let available = if !group.data_blocks.is_empty() {
2210 Self::stored_records(group)?
2211 } else {
2212 let me = self.channel_groups.iter().position(|g| std::ptr::eq(g, group));
2213 self.channel_groups
2214 .iter()
2215 .filter(|g| me.is_some() && g.master_group == me && !g.data_blocks.is_empty())
2216 .filter_map(|g| Self::stored_records(g).ok())
2217 .max()
2218 .unwrap_or(group.record_count)
2220 };
2221 match start.checked_add(count) {
2222 Some(end) if end <= available => {}
2223 _ => {
2224 return Err(MdfError::BlockSerializationError(format!(
2225 "virtual channel read of {} records from {} exceeds the {} records the \
2226 group's data holds (rebuild the index)",
2227 count, start, available
2228 )))
2229 }
2230 }
2231 let mut values = Vec::with_capacity((count as usize).min(1 << 24));
2232 for i in start..start + count {
2233 let raw = DecodedValue::UnsignedInteger(i);
2234 values.push(Some(match conversion {
2235 Some(conv) => conv.apply_decoded(raw, &[])?,
2236 None => raw,
2237 }));
2238 }
2239 Ok(values)
2240 }
2241
2242 pub(crate) fn read_channel_values_window<R: ByteRangeReader<Error = MdfError>>(
2250 &self,
2251 g: usize,
2252 c: usize,
2253 start: u64,
2254 count: u64,
2255 raw: bool,
2256 reader: &mut R,
2257 ) -> Result<Vec<Option<DecodedValue>>, MdfError> {
2258 let (group, channel) = self.group_and_channel(g, c)?;
2259 Self::check_window(group, start, count)?;
2260 let conversion = Self::read_conversion(channel, reader, raw)?;
2261 self.window_values(group, channel, conversion.as_deref(), start, count, reader)
2262 }
2263
2264 fn window_values<R: ByteRangeReader<Error = MdfError>>(
2265 &self,
2266 group: &IndexedChannelGroup,
2267 channel: &IndexedChannel,
2268 conversion: Option<&ConversionBlock>,
2269 start: u64,
2270 count: u64,
2271 reader: &mut R,
2272 ) -> Result<Vec<Option<DecodedValue>>, MdfError> {
2273 if channel.is_virtual() {
2274 return self.virtual_values(group, start, count, conversion);
2275 }
2276 if channel.channel_type == 1 {
2277 return self.read_vlsd_window_values(group, channel, conversion, start, count, reader);
2278 }
2279 let record_size = Self::checked_record_size(group)?;
2280 let temp_cb = channel.to_decode_only_channel_block();
2281 let mut values = Vec::with_capacity((count as usize).min(1 << 24));
2282 Self::for_each_window_section(reader, group, record_size, start, count, |data| {
2283 Self::decode_records_to_values(data, record_size, group, conversion, &temp_cb, &mut values)
2284 })?;
2285 Ok(values)
2286 }
2287
2288 fn window_values_f64<R: ByteRangeReader<Error = MdfError>>(
2291 &self,
2292 group: &IndexedChannelGroup,
2293 channel: &IndexedChannel,
2294 conversion: Option<&ConversionBlock>,
2295 start: u64,
2296 count: u64,
2297 reader: &mut R,
2298 ) -> Result<Vec<f64>, MdfError> {
2299 if channel.is_virtual() || channel.channel_type == 1 {
2300 let vals = self.window_values(group, channel, conversion, start, count, reader)?;
2301 return Ok(Self::vlsd_values_to_f64(vals));
2302 }
2303 let record_size = Self::checked_record_size(group)?;
2304 let temp_cb = channel.to_decode_only_channel_block();
2305 let linear_coeffs = Self::get_linear_coeffs(conversion);
2306 let mut values = Vec::with_capacity((count as usize).min(1 << 24));
2307 Self::for_each_window_section(reader, group, record_size, start, count, |data| {
2308 Self::decode_records_to_f64(data, record_size, group, channel, conversion, &temp_cb, linear_coeffs, conversion.is_some(), &mut values)
2309 })?;
2310 Ok(values)
2311 }
2312
2313 fn for_each_window_section<R, F>(
2321 reader: &mut R,
2322 group: &IndexedChannelGroup,
2323 record_size: usize,
2324 start: u64,
2325 count: u64,
2326 mut f: F,
2327 ) -> Result<(), MdfError>
2328 where
2329 R: ByteRangeReader<Error = MdfError>,
2330 F: FnMut(&[u8]) -> Result<(), MdfError>,
2331 {
2332 let size = record_size as u64;
2333 let overflow = || MdfError::BlockSerializationError("record window overflows".to_string());
2334 let window_start = start.checked_mul(size).ok_or_else(overflow)?;
2335 let window_end = start.checked_add(count).and_then(|e| e.checked_mul(size)).ok_or_else(overflow)?;
2336 let mut records = RecordCarry::new(record_size);
2337 let mut block_start = 0u64;
2339 let mut first_err = None;
2342 for block in &group.data_blocks {
2343 if block_start >= window_end {
2344 break;
2345 }
2346 if block.is_compressed {
2347 return Err(MdfError::BlockSerializationError(
2348 "Compressed blocks not yet supported in index reader".to_string(),
2349 ));
2350 }
2351 let block_end = block_start.saturating_add(Self::data_section_size(block)?);
2352 let (from, to) = (window_start.max(block_start), window_end.min(block_end));
2353 if from < to {
2354 let rel = from - block_start;
2355 let len = to - from;
2356 let read = if rel == 0 {
2360 reader.read_range(block.file_offset, 24 + len).map(|mut bytes| {
2361 let data = bytes.split_off(24.min(bytes.len()));
2362 (bytes, data)
2363 })
2364 } else {
2365 let header = reader.read_range(block.file_offset, 24);
2366 let data = reader.read_range(block.file_offset + 24 + rel, len);
2367 header.and_then(|h| data.map(|d| (h, d)))
2368 };
2369 match read {
2370 Ok((header, data)) if first_err.is_none() => {
2371 let real_len = Self::verified_data_len(Some(&header), block)?;
2372 if rel + len > real_len || data.len() as u64 != len {
2373 return Err(MdfError::BlockSerializationError(format!(
2374 "data block at offset {} holds {} data bytes but the index \
2375 expects at least {} (inconsistent file; rebuild the index)",
2376 block.file_offset, real_len, rel + len
2377 )));
2378 }
2379 records.feed(&data, &mut f)?;
2380 }
2381 Ok(_) => {}
2382 Err(e) if reader.is_probing() => {
2383 first_err.get_or_insert(e);
2384 }
2385 Err(e) => return Err(e),
2386 }
2387 }
2388 block_start = block_end;
2389 }
2390 if let Some(e) = first_err {
2391 return Err(e);
2392 }
2393 if block_start < window_end {
2394 return Err(MdfError::BlockSerializationError(format!(
2395 "record window ending at {} exceeds the {} records held by the data blocks",
2396 start + count,
2397 block_start / size
2398 )));
2399 }
2400 Ok(())
2401 }
2402
2403 fn whole_read_records(group: &IndexedChannelGroup) -> Result<usize, MdfError> {
2406 if group.data_blocks.iter().any(|b| b.is_compressed) {
2407 return Err(MdfError::BlockSerializationError(
2408 "Compressed blocks not yet supported in index reader".to_string(),
2409 ));
2410 }
2411 Ok(Self::stored_records(group)? as usize)
2412 }
2413
2414 fn stored_records(group: &IndexedChannelGroup) -> Result<u64, MdfError> {
2418 let record_size = Self::checked_record_size(group)?;
2419 let mut bytes = 0u64;
2420 for block in &group.data_blocks {
2421 bytes = bytes.saturating_add(Self::data_section_size(block)?);
2422 }
2423 Ok(bytes / record_size as u64)
2424 }
2425
2426 fn group_and_channel(&self, g: usize, c: usize) -> Result<(&IndexedChannelGroup, &IndexedChannel), MdfError> {
2427 let group = self.channel_groups.get(g)
2428 .ok_or_else(|| MdfError::BlockSerializationError("Invalid group index".to_string()))?;
2429 let channel = group.channels.get(c)
2430 .ok_or_else(|| MdfError::BlockSerializationError("Invalid channel index".to_string()))?;
2431 Ok((group, channel))
2432 }
2433
2434 fn check_window(group: &IndexedChannelGroup, start: u64, count: u64) -> Result<(), MdfError> {
2435 match start.checked_add(count) {
2436 Some(end) if end <= group.record_count => Ok(()),
2437 _ => Err(MdfError::BlockSerializationError(format!(
2438 "record window starting at {} for {} records exceeds the group's {} records",
2439 start, count, group.record_count
2440 ))),
2441 }
2442 }
2443
2444 fn time_axis_location(&self, g: usize, c: usize) -> Option<(usize, usize)> {
2447 match self.master_location(g, c) {
2448 Some(m) => Some(m),
2449 None => self.channel_groups.get(g)?.channels.get(c)?.is_master().then_some((g, c)),
2450 }
2451 }
2452
2453 pub(crate) fn record_window_for_time<R: ByteRangeReader<Error = MdfError>>(
2464 &self,
2465 g: usize,
2466 c: usize,
2467 t_start: Option<f64>,
2468 t_end: Option<f64>,
2469 reader: &mut R,
2470 ) -> Result<(u64, u64), MdfError> {
2471 let (group, channel) = self.group_and_channel(g, c)?;
2472 let Some((mg, m)) = self.time_axis_location(g, c) else {
2473 if group.record_count == 0 {
2476 return Ok((0, 0));
2477 }
2478 return Err(MdfError::InvalidArgument(format!(
2479 "channel '{}' has no master (time) channel; cannot select by time",
2480 channel.name.as_deref().unwrap_or_default()
2481 )));
2482 };
2483 let (mgroup, mchannel) = self.group_and_channel(mg, m)?;
2484 let n = group.record_count.min(mgroup.record_count);
2485 let conversion = Self::resolve_conversion(mchannel, reader)?;
2486 search_time_window(n, t_start, t_end, |i| {
2487 Ok(self.window_values_f64(mgroup, mchannel, conversion.as_deref(), i, 1, reader)?[0])
2488 })
2489 }
2490
2491 fn resolve_conversion<'c, R: ByteRangeReader<Error = MdfError>>(
2500 channel: &'c IndexedChannel,
2501 reader: &mut R,
2502 ) -> Result<Option<Cow<'c, ConversionBlock>>, MdfError> {
2503 if let Some(conv) = &channel.conversion {
2504 return Ok(Some(Cow::Borrowed(conv)));
2505 }
2506 if channel.conversion_addr == 0 {
2507 return Ok(None);
2508 }
2509 let addr = channel.conversion_addr;
2510 let header_bytes = reader.read_range(addr, 24)?;
2511 let header = BlockHeader::from_bytes(&header_bytes)?;
2512 if header.id != "##CC" {
2513 return Err(MdfError::BlockIDError {
2514 actual: header.id,
2515 expected: "##CC".to_string(),
2516 });
2517 }
2518 let full = reader.read_range(addr, header.block_len)?;
2519 let mut cc = ConversionBlock::from_bytes(&full)?;
2520 cc.resolve_all_dependencies_via_reader(reader, addr)?;
2521 Ok(Some(Cow::Owned(cc)))
2522 }
2523
2524 fn read_conversion<'c, R: ByteRangeReader<Error = MdfError>>(
2528 channel: &'c IndexedChannel,
2529 reader: &mut R,
2530 raw: bool,
2531 ) -> Result<Option<Cow<'c, ConversionBlock>>, MdfError> {
2532 if raw {
2533 return Ok(None);
2534 }
2535 Self::resolve_conversion(channel, reader)
2536 }
2537
2538 #[allow(dead_code)] pub(crate) fn resolve_channel_conversion<R: ByteRangeReader<Error = MdfError>>(
2545 &self,
2546 g: usize,
2547 c: usize,
2548 reader: &mut R,
2549 ) -> Result<Option<ConversionBlock>, MdfError> {
2550 let channel = self
2551 .channel_groups
2552 .get(g)
2553 .and_then(|grp| grp.channels.get(c))
2554 .ok_or_else(|| {
2555 MdfError::BlockSerializationError("Invalid channel index".to_string())
2556 })?;
2557 Ok(Self::resolve_conversion(channel, reader)?.map(Cow::into_owned))
2558 }
2559
2560 fn get_linear_coeffs(conversion: Option<&ConversionBlock>) -> Option<(f64, f64)> {
2562 conversion.and_then(|conv| {
2563 if conv.cc_type == ConversionType::Linear && conv.cc_val.len() >= 2 {
2564 Some((conv.cc_val[0], conv.cc_val[1]))
2565 } else {
2566 None
2567 }
2568 })
2569 }
2570
2571 fn read_regular_channel_values<R: ByteRangeReader<Error = MdfError>>(
2573 &self,
2574 group: &IndexedChannelGroup,
2575 channel: &IndexedChannel,
2576 conversion: Option<&ConversionBlock>,
2577 reader: &mut R,
2578 ) -> Result<Vec<Option<DecodedValue>>, MdfError> {
2579 let record_size = Self::checked_record_size(group)?;
2580 let total_records = Self::whole_read_records(group)?;
2581 let mut values = Vec::with_capacity(total_records.min(1 << 24));
2585 let temp_cb = channel.to_decode_only_channel_block();
2586
2587 let mut records = RecordCarry::new(record_size);
2589 Self::for_each_data_section(reader, &group.data_blocks, |block_data| {
2590 records.feed(block_data, |run| {
2591 Self::decode_records_to_values(run, record_size, group, conversion, &temp_cb, &mut values)
2592 })
2593 })?;
2594
2595 Ok(values)
2596 }
2597
2598 fn read_vlsd_channel_values<R: ByteRangeReader<Error = MdfError>>(
2607 &self,
2608 group: &IndexedChannelGroup,
2609 channel: &IndexedChannel,
2610 conversion: Option<&ConversionBlock>,
2611 reader: &mut R,
2612 ) -> Result<Vec<Option<DecodedValue>>, MdfError> {
2613 Self::check_vlsd_readable(group, channel)?;
2614
2615 let mut fragments: Vec<Vec<u8>> = Vec::with_capacity(channel.vlsd_data_blocks.len());
2618 let mut frag_starts: Vec<u64> = Vec::with_capacity(channel.vlsd_data_blocks.len());
2619 let mut running: u64 = 0;
2620 for db in &channel.vlsd_data_blocks {
2621 let data_len = Self::data_section_size(db)?;
2622 let bytes = reader.read_range(db.file_offset + 24, data_len)?;
2623 frag_starts.push(running);
2624 running = running.checked_add(bytes.len() as u64).ok_or_else(|| {
2625 MdfError::BlockSerializationError(
2626 "VLSD ##SD chain total size overflows the address space".to_string(),
2627 )
2628 })?;
2629 fragments.push(bytes);
2630 }
2631 let stream_len = running;
2632
2633 let record_size = Self::checked_record_size(group)?;
2634 let record_id_len = group.record_id_len as usize;
2635 let cg_data_bytes = group.record_size;
2636 let has_invalidation = group.invalidation_bytes > 0;
2637 let all_invalid = channel.flags & 0x1 != 0;
2638
2639 let validity_cb = channel.to_decode_only_channel_block();
2642 let mut payload_cb = channel.to_decode_only_channel_block();
2643 payload_cb.data = 1;
2644
2645 let total_records = Self::whole_read_records(group)?;
2646 let mut values = Vec::with_capacity(total_records.min(1 << 24));
2647
2648 let mut records = RecordCarry::new(record_size);
2650 Self::for_each_data_section(reader, &group.data_blocks, |section| records.feed(section, |block_data| {
2651 let record_count = block_data.len() / record_size;
2652 for i in 0..record_count {
2653 let record = &block_data[i * record_size..(i + 1) * record_size];
2654
2655 if all_invalid
2656 || (has_invalidation
2657 && !check_value_validity(record, record_id_len, cg_data_bytes, &validity_cb))
2658 {
2659 values.push(None);
2660 continue;
2661 }
2662
2663 let virtual_offset = vlsd_offset(&validity_cb, record, record_id_len)?;
2666
2667 if virtual_offset >= stream_len {
2668 return Err(MdfError::BlockSerializationError(format!(
2669 "VLSD inline offset {} is past the end of the {}-byte signal-data stream",
2670 virtual_offset, stream_len
2671 )));
2672 }
2673
2674 let frag_idx = frag_starts.partition_point(|&s| s <= virtual_offset) - 1;
2676 let frag = &fragments[frag_idx];
2677 let pos = (virtual_offset - frag_starts[frag_idx]) as usize;
2678
2679 if pos + 4 > frag.len() {
2680 return Err(MdfError::BlockSerializationError(format!(
2681 "VLSD entry at virtual offset {} is truncated: no room for its \
2682 length prefix in fragment {}",
2683 virtual_offset, frag_idx
2684 )));
2685 }
2686 let len = u32::from_le_bytes(frag[pos..pos + 4].try_into().unwrap()) as usize;
2687 let start = pos + 4;
2688 let end = match start.checked_add(len) {
2689 Some(e) if e <= frag.len() => e,
2690 _ => {
2691 return Err(MdfError::BlockSerializationError(format!(
2692 "VLSD entry at virtual offset {} declares length {} which \
2693 exceeds fragment {} (size {})",
2694 virtual_offset, len, frag_idx, frag.len()
2695 )));
2696 }
2697 };
2698 let payload = &frag[start..end];
2699
2700 if let Some(value) = decode_channel_value(payload, 0, &payload_cb) {
2701 let final_value = if let Some(conversion) = conversion {
2702 conversion.apply_decoded(value, &[])?
2703 } else {
2704 value
2705 };
2706 values.push(Some(final_value));
2707 } else {
2708 values.push(None);
2709 }
2710 }
2711 Ok(())
2712 }))?;
2713
2714 Ok(values)
2715 }
2716
2717 fn check_vlsd_readable(group: &IndexedChannelGroup, channel: &IndexedChannel) -> Result<(), MdfError> {
2721 if group.data_blocks.iter().any(|b| b.is_compressed)
2724 || channel.vlsd_data_blocks.iter().any(|b| b.is_compressed)
2725 {
2726 return Err(MdfError::BlockSerializationError(
2727 "Compressed blocks not yet supported in index reader".to_string(),
2728 ));
2729 }
2730
2731 if channel.vlsd_data_blocks.is_empty() {
2735 if channel.vlsd_data_address.is_none() {
2736 return Err(MdfError::BlockSerializationError(format!(
2737 "VLSD channel '{}' has no signal data (its ##SD data link is 0)",
2738 channel.name.as_deref().unwrap_or("<unnamed>")
2739 )));
2740 }
2741 return Err(MdfError::BlockSerializationError(format!(
2742 "VLSD channel '{}' has no signal-data fragments recorded in the index; \
2743 rebuild the index with this version to read it",
2744 channel.name.as_deref().unwrap_or("<unnamed>")
2745 )));
2746 }
2747
2748 Ok(())
2751 }
2752
2753 fn read_vlsd_window_values<R: ByteRangeReader<Error = MdfError>>(
2759 &self,
2760 group: &IndexedChannelGroup,
2761 channel: &IndexedChannel,
2762 conversion: Option<&ConversionBlock>,
2763 start: u64,
2764 count: u64,
2765 reader: &mut R,
2766 ) -> Result<Vec<Option<DecodedValue>>, MdfError> {
2767 Self::check_vlsd_readable(group, channel)?;
2768 let record_size = Self::checked_record_size(group)?;
2769 let record_id_len = group.record_id_len as usize;
2770 let has_invalidation = group.invalidation_bytes > 0;
2771 let all_invalid = channel.flags & 0x1 != 0;
2772 let validity_cb = channel.to_decode_only_channel_block();
2773 let mut payload_cb = channel.to_decode_only_channel_block();
2774 payload_cb.data = 1;
2775
2776 let mut offsets: Vec<Option<u64>> = Vec::with_capacity((count as usize).min(1 << 24));
2778 Self::for_each_window_section(reader, group, record_size, start, count, |data| {
2779 for record in data.chunks_exact(record_size) {
2780 if all_invalid
2781 || (has_invalidation
2782 && !check_value_validity(record, record_id_len, group.record_size, &validity_cb))
2783 {
2784 offsets.push(None);
2785 continue;
2786 }
2787 offsets.push(Some(vlsd_offset(&validity_cb, record, record_id_len)?));
2788 }
2789 Ok(())
2790 })?;
2791
2792 let mut frag_starts = Vec::with_capacity(channel.vlsd_data_blocks.len());
2794 let mut stream_len = 0u64;
2795 for db in &channel.vlsd_data_blocks {
2796 frag_starts.push(stream_len);
2797 stream_len = stream_len.checked_add(Self::data_section_size(db)?).ok_or_else(|| {
2798 MdfError::BlockSerializationError("VLSD ##SD chain total size overflows the address space".to_string())
2799 })?;
2800 }
2801 let present = || offsets.iter().flatten().copied();
2802 let (Some(lo), Some(hi)) = (present().min(), present().max()) else {
2803 return Ok(vec![None; offsets.len()]);
2804 };
2805 let prefix_end = hi.checked_add(4).filter(|&e| e <= stream_len).ok_or_else(|| {
2806 MdfError::BlockSerializationError(format!(
2807 "VLSD inline offset {hi} leaves no room for a length prefix in the {stream_len}-byte signal-data stream"
2808 ))
2809 })?;
2810 let mut buf = Self::read_vlsd_stream(reader, channel, &frag_starts, lo, prefix_end - lo)?;
2811 let entry_len = |buf: &[u8], off: u64| -> usize {
2812 let p = (off - lo) as usize;
2813 u32::from_le_bytes(buf[p..p + 4].try_into().unwrap()) as usize
2814 };
2815 let end = present().map(|off| off + 4 + entry_len(&buf, off) as u64).max().unwrap_or(prefix_end);
2816 if end > stream_len {
2817 return Err(MdfError::BlockSerializationError(format!(
2818 "VLSD entry ending at virtual offset {end} is past the end of the {stream_len}-byte signal-data stream"
2819 )));
2820 }
2821 if end > prefix_end {
2822 let more = Self::read_vlsd_stream(reader, channel, &frag_starts, prefix_end, end - prefix_end)?;
2823 buf.extend_from_slice(&more);
2824 }
2825
2826 let mut values = Vec::with_capacity(offsets.len());
2827 for off in &offsets {
2828 let Some(off) = *off else {
2829 values.push(None);
2830 continue;
2831 };
2832 let frag_idx = frag_starts.partition_point(|&s| s <= off) - 1;
2835 let frag_end = frag_starts.get(frag_idx + 1).copied().unwrap_or(stream_len);
2836 let len = entry_len(&buf, off);
2837 if off + 4 + len as u64 > frag_end {
2838 return Err(MdfError::BlockSerializationError(format!(
2839 "VLSD entry at virtual offset {} declares length {} which exceeds fragment {} (size {})",
2840 off,
2841 len,
2842 frag_idx,
2843 frag_end - frag_starts[frag_idx]
2844 )));
2845 }
2846 let p = (off - lo) as usize + 4;
2847 let payload = &buf[p..p + entry_len(&buf, off)];
2848 values.push(match decode_channel_value(payload, 0, &payload_cb) {
2849 Some(value) => Some(match conversion {
2850 Some(conversion) => conversion.apply_decoded(value, &[])?,
2851 None => value,
2852 }),
2853 None => None,
2854 });
2855 }
2856 Ok(values)
2857 }
2858
2859 fn read_vlsd_stream<R: ByteRangeReader<Error = MdfError>>(
2862 reader: &mut R,
2863 channel: &IndexedChannel,
2864 frag_starts: &[u64],
2865 from: u64,
2866 len: u64,
2867 ) -> Result<Vec<u8>, MdfError> {
2868 let to = from + len;
2869 let mut out = Vec::with_capacity(len as usize);
2870 let mut first_err = None;
2873 for (db, &fs) in channel.vlsd_data_blocks.iter().zip(frag_starts) {
2874 let fe = fs + Self::data_section_size(db)?;
2875 let (a, b) = (from.max(fs), to.min(fe));
2876 if a >= b {
2877 continue;
2878 }
2879 match reader.read_range(db.file_offset + 24 + (a - fs), b - a) {
2880 Ok(bytes) if bytes.len() as u64 != b - a => {
2883 return Err(MdfError::TooShortBuffer {
2884 actual: bytes.len(),
2885 expected: (b - a) as usize,
2886 file: file!(),
2887 line: line!(),
2888 });
2889 }
2890 Ok(bytes) => out.extend_from_slice(&bytes),
2891 Err(e) if reader.is_probing() => {
2892 first_err.get_or_insert(e);
2893 }
2894 Err(e) => return Err(e),
2895 }
2896 }
2897 if let Some(e) = first_err {
2898 return Err(e);
2899 }
2900 Ok(out)
2901 }
2902
2903 fn vlsd_values_to_f64(values: Vec<Option<DecodedValue>>) -> Vec<f64> {
2907 values
2908 .into_iter()
2909 .map(|v| match v {
2910 Some(DecodedValue::Float(f)) => f,
2911 Some(DecodedValue::UnsignedInteger(u)) => u as f64,
2912 Some(DecodedValue::SignedInteger(i)) => i as f64,
2913 _ => f64::NAN,
2914 })
2915 .collect()
2916 }
2917
2918 fn decode_records_to_values(
2921 block_data: &[u8],
2922 record_size: usize,
2923 group: &IndexedChannelGroup,
2924 conversion: Option<&ConversionBlock>,
2925 temp_cb: &crate::blocks::channel_block::ChannelBlock,
2926 values: &mut Vec<Option<DecodedValue>>,
2927 ) -> Result<(), MdfError> {
2928 if record_size == 0 {
2929 return Err(MdfError::BlockSerializationError(
2930 "invalid index: record size is 0".to_string(),
2931 ));
2932 }
2933 if !block_data.len().is_multiple_of(record_size) {
2935 return Err(MdfError::BlockSerializationError(format!(
2936 "internal error: {} bytes are not a whole number of {}-byte records",
2937 block_data.len(),
2938 record_size
2939 )));
2940 }
2941 let record_count = block_data.len() / record_size;
2942 let record_id_len = group.record_id_len as usize;
2943 let cg_data_bytes = group.record_size;
2944
2945 for i in 0..record_count {
2946 let record = &block_data[i * record_size..(i + 1) * record_size];
2947 if let Some(decoded) = decode_channel_value_with_validity(
2948 record, record_id_len, cg_data_bytes, temp_cb,
2949 ) {
2950 if decoded.is_valid {
2951 let final_value = if let Some(conversion) = conversion {
2952 conversion.apply_decoded(decoded.value, &[])?
2953 } else {
2954 decoded.value
2955 };
2956 values.push(Some(final_value));
2957 } else {
2958 values.push(None);
2959 }
2960 } else {
2961 values.push(None);
2962 }
2963 }
2964 Ok(())
2965 }
2966
2967 fn decode_records_to_f64(
2971 block_data: &[u8],
2972 record_size: usize,
2973 group: &IndexedChannelGroup,
2974 channel: &IndexedChannel,
2975 conversion: Option<&ConversionBlock>,
2976 temp_cb: &crate::blocks::channel_block::ChannelBlock,
2977 linear_coeffs: Option<(f64, f64)>,
2978 has_conversion: bool,
2979 values: &mut Vec<f64>,
2980 ) -> Result<(), MdfError> {
2981 if record_size == 0 {
2982 return Err(MdfError::BlockSerializationError(
2983 "invalid index: record size is 0".to_string(),
2984 ));
2985 }
2986 if !block_data.len().is_multiple_of(record_size) {
2988 return Err(MdfError::BlockSerializationError(format!(
2989 "internal error: {} bytes are not a whole number of {}-byte records",
2990 block_data.len(),
2991 record_size
2992 )));
2993 }
2994 let record_count = block_data.len() / record_size;
2995 let record_id_len = group.record_id_len as usize;
2996 let cg_data_bytes = group.record_size;
2997 let has_invalidation = group.invalidation_bytes > 0;
2998
2999 if channel.flags & 0x1 != 0 {
3003 values.extend(std::iter::repeat_n(f64::NAN, record_count));
3004 return Ok(());
3005 }
3006
3007 let valid = |record: &[u8]| {
3011 !has_invalidation || check_value_validity(record, record_id_len, cg_data_bytes, temp_cb)
3012 };
3013 let records = block_data.chunks_exact(record_size);
3014 match (linear_coeffs, conversion.filter(|_| has_conversion)) {
3015 (Some((a, b)), _) => {
3016 for record in records {
3017 values.push(match valid(record) {
3018 true => a + b * decode_f64_from_record(record, record_id_len, temp_cb),
3019 false => f64::NAN,
3020 });
3021 }
3022 }
3023 (None, Some(conversion)) => {
3024 for record in records {
3025 let value = match valid(record) {
3026 true => decode_channel_value(record, record_id_len, temp_cb),
3027 false => None,
3028 };
3029 values.push(match value {
3030 Some(value) => match conversion.apply_decoded(value, &[])? {
3031 DecodedValue::Float(v) => v,
3032 DecodedValue::UnsignedInteger(v) => v as f64,
3033 DecodedValue::SignedInteger(v) => v as f64,
3034 _ => f64::NAN,
3035 },
3036 None => f64::NAN,
3037 });
3038 }
3039 }
3040 (None, None) => {
3041 for record in records {
3042 values.push(match valid(record) {
3043 true => decode_f64_from_record(record, record_id_len, temp_cb),
3044 false => f64::NAN,
3045 });
3046 }
3047 }
3048 }
3049 Ok(())
3050 }
3051
3052 pub fn groups(&self) -> Result<Vec<GroupInfo>, MdfError> {
3060 Ok((0..self.channel_groups.len()).map(|g| self.group_info(g)).collect())
3061 }
3062
3063 pub fn group(&self, name: &str) -> Result<Option<GroupInfo>, MdfError> {
3068 let names = self.group_names();
3069 let Some(first) = names.iter().position(|n| n.as_deref() == Some(name)) else {
3070 return Ok(None);
3071 };
3072 let channel_counts: Vec<usize> = self.channel_groups.iter().map(|g| g.channels.len()).collect();
3073 let members = logical_group_members(&names, &self.time_groups(), &channel_counts, first);
3074 Ok(Some(merge_group_infos(
3075 self.group_info(first),
3076 members.iter().map(|&m| self.group_info(m)),
3077 )))
3078 }
3079
3080 fn group_names(&self) -> Vec<Option<String>> {
3081 self.channel_groups.iter().map(|g| g.name.clone()).collect()
3082 }
3083
3084 fn time_groups(&self) -> Vec<Option<usize>> {
3088 (0..self.channel_groups.len()).map(|g| self.time_group(g)).collect()
3089 }
3090
3091 fn time_group(&self, g: usize) -> Option<usize> {
3092 let group = self.channel_groups.get(g)?;
3093 if group.master_channel().is_some() {
3094 return Some(g);
3095 }
3096 group
3097 .master_group
3098 .filter(|&m| m != g && self.channel_groups.get(m).is_some_and(|mg| mg.master_channel().is_some()))
3099 }
3100
3101 pub fn channel(&self, name: &str, group: Option<&str>) -> Result<Option<ChannelInfo>, MdfError> {
3104 Ok(self.indexed_channel(name, group).map(IndexedChannel::info))
3105 }
3106
3107 pub fn channel_names(&self) -> Result<Vec<String>, MdfError> {
3109 Ok(self
3110 .channel_groups
3111 .iter()
3112 .flat_map(|g| g.channels.iter())
3113 .filter_map(|c| c.name.clone())
3114 .collect())
3115 }
3116
3117 pub fn start_time_ns(&self) -> Option<u64> {
3120 self.start_time_ns
3121 }
3122
3123 pub fn file_size(&self) -> u64 {
3125 self.file_size
3126 }
3127
3128 pub fn indexed_channel(&self, name: &str, group: Option<&str>) -> Option<&IndexedChannel> {
3132 let (g, c) = self.locate_opt(name, group)?;
3133 self.channel_groups.get(g)?.channels.get(c)
3134 }
3135
3136 fn group_info(&self, g: usize) -> GroupInfo {
3137 let group = &self.channel_groups[g];
3138 GroupInfo {
3139 name: group.name.clone(),
3140 comment: group.comment.clone(),
3141 record_count: group.record_count,
3142 channel_names: group.channels.iter().filter_map(|c| c.name.clone()).collect(),
3143 master_channel: group
3146 .master_channel()
3147 .or_else(|| {
3148 group
3149 .master_group
3150 .and_then(|mg| self.channel_groups.get(mg))
3151 .and_then(|mg| mg.master_channel())
3152 })
3153 .and_then(|c| c.name.clone()),
3154 channels: group.channels.iter().map(IndexedChannel::info).collect(),
3155 }
3156 }
3157
3158 pub(crate) fn locate_opt(&self, name: &str, group: Option<&str>) -> Option<(usize, usize)> {
3160 match group {
3161 Some(group) => self.locate_in(group, name),
3162 None => self.locate(name),
3163 }
3164 }
3165
3166 pub(crate) fn locate_checked(&self, name: &str, group: Option<&str>) -> Result<(usize, usize), MdfError> {
3168 self.locate_opt(name, group)
3169 .ok_or_else(|| MdfError::channel_not_found(name, group))
3170 }
3171
3172 pub(crate) fn locate(&self, name: &str) -> Option<(usize, usize)> {
3177 for (g, group) in self.channel_groups.iter().enumerate() {
3178 for (c, channel) in group.channels.iter().enumerate() {
3179 if channel.name.as_deref() == Some(name) {
3180 return Some((g, c));
3181 }
3182 }
3183 }
3184 None
3185 }
3186
3187 pub(crate) fn locate_in(&self, group: &str, name: &str) -> Option<(usize, usize)> {
3194 let named: Vec<usize> = (0..self.channel_groups.len())
3195 .filter(|&g| self.channel_groups[g].name.as_deref() == Some(group))
3196 .collect();
3197 let remote = named
3198 .iter()
3199 .filter_map(|&g| self.time_group(g))
3200 .filter(|&t| self.channel_groups[t].name.as_deref() != Some(group));
3201 named.iter().copied().chain(remote).find_map(|g| {
3202 self.channel_groups[g]
3203 .channels
3204 .iter()
3205 .position(|ch| ch.name.as_deref() == Some(name))
3206 .map(|c| (g, c))
3207 })
3208 }
3209
3210 pub(crate) fn master_location(&self, g: usize, c: usize) -> Option<(usize, usize)> {
3215 let grp = self.channel_groups.get(g)?;
3216 if let Some(m) = grp.channels.iter().position(|ch| ch.is_master()) {
3217 return (m != c).then_some((g, m));
3218 }
3219 let mg = grp.master_group?;
3220 let m = self.channel_groups.get(mg)?.channels.iter().position(|ch| ch.is_master())?;
3221 Some((mg, m))
3222 }
3223
3224 pub fn open<R: ByteRangeReader<Error = MdfError>>(&self, reader: R) -> MdfReader<'_, R> {
3229 MdfReader { index: self, reader }
3230 }
3231
3232 #[cfg(not(target_arch = "wasm32"))]
3237 pub fn open_file(&self, path: &str) -> Result<MdfReader<'_, MmapRangeReader>, MdfError> {
3238 Ok(self.open(MmapRangeReader { mmap: self.map_source_file(path)? }))
3239 }
3240
3241 pub fn source(&self) -> Option<&Source> {
3243 self.source.as_ref()
3244 }
3245
3246 pub fn set_source(&mut self, source: impl Into<Source>) {
3251 self.source = Some(source.into());
3252 }
3253
3254 pub fn clear_source(&mut self) {
3256 self.source = None;
3257 }
3258
3259 pub fn read<'o>(&self, name: &str, options: impl Into<Option<&'o ReadOptions>>) -> Result<Signal, MdfError> {
3275 let default = ReadOptions::default();
3276 let options = options.into().unwrap_or(&default);
3277 let window = options.window()?;
3278 let (g, c) = self.locate_checked(name, options.group_name())?;
3279 #[cfg(feature = "http")]
3281 if let Source::Url(url) = self.require_source()? {
3282 let mut signals = self.read_many_url(url, &[(g, c)], window, options.raw)?;
3283 return signals.pop().ok_or_else(|| MdfError::BlockSerializationError("no signal read".to_string()));
3284 }
3285 if window == Window::All {
3286 return self.read_signal(g, c, options.raw);
3287 }
3288 let mut reader = self.source_reader(g, c, options.raw, true)?;
3289 let (start, count) = self.resolve_window_via(g, c, window, &mut reader)?;
3290 read_signal_window(self, g, c, start, count, options.raw, &mut reader)
3291 }
3292
3293 pub fn read_many<'o, S: AsRef<str>>(
3304 &self,
3305 names: &[S],
3306 options: impl Into<Option<&'o ReadOptions>>,
3307 ) -> Result<Vec<Signal>, MdfError> {
3308 let default = ReadOptions::default();
3309 let options = options.into().unwrap_or(&default);
3310 let window = options.window()?;
3311 let targets = self.locate_all(names, options.group_name())?;
3312 if targets.is_empty() {
3313 return Ok(Vec::new());
3314 }
3315 #[cfg(all(target_arch = "wasm32", not(feature = "http")))]
3316 let _ = window;
3317 match self.require_source()? {
3318 #[cfg(not(target_arch = "wasm32"))]
3319 Source::File(path) => {
3320 let mmap = self.map_source_file(path)?;
3321 if window == Window::All {
3322 return self.read_many_from_slice(&targets, options.raw, &mmap);
3323 }
3324 self.read_many_at(&targets, window, options.raw, &mut MmapRangeReader { mmap })
3325 }
3326 #[cfg(target_arch = "wasm32")]
3327 Source::File(_) => Err(MdfError::BlockSerializationError(
3328 "file sources are not available on wasm32".to_string(),
3329 )),
3330 #[cfg(feature = "http")]
3331 Source::Url(url) => self.read_many_url(url, &targets, window, options.raw),
3332 }
3333 }
3334
3335 pub fn values<'o>(&self, name: &str, options: impl Into<Option<&'o ReadOptions>>) -> Result<Vec<f64>, MdfError> {
3339 let default = ReadOptions::default();
3340 let options = options.into().unwrap_or(&default);
3341 let window = options.window()?;
3342 let (g, c) = self.locate_checked(name, options.group_name())?;
3343 if window == Window::All {
3344 return self.read_values_f64_via_source(g, c, options.raw);
3345 }
3346 #[cfg(feature = "http")]
3349 if let Source::Url(url) = self.require_source()? {
3350 return self.values_window_url(url, g, c, window, options.raw, BATCH_MEMORY_LIMIT);
3351 }
3352 let mut reader = self.source_reader(g, c, options.raw, false)?;
3353 let (start, count) = self.resolve_window_via(g, c, window, &mut reader)?;
3354 self.values_f64_window(g, c, start, count, options.raw, &mut reader)
3355 }
3356
3357 #[cfg(feature = "http")]
3365 fn values_window_url(
3366 &self,
3367 url: &str,
3368 g: usize,
3369 c: usize,
3370 window: Window,
3371 raw: bool,
3372 batch_limit: u64,
3373 ) -> Result<Vec<f64>, MdfError> {
3374 let mut cached = CachingRangeReader::with_chunk_size(self.http_source(url)?, 64 * 1024);
3375 if self.file_size > 0 {
3376 cached.set_known_size(self.file_size);
3377 }
3378 let mut conversions = Vec::with_capacity(2);
3379 if !raw {
3380 conversions.push((g, c));
3381 }
3382 if matches!(window, Window::Time(..)) {
3383 conversions.extend(self.time_axis_location(g, c));
3384 }
3385 let mut primed = std::collections::HashSet::new();
3386 for (tg, tc) in conversions {
3387 let channel = &self.channel_groups[tg].channels[tc];
3388 if channel.conversion.is_none() && channel.conversion_addr != 0 && primed.insert(channel.conversion_addr) {
3389 self.resolve_channel_conversion(tg, tc, &mut cached)?;
3390 }
3391 }
3392 let (mut http, fetched) = cached.into_parts();
3393 let mut store = FragmentStore::from_pairs(fetched)?;
3394 let (start, count) = self.batched_reads_seeded(&mut http, &mut store, |r| self.resolve_window(g, c, window, r))?;
3395
3396 let group = &self.channel_groups[g];
3397 let record = Self::checked_record_size(group).unwrap_or(0) as u64;
3400 let vlsd: u64 = group.channels[c].vlsd_data_blocks.iter().map(|b| b.size).sum();
3401 if count.saturating_mul(record).saturating_add(vlsd) > batch_limit {
3402 let mut reader = ChunkedUrlReader { http, store };
3403 return self.values_f64_window(g, c, start, count, raw, &mut reader);
3404 }
3405 self.batched_reads_seeded(&mut http, &mut store, |r| self.values_f64_window(g, c, start, count, raw, r))
3406 }
3407
3408 pub fn time_range(&self, name: &str, group: Option<&str>) -> Result<Option<TimeRange>, MdfError> {
3412 let (g, c) = self.locate_checked(name, group)?;
3413 #[cfg(feature = "http")]
3416 if let Source::Url(url) = self.require_source()? {
3417 let mut http = self.http_source(url)?;
3418 return self.batched_reads(&mut http, |r| self.time_range_at(g, c, r));
3419 }
3420 let mut reader = self.source_reader(g, c, false, true)?;
3422 self.time_range_at(g, c, &mut reader)
3423 }
3424
3425 fn resolve_window_via(
3430 &self,
3431 g: usize,
3432 c: usize,
3433 window: Window,
3434 reader: &mut SourceReader,
3435 ) -> Result<(u64, u64), MdfError> {
3436 match (window, reader) {
3437 #[cfg(feature = "http")]
3438 (Window::Time(..), SourceReader::Url(cached)) => {
3439 self.batched_reads(cached.inner_mut(), |r| self.resolve_window(g, c, window, r))
3440 }
3441 (_, reader) => self.resolve_window(g, c, window, reader),
3442 }
3443 }
3444
3445 #[cfg(feature = "http")]
3452 fn batched_reads<T>(
3453 &self,
3454 http: &mut HttpRangeReader,
3455 op: impl FnMut(&mut RecordingRangeReader<'_>) -> Result<T, MdfError>,
3456 ) -> Result<T, MdfError> {
3457 self.batched_reads_seeded(http, &mut FragmentStore::new(), op)
3458 }
3459
3460 #[cfg(feature = "http")]
3465 fn batched_reads_seeded<T>(
3466 &self,
3467 http: &mut HttpRangeReader,
3468 store: &mut FragmentStore,
3469 mut op: impl FnMut(&mut RecordingRangeReader<'_>) -> Result<T, MdfError>,
3470 ) -> Result<T, MdfError> {
3471 for _ in 0..MAX_BATCH_ROUNDS {
3472 let mut recorder = RecordingRangeReader { store: &*store, misses: Vec::new(), whole_request: true };
3473 let result = op(&mut recorder);
3474 let misses = std::mem::take(&mut recorder.misses);
3475 if misses.is_empty() {
3476 return result;
3477 }
3478 let spans = split_spans(merge_ranges_bridging(misses, BATCH_BRIDGE_BYTES), PARALLEL_CHUNK_BYTES);
3479 let fetched = http.read_ranges_parallel(&spans)?;
3480 for ((offset, _), bytes) in spans.iter().zip(fetched) {
3481 store.push(*offset, bytes)?;
3482 }
3483 }
3484 Err(MdfError::BlockSerializationError(
3485 "batched read did not converge; the index or source may be inconsistent".to_string(),
3486 ))
3487 }
3488
3489 pub fn conversion(&self, name: &str, group: Option<&str>) -> Result<Option<ConversionInfo>, MdfError> {
3495 Ok(self.conversion_block(name, group)?.as_ref().map(ConversionInfo::from))
3496 }
3497
3498 pub(crate) fn locate_all<S: AsRef<str>>(&self, names: &[S], group: Option<&str>) -> Result<Vec<(usize, usize)>, MdfError> {
3501 names.iter().map(|name| self.locate_checked(name.as_ref(), group)).collect()
3502 }
3503
3504 fn make_signal(&self, g: usize, c: usize, timestamps: Vec<f64>, values: Vec<Option<DecodedValue>>) -> Signal {
3506 let channel = &self.channel_groups[g].channels[c];
3507 Signal { name: channel.name.clone().unwrap_or_default(), unit: channel.unit.clone(), timestamps, values }
3508 }
3509
3510 #[cfg(not(target_arch = "wasm32"))]
3513 fn read_many_from_slice(&self, targets: &[(usize, usize)], raw: bool, data: &[u8]) -> Result<Vec<Signal>, MdfError> {
3514 let mut axes: HashMap<(usize, usize), Vec<f64>> = HashMap::new();
3515 let mut out = Vec::with_capacity(targets.len());
3516 for &(g, c) in targets {
3517 let values = self.read_channel_values_from_slice(g, c, raw, data)?;
3518 let timestamps = match self.master_location(g, c) {
3519 Some(m) => match axes.get(&m) {
3520 Some(axis) => axis.clone(),
3521 None => {
3522 let axis = self.read_channel_values_from_slice_as_f64(m.0, m.1, false, data)?;
3523 axes.insert(m, axis.clone());
3524 axis
3525 }
3526 },
3527 None => Vec::new(),
3528 };
3529 out.push(self.make_signal(g, c, timestamps, values));
3530 }
3531 Ok(out)
3532 }
3533
3534 pub(crate) fn read_many_at<R: ByteRangeReader<Error = MdfError>>(
3544 &self,
3545 targets: &[(usize, usize)],
3546 window: Window,
3547 raw: bool,
3548 reader: &mut R,
3549 ) -> Result<Vec<Signal>, MdfError> {
3550 let mut windows = WindowCache::new();
3551 let mut axes = AxisCache::new();
3552 let mut out = Vec::with_capacity(targets.len());
3553 let mut first_error = None;
3554 for &(g, c) in targets {
3555 match self.read_one_at(g, c, window, raw, reader, &mut windows, &mut axes) {
3556 Ok(signal) => out.push(signal),
3557 Err(e) if reader.is_probing() => {
3561 first_error.get_or_insert(e);
3562 }
3563 Err(e) => return Err(e),
3564 }
3565 }
3566 match first_error {
3567 Some(e) => Err(e),
3568 None => Ok(out),
3569 }
3570 }
3571
3572 #[allow(clippy::too_many_arguments)]
3576 fn read_one_at<R: ByteRangeReader<Error = MdfError>>(
3577 &self,
3578 g: usize,
3579 c: usize,
3580 window: Window,
3581 raw: bool,
3582 reader: &mut R,
3583 windows: &mut WindowCache,
3584 axes: &mut AxisCache,
3585 ) -> Result<Signal, MdfError> {
3586 let master = self.master_location(g, c);
3587 if window == Window::All {
3588 let values = self.read_channel_values(g, c, raw, reader);
3589 let timestamps = match master {
3592 Some((mg, m)) => Self::cached_axis(axes, (mg, m, 0, u64::MAX), || {
3593 self.read_channel_values_as_f64(mg, m, false, reader)
3594 }),
3595 None => Ok(Vec::new()),
3596 };
3597 let values = values?;
3599 return Ok(self.make_signal(g, c, timestamps?, values));
3600 }
3601 let (start, count) = self.cached_window(g, c, window, reader, windows)?;
3602 let values = self.read_channel_values_window(g, c, start, count, raw, reader);
3603 let timestamps = match master {
3604 Some((mg, m)) => Self::cached_axis(axes, (mg, m, start, count), || {
3605 self.values_f64_window(mg, m, start, count, false, reader)
3606 }),
3607 None => Ok(Vec::new()),
3608 };
3609 let values = values?;
3610 Ok(self.make_signal(g, c, timestamps?, values))
3611 }
3612
3613 fn cached_window<R: ByteRangeReader<Error = MdfError>>(
3617 &self,
3618 g: usize,
3619 c: usize,
3620 window: Window,
3621 reader: &mut R,
3622 cache: &mut WindowCache,
3623 ) -> Result<(u64, u64), MdfError> {
3624 let axis = match window {
3625 Window::Time(..) => self.time_axis_location(g, c),
3626 _ => None,
3627 };
3628 let key = (axis, self.channel_groups[g].record_count);
3629 if let Some(&resolved) = cache.get(&key) {
3630 return Ok(resolved);
3631 }
3632 let resolved = self.resolve_window(g, c, window, reader)?;
3633 cache.insert(key, resolved);
3634 Ok(resolved)
3635 }
3636
3637 fn cached_axis(
3638 axes: &mut AxisCache,
3639 key: (usize, usize, u64, u64),
3640 decode: impl FnOnce() -> Result<Vec<f64>, MdfError>,
3641 ) -> Result<Vec<f64>, MdfError> {
3642 if let Some(axis) = axes.get(&key) {
3643 return Ok(axis.clone());
3644 }
3645 let axis = decode()?;
3646 axes.insert(key, axis.clone());
3647 Ok(axis)
3648 }
3649
3650 #[cfg(feature = "http")]
3660 fn read_many_url(
3661 &self,
3662 url: &str,
3663 targets: &[(usize, usize)],
3664 window: Window,
3665 raw: bool,
3666 ) -> Result<Vec<Signal>, MdfError> {
3667 self.read_many_url_limited(url, targets, window, raw, BATCH_MEMORY_LIMIT)
3668 }
3669
3670 #[cfg(feature = "http")]
3673 fn read_many_url_limited(
3674 &self,
3675 url: &str,
3676 targets: &[(usize, usize)],
3677 window: Window,
3678 raw: bool,
3679 batch_limit: u64,
3680 ) -> Result<Vec<Signal>, MdfError> {
3681 let mut cached = CachingRangeReader::with_chunk_size(self.http_source(url)?, 64 * 1024);
3682 if self.file_size > 0 {
3683 cached.set_known_size(self.file_size);
3684 }
3685 let mut primed = std::collections::HashSet::new();
3686 for &(g, c) in targets {
3687 let mut conversions = Vec::with_capacity(3);
3688 if !raw {
3689 conversions.push((g, c));
3690 }
3691 conversions.extend(self.master_location(g, c));
3692 if matches!(window, Window::Time(..)) {
3693 conversions.extend(self.time_axis_location(g, c));
3694 }
3695 for (tg, tc) in conversions {
3696 let channel = &self.channel_groups[tg].channels[tc];
3697 if channel.conversion.is_none() && channel.conversion_addr != 0 && primed.insert(channel.conversion_addr) {
3698 self.resolve_channel_conversion(tg, tc, &mut cached)?;
3699 }
3700 }
3701 }
3702 let (mut http, fetched) = cached.into_parts();
3703 let mut store = FragmentStore::from_pairs(fetched)?;
3704 let bytes = if window == Window::All {
3705 self.whole_read_bytes(targets)
3706 } else {
3707 match self.batched_reads_seeded(&mut http, &mut store, |r| self.resolve_windows(targets, window, r)) {
3714 Ok(resolved) => self.window_read_bytes(targets, &resolved),
3715 Err(_) => u64::MAX,
3716 }
3717 };
3718 if bytes > batch_limit {
3719 let mut reader = ChunkedUrlReader { http, store };
3724 return self.read_many_at(targets, window, raw, &mut reader);
3725 }
3726 self.batched_reads_seeded(&mut http, &mut store, |r| self.read_many_at(targets, window, raw, r))
3727 }
3728
3729 #[cfg(feature = "http")]
3733 fn resolve_windows<R: ByteRangeReader<Error = MdfError>>(
3734 &self,
3735 targets: &[(usize, usize)],
3736 window: Window,
3737 reader: &mut R,
3738 ) -> Result<Vec<(u64, u64)>, MdfError> {
3739 let mut cache = WindowCache::new();
3740 let mut out = Vec::with_capacity(targets.len());
3741 let mut first_error = None;
3742 for &(g, c) in targets {
3743 match self.cached_window(g, c, window, reader, &mut cache) {
3744 Ok(resolved) => out.push(resolved),
3745 Err(e) => {
3746 first_error.get_or_insert(e);
3747 }
3748 }
3749 }
3750 match first_error {
3751 Some(e) => Err(e),
3752 None => Ok(out),
3753 }
3754 }
3755
3756 #[cfg(feature = "http")]
3761 fn window_read_bytes(&self, targets: &[(usize, usize)], resolved: &[(u64, u64)]) -> u64 {
3762 let mut records: std::collections::BTreeMap<usize, u64> = std::collections::BTreeMap::new();
3763 let mut total = 0u64;
3764 for (&(g, c), &(_, count)) in targets.iter().zip(resolved) {
3765 for group in std::iter::once(g).chain(self.master_location(g, c).map(|(mg, _)| mg)) {
3766 let widest = records.entry(group).or_default();
3767 *widest = (*widest).max(count);
3768 }
3769 let channel = &self.channel_groups[g].channels[c];
3770 total = total.saturating_add(channel.vlsd_data_blocks.iter().map(|b| b.size).sum());
3771 }
3772 records.into_iter().fold(total, |sum, (g, count)| {
3773 let record = Self::checked_record_size(&self.channel_groups[g]).unwrap_or(0) as u64;
3774 sum.saturating_add(count.saturating_mul(record))
3775 })
3776 }
3777
3778 #[cfg(feature = "http")]
3782 fn whole_read_bytes(&self, targets: &[(usize, usize)]) -> u64 {
3783 let mut groups = std::collections::BTreeSet::new();
3784 let mut total = 0u64;
3785 for &(g, c) in targets {
3786 groups.insert(g);
3787 if let Some((mg, _)) = self.master_location(g, c) {
3788 groups.insert(mg);
3789 }
3790 let channel = &self.channel_groups[g].channels[c];
3791 total = total.saturating_add(channel.vlsd_data_blocks.iter().map(|b| b.size).sum());
3792 }
3793 groups
3794 .iter()
3795 .flat_map(|&g| self.channel_groups[g].data_blocks.iter())
3796 .fold(total, |sum, b| sum.saturating_add(b.size))
3797 }
3798
3799 pub(crate) fn resolve_window<R: ByteRangeReader<Error = MdfError>>(
3801 &self,
3802 g: usize,
3803 c: usize,
3804 window: Window,
3805 reader: &mut R,
3806 ) -> Result<(u64, u64), MdfError> {
3807 let total = self.channel_groups[g].record_count;
3808 match window {
3809 Window::All => Ok((0, total)),
3810 Window::Records(start, count) => resolve_records(start, count, total),
3811 Window::Time(t_start, t_end) => self.record_window_for_time(g, c, t_start, t_end, reader),
3812 }
3813 }
3814
3815 pub(crate) fn values_f64_window<R: ByteRangeReader<Error = MdfError>>(
3817 &self,
3818 g: usize,
3819 c: usize,
3820 start: u64,
3821 count: u64,
3822 raw: bool,
3823 reader: &mut R,
3824 ) -> Result<Vec<f64>, MdfError> {
3825 let (group, channel) = self.group_and_channel(g, c)?;
3828 Self::check_window(group, start, count)?;
3829 let conversion = Self::read_conversion(channel, reader, raw)?;
3830 self.window_values_f64(group, channel, conversion.as_deref(), start, count, reader)
3831 }
3832
3833 pub(crate) fn time_range_at<R: ByteRangeReader<Error = MdfError>>(
3835 &self,
3836 g: usize,
3837 c: usize,
3838 reader: &mut R,
3839 ) -> Result<Option<TimeRange>, MdfError> {
3840 let total = self.channel_groups[g].record_count;
3841 let Some((mg, m)) = self.time_axis_location(g, c) else {
3842 if total == 0 {
3843 return Ok(None);
3844 }
3845 let name = self.channel_groups[g].channels[c].name.clone().unwrap_or_default();
3846 return Err(MdfError::InvalidArgument(format!(
3847 "channel '{name}' has no master (time) channel"
3848 )));
3849 };
3850 let n = total.min(self.channel_groups[mg].record_count);
3851 if n == 0 {
3852 return Ok(None);
3853 }
3854 let first = self.values_f64_window(mg, m, 0, 1, false, reader);
3855 let last = self.values_f64_window(mg, m, n - 1, 1, false, reader)?;
3858 Ok(Some(TimeRange { start: first?[0], end: last[0] }))
3859 }
3860
3861 #[cfg(not(target_arch = "wasm32"))]
3864 fn map_source_file(&self, path: &str) -> Result<memmap2::Mmap, MdfError> {
3865 if is_http_url(path) {
3866 #[cfg(not(feature = "http"))]
3867 return Err(MdfError::InvalidArgument(format!(
3868 "'{path}' is a URL, but mf4-rs was built without the `http` feature"
3869 )));
3870 #[cfg(feature = "http")]
3871 return Err(MdfError::InvalidArgument(format!(
3872 "'{path}' is a URL, not a local file: attach URLs with `set_source` or build the \
3873 index with `from_url`"
3874 )));
3875 }
3876 if let Some(scheme) = url_scheme(path) {
3877 return Err(MdfError::InvalidArgument(format!(
3878 "unsupported source '{path}': {scheme}:// URLs cannot be read directly — use a \
3879 local file path or an http(s):// URL (e.g. a presigned S3 / GCS / Azure URL)"
3880 )));
3881 }
3882 let file = std::fs::File::open(path).map_err(|e| {
3883 MdfError::IOError(std::io::Error::new(e.kind(), format!("cannot open source '{path}': {e}")))
3884 })?;
3885 let mmap = unsafe { memmap2::Mmap::map(&file) }.map_err(MdfError::IOError)?;
3886 check_resource_size(path, self.file_size, mmap.len() as u64)?;
3887 Ok(mmap)
3888 }
3889
3890 #[cfg(feature = "http")]
3893 fn http_source(&self, url: &str) -> Result<HttpRangeReader, MdfError> {
3894 let mut http = HttpRangeReader::new(url)?;
3895 if self.file_size > 0 {
3896 http.expect_size(self.file_size);
3897 }
3898 Ok(http)
3899 }
3900
3901 fn source_reader(&self, g: usize, c: usize, raw: bool, with_master: bool) -> Result<SourceReader, MdfError> {
3907 let _ = (g, c, raw, with_master);
3908 match self.require_source()? {
3909 #[cfg(not(target_arch = "wasm32"))]
3910 Source::File(path) => Ok(SourceReader::File(MmapRangeReader { mmap: self.map_source_file(path)? })),
3911 #[cfg(target_arch = "wasm32")]
3912 Source::File(_) => Err(MdfError::BlockSerializationError(
3913 "file sources are not available on wasm32".to_string(),
3914 )),
3915 #[cfg(feature = "http")]
3916 Source::Url(url) => {
3917 let http = self.http_source(url)?;
3918 Ok(SourceReader::Url(self.url_reader_with_conversion(http, g, c, raw, with_master)?))
3919 }
3920 }
3921 }
3922
3923 fn read_signal(&self, g: usize, c: usize, raw: bool) -> Result<Signal, MdfError> {
3925 let channel = &self.channel_groups[g].channels[c];
3926 let (name, unit) = (channel.name.clone().unwrap_or_default(), channel.unit.clone());
3927
3928 #[cfg(not(target_arch = "wasm32"))]
3930 #[allow(irrefutable_let_patterns)] if let Source::File(path) = self.require_source()? {
3932 let mmap = self.map_source_file(path)?;
3933 let values = self.read_channel_values_from_slice(g, c, raw, &mmap)?;
3934 let timestamps = match self.master_location(g, c) {
3935 Some((mg, m)) => self.read_channel_values_from_slice_as_f64(mg, m, false, &mmap)?,
3936 None => Vec::new(),
3937 };
3938 return Ok(Signal { name, unit, timestamps, values });
3939 }
3940
3941 let values = self.read_values_via_source(g, c, raw)?;
3942 let timestamps = match self.master_location(g, c) {
3943 Some((mg, m)) => self.read_values_f64_via_source(mg, m, false)?,
3944 None => Vec::new(),
3945 };
3946
3947 Ok(Signal { name, unit, timestamps, values })
3948 }
3949
3950 #[cfg(feature = "http")]
3962 fn url_reader_with_conversion(
3963 &self,
3964 http: HttpRangeReader,
3965 g: usize,
3966 c: usize,
3967 raw: bool,
3968 with_master: bool,
3969 ) -> Result<CachingRangeReader<HttpRangeReader>, MdfError> {
3970 let mut cached = CachingRangeReader::with_chunk_size(http, 64 * 1024);
3971 if self.file_size > 0 {
3972 cached.set_known_size(self.file_size);
3973 }
3974 let mut targets = Vec::with_capacity(2);
3975 if !raw {
3976 targets.push((g, c));
3977 }
3978 if with_master {
3979 targets.extend(self.master_location(g, c));
3980 }
3981 for (tg, tc) in targets {
3982 let channel = &self.channel_groups[tg].channels[tc];
3983 if channel.conversion.is_none() && channel.conversion_addr != 0 {
3984 self.resolve_channel_conversion(tg, tc, &mut cached)?;
3985 }
3986 }
3987 cached.set_bypass(true);
3988 Ok(cached)
3989 }
3990
3991 fn require_source(&self) -> Result<&Source, MdfError> {
3993 let source = self.source.as_ref().ok_or_else(|| {
3994 MdfError::BlockSerializationError(
3995 "no data source attached to index; build with from_file/from_url or call set_source".to_string(),
3996 )
3997 })?;
3998 #[cfg(not(feature = "http"))]
3999 {
4000 let Source::File(path) = source;
4001 if is_http_url(path) {
4002 return Err(MdfError::InvalidArgument(format!(
4003 "'{path}' is a URL, but mf4-rs was built without the `http` feature"
4004 )));
4005 }
4006 }
4007 Ok(source)
4008 }
4009
4010 pub(crate) fn read_values_via_source(
4012 &self,
4013 g: usize,
4014 c: usize,
4015 raw: bool,
4016 ) -> Result<Vec<Option<DecodedValue>>, MdfError> {
4017 #[cfg(target_arch = "wasm32")]
4018 let _ = (g, c, raw);
4019 match self.require_source()? {
4020 #[cfg(not(target_arch = "wasm32"))]
4021 Source::File(path) => {
4022 let mmap = self.map_source_file(path)?;
4023 self.read_channel_values_from_slice(g, c, raw, &mmap)
4024 }
4025 #[cfg(target_arch = "wasm32")]
4026 Source::File(_) => Err(MdfError::BlockSerializationError(
4027 "file sources are not available on wasm32".to_string(),
4028 )),
4029 #[cfg(feature = "http")]
4030 Source::Url(url) => {
4031 let http = self.http_source(url)?;
4032 let mut cached = self.url_reader_with_conversion(http, g, c, raw, false)?;
4033 self.read_channel_values(g, c, raw, &mut cached)
4034 }
4035 }
4036 }
4037
4038 pub fn conversion_block(&self, name: &str, group: Option<&str>) -> Result<Option<ConversionBlock>, MdfError> {
4049 let (g, c) = self.locate_checked(name, group)?;
4050 let channel = &self.channel_groups[g].channels[c];
4051 if let Some(conv) = &channel.conversion {
4052 return Ok(Some(conv.clone()));
4053 }
4054 if channel.conversion_addr == 0 {
4055 return Ok(None);
4056 }
4057 match self.require_source()? {
4058 #[cfg(not(target_arch = "wasm32"))]
4059 Source::File(path) => {
4060 let mmap = self.map_source_file(path)?;
4061 let mut slice_reader = BorrowedSliceReader { data: &mmap };
4062 Ok(Self::resolve_conversion(channel, &mut slice_reader)?.map(Cow::into_owned))
4063 }
4064 #[cfg(target_arch = "wasm32")]
4065 Source::File(_) => Err(MdfError::BlockSerializationError(
4066 "file sources are not available on wasm32".to_string(),
4067 )),
4068 #[cfg(feature = "http")]
4069 Source::Url(url) => {
4070 let http = self.http_source(url)?;
4071 let mut cached = CachingRangeReader::new(http);
4072 Ok(Self::resolve_conversion(channel, &mut cached)?.map(Cow::into_owned))
4073 }
4074 }
4075 }
4076
4077 pub(crate) fn read_values_f64_via_source(
4079 &self,
4080 g: usize,
4081 c: usize,
4082 raw: bool,
4083 ) -> Result<Vec<f64>, MdfError> {
4084 #[cfg(target_arch = "wasm32")]
4085 let _ = (g, c, raw);
4086 match self.require_source()? {
4087 #[cfg(not(target_arch = "wasm32"))]
4088 Source::File(path) => {
4089 let mmap = self.map_source_file(path)?;
4090 self.read_channel_values_from_slice_as_f64(g, c, raw, &mmap)
4091 }
4092 #[cfg(target_arch = "wasm32")]
4093 Source::File(_) => Err(MdfError::BlockSerializationError(
4094 "file sources are not available on wasm32".to_string(),
4095 )),
4096 #[cfg(feature = "http")]
4097 Source::Url(url) => {
4098 let http = self.http_source(url)?;
4099 let mut cached = self.url_reader_with_conversion(http, g, c, raw, false)?;
4100 self.read_channel_values_as_f64(g, c, raw, &mut cached)
4101 }
4102 }
4103 }
4104
4105 pub(crate) fn get_channel_byte_ranges(
4118 &self,
4119 group_index: usize,
4120 channel_index: usize,
4121 ) -> Result<Vec<(u64, u64)>, MdfError> {
4122 let group = self.channel_groups.get(group_index)
4123 .ok_or_else(|| MdfError::BlockSerializationError("Invalid group index".to_string()))?;
4124
4125 let channel = group.channels.get(channel_index)
4126 .ok_or_else(|| MdfError::BlockSerializationError("Invalid channel index".to_string()))?;
4127
4128 Self::ensure_not_vlsd(channel)?;
4130
4131 self.calculate_regular_channel_byte_ranges(group, channel)
4133 }
4134
4135 pub(crate) fn get_channel_byte_ranges_for_records(
4149 &self,
4150 group_index: usize,
4151 channel_index: usize,
4152 start_record: u64,
4153 record_count: u64,
4154 ) -> Result<Vec<(u64, u64)>, MdfError> {
4155 let group = self.channel_groups.get(group_index)
4156 .ok_or_else(|| MdfError::BlockSerializationError("Invalid group index".to_string()))?;
4157
4158 let channel = group.channels.get(channel_index)
4159 .ok_or_else(|| MdfError::BlockSerializationError("Invalid channel index".to_string()))?;
4160
4161 let end_record = start_record.checked_add(record_count).ok_or_else(|| {
4164 MdfError::BlockSerializationError(format!(
4165 "Record range overflow: start {} + count {}",
4166 start_record, record_count
4167 ))
4168 })?;
4169 if end_record > group.record_count {
4170 return Err(MdfError::BlockSerializationError(
4171 format!("Record range starting at {} for {} records exceeds total records {}",
4172 start_record, record_count, group.record_count)
4173 ));
4174 }
4175
4176 Self::ensure_not_vlsd(channel)?;
4178
4179 self.calculate_channel_byte_ranges_for_records(group, channel, start_record, record_count)
4180 }
4181
4182 fn calculate_regular_channel_byte_ranges(
4184 &self,
4185 group: &IndexedChannelGroup,
4186 channel: &IndexedChannel,
4187 ) -> Result<Vec<(u64, u64)>, MdfError> {
4188 self.calculate_channel_byte_ranges_for_records(group, channel, 0, group.record_count)
4189 }
4190
4191 fn calculate_channel_byte_ranges_for_records(
4193 &self,
4194 group: &IndexedChannelGroup,
4195 channel: &IndexedChannel,
4196 start_record: u64,
4197 record_count: u64,
4198 ) -> Result<Vec<(u64, u64)>, MdfError> {
4199 let record_size = Self::checked_record_size(group)?;
4201 let channel_offset_in_record = group.record_id_len as usize + channel.byte_offset as usize;
4202
4203 let channel_bytes_per_record = if matches!(channel.data_type,
4205 DataType::StringLatin1 | DataType::StringUtf8 | DataType::StringUtf16LE |
4206 DataType::StringUtf16BE | DataType::ByteArray | DataType::MimeSample | DataType::MimeStream)
4207 {
4208 channel.bit_count as usize / 8
4209 } else {
4210 (channel.bit_offset as usize + channel.bit_count as usize).div_ceil(8).max(1)
4211 };
4212
4213 let size = record_size as u64;
4219 let (field_offset, field_len) = (channel_offset_in_record as u64, channel_bytes_per_record as u64);
4220 let end_record = start_record + record_count;
4221 let mut byte_ranges = Vec::new();
4222 let mut block_start = 0u64; for data_block in &group.data_blocks {
4225 if data_block.is_compressed {
4226 return Err(MdfError::BlockSerializationError(
4227 "Compressed blocks not supported for byte range calculation".to_string()
4228 ));
4229 }
4230 let block_end = block_start.saturating_add(Self::data_section_size(data_block)?);
4231 if record_count == 0 || field_len == 0 || block_start >= end_record.saturating_mul(size) {
4232 break;
4233 }
4234 let first = (block_start + 1).saturating_sub(field_offset + field_len).div_ceil(size);
4237 let first = first.max(start_record);
4238 let last = match block_end.checked_sub(field_offset + 1) {
4239 Some(v) => (v / size).min(end_record - 1),
4240 None => {
4241 block_start = block_end;
4242 continue;
4243 }
4244 };
4245 if first <= last {
4246 let lo = (first * size + field_offset).max(block_start);
4247 let hi = (last * size + field_offset + field_len).min(block_end);
4248 if lo < hi {
4249 byte_ranges.push((data_block.file_offset + 24 + (lo - block_start), hi - lo));
4250 }
4251 }
4252 block_start = block_end;
4253 }
4254
4255 Ok(byte_ranges)
4256 }
4257
4258 pub fn byte_ranges(&self, name: &str, group: Option<&str>) -> Result<Vec<(u64, u64)>, MdfError> {
4276 let (g, c) = self.locate_checked(name, group)?;
4277 self.get_channel_byte_ranges(g, c)
4278 }
4279
4280 pub fn byte_ranges_for_records(
4287 &self,
4288 name: &str,
4289 start_record: u64,
4290 record_count: u64,
4291 group: Option<&str>,
4292 ) -> Result<Vec<(u64, u64)>, MdfError> {
4293 let (g, c) = self.locate_checked(name, group)?;
4294 self.get_channel_byte_ranges_for_records(g, c, start_record, record_count)
4295 }
4296
4297 pub(crate) fn read_channel_values_as_f64<R: ByteRangeReader<Error = MdfError>>(
4303 &self,
4304 group_index: usize,
4305 channel_index: usize,
4306 raw: bool,
4307 reader: &mut R,
4308 ) -> Result<Vec<f64>, MdfError> {
4309 let group = self.channel_groups.get(group_index)
4310 .ok_or_else(|| MdfError::BlockSerializationError("Invalid group index".to_string()))?;
4311 let channel = group.channels.get(channel_index)
4312 .ok_or_else(|| MdfError::BlockSerializationError("Invalid channel index".to_string()))?;
4313
4314 let conversion = Self::read_conversion(channel, reader, raw)?;
4315
4316 if channel.is_virtual() {
4317 let vals = self.virtual_values(group, 0, group.record_count, conversion.as_deref())?;
4318 return Ok(Self::vlsd_values_to_f64(vals));
4319 }
4320 if channel.channel_type == 1 {
4321 let vals = self.read_vlsd_channel_values(group, channel, conversion.as_deref(), reader)?;
4322 return Ok(Self::vlsd_values_to_f64(vals));
4323 }
4324
4325 let record_size = Self::checked_record_size(group)?;
4326 let total_records = Self::whole_read_records(group)?;
4327 let mut values = Vec::with_capacity(total_records.min(1 << 24));
4331
4332 let temp_cb = channel.to_decode_only_channel_block();
4333 let linear_coeffs = Self::get_linear_coeffs(conversion.as_deref());
4334 let has_conversion = conversion.is_some();
4335
4336 let mut records = RecordCarry::new(record_size);
4338 Self::for_each_data_section(reader, &group.data_blocks, |block_data| {
4339 records.feed(block_data, |run| {
4340 Self::decode_records_to_f64(run, record_size, group, channel, conversion.as_deref(), &temp_cb, linear_coeffs, has_conversion, &mut values)
4341 })
4342 })?;
4343
4344 Ok(values)
4345 }
4346
4347 #[allow(dead_code)] pub(crate) fn read_channel_values_from_slice(
4354 &self,
4355 group_index: usize,
4356 channel_index: usize,
4357 raw: bool,
4358 file_data: &[u8],
4359 ) -> Result<Vec<Option<DecodedValue>>, MdfError> {
4360 let group = self.channel_groups.get(group_index)
4361 .ok_or_else(|| MdfError::BlockSerializationError("Invalid group index".to_string()))?;
4362 let channel = group.channels.get(channel_index)
4363 .ok_or_else(|| MdfError::BlockSerializationError("Invalid channel index".to_string()))?;
4364
4365 let mut slice_reader = BorrowedSliceReader { data: file_data };
4366 let conversion = Self::read_conversion(channel, &mut slice_reader, raw)?;
4367
4368 if channel.is_virtual() {
4369 return self.virtual_values(group, 0, group.record_count, conversion.as_deref());
4370 }
4371 if channel.channel_type == 1 {
4372 return self.read_vlsd_channel_values(group, channel, conversion.as_deref(), &mut slice_reader);
4373 }
4374
4375 let record_size = Self::checked_record_size(group)?;
4376 let total_records = Self::whole_read_records(group)?;
4377 let mut values = Vec::with_capacity(total_records.min(1 << 24));
4381 let temp_cb = channel.to_decode_only_channel_block();
4382
4383 let mut records = RecordCarry::new(record_size);
4385 for data_block in &group.data_blocks {
4386 let block_data = Self::slice_data_block(file_data, data_block)?;
4387 records.feed(block_data, |run| {
4388 Self::decode_records_to_values(run, record_size, group, conversion.as_deref(), &temp_cb, &mut values)
4389 })?;
4390 }
4391
4392 Ok(values)
4393 }
4394
4395 #[allow(dead_code)] pub(crate) fn read_channel_values_from_slice_as_f64(
4402 &self,
4403 group_index: usize,
4404 channel_index: usize,
4405 raw: bool,
4406 file_data: &[u8],
4407 ) -> Result<Vec<f64>, MdfError> {
4408 let group = self.channel_groups.get(group_index)
4409 .ok_or_else(|| MdfError::BlockSerializationError("Invalid group index".to_string()))?;
4410 let channel = group.channels.get(channel_index)
4411 .ok_or_else(|| MdfError::BlockSerializationError("Invalid channel index".to_string()))?;
4412
4413 let mut slice_reader = BorrowedSliceReader { data: file_data };
4414 let conversion = Self::read_conversion(channel, &mut slice_reader, raw)?;
4415
4416 if channel.is_virtual() {
4417 let vals = self.virtual_values(group, 0, group.record_count, conversion.as_deref())?;
4418 return Ok(Self::vlsd_values_to_f64(vals));
4419 }
4420 if channel.channel_type == 1 {
4421 let vals = self.read_vlsd_channel_values(group, channel, conversion.as_deref(), &mut slice_reader)?;
4422 return Ok(Self::vlsd_values_to_f64(vals));
4423 }
4424
4425 let record_size = Self::checked_record_size(group)?;
4426 let total_records = Self::whole_read_records(group)?;
4427 let mut values = Vec::with_capacity(total_records.min(1 << 24));
4431 let temp_cb = channel.to_decode_only_channel_block();
4432 let linear_coeffs = Self::get_linear_coeffs(conversion.as_deref());
4433 let has_conversion = conversion.is_some();
4434
4435 let mut records = RecordCarry::new(record_size);
4437 for data_block in &group.data_blocks {
4438 let block_data = Self::slice_data_block(file_data, data_block)?;
4439 records.feed(block_data, |run| {
4440 Self::decode_records_to_f64(run, record_size, group, channel, conversion.as_deref(), &temp_cb, linear_coeffs, has_conversion, &mut values)
4441 })?;
4442 }
4443
4444 Ok(values)
4445 }
4446
4447 #[allow(dead_code)] fn slice_data_block<'a>(file_data: &'a [u8], data_block: &DataBlockInfo) -> Result<&'a [u8], MdfError> {
4452 Self::data_section_size(data_block)?;
4453 let too_short = |expected: usize| MdfError::TooShortBuffer {
4454 actual: file_data.len(),
4455 expected,
4456 file: file!(),
4457 line: line!(),
4458 };
4459 let data_start = usize::try_from(data_block.file_offset)
4460 .ok()
4461 .and_then(|o| o.checked_add(24))
4462 .ok_or_else(|| too_short(usize::MAX))?;
4463 let data_len = Self::verified_data_len(file_data.get(data_start - 24..data_start), data_block)?;
4465 let data_end = usize::try_from(data_len)
4466 .ok()
4467 .and_then(|l| data_start.checked_add(l))
4468 .ok_or_else(|| too_short(usize::MAX))?;
4469 file_data.get(data_start..data_end).ok_or_else(|| too_short(data_end))
4470 }
4471}
4472
4473pub struct MdfReader<'a, R: ByteRangeReader<Error = MdfError>> {
4481 index: &'a MdfIndex,
4482 reader: R,
4483}
4484
4485impl<'a, R: ByteRangeReader<Error = MdfError>> MdfReader<'a, R> {
4486 pub fn index(&self) -> &MdfIndex {
4488 self.index
4489 }
4490
4491 pub fn reader_mut(&mut self) -> &mut R {
4494 &mut self.reader
4495 }
4496
4497 pub fn into_inner(self) -> R {
4499 self.reader
4500 }
4501
4502 pub fn read<'o>(&mut self, name: &str, options: impl Into<Option<&'o ReadOptions>>) -> Result<Signal, MdfError> {
4504 let default = ReadOptions::default();
4505 let options = options.into().unwrap_or(&default);
4506 let window = options.window()?;
4507 let (g, c) = self.index.locate_checked(name, options.group_name())?;
4508 if window == Window::All {
4509 return self.read_signal(g, c, options.raw);
4510 }
4511 let (start, count) = self.index.resolve_window(g, c, window, &mut self.reader)?;
4512 read_signal_window(self.index, g, c, start, count, options.raw, &mut self.reader)
4513 }
4514
4515 pub fn read_many<'o, S: AsRef<str>>(
4517 &mut self,
4518 names: &[S],
4519 options: impl Into<Option<&'o ReadOptions>>,
4520 ) -> Result<Vec<Signal>, MdfError> {
4521 let default = ReadOptions::default();
4522 let options = options.into().unwrap_or(&default);
4523 let window = options.window()?;
4524 let targets = self.index.locate_all(names, options.group_name())?;
4525 self.index.read_many_at(&targets, window, options.raw, &mut self.reader)
4526 }
4527
4528 pub fn values<'o>(&mut self, name: &str, options: impl Into<Option<&'o ReadOptions>>) -> Result<Vec<f64>, MdfError> {
4530 let default = ReadOptions::default();
4531 let options = options.into().unwrap_or(&default);
4532 let window = options.window()?;
4533 let (g, c) = self.index.locate_checked(name, options.group_name())?;
4534 if window == Window::All {
4535 return self.index.read_channel_values_as_f64(g, c, options.raw, &mut self.reader);
4536 }
4537 let (start, count) = self.index.resolve_window(g, c, window, &mut self.reader)?;
4538 self.index.values_f64_window(g, c, start, count, options.raw, &mut self.reader)
4539 }
4540
4541 pub fn decoded_values(&mut self, name: &str, group: Option<&str>) -> Result<Vec<Option<DecodedValue>>, MdfError> {
4544 let (g, c) = self.index.locate_checked(name, group)?;
4545 self.index.read_channel_values(g, c, false, &mut self.reader)
4546 }
4547
4548 pub fn time_range(&mut self, name: &str, group: Option<&str>) -> Result<Option<TimeRange>, MdfError> {
4551 let (g, c) = self.index.locate_checked(name, group)?;
4552 self.index.time_range_at(g, c, &mut self.reader)
4553 }
4554
4555 fn read_signal(&mut self, g: usize, c: usize, raw: bool) -> Result<Signal, MdfError> {
4556 let channel = &self.index.channel_groups[g].channels[c];
4557 let (name, unit) = (channel.name.clone().unwrap_or_default(), channel.unit.clone());
4558
4559 let values = self.index.read_channel_values(g, c, raw, &mut self.reader)?;
4560 let timestamps = match self.index.master_location(g, c) {
4561 Some((mg, m)) => self.index.read_channel_values_as_f64(mg, m, false, &mut self.reader)?,
4562 None => Vec::new(),
4563 };
4564 Ok(Signal { name, unit, timestamps, values })
4565 }
4566}
4567
4568pub(crate) fn read_signal_window<R: ByteRangeReader<Error = MdfError>>(
4572 index: &MdfIndex,
4573 g: usize,
4574 c: usize,
4575 start: u64,
4576 count: u64,
4577 raw: bool,
4578 reader: &mut R,
4579) -> Result<Signal, MdfError> {
4580 let channel = &index.channel_groups[g].channels[c];
4581 let (name, unit) = (channel.name.clone().unwrap_or_default(), channel.unit.clone());
4582 let values = index.read_channel_values_window(g, c, start, count, raw, reader);
4583 let timestamps = match index.master_location(g, c) {
4587 Some((mg, m)) => index.values_f64_window(mg, m, start, count, false, reader)?,
4588 None => Vec::new(),
4589 };
4590 Ok(Signal { name, unit, timestamps, values: values? })
4591}
4592
4593#[cfg(all(test, feature = "http"))]
4594mod http_header_tests {
4595 use super::{content_range_span, content_range_total};
4596
4597 #[test]
4598 fn parses_content_range() {
4599 assert_eq!(content_range_span(Some("bytes 10-19/100")), Some((10, 19)));
4600 assert_eq!(content_range_span(Some(" bytes 0-0/*")), Some((0, 0)));
4601 assert_eq!(content_range_span(Some("bytes */100")), None);
4602 assert_eq!(content_range_span(None), None);
4603 assert_eq!(content_range_total(Some("bytes 10-19/100")), Some(100));
4604 assert_eq!(content_range_total(Some("bytes */100")), Some(100));
4605 assert_eq!(content_range_total(Some("bytes 0-0/*")), None);
4606 }
4607}
4608
4609#[cfg(all(test, feature = "http"))]
4610mod http_retry_tests {
4611 use super::{ByteRangeReader, HttpRangeReader};
4612 use std::collections::VecDeque;
4613 use std::io::{Read, Write};
4614 use std::sync::atomic::{AtomicU64, Ordering};
4615 use std::sync::{Arc, Mutex};
4616
4617 const OK: &str = "HTTP/1.1 206 Partial Content\r\nContent-Range: bytes 0-3/10\r\nContent-Length: 4\r\n\
4618 Connection: close\r\n\r\nabcd";
4619 const BUSY: &str = "HTTP/1.1 503 Slow Down\r\nRetry-After: 0\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
4620 const MISSING: &str = "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
4621
4622 fn serve(script: &[&'static str]) -> (String, Arc<AtomicU64>) {
4624 let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
4625 let url = format!("http://{}/file.mf4", listener.local_addr().unwrap());
4626 let script = Arc::new(Mutex::new(script.iter().copied().collect::<VecDeque<_>>()));
4627 let count = Arc::new(AtomicU64::new(0));
4628 let served = count.clone();
4629 std::thread::spawn(move || {
4630 for stream in listener.incoming() {
4631 let Ok(mut stream) = stream else { return };
4632 let mut head = Vec::new();
4633 let mut byte = [0u8; 1];
4634 while !head.ends_with(b"\r\n\r\n") && stream.read(&mut byte).unwrap_or(0) == 1 {
4635 head.push(byte[0]);
4636 }
4637 served.fetch_add(1, Ordering::SeqCst);
4638 let response = script.lock().unwrap().pop_front().unwrap_or(MISSING);
4639 let _ = stream.write_all(response.as_bytes());
4640 }
4641 });
4642 (url, count)
4643 }
4644
4645 #[test]
4646 fn transient_failures_are_retried() {
4647 let (url, count) = serve(&[BUSY, BUSY, OK]);
4648 let bytes = HttpRangeReader::new(url).unwrap().read_range(0, 4).unwrap();
4649 assert_eq!(bytes, b"abcd");
4650 assert_eq!(count.load(Ordering::SeqCst), 3);
4651 }
4652
4653 #[test]
4654 fn retries_are_bounded() {
4655 let (url, count) = serve(&[BUSY, BUSY, BUSY, BUSY, BUSY, OK]);
4656 let error = HttpRangeReader::new(url).unwrap().read_range(0, 4).unwrap_err().to_string();
4657 assert!(error.contains("503") && error.contains("gave up after 4 attempts"), "{error}");
4658 assert_eq!(count.load(Ordering::SeqCst), 4);
4659 }
4660
4661 #[test]
4662 fn permanent_failures_are_not_retried() {
4663 let (url, count) = serve(&[MISSING, OK]);
4664 let error = HttpRangeReader::new(url).unwrap().read_range(0, 4).unwrap_err().to_string();
4665 assert!(error.contains("404"), "{error}");
4666 assert_eq!(count.load(Ordering::SeqCst), 1);
4667 }
4668}
4669
4670#[cfg(all(test, feature = "http"))]
4671mod url_read_tests {
4672 use super::{DataBlockInfo, MdfIndex, Window};
4673 use crate::fragments::{FragmentStore, RecordingRangeReader};
4674 use crate::{ColumnData, Mdf, MdfWriter, ReadOptions};
4675 use std::io::{BufRead, BufReader, Write};
4676 use std::sync::Arc;
4677
4678 fn serve(bytes: Vec<u8>) -> String {
4680 let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
4681 let url = format!("http://{}/f.mf4", listener.local_addr().unwrap());
4682 let bytes = Arc::new(bytes);
4683 std::thread::spawn(move || {
4684 for stream in listener.incoming() {
4685 let Ok(stream) = stream else { return };
4686 let bytes = bytes.clone();
4687 std::thread::spawn(move || {
4688 let mut reader = BufReader::new(stream.try_clone().unwrap());
4689 let mut stream = stream;
4690 loop {
4691 let mut range = None;
4692 let mut line = String::new();
4693 loop {
4694 line.clear();
4695 if reader.read_line(&mut line).unwrap_or(0) == 0 {
4696 return;
4697 }
4698 if line == "\r\n" {
4699 break;
4700 }
4701 if let Some(v) = line.to_ascii_lowercase().strip_prefix("range: bytes=") {
4702 let (a, b) = v.trim().split_once('-').unwrap();
4703 range = Some((a.parse::<usize>().unwrap(), b.parse::<usize>().unwrap()));
4704 }
4705 }
4706 let (a, b) = range.unwrap_or((0, bytes.len() - 1));
4707 let b = b.min(bytes.len() - 1);
4708 let head = format!(
4709 "HTTP/1.1 206 Partial Content\r\nContent-Range: bytes {a}-{b}/{}\r\nContent-Length: {}\r\n\r\n",
4710 bytes.len(),
4711 b + 1 - a
4712 );
4713 let mut response = head.into_bytes();
4716 response.extend_from_slice(&bytes[a..=b]);
4717 if stream.write_all(&response).is_err() {
4718 return;
4719 }
4720 }
4721 });
4722 }
4723 });
4724 url
4725 }
4726
4727 fn build(path: &std::path::Path) {
4728 let mut w = MdfWriter::new(path.to_str().unwrap()).unwrap();
4729 w.init_mdf_file().unwrap();
4730 let g = w.add_channel_group(Some("G")).unwrap();
4731 w.add_time_channel(&g, "t").unwrap();
4732 let a = w.add_float_channel(&g, "A").unwrap();
4733 w.add_float_channel(&g, "B").unwrap();
4734 w.add_linear_conversion(&a, 1.0, 2.0).unwrap();
4735 let n = 300_000;
4736 let t: Vec<f64> = (0..n).map(|i| i as f64 * 1e-3).collect();
4737 let x: Vec<f64> = (0..n).map(|i| (i % 977) as f64).collect();
4738 w.start_data_block(&g).unwrap();
4739 w.write_columns(&g, &[ColumnData::F64(&t), ColumnData::F64(&x), ColumnData::F64(&x)]).unwrap();
4740 w.finish_data_block(&g).unwrap();
4741 w.finalize().unwrap();
4742 }
4743
4744 #[test]
4748 fn streamed_and_batched_whole_reads_agree() {
4749 let dir = tempfile::tempdir().unwrap();
4750 let (row, col) = (dir.path().join("row.mf4"), dir.path().join("col.mf4"));
4751 build(&row);
4752 let opts = crate::ColumnOptions { block_size: 256 * 1024, ..Default::default() };
4753 crate::to_column_oriented(&row, &col, &opts).unwrap();
4754 for path in [&row, &col] {
4755 let mdf = Mdf::from_file(path.to_str().unwrap()).unwrap();
4756 let index = MdfIndex::from_file(path.to_str().unwrap()).unwrap();
4757 assert!(index.channel_groups.iter().any(|g| g.data_blocks.len() > 1), "several data blocks");
4758 let url = serve(std::fs::read(path).unwrap());
4759 let names = ["A", "t", "B", "A"];
4760 let targets = index.locate_all(&names, None).unwrap();
4761 let option_sets = [
4762 ReadOptions::new(),
4763 ReadOptions::new().raw(true),
4764 ReadOptions::new().time(Some(12.5), Some(250.0)),
4765 ReadOptions::new().time(Some(100.0), None).raw(true),
4766 ReadOptions::new().records(1000, 150_000),
4767 ];
4768 for options in &option_sets {
4769 let want = mdf.read_many(&names, options).unwrap();
4770 let window = options.window().unwrap();
4771 for limit in [0, u64::MAX] {
4772 let got = index.read_many_url_limited(&url, &targets, window, options.raw, limit).unwrap();
4773 for (g, w) in got.iter().zip(&want) {
4774 assert_eq!((&g.values, &g.timestamps), (&w.values, &w.timestamps), "limit {limit} {options:?}");
4775 }
4776 if window != Window::All {
4778 for (&(g, c), name) in targets.iter().zip(names) {
4779 let got = index.values_window_url(&url, g, c, window, options.raw, limit).unwrap();
4780 let want = mdf.values(name, options).unwrap();
4781 assert_eq!(format!("{got:?}"), format!("{want:?}"), "values limit {limit} {options:?}");
4782 }
4783 }
4784 }
4785 }
4786 }
4787 }
4788
4789 #[test]
4791 fn probing_whole_reads_record_every_section() {
4792 let blocks: Vec<DataBlockInfo> = [0u64, 10_000, 20_000]
4793 .iter()
4794 .map(|&o| DataBlockInfo { file_offset: o, size: 24 + 800, is_compressed: false })
4795 .collect();
4796 let store = FragmentStore::new();
4797 let mut reader = RecordingRangeReader { store: &store, misses: Vec::new(), whole_request: true };
4798 let result = MdfIndex::for_each_data_section(&mut reader, &blocks, |_| Ok(()));
4799 assert!(result.is_err());
4800 assert_eq!(reader.misses, vec![(0, 824), (10_000, 824), (20_000, 824)]);
4801 }
4802}