1use crate::blocks::channel_block::ChannelBlock;
2use crate::blocks::common::DataType;
3use byteorder::{LittleEndian, BigEndian, ByteOrder};
4
5const CN_FLAG_ALL_INVALID: u32 = 0x01; const CN_FLAG_INVAL_BIT_VALID: u32 = 0x02; const MAX_INTEGER_BITS: usize = 64;
12
13#[inline(always)]
17fn bits_le(slice: &[u8], bit_offset: usize, bit_count: usize) -> u64 {
18 let raw = slice.iter().rev().fold(0u128, |acc, &b| (acc << 8) | b as u128);
19 mask_bits((raw >> bit_offset) as u64, bit_count)
20}
21
22#[inline(always)]
24fn bits_be(slice: &[u8], bit_offset: usize, bit_count: usize) -> u64 {
25 let raw = slice.iter().fold(0u128, |acc, &b| (acc << 8) | b as u128);
26 mask_bits((raw >> bit_offset) as u64, bit_count)
27}
28
29#[inline(always)]
30fn mask_bits(value: u64, bit_count: usize) -> u64 {
31 if bit_count >= 64 { value } else { value & ((1u64 << bit_count) - 1) }
32}
33
34#[inline(always)]
36fn sign_extend(value: u64, bit_count: usize) -> i64 {
37 let shift = 64 - bit_count.min(64) as u32;
38 ((value << shift) as i64) >> shift
39}
40
41pub(crate) fn vlsd_offset(channel: &ChannelBlock, record: &[u8], record_id_size: usize) -> Result<u64, crate::error::MdfError> {
44 let start = record_id_size + channel.byte_offset as usize;
45 let bit_offset = channel.bit_offset as usize;
46 let bit_count = channel.bit_count as usize;
47 let len = (bit_offset + bit_count).div_ceil(8);
48 match record.get(start..start + len) {
49 Some(field) if bit_count > 0 && bit_count <= MAX_INTEGER_BITS && bit_offset <= 7 => {
50 Ok(bits_le(field, bit_offset, bit_count))
51 }
52 Some(_) => Err(crate::error::MdfError::BlockSerializationError(format!(
53 "VLSD channel has a {bit_count}-bit offset field at bit offset {bit_offset}; \
54 the offset must be an integer of at most 64 bits"
55 ))),
56 None => Err(crate::error::MdfError::TooShortBuffer {
57 actual: record.len(),
58 expected: start + len,
59 file: file!(),
60 line: line!(),
61 }),
62 }
63}
64
65#[derive(Debug, Clone, PartialEq)]
67pub enum DecodedValue {
68 UnsignedInteger(u64),
69 SignedInteger(i64),
70 Float(f64),
71 String(String),
72 ByteArray(Vec<u8>),
73 MimeSample(Vec<u8>),
74 MimeStream(Vec<u8>),
75 Unknown,
76}
77
78#[derive(Debug, Clone, PartialEq)]
80pub struct DecodedChannelValue {
81 pub value: DecodedValue,
82 pub is_valid: bool,
83}
84
85pub fn check_value_validity(
101 record: &[u8],
102 record_id_size: usize,
103 cg_data_bytes: u32,
104 channel: &ChannelBlock,
105) -> bool {
106 if channel.flags & CN_FLAG_ALL_INVALID != 0 {
108 return false;
110 }
111
112 if channel.flags & (CN_FLAG_ALL_INVALID | CN_FLAG_INVAL_BIT_VALID) == 0 {
113 return true;
115 }
116
117 let inval_byte_offset = record_id_size + cg_data_bytes as usize
120 + (channel.pos_invalidation_bit >> 3) as usize;
121 let inval_bit_index = (channel.pos_invalidation_bit & 0x07) as usize;
122
123 if inval_byte_offset < record.len() {
124 let inval_byte = record[inval_byte_offset];
125 let bit_is_set = (inval_byte >> inval_bit_index) & 0x01 != 0;
126 !bit_is_set
128 } else {
129 true
131 }
132}
133
134pub fn decode_channel_value(
154 record: &[u8],
155 record_id_size: usize,
156 channel: &ChannelBlock,
157) -> Option<DecodedValue> {
158 decode_value_internal(record, record_id_size, channel)
159}
160
161pub fn decode_channel_value_with_validity(
177 record: &[u8],
178 record_id_size: usize,
179 cg_data_bytes: u32,
180 channel: &ChannelBlock,
181) -> Option<DecodedChannelValue> {
182 let value = decode_value_internal(record, record_id_size, channel)?;
183 let is_valid = check_value_validity(record, record_id_size, cg_data_bytes, channel);
184
185 Some(DecodedChannelValue { value, is_valid })
186}
187
188#[inline(always)]
192pub fn decode_f64_from_record(
193 record: &[u8],
194 record_id_size: usize,
195 channel: &ChannelBlock,
196) -> f64 {
197 let base_offset = record_id_size + channel.byte_offset as usize;
198 let bit_offset = channel.bit_offset as usize;
199 let bit_count = channel.bit_count as usize;
200
201 if channel.channel_type == 1 && channel.data != 0 {
203 return f64::NAN;
204 }
205
206 if bit_count == 0 || bit_offset > 7 || bit_count > MAX_INTEGER_BITS {
210 return f64::NAN;
211 }
212
213 let num_bytes = (bit_offset + bit_count).div_ceil(8).max(1);
214 if base_offset + num_bytes > record.len() {
215 return f64::NAN;
216 }
217 let slice = &record[base_offset..base_offset + num_bytes];
218
219 match &channel.data_type {
220 DataType::FloatLE => {
221 if bit_offset == 0 {
222 if bit_count == 64 {
223 return LittleEndian::read_f64(slice);
224 } else if bit_count == 32 {
225 return LittleEndian::read_f32(slice) as f64;
226 }
227 }
228 let raw = slice.iter().rev().fold(0u128, |acc, &b| (acc << 8) | b as u128);
231 let raw = (raw >> bit_offset) as u64;
232 if bit_count == 32 {
233 f32::from_bits(raw as u32) as f64
234 } else if bit_count == 64 {
235 f64::from_bits(raw)
236 } else {
237 f64::NAN
238 }
239 },
240 DataType::FloatBE => {
241 if bit_offset == 0 {
242 if bit_count == 64 {
243 return BigEndian::read_f64(slice);
244 } else if bit_count == 32 {
245 return BigEndian::read_f32(slice) as f64;
246 }
247 }
248 let raw = slice.iter().fold(0u128, |acc, &b| (acc << 8) | b as u128);
249 let raw = (raw >> bit_offset) as u64;
250 if bit_count == 32 {
251 f32::from_bits(raw as u32) as f64
252 } else if bit_count == 64 {
253 f64::from_bits(raw)
254 } else {
255 f64::NAN
256 }
257 },
258 DataType::UnsignedIntegerLE => {
259 if bit_offset == 0 {
260 match bit_count {
261 8 => return slice[0] as f64,
262 16 => return LittleEndian::read_u16(slice) as f64,
263 32 => return LittleEndian::read_u32(slice) as f64,
264 64 => return LittleEndian::read_u64(slice) as f64,
265 _ => {}
266 }
267 }
268 bits_le(slice, bit_offset, bit_count) as f64
269 },
270 DataType::UnsignedIntegerBE => {
271 if bit_offset == 0 {
272 match bit_count {
273 8 => return slice[0] as f64,
274 16 => return BigEndian::read_u16(slice) as f64,
275 32 => return BigEndian::read_u32(slice) as f64,
276 64 => return BigEndian::read_u64(slice) as f64,
277 _ => {}
278 }
279 }
280 bits_be(slice, bit_offset, bit_count) as f64
281 },
282 DataType::SignedIntegerLE => {
283 if bit_offset == 0 {
284 match bit_count {
285 8 => return (slice[0] as i8) as f64,
286 16 => return LittleEndian::read_i16(slice) as f64,
287 32 => return LittleEndian::read_i32(slice) as f64,
288 64 => return LittleEndian::read_i64(slice) as f64,
289 _ => {}
290 }
291 }
292 sign_extend(bits_le(slice, bit_offset, bit_count), bit_count) as f64
293 },
294 DataType::SignedIntegerBE => {
295 if bit_offset == 0 {
296 match bit_count {
297 8 => return (slice[0] as i8) as f64,
298 16 => return BigEndian::read_i16(slice) as f64,
299 32 => return BigEndian::read_i32(slice) as f64,
300 64 => return BigEndian::read_i64(slice) as f64,
301 _ => {}
302 }
303 }
304 sign_extend(bits_be(slice, bit_offset, bit_count), bit_count) as f64
305 },
306 _ => f64::NAN,
307 }
308}
309
310fn decode_value_internal(
315 record: &[u8],
316 record_id_size: usize,
317 channel: &ChannelBlock,
318) -> Option<DecodedValue> {
319
320 let base_offset = record_id_size + channel.byte_offset as usize;
322 let bit_offset = channel.bit_offset as usize;
323 let bit_count = channel.bit_count as usize;
324
325 let is_numeric = matches!(
326 channel.data_type,
327 DataType::UnsignedIntegerLE
328 | DataType::UnsignedIntegerBE
329 | DataType::SignedIntegerLE
330 | DataType::SignedIntegerBE
331 | DataType::FloatLE
332 | DataType::FloatBE
333 );
334
335 if is_numeric && (bit_count == 0 || bit_offset > 7 || bit_count > MAX_INTEGER_BITS) {
339 return None;
340 }
341
342 let slice: &[u8] = if channel.channel_type == 1 && channel.data != 0 {
343 if is_numeric {
347 let needed = (bit_offset + bit_count).div_ceil(8).max(1);
348 if record.len() < needed {
349 return None;
350 }
351 &record[..needed]
352 } else {
353 record
354 }
355 } else {
356 let num_bytes = if matches!(channel.data_type,
358 DataType::StringLatin1 | DataType::StringUtf8 | DataType::StringUtf16LE | DataType::StringUtf16BE |
359 DataType::ByteArray | DataType::MimeSample | DataType::MimeStream)
360 {
361 bit_count / 8
362 } else {
363 (bit_offset + bit_count).div_ceil(8).max(1)
364 };
365
366 if base_offset + num_bytes > record.len() {
367 return None;
368 }
369 &record[base_offset..base_offset + num_bytes]
370 };
371
372 match &channel.data_type {
373 DataType::UnsignedIntegerLE => {
374 if bit_offset == 0 {
375 match bit_count {
376 8 => return Some(DecodedValue::UnsignedInteger(slice[0] as u64)),
377 16 => return Some(DecodedValue::UnsignedInteger(LittleEndian::read_u16(slice) as u64)),
378 32 => return Some(DecodedValue::UnsignedInteger(LittleEndian::read_u32(slice) as u64)),
379 64 => return Some(DecodedValue::UnsignedInteger(LittleEndian::read_u64(slice))),
380 _ => {}
381 }
382 }
383 Some(DecodedValue::UnsignedInteger(bits_le(slice, bit_offset, bit_count)))
384 },
385 DataType::UnsignedIntegerBE => {
386 if bit_offset == 0 {
387 match bit_count {
388 8 => return Some(DecodedValue::UnsignedInteger(slice[0] as u64)),
389 16 => return Some(DecodedValue::UnsignedInteger(BigEndian::read_u16(slice) as u64)),
390 32 => return Some(DecodedValue::UnsignedInteger(BigEndian::read_u32(slice) as u64)),
391 64 => return Some(DecodedValue::UnsignedInteger(BigEndian::read_u64(slice))),
392 _ => {}
393 }
394 }
395 Some(DecodedValue::UnsignedInteger(bits_be(slice, bit_offset, bit_count)))
396 },
397 DataType::SignedIntegerLE => {
398 if bit_offset == 0 {
399 match bit_count {
400 8 => return Some(DecodedValue::SignedInteger(slice[0] as i8 as i64)),
401 16 => return Some(DecodedValue::SignedInteger(LittleEndian::read_i16(slice) as i64)),
402 32 => return Some(DecodedValue::SignedInteger(LittleEndian::read_i32(slice) as i64)),
403 64 => return Some(DecodedValue::SignedInteger(LittleEndian::read_i64(slice))),
404 _ => {}
405 }
406 }
407 Some(DecodedValue::SignedInteger(sign_extend(bits_le(slice, bit_offset, bit_count), bit_count)))
408 },
409 DataType::SignedIntegerBE => {
410 if bit_offset == 0 {
411 match bit_count {
412 8 => return Some(DecodedValue::SignedInteger(slice[0] as i8 as i64)),
413 16 => return Some(DecodedValue::SignedInteger(BigEndian::read_i16(slice) as i64)),
414 32 => return Some(DecodedValue::SignedInteger(BigEndian::read_i32(slice) as i64)),
415 64 => return Some(DecodedValue::SignedInteger(BigEndian::read_i64(slice))),
416 _ => {}
417 }
418 }
419 Some(DecodedValue::SignedInteger(sign_extend(bits_be(slice, bit_offset, bit_count), bit_count)))
420 },
421 DataType::FloatLE => {
422 if bit_offset == 0 {
423 if bit_count == 32 {
424 return Some(DecodedValue::Float(LittleEndian::read_f32(slice) as f64));
425 } else if bit_count == 64 {
426 return Some(DecodedValue::Float(LittleEndian::read_f64(slice)));
427 }
428 }
429 let raw = slice.iter().rev().fold(0u128, |acc, &b| (acc << 8) | b as u128);
432 let raw = (raw >> bit_offset) as u64;
433 if bit_count == 32 {
434 Some(DecodedValue::Float(f32::from_bits(raw as u32) as f64))
435 } else if bit_count == 64 {
436 Some(DecodedValue::Float(f64::from_bits(raw)))
437 } else {
438 None
439 }
440 },
441 DataType::FloatBE => {
442 if bit_offset == 0 {
443 if bit_count == 32 {
444 return Some(DecodedValue::Float(BigEndian::read_f32(slice) as f64));
445 } else if bit_count == 64 {
446 return Some(DecodedValue::Float(BigEndian::read_f64(slice)));
447 }
448 }
449 let raw = slice.iter().fold(0u128, |acc, &b| (acc << 8) | b as u128);
450 let raw = (raw >> bit_offset) as u64;
451 if bit_count == 32 {
452 Some(DecodedValue::Float(f32::from_bits(raw as u32) as f64))
453 } else if bit_count == 64 {
454 Some(DecodedValue::Float(f64::from_bits(raw)))
455 } else {
456 None
457 }
458 },
459 DataType::StringLatin1 => {
460 let end = slice.iter().position(|&b| b == 0).unwrap_or(slice.len());
464 let s: String = slice[..end].iter().map(|&b| b as char).collect();
465 Some(DecodedValue::String(s))
466 },
467 DataType::StringUtf8 => {
468 let end = slice.iter().position(|&b| b == 0).unwrap_or(slice.len());
469 match std::str::from_utf8(&slice[..end]) {
470 Ok(s) => Some(DecodedValue::String(s.to_string())),
471 Err(_) => Some(DecodedValue::String(String::from("<Invalid UTF8>")))
472 }
473 },
474 DataType::StringUtf16LE => {
475 let even = &slice[..slice.len() & !1];
478 let u16_data: Vec<u16> = even.chunks_exact(2)
479 .map(LittleEndian::read_u16)
480 .collect();
481 let end = u16_data.iter().position(|&u| u == 0).unwrap_or(u16_data.len());
482 match String::from_utf16(&u16_data[..end]) {
483 Ok(s) => Some(DecodedValue::String(s)),
484 Err(_) => Some(DecodedValue::String(String::from("<Invalid UTF16LE>")))
485 }
486 },
487 DataType::StringUtf16BE => {
488 let even = &slice[..slice.len() & !1];
489 let u16_data: Vec<u16> = even.chunks_exact(2)
490 .map(BigEndian::read_u16)
491 .collect();
492 let end = u16_data.iter().position(|&u| u == 0).unwrap_or(u16_data.len());
493 match String::from_utf16(&u16_data[..end]) {
494 Ok(s) => Some(DecodedValue::String(s)),
495 Err(_) => Some(DecodedValue::String(String::from("<Invalid UTF16BE>")))
496 }
497 },
498 DataType::ByteArray => Some(DecodedValue::ByteArray(slice.to_vec())),
499 DataType::MimeSample => Some(DecodedValue::MimeSample(slice.to_vec())),
500 DataType::MimeStream => Some(DecodedValue::MimeStream(slice.to_vec())),
501 _ => Some(DecodedValue::Unknown),
502 }
503}