deep_time/dt/to_bin_ccsds.rs
1use crate::{Dt, DtErr, DtErrKind, SEC_PER_DAYI64, Scale, an_err};
2
3impl Dt {
4 /// Maximum size needed for a CCSDS C & D (CUC) binary packet (with extended P-field).
5 pub const CCSDS_C_AND_D_MAX_SIZE: usize = 32;
6
7 /// Formats this [`Dt`] as a **CCSDS C (CUC – Unsegmented Time Code)** binary packet.
8 ///
9 /// Fully configurable for round-tripping with [`Dt::from_ccsds_cuc`].
10 /// Conforms to **CCSDS 301.0-B-4 §3.2 (Level 1)**, including full support for the
11 /// extended 2-byte P-field.
12 ///
13 /// - The time is always encoded on the **TAI** timescale (Code ID `001`).
14 /// - The `target` field of this [`Dt`] is ignored.
15 ///
16 /// ## Parameters
17 ///
18 /// - `n_coarse`: Number of bytes used for the coarse (integer) seconds since the
19 /// 1958 epoch. Must be in `1..=7`. The chosen value must be large enough to
20 /// represent the full time; otherwise the high-order bytes are silently
21 /// truncated. For example, a date in the year 2025 requires at least 4 bytes
22 /// (`n_coarse >= 4`), while 3 bytes is only sufficient for dates up to roughly
23 /// mid-1968.
24 /// - `n_frac`: Number of bytes used for the fractional seconds. Must be in `0..=10`.
25 /// Higher values provide greater sub-second precision, but values of `8` or
26 /// above may produce reduced accuracy when round-tripping due to internal
27 /// 128-bit integer limits.
28 /// - `extension`: If `true`, forces inclusion of the second P-field octet even
29 /// when it is not strictly required by the field sizes.
30 ///
31 /// ## Epoch
32 ///
33 /// Seconds are counted since **1958-01-01 00:00:00 TAI**.
34 ///
35 /// ## Returns
36 ///
37 /// `(buffer, len)` where `buffer` is a fixed-size array of length
38 /// [`CCSDS_C_AND_D_MAX_SIZE`] and `len` is the number of bytes written.
39 ///
40 /// ## Errors
41 ///
42 /// - [`DtErrKind::OutOfRange`] if `n_coarse` is not in `1..=7`, `n_frac > 10`,
43 /// or if this instant is before **1958-01-01 00:00:00 TAI** (the CUC epoch).
44 ///
45 /// ## See also
46 ///
47 /// - [`Dt::from_ccsds_cuc`](../struct.Dt.html#method.from_ccsds_cuc)
48 pub fn to_ccsds_cuc(
49 &self,
50 n_coarse: u8,
51 n_frac: u8,
52 extension: bool,
53 ) -> Result<([u8; Self::CCSDS_C_AND_D_MAX_SIZE], usize), DtErr> {
54 if !(1..=7).contains(&n_coarse) {
55 return Err(an_err!(DtErrKind::OutOfRange, "coarse: {}", n_coarse));
56 } else if n_frac > 10 {
57 return Err(an_err!(DtErrKind::OutOfRange, "frac: {}", n_frac));
58 }
59
60 let tai_since_1958 = self
61 .target(Scale::TAI)
62 .to_scale_and_diff(Self::CCSDS_EPOCH, false);
63
64 let rem_attos = tai_since_1958.to_sec_ufrac();
65 let total_tai_seconds = tai_since_1958.to_sec64();
66
67 if total_tai_seconds < 0 {
68 return Err(an_err!(
69 DtErrKind::OutOfRange,
70 "time before 1958-01-01 TAI (CUC epoch)"
71 ));
72 }
73
74 let frac_scaled = if n_frac == 0 {
75 0u128
76 } else {
77 let scale = 1u128 << (8 * n_frac as u32);
78 let half = scale / 2;
79 ((rem_attos as u128)
80 .saturating_mul(scale)
81 .saturating_add(half))
82 / 1_000_000_000_000_000_000
83 };
84
85 let mut buf = [0u8; Self::CCSDS_C_AND_D_MAX_SIZE];
86 let mut pos = 0usize;
87
88 // Decide whether we need the extended (2-byte) P-field.
89 // Required when coarse > 4 octets, fractional > 3 octets, or caller forces it.
90 let needs_extension = n_coarse > 4 || n_frac > 3 || extension;
91
92 // Base values that fit in the first P-field octet.
93 // Coarse: 2 bits (0-3) → actual octets = base + 1
94 // Fractional: 2 bits (0-3)
95 let base_coarse = if n_coarse <= 4 { n_coarse - 1 } else { 3 };
96 let base_frac = if n_frac <= 3 { n_frac } else { 3 };
97
98 // Build P-field octet 1
99 // Bit 7 = extension flag
100 // Bits 6-4 = Code ID (001 for CUC Level 1)
101 // Bits 3-2 = base coarse (octets - 1)
102 // Bits 1-0 = base fractional octets
103 let mut p1 = 0b0001_0000u8; // Code ID = 001
104 p1 |= (base_coarse << 2) & 0b0000_1100;
105 p1 |= base_frac & 0b0000_0011;
106 if needs_extension {
107 p1 |= 0b1000_0000;
108 }
109 buf[pos] = p1;
110 pos += 1;
111
112 if needs_extension {
113 // Build P-field octet 2 (extended P-field)
114 // Bit 7 = further extension (must be 0)
115 // Bits 6-5 = additional coarse octets (0-3)
116 // Bits 4-2 = additional fractional octets (0-7)
117 // Bits 1-0 = reserved
118 let add_coarse = n_coarse.saturating_sub(4);
119 let add_frac = n_frac.saturating_sub(3);
120
121 let mut p2 = 0u8;
122 p2 |= (add_coarse & 0b11) << 5;
123 p2 |= (add_frac & 0b111) << 2;
124 buf[pos] = p2;
125 pos += 1;
126 }
127
128 // Write coarse time (big-endian)
129 let coarse = total_tai_seconds as u64;
130 for i in (0..n_coarse).rev() {
131 buf[pos] = (coarse >> (i as u32 * 8)) as u8;
132 pos += 1;
133 }
134
135 // Write fractional time (big-endian)
136 for i in (0..n_frac).rev() {
137 buf[pos] = (frac_scaled >> (i as u32 * 8)) as u8;
138 pos += 1;
139 }
140
141 Ok((buf, pos))
142 }
143
144 /// Formats this [`Dt`] as a **CCSDS D (CDS – Day Segmented Time Code)** binary packet.
145 ///
146 /// Fully configurable for round-tripping with [`from_ccsds_cds`](Self::from_ccsds_cds).
147 /// Conforms to **CCSDS 301.0-B-4 §3.3 (Level 1)**.
148 ///
149 /// The time is always encoded on the **UTC** timescale (day count + milliseconds
150 /// since midnight UTC). Leap-second handling follows the library’s conversion rules.
151 ///
152 /// ## Parameters
153 ///
154 /// - `n_day`: Number of day-count octets. Must be `2` or `3`.
155 /// - `sub_ms_code`: Sub-millisecond resolution:
156 /// - `0`: none
157 /// - `1`: 2 bytes (microseconds within the millisecond)
158 /// - `2`: 4 bytes (fraction of a millisecond as 2⁻³²)
159 /// - `extension`: If `true`, emits the second P-field octet.
160 ///
161 /// ## Epoch
162 ///
163 /// Day count is days since **1958-01-01 00:00:00 UTC**.
164 ///
165 /// ## Returns
166 ///
167 /// `(buffer, len)` where `buffer` is a fixed-size array of length
168 /// [`CCSDS_C_AND_D_MAX_SIZE`] and `len` is the number of bytes written.
169 ///
170 /// ## Errors
171 ///
172 /// - [`DtErrKind::InvalidNumber`] if `n_day` is not `2` or `3`.
173 /// - [`DtErrKind::InvalidItem`] if `sub_ms_code` is not in `0..=2`.
174 /// - [`DtErrKind::OutOfRange`] if this instant is before **1958-01-01 00:00:00 UTC**
175 /// (the CDS Level 1 epoch).
176 ///
177 /// ## See also
178 ///
179 /// - [`Dt::from_ccsds_cds`](../struct.Dt.html#method.from_ccsds_cds)
180 pub fn to_ccsds_cds(
181 &self,
182 n_day: u8,
183 sub_ms_code: u8,
184 extension: bool,
185 ) -> Result<([u8; Self::CCSDS_C_AND_D_MAX_SIZE], usize), DtErr> {
186 if !matches!(n_day, 2 | 3) {
187 return Err(an_err!(DtErrKind::InvalidNumber, "n_day: {}", n_day));
188 } else if !matches!(sub_ms_code, 0..=2) {
189 return Err(an_err!(DtErrKind::InvalidItem, "sub-millisecond code"));
190 }
191
192 let utc_since_1958 = self
193 .target(Scale::UTC)
194 .to_scale_and_diff(Self::CCSDS_EPOCH, false);
195
196 let rem_attos = utc_since_1958.to_sec_ufrac();
197 let total_utc_seconds = utc_since_1958.to_sec64();
198
199 if total_utc_seconds < 0 {
200 return Err(an_err!(
201 DtErrKind::OutOfRange,
202 "time before 1958-01-01 UTC (CDS epoch)"
203 ));
204 }
205
206 let day_count = (total_utc_seconds / SEC_PER_DAYI64) as u64;
207 let sec_of_day = (total_utc_seconds % SEC_PER_DAYI64) as u64;
208
209 // Round to nearest millisecond
210 let additional_ms =
211 ((rem_attos as u128 + 500_000_000_000_000) / 1_000_000_000_000_000) as u64;
212
213 let millis_of_day = sec_of_day * 1000 + additional_ms;
214
215 // Remaining attoseconds inside the current millisecond
216 let remaining_attos_in_ms = (rem_attos as u128) % 1_000_000_000_000_000;
217
218 let frac_scaled = match sub_ms_code {
219 0 => 0u64,
220 1 => ((remaining_attos_in_ms * 65_536u128) / 1_000_000_000_000_000u128) as u64,
221 2 => {
222 const PS_SCALE: u128 = 1u128 << 32;
223 ((remaining_attos_in_ms * PS_SCALE) / 1_000_000_000_000_000u128) as u64
224 }
225 _ => unreachable!(),
226 };
227
228 let mut buf = [0u8; Self::CCSDS_C_AND_D_MAX_SIZE];
229 let mut pos = 0usize;
230
231 let mut p1 = 0b0100_0000u8;
232 if extension {
233 p1 |= 0b1000_0000;
234 }
235 if n_day == 3 {
236 p1 |= 0b0000_0100;
237 }
238 p1 |= sub_ms_code;
239 buf[pos] = p1;
240 pos += 1;
241
242 if extension {
243 buf[pos] = 0;
244 pos += 1;
245 }
246
247 for i in (0..n_day).rev() {
248 buf[pos] = (day_count >> (i * 8)) as u8;
249 pos += 1;
250 }
251
252 for i in (0..4).rev() {
253 buf[pos] = (millis_of_day >> (i * 8)) as u8;
254 pos += 1;
255 }
256
257 let n_frac = match sub_ms_code {
258 0 => 0,
259 1 => 2,
260 2 => 4,
261 _ => unreachable!(),
262 };
263 for i in (0..n_frac).rev() {
264 buf[pos] = (frac_scaled >> (i * 8)) as u8;
265 pos += 1;
266 }
267
268 Ok((buf, pos))
269 }
270
271 /// Maximum size needed for a CCSDS CCS binary packet (P-field + T-field).
272 pub const CCSDS_CCS_MAX_SIZE: usize = 14; // 1 + 2(year) + 2(date) + 3(HMS) + 6(subsec)
273
274 /// Formats this [`Dt`] as a **CCSDS CCS (Calendar Segmented Time Code)** binary packet.
275 ///
276 /// Fully configurable for round-tripping with [`from_ccsds_ccs`](Self::from_ccsds_ccs).
277 /// Conforms to **CCSDS 301.0-B-4 §3.4** (Level 1 only).
278 ///
279 /// Both CCS variants are **UTC-based** and use BCD encoding.
280 /// Leap seconds are supported (`second = 60`).
281 ///
282 /// ## Parameters
283 ///
284 /// - `use_doy`: `false` = Month/Day variant (most common), `true` = Day-of-Year variant.
285 /// - `n_subsec`: Number of subsecond BCD octets (`0`–`6`). Each octet holds two decimal digits
286 /// (so `n_subsec = 6` gives up to 12 decimal digits of subsecond precision).
287 ///
288 /// ## Year Range
289 ///
290 /// The year must be in the range **1 to 9999** (as defined by the CCSDS standard).
291 ///
292 /// ## Returns
293 ///
294 /// `(buffer, len)` where `buffer` is a fixed-size array of length
295 /// [`CCSDS_CCS_MAX_SIZE`] and `len` is the number of bytes written.
296 ///
297 /// ## Errors
298 ///
299 /// - [`DtErrKind::OutOfRange`] if `n_subsec > 6` or if the year is outside `1..=9999`.
300 ///
301 /// ## See also
302 ///
303 /// - [`Dt::from_ccsds_ccs`](../struct.Dt.html#method.from_ccsds_ccs)
304 pub fn to_ccsds_ccs(
305 &self,
306 use_doy: bool,
307 n_subsec: u8,
308 ) -> Result<([u8; Self::CCSDS_CCS_MAX_SIZE], usize), DtErr> {
309 if n_subsec > 6 {
310 return Err(an_err!(DtErrKind::OutOfRange, "n_subsec: {}", n_subsec));
311 }
312
313 // ── Convert to UTC civil time (CCS uses the same 1958-01-01 UTC epoch as CDS) ─────
314 let ymd = self.target(Scale::UTC).to_ymd();
315
316 let year = ymd.yr;
317 if !(1..=9999).contains(&year) {
318 return Err(an_err!(DtErrKind::OutOfRange, "year: {}", year));
319 }
320
321 let mut buf = [0u8; Self::CCSDS_CCS_MAX_SIZE];
322 let mut pos = 0usize;
323
324 // ── P-field (exactly 1 byte, no extension) ─────────────────────────────────────
325 let mut p1 = 0b0101_0000u8; // bits 6-4 = 101 (Code ID)
326 if use_doy {
327 p1 |= 0b0000_1000; // bit 3 = 1 for DOY
328 }
329 p1 |= n_subsec & 0b0000_0111; // bits 2-0 = subsecond count
330 buf[pos] = p1;
331 pos += 1;
332
333 // ── BCD encoder helper (2 decimal digits per byte) ─────────────────────────────
334 let bcd = |val: u32| -> u8 {
335 let hi = (val / 10) as u8;
336 let lo = (val % 10) as u8;
337 (hi << 4) | lo
338 };
339
340 // ── Year (4 BCD digits) ───────────────────────────────────────────────────────
341 let year = year as u32;
342 let y_hi = year / 100;
343 let y_lo = year % 100;
344 buf[pos] = bcd(y_hi);
345 buf[pos + 1] = bcd(y_lo);
346 pos += 2;
347
348 // ── Date field (Month+Day or Day-of-Year) ─────────────────────────────────────
349 if !use_doy {
350 // Month/Day variant
351 buf[pos] = bcd(ymd.mo as u32);
352 buf[pos + 1] = bcd(ymd.day as u32);
353 } else {
354 // Day-of-Year variant
355 let doy = ymd.day_of_yr() as u32;
356 buf[pos] = bcd(doy / 100);
357 buf[pos + 1] = bcd(doy % 100);
358 }
359 pos += 2;
360
361 // ── Hour / Minute / Second (BCD) ──────────────────────────────────────────────
362 buf[pos] = bcd(ymd.hr as u32);
363 buf[pos + 1] = bcd(ymd.min as u32);
364 buf[pos + 2] = bcd(ymd.sec as u32); // leap second 60 is allowed by spec
365 pos += 3;
366
367 // ── Subsecond BCD (0–12 decimal digits, 2 per byte, rounded) ──────────────────
368 if n_subsec > 0 {
369 let decimal_places = (2 * n_subsec) as u32;
370 let scale = 10u128.pow(decimal_places);
371
372 // Round attos to nearest representable value at this precision
373 let frac_scaled =
374 (ymd.attos as u128 * scale + 500_000_000_000_000_000) / 1_000_000_000_000_000_000;
375
376 let mut remaining = frac_scaled;
377 for i in (0..n_subsec).rev() {
378 let pair = (remaining % 100) as u32;
379 remaining /= 100;
380 buf[pos + i as usize] = bcd(pair);
381 }
382 pos += n_subsec as usize;
383 }
384
385 Ok((buf, pos))
386 }
387
388 /// Convenience method that automatically selects the most appropriate
389 /// CCSDS binary time code based on this [`Dt`]'s `target` time [`Scale`].
390 ///
391 /// - If the `target` [`Scale`] **uses leap seconds** then **ccsds_cds is chosen**.
392 /// - Otherwise ccsds_cuc is chosen.
393 #[inline(always)]
394 pub fn to_ccsds_bin(&self) -> Result<([u8; Self::CCSDS_C_AND_D_MAX_SIZE], usize), DtErr> {
395 if self.target.uses_leap_seconds() {
396 self.to_ccsds_cds(2, 1, false)
397 } else {
398 self.to_ccsds_cuc(4, 4, false)
399 }
400 }
401}