korri-n2k 0.7.1

no_std-first NMEA 2000 protocol stack for embedded and Linux systems
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
//! Generic serialization/deserialization engine driven by compile-time PGN descriptors.
//! It controls the bit-level readers/writers and turns dynamic `PgnValue`s into
//! strongly typed domain structures.
use super::bits::{BitReader, BitWriter};
use super::traits::FieldAccess;
use crate::core::{FieldDescriptor, FieldKind, PgnBytes, PgnDescriptor, PgnValue, MAX_PGN_BYTES};
use crate::error::{CodecError, DeserializationError, SerializationError};

/// Deserializes a payload into a generic PGN struct `T`.
// WARNING: tightly coupled with the `map_type()` function in build.rs.
// Keep both locations in sync when making changes.
///
/// # Parameters
/// * `instance` – object to populate field by field
/// * `payload` – raw buffer received from the CAN bus
/// * `descriptor` – static descriptor that defines the PGN layout
///
/// # Return value
/// Returns `Ok(())` when every field is read and assigned correctly.
pub fn deserialize_into<T: FieldAccess>(
    instance: &mut T,
    payload: &[u8],
    descriptor: &'static PgnDescriptor,
) -> Result<(), DeserializationError> {
    let mut reader = BitReader::new(payload);

    // Helper to detect whether a field belongs to a repeating group
    let is_repetitive_field = |field_idx: usize| -> bool {
        for rfs in descriptor.repeating_field_sets {
            if field_idx >= rfs.start_field_index && field_idx < (rfs.start_field_index + rfs.size)
            {
                return true;
            }
        }
        false
    };

    for (field_idx, field_desc) in descriptor.fields.iter().enumerate() {
        // Skip fields that belong to repeating groups; they are handled later
        if is_repetitive_field(field_idx) {
            continue;
        }

        if let Some(value) = read_field_value(&mut reader, field_desc)? {
            instance.field_mut(field_desc.id, value).ok_or(
                DeserializationError::FieldAssignmentFailed {
                    desc: field_desc.id,
                },
            )?
        }
    }

    // ==================== Repeating field handling ====================
    // After processing all regular fields, handle repeating groups
    for rfs in descriptor.repeating_field_sets {
        // 1. Read the counter field to know how many elements to expect
        let count = if let Some(counter_idx) = rfs.count_field_index {
            // The counter is a regular field already parsed; retrieve it via the descriptor
            let counter_field = descriptor
                .fields
                .get(counter_idx)
                .ok_or(DeserializationError::InvalidDataLength)?;

            // Fetch the counter value from the instance
            let raw = match instance.field(counter_field.id) {
                Some(PgnValue::U8(v)) => v as usize,
                Some(PgnValue::U16(v)) => v as usize,
                Some(PgnValue::U32(v)) => v as usize,
                _ => return Err(DeserializationError::InvalidDataLength),
            };

            // An all-ones counter is the N2K "not available" sentinel, not a
            // count. A GNSS receiver with no DGNSS station sends 0xFF here, and
            // reading it literally rejected every real 129029 on the bus.
            let counter_bits = counter_field.bits_length.unwrap_or(8).min(64);
            let unavailable = (u64::MAX >> (64 - counter_bits)) as usize;
            if raw == unavailable {
                0
            } else {
                raw
            }
        } else {
            // No explicit counter: would require computing the length on the fly.
            // This branch is not supported yet because the scenario is uncommon.
            return Err(DeserializationError::UnsupportedFieldKind {
                field_kind: crate::core::FieldKind::Unimplemented,
            });
        };

        // Clamp against the storage available, then against the payload itself:
        // a group announcing more repetitions than the frame carries should yield
        // the ones that are there, not discard the scalar fields already parsed.
        let group_bits: usize = descriptor
            .fields
            .iter()
            .skip(rfs.start_field_index)
            .take(rfs.size)
            .map(|f| f.bits_length.unwrap_or(0) as usize)
            .sum();
        let fits = reader.bits_remaining().checked_div(group_bits).unwrap_or(0);
        let count = count.min(rfs.max_repetitions).min(fits);

        // 2. Set the number of valid elements through the FieldAccess trait
        instance
            .set_repetitive_count(rfs.array_id, count)
            .ok_or(DeserializationError::FieldAssignmentFailed { desc: rfs.array_id })?;

        // 3. Iterate through every element of the repeating group
        for elem_idx in 0..count {
            // For each field in the group
            for field_offset in 0..rfs.size {
                let field_idx = rfs.start_field_index + field_offset;
                let field_desc = descriptor
                    .fields
                    .get(field_idx)
                    .ok_or(DeserializationError::InvalidDataLength)?;

                if let Some(value) = read_field_value(&mut reader, field_desc)? {
                    // Write the value into the array entry through FieldAccess
                    instance
                        .repetitive_field_mut(rfs.array_id, elem_idx, field_desc.id, value)
                        .ok_or(DeserializationError::FieldAssignmentFailed {
                            desc: field_desc.id,
                        })?;
                }
            }
        }
    }

    Ok(())
}

/// Serializes a PGN struct `T` into a buffer.
///
/// # Parameters
/// * `pgn_instance` – domain instance ready to convert into a raw payload
/// * `buffer` – output buffer (8 bytes for single frames, larger for Fast Packet)
/// * `descriptor` – static PGN metadata
///
/// # Return value
/// Number of bytes written into the buffer.
pub fn serialize<T: FieldAccess>(
    pgn_instance: &T,
    buffer: &mut [u8],
    descriptor: &'static PgnDescriptor,
) -> Result<usize, SerializationError> {
    // Initialize buffer with 0xFF for reserved bits.
    buffer.fill(0xFF);

    let mut writer = BitWriter::new(buffer);

    // Helper to detect whether a field belongs to a repeating group
    let is_repetitive_field = |field_idx: usize| -> bool {
        for rfs in descriptor.repeating_field_sets {
            if field_idx >= rfs.start_field_index && field_idx < (rfs.start_field_index + rfs.size)
            {
                return true;
            }
        }
        false
    };

    for (field_idx, field_desc) in descriptor.fields.iter().enumerate() {
        // Skip repeating fields; they are processed afterwards
        if is_repetitive_field(field_idx) {
            continue;
        }

        let value = pgn_instance
            .field(field_desc.id)
            .ok_or(SerializationError::FieldNotFound {
                field_id: field_desc.id,
            })?;
        write_field(&mut writer, field_desc, &value)?;
    }

    // ==================== Repeating field serialization ====================
    // After writing regular fields, serialize the repeating groups
    for rfs in descriptor.repeating_field_sets {
        // 1. Retrieve the number of valid elements for the array
        let count = pgn_instance.repetitive_count(rfs.array_id).ok_or(
            SerializationError::FieldNotFound {
                field_id: rfs.array_id,
            },
        )?;

        // 2. Clamp the counter against the allowed maximum
        let count = count.min(rfs.max_repetitions);

        // 3. Serialize every element of the repeating group
        for elem_idx in 0..count {
            // For each field in the group
            for field_offset in 0..rfs.size {
                let field_idx = rfs.start_field_index + field_offset;
                let field_desc = descriptor
                    .fields
                    .get(field_idx)
                    .ok_or(SerializationError::InvalidData)?;

                // Fetch the value from the structure via the trait
                let value = pgn_instance
                    .repetitive_field(rfs.array_id, elem_idx, field_desc.id)
                    .ok_or(SerializationError::FieldNotFound {
                        field_id: field_desc.id,
                    })?;

                // Write the value into the buffer
                write_field(&mut writer, field_desc, &value)?;
            }
        }
    }

    let bits_written = writer.bit_cursor();

    Ok(bits_written.div_ceil(8))
}

/// Shared helper to read a single field, applying business logic (signedness,
/// resolutions, special formats, etc.).
fn read_field_value(
    reader: &mut BitReader,
    field_desc: &'static FieldDescriptor,
) -> Result<Option<PgnValue>, DeserializationError> {
    match field_desc.kind {
        // BitLookup: bitfield where each bit has its own meaning (bitmask).
        // Always treated as an unsigned integer without resolution regardless of descriptor.
        // Multiple bits may be set simultaneously (unlike Lookup, which is exclusive).
        FieldKind::BitLookup => {
            let raw_val = if let Some(bits) = field_desc.bits_length {
                match reader.read_u64(bits as u8) {
                    Ok(val) => val,
                    Err(_) => return Err(DeserializationError::InvalidDataLength),
                }
            } else {
                return Err(DeserializationError::InvalidDataLength);
            };

            // Map the raw value to the appropriate type based on bit length
            // (always unsigned and without resolution)
            let value = match field_desc.bits_length {
                Some(1..=8) => PgnValue::U8(raw_val as u8),
                Some(9..=16) => PgnValue::U16(raw_val as u16),
                Some(17..=32) => PgnValue::U32(raw_val as u32),
                _ => PgnValue::U64(raw_val),
            };

            Ok(Some(value))
        }

        FieldKind::Number
        | FieldKind::Lookup
        | FieldKind::IndirectLookup
        | FieldKind::Pgn
        | FieldKind::IsoName => {
            let raw_val = if let Some(bits) = field_desc.bits_length {
                match reader.read_u64(bits as u8) {
                    Ok(val) => val,
                    Err(_) => return Err(DeserializationError::InvalidDataLength),
                }
            } else {
                return Err(DeserializationError::InvalidDataLength);
            };

            let value = if field_desc.is_signed.is_some_and(|s| s) {
                let signed_val = sign_extend(raw_val, field_desc.bits_length.unwrap_or(0) as u8);
                if let Some(res) = field_desc.resolution {
                    match field_desc
                        .bits_length
                        .ok_or(DeserializationError::InvalidDataLength)?
                    {
                        1..=24 => PgnValue::F32(signed_val as f32 * res),
                        _ => PgnValue::F64(signed_val as f64 * res as f64),
                    }
                } else {
                    match field_desc.bits_length {
                        Some(1..=8) => PgnValue::I8(signed_val as i8),
                        Some(9..=16) => PgnValue::I16(signed_val as i16),
                        Some(17..=32) => PgnValue::I32(signed_val as i32),
                        _ => PgnValue::I64(signed_val),
                    }
                }
            } else if let Some(res) = field_desc.resolution {
                match field_desc
                    .bits_length
                    .ok_or(DeserializationError::InvalidDataLength)?
                {
                    1..=24 => PgnValue::F32(raw_val as f32 * res),
                    _ => PgnValue::F64(raw_val as f64 * res as f64),
                }
            } else {
                match field_desc.bits_length {
                    Some(1..=8) => PgnValue::U8(raw_val as u8),
                    Some(9..=16) => PgnValue::U16(raw_val as u16),
                    Some(17..=32) => PgnValue::U32(raw_val as u32),
                    _ => PgnValue::U64(raw_val),
                }
            };

            Ok(Some(value))
        }

        // IEEE-754 single precision, carried as raw bits. No resolution applies.
        FieldKind::Float => {
            let raw_val = reader
                .read_u64(32)
                .map_err(|e| DeserializationError::BitReaderError { err: e })?;
            Ok(Some(PgnValue::F32(f32::from_bits(raw_val as u32))))
        }

        FieldKind::Reserved | FieldKind::Spare => {
            if let Some(val) = field_desc.bits_length {
                reader
                    .advance(val as u8)
                    .map_err(|e| DeserializationError::BitReaderError { err: e })?;
            }
            Ok(None)
        }

        FieldKind::StringFix => {
            let num_bits = field_desc
                .bits_length
                .ok_or(DeserializationError::InvalidDataLength)?;
            // The declared size is the field's capacity, not the bytes on the wire:
            // Navico 130821 reserves 230 for its text and sends about 155, the real
            // length being carried by the Fast Packet header. Read what is there.
            let num_bytes = ((num_bits / 8) as usize).min(reader.bits_remaining() / 8);
            let slice = reader
                .read_slice(num_bytes)
                .map_err(|e| DeserializationError::BitReaderError { err: e })?;
            let mut pgn_bytes = PgnBytes {
                len: num_bytes,
                ..Default::default()
            };
            pgn_bytes.data[..num_bytes].copy_from_slice(slice);
            Ok(Some(PgnValue::Bytes(pgn_bytes)))
        }

        FieldKind::StringLz => {
            let strlen = reader
                .read_u8(8)
                .map_err(|e| DeserializationError::BitReaderError { err: e })?
                as usize;
            if strlen > MAX_PGN_BYTES {
                return Err(DeserializationError::InvalidDataLength);
            }
            let mut pgn_bytes = PgnBytes::default();
            if strlen > 0 {
                let slice = reader
                    .read_slice(strlen)
                    .map_err(|e| DeserializationError::BitReaderError { err: e })?;
                pgn_bytes.copy_from_slice(slice);
            }
            pgn_bytes.len = strlen;
            Ok(Some(PgnValue::Bytes(pgn_bytes)))
        }

        FieldKind::StringLau => {
            let total_len = reader
                .read_u8(8)
                .map_err(|e| DeserializationError::BitReaderError { err: e })?
                as usize;
            if total_len > MAX_PGN_BYTES {
                return Err(DeserializationError::InvalidDataLength);
            }
            let mut pgn_bytes = PgnBytes::default();
            // Below two bytes there is no room for the encoding byte: the field is
            // empty and nothing follows the length itself.
            if total_len >= 2 {
                let encoding = reader
                    .read_u8(8)
                    .map_err(|e| DeserializationError::BitReaderError { err: e })?;
                pgn_bytes.data[0] = encoding;
                // The declared length counts itself and the encoding byte, so the
                // text is two bytes shorter. Reading one byte too many swallowed
                // the following field and derailed the rest of the message.
                let payload_len = total_len.saturating_sub(2);
                if payload_len > 0 {
                    let slice = reader
                        .read_slice(payload_len)
                        .map_err(|e| DeserializationError::BitReaderError { err: e })?;
                    pgn_bytes.data[1..1 + payload_len].copy_from_slice(slice);
                }
                pgn_bytes.len = 1 + payload_len;
            }
            Ok(Some(PgnValue::Bytes(pgn_bytes)))
        }

        FieldKind::Binary => {
            let num_bits =
                field_desc
                    .bits_length
                    .ok_or(DeserializationError::InvalidFieldBits {
                        field_name: field_desc.id,
                    })?;
            // A BINARY field that does not fill whole bytes is a scalar, not a
            // buffer — that is how the generator types it too. AIS 129038/129039
            // carry a 19-bit `CommunicationState` this way.
            if num_bits % 8 != 0 {
                let raw_val = reader
                    .read_u64(num_bits as u8)
                    .map_err(|e| DeserializationError::BitReaderError { err: e })?;
                return Ok(Some(match num_bits {
                    1..=8 => PgnValue::U8(raw_val as u8),
                    9..=16 => PgnValue::U16(raw_val as u16),
                    17..=32 => PgnValue::U32(raw_val as u32),
                    _ => PgnValue::U64(raw_val),
                }));
            }
            let num_bytes = (num_bits / 8) as usize;
            let slice = reader
                .read_slice(num_bytes)
                .map_err(|e| DeserializationError::BitReaderError { err: e })?;
            let mut pgn_bytes = PgnBytes {
                len: num_bytes,
                ..Default::default()
            };
            pgn_bytes.data[..num_bytes].copy_from_slice(slice);
            Ok(Some(PgnValue::Bytes(pgn_bytes)))
        }

        FieldKind::Date | FieldKind::Mmsi => {
            let raw_val = if let Some(value) = field_desc.bits_length {
                reader
                    .read_u64(value as u8)
                    .map_err(|e| DeserializationError::BitReaderError { err: e })?
            } else {
                return Err(DeserializationError::InvalidFieldBits {
                    field_name: field_desc.id,
                });
            };
            let value = if let Some(res) = field_desc.resolution {
                let scaled = raw_val as f64 * res as f64;
                match field_desc.bits_length.unwrap() {
                    1..=24 => PgnValue::F32(scaled as f32),
                    _ => PgnValue::F64(scaled),
                }
            } else {
                match field_desc.bits_length.unwrap() {
                    16 => PgnValue::U16(raw_val as u16),
                    32 => PgnValue::U32(raw_val as u32),
                    _ => {
                        return Err(DeserializationError::InvalidFieldBits {
                            field_name: field_desc.id,
                        })
                    }
                }
            };
            Ok(Some(value))
        }

        FieldKind::Duration => {
            let raw_val = if let Some(value) = field_desc.bits_length {
                reader
                    .read_u64(value as u8)
                    .map_err(|e| DeserializationError::BitReaderError { err: e })?
            } else {
                return Err(DeserializationError::InvalidFieldBits {
                    field_name: field_desc.id,
                });
            };

            let value = if let Some(res) = field_desc.resolution {
                let scaled = raw_val as f64 * res as f64;
                match field_desc.bits_length.unwrap() {
                    1..=24 => PgnValue::F32(scaled as f32),
                    _ => PgnValue::F64(scaled),
                }
            } else {
                match field_desc.bits_length.unwrap() {
                    1..=16 => PgnValue::U16(raw_val as u16),
                    17..=32 => PgnValue::U32(raw_val as u32),
                    _ => PgnValue::U64(raw_val),
                }
            };
            Ok(Some(value))
        }

        FieldKind::Time => {
            let raw_val = if let Some(value) = field_desc.bits_length {
                reader
                    .read_u64(value as u8)
                    .map_err(|e| DeserializationError::BitReaderError { err: e })?
            } else {
                return Err(DeserializationError::InvalidFieldBits {
                    field_name: field_desc.id,
                });
            };

            let value = if let Some(res) = field_desc.resolution {
                let scaled = raw_val as f64 * res as f64;
                PgnValue::F64(scaled)
            } else {
                PgnValue::U64(raw_val)
            };
            Ok(Some(value))
        }

        // Other kinds are not supported yet
        _ => Err(DeserializationError::UnsupportedFieldKind {
            field_kind: field_desc.kind,
        }),
    }
}

/// Private helper that writes a single value according to its descriptor.
/// Encapsulates all business rules tied to `FieldKind` (signed/unsigned,
/// lookup, strings, binary blocks, etc.).
fn write_field(
    writer: &mut BitWriter,
    field_desc: &'static FieldDescriptor,
    value: &PgnValue,
) -> Result<(), SerializationError> {
    match field_desc.kind {
        FieldKind::Number | FieldKind::Pgn | FieldKind::IsoName => {
            let bits_to_write = if field_desc.is_signed.is_some_and(|s| s) {
                let prepared_val = if let Some(res) = field_desc.resolution {
                    // Common path: floating-point value that must be scaled back to an integer
                    let float_val = pgn_value_to_f64(value)
                        .map_err(|e| SerializationError::CodecError { source: e })?;
                    scale_to_i64(float_val, res)
                } else {
                    pgn_value_to_i64(value)
                        .map_err(|e| SerializationError::CodecError { source: e })?
                };
                // Use the helper to reinterpret the signed integer as u64
                i64_to_u64_bitwise(prepared_val)
            } else if let Some(res) = field_desc.resolution {
                let float_val = pgn_value_to_f64(value)
                    .map_err(|e| SerializationError::CodecError { source: e })?;
                i64_to_u64_bitwise(scale_to_i64(float_val, res))
            } else {
                pgn_value_to_u64(value).map_err(|e| SerializationError::CodecError { source: e })?
            };

            if let Some(bit_length) = field_desc.bits_length {
                writer
                    .write_u64(bits_to_write, bit_length as u8)
                    .map_err(|e| SerializationError::BitWriteError { err: e })?;
            } else {
                return Err(SerializationError::InvalidData);
            };
        }

        FieldKind::Date | FieldKind::Time | FieldKind::Mmsi => {
            let bits_to_write =
                field_desc
                    .bits_length
                    .ok_or(SerializationError::InvalidFieldBits {
                        field_name: field_desc.id,
                    })?;

            let int_val = if field_desc.resolution.is_some_and(|res| res as u8 != 1) {
                // With resolution: value stored as F32/F64
                let float_val = pgn_value_to_f64(value)
                    .map_err(|e| SerializationError::CodecError { source: e })?;
                scale_to_i64(float_val, field_desc.resolution.unwrap()) as u64 // Direct cast; two's-complement helper not required
            } else {
                // Without resolution: value stored as U16/U32
                pgn_value_to_u64(value).map_err(|e| SerializationError::CodecError { source: e })?
            };

            writer
                .write_u64(int_val, bits_to_write as u8)
                .map_err(|e| SerializationError::BitWriteError { err: e })?;
        }

        FieldKind::Duration => {
            // Treat as a Number with resolution
            let bits_to_write =
                field_desc
                    .bits_length
                    .ok_or(SerializationError::InvalidFieldBits {
                        field_name: field_desc.id,
                    })?;

            let prepared_val = if let Some(res) = field_desc.resolution {
                // Apply the inverse resolution
                let float_val = pgn_value_to_f64(value)
                    .map_err(|e| SerializationError::CodecError { source: e })?;
                scale_to_i64(float_val, res) as u64
            } else {
                // No resolution involved
                pgn_value_to_u64(value).map_err(|e| SerializationError::CodecError { source: e })?
            };

            writer
                .write_u64(prepared_val, bits_to_write as u8)
                .map_err(|e| SerializationError::BitWriteError { err: e })?;
        }
        FieldKind::Lookup => {
            let int_val = pgn_value_to_u64(value)
                .map_err(|e| SerializationError::CodecError { source: e })?;
            if let Some(bit_len) = field_desc.bits_length {
                writer
                    .write_u64(int_val, bit_len as u8)
                    .map_err(|e| SerializationError::BitWriteError { err: e })?;
            };
        }

        // BitLookup: write a bitmask (unsigned integer without resolution).
        // Each bit carries its own meaning and multiple bits may be active simultaneously.
        // Handling is identical to Lookup but documented separately for clarity.
        FieldKind::BitLookup => {
            let int_val = pgn_value_to_u64(value)
                .map_err(|e| SerializationError::CodecError { source: e })?;

            let bit_len = field_desc
                .bits_length
                .ok_or(SerializationError::InvalidFieldBits {
                    field_name: field_desc.id,
                })?;

            writer
                .write_u64(int_val, bit_len as u8)
                .map_err(|e| SerializationError::BitWriteError { err: e })?;
        }
        FieldKind::IndirectLookup => {
            // Value is received as a combined u16 (high + low byte).
            let combined_value = pgn_value_to_u64(value)
                .map_err(|e| SerializationError::CodecError { source: e })?
                as u16;
            // Only the low byte belongs to this field; the master field writes the high byte.
            let value_to_write = (combined_value & 0x00FF) as u64;

            if let Some(bit_len) = field_desc.bits_length {
                writer
                    .write_u64(value_to_write, bit_len as u8)
                    .map_err(|e| SerializationError::BitWriteError { err: e })?;
            };
        }
        FieldKind::Spare => {
            if let Some(bit_len) = field_desc.bits_length {
                writer
                    .write_u64(0, bit_len as u8)
                    .map_err(|e| SerializationError::BitWriteError { err: e })?;
            }
        }

        // Mirror of the read path: raw IEEE-754 bits, no resolution.
        FieldKind::Float => {
            let val = pgn_value_to_f64(value)
                .map_err(|e| SerializationError::CodecError { source: e })?;
            writer
                .write_u64((val as f32).to_bits() as u64, 32)
                .map_err(|e| SerializationError::BitWriteError { err: e })?;
        }

        FieldKind::Reserved => {
            if let Some(bit_len) = field_desc.bits_length {
                writer
                    .advance(bit_len as u8)
                    .map_err(|e| SerializationError::BitWriteError { err: e })?
            }
        }

        FieldKind::StringFix => {
            if let PgnValue::Bytes(val) = value {
                writer
                    .write_slice(&val.data[..val.len])
                    .map_err(|e| SerializationError::BitWriteError { err: e })?;
            } else {
                return Err(SerializationError::CodecError {
                    source: CodecError::DataTypeMismatch {
                        value_kind: value.kind(),
                        func: "write_field // StringFix",
                    },
                });
            }
        }
        FieldKind::StringLz => {
            if let PgnValue::Bytes(val) = value {
                if val.len > u8::MAX as usize {
                    return Err(SerializationError::InvalidData);
                }
                writer
                    .write_u64(val.len as u64, 8)
                    .map_err(|e| SerializationError::BitWriteError { err: e })?;
                if val.len > 0 {
                    writer
                        .write_slice(&val.data[..val.len])
                        .map_err(|e| SerializationError::BitWriteError { err: e })?;
                }
            } else {
                return Err(SerializationError::CodecError {
                    source: CodecError::DataTypeMismatch {
                        value_kind: value.kind(),
                        func: "write_field // StringLz",
                    },
                });
            }
        }
        FieldKind::StringLau => {
            if let PgnValue::Bytes(val) = value {
                // `val` holds the encoding byte followed by the text; the declared
                // length also counts the length byte itself. An empty field
                // declares zero, so that reading it back consumes one byte too.
                let declared = if val.len == 0 { 0 } else { val.len + 1 };
                if declared > u8::MAX as usize {
                    return Err(SerializationError::InvalidData);
                }
                writer
                    .write_u64(declared as u64, 8)
                    .map_err(|e| SerializationError::BitWriteError { err: e })?;
                if val.len > 0 {
                    writer
                        .write_u64(val.data[0] as u64, 8)
                        .map_err(|e| SerializationError::BitWriteError { err: e })?;
                    if val.len > 1 {
                        writer
                            .write_slice(&val.data[1..val.len])
                            .map_err(|e| SerializationError::BitWriteError { err: e })?;
                    }
                }
            } else {
                return Err(SerializationError::CodecError {
                    source: CodecError::DataTypeMismatch {
                        value_kind: value.kind(),
                        func: "write_field // StringLau",
                    },
                });
            }
        }
        FieldKind::Binary => {
            let expected_bits =
                field_desc
                    .bits_length
                    .ok_or(SerializationError::InvalidFieldBits {
                        field_name: field_desc.id,
                    })?;

            // Mirror of the read path: a sub-byte BINARY field is a scalar.
            if expected_bits % 8 != 0 {
                let raw_val = pgn_value_to_u64(value)
                    .map_err(|e| SerializationError::CodecError { source: e })?;
                return writer
                    .write_u64(raw_val, expected_bits as u8)
                    .map_err(|e| SerializationError::BitWriteError { err: e });
            }

            if let PgnValue::Bytes(val) = value {
                let expected_len = (expected_bits / 8) as usize;
                if val.len != expected_len {
                    return Err(SerializationError::InvalidData);
                }
                writer
                    .write_slice(&val.data[..expected_len])
                    .map_err(|e| SerializationError::BitWriteError { err: e })?;
            } else {
                return Err(SerializationError::CodecError {
                    source: CodecError::DataTypeMismatch {
                        value_kind: value.kind(),
                        func: "write_field // Binary",
                    },
                });
            }
        }
        _ => return Err(SerializationError::UnsupportedFieldKind),
    }
    Ok(())
}

/// Undoes a field's resolution, rounding half away from zero.
/// Truncating instead would shift every scaled value one LSB towards zero:
/// 23.767 at a resolution of 0.001 divides to 23766.999… and came back as 23.766.
/// `f64::round` lives in `std`, which this crate does not have.
fn scale_to_i64(value: f64, resolution: f32) -> i64 {
    let scaled = value / resolution as f64;
    if scaled >= 0.0 {
        (scaled + 0.5) as i64
    } else {
        (scaled - 0.5) as i64
    }
}

/// Converts a `PgnValue` into `f64`.
/// Normalizes values to double precision when a resolution must be applied during serialization.
fn pgn_value_to_f64(value: &PgnValue) -> Result<f64, CodecError> {
    match value {
        PgnValue::F64(v) => Ok(*v),
        PgnValue::F32(v) => Ok(*v as f64),
        PgnValue::I64(v) => Ok(*v as f64),
        PgnValue::I32(v) => Ok(*v as f64),
        PgnValue::I16(v) => Ok(*v as f64),
        PgnValue::I8(v) => Ok(*v as f64),
        _ => Err(CodecError::DataTypeMismatch {
            value_kind: value.kind(),
            func: "pgn_value_to_f64",
        }),
    }
}

/// Converts a `PgnValue` into `i64`.
/// Used to serialize signed fields while handling implicit widening from smaller integer sizes.
fn pgn_value_to_i64(value: &PgnValue) -> Result<i64, CodecError> {
    match value {
        PgnValue::I64(v) => Ok(*v),
        PgnValue::I32(v) => Ok(*v as i64),
        PgnValue::I16(v) => Ok(*v as i64),
        PgnValue::I8(v) => Ok(*v as i64),
        _ => Err(CodecError::DataTypeMismatch {
            value_kind: value.kind(),
            func: "pgn_value_to_i64",
        }),
    }
}

/// Converts a `PgnValue` into `u64`.
/// Covers unsigned variants; anything else indicates a misuse of the descriptor.
fn pgn_value_to_u64(value: &PgnValue) -> Result<u64, CodecError> {
    match value {
        PgnValue::U64(v) => Ok(*v),
        PgnValue::U32(v) => Ok(*v as u64),
        PgnValue::U16(v) => Ok(*v as u64),
        PgnValue::U8(v) => Ok(*v as u64),
        _ => Err(CodecError::DataTypeMismatch {
            value_kind: value.kind(),
            func: "pgn_value_to_u64",
        }),
    }
}

//==================================================================================

/// Two's complement helper.
/// Extends the sign of a value read on a limited number of bits.
/// If the sign bit is set, the function propagates it across the `i64` tail to rebuild the negative value.
/// Essential logic to reinterpret small integers (up to 64 bits) into `i64` without losing information.
fn sign_extend(value: u64, bits: u8) -> i64 {
    // Reading the full 64 bits already yields the correct representation.
    if bits >= 64 {
        return value as i64;
    }

    // Locate the sign bit.
    let sign_bit_mask = 1u64 << (bits - 1);

    // Check whether the sign bit is set.
    if (value & sign_bit_mask) != 0 {
        // Extend the sign by filling the upper bits with ones.
        let extension_mask = u64::MAX << bits;
        (value | extension_mask) as i64
    } else {
        // Positive values are returned as-is.
        value as i64
    }
}

/// Reinterprets the bits of an `i64` as `u64` for writing.
/// Negative `i64` values are already stored in two's complement, so the bits can be reused verbatim.
/// Keeps the bitwise `as` cast in a single helper to simplify debugging and reviews.
/// The `inline` annotation avoids the overhead of a function call for a trivial conversion.
#[inline] // The function is tiny; encourage inlining.
fn i64_to_u64_bitwise(value: i64) -> u64 {
    value as u64
}

//==================================================================================TESTS

#[cfg(test)]
#[path = "tests.rs"]
mod tests;