kdi/commands.rs
1// GENERATED FROM kdi/contract.yaml BY kdi/gen.py — DO NOT EDIT.
2//
3// Regenerate with `make kdi-gen`. A hand edit is caught by
4// kdi/tests/test_end_to_end.py::test_generated_rust_is_current, which re-renders this file and
5// compares it byte-for-byte; there is no merge path for a local change.
6//
7// This file is COMMITTED even though the repo otherwise never tracks generated artifacts, because
8// a crates.io tarball carries no Python: a consumer who cannot run the generator has to find the
9// contract already compiled in.
10
11// A TRAIT, not an inherent impl: this file is generated, so it may reach the device only through
12// the one PUBLIC entry point (`Device::raw_cmd`) — no private field of `Device` and no endpoint
13// number may leak into a file no human is allowed to edit, which is the same binding quarantine
14// lib.rs opens with. A generated method knows a command NAME and an argument ORDER, nothing else.
15//
16// Why type them at all: `Device::raw_cmd` is stringly-typed, so `raw_cmd("adio.adc", &["1", "0"])`
17// transposes slot and channel with no complaint (the failure kdi/frontpanel.py:61 documents),
18// an out-of-range slot is learned a round trip later, and a misspelled name is learned on the
19// wire. Every range below comes from contract.yaml and is checked BEFORE a byte is sent; the
20// refusal is `HostErr::HostUnsafeArg`, which is the contract's own token for "refused by the host
21// before it reached the wire" — `host_errors` is a CLOSED set and a conforming library mints none
22// of its own (kdi/contract.yaml:93).
23
24#![allow(dead_code)]
25
26use std::io::ErrorKind;
27
28use serde_json::Value;
29
30use crate::{io_err, Device, Error, HostErr, Reply};
31
32/// Every published command with its declared argument order. THE ORDER IS THE WIRE
33/// (`request.arg_order: declared`, kdi/contract.yaml:874), so a host serialising a
34/// positional `Device::raw_cmd` call reads it from here instead of keeping a second copy of
35/// the registry — the copy that goes stale is the one that transposes two arguments.
36/// The `scope: session` commands are listed too: they have no typed method, but they are
37/// still callable through `Device::raw_cmd`.
38pub const COMMANDS: &[(&str, &[&str])] = &[
39 ("sys.claim", &[]),
40 ("sys.release", &[]),
41 ("sys.challenge", &[]),
42 ("sys.unlock", &["tier", "nonce", "dna", "sig"]),
43 ("sys.hello", &[]),
44 ("id.boards", &["seg"]),
45 ("power.status", &[]),
46 ("power.up", &[]),
47 ("adio.mode", &["slot", "ch1", "ch2"]),
48 ("adio.fb", &["slot", "on"]),
49 ("adio.dout", &["slot", "mask"]),
50 ("adio.adc", &["slot", "ch", "n"]),
51];
52
53/// A mode token, 1:1 with the contract's `of:` list. One enum for every argument that
54/// takes this value set — `adio.mode` declares it twice and two identical types would be
55/// two things to keep in step.
56#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
57#[non_exhaustive]
58pub enum SegBoards {
59 /// The contract token `main`.
60 Main,
61
62 /// The contract token `slot0`.
63 Slot0,
64
65 /// The contract token `slot1`.
66 Slot1,
67
68 /// The contract token `slot2`.
69 Slot2,
70
71 /// The contract token `slot3`.
72 Slot3,
73
74 /// The contract token `slot4`.
75 Slot4,
76
77 /// The contract token `slot5`.
78 Slot5,
79
80 /// The contract token `slot6`.
81 Slot6,
82
83 /// The contract token `slot7`.
84 Slot7,
85}
86
87impl SegBoards {
88 /// The contract token, 1:1 with contract.yaml.
89 pub const fn token(self) -> &'static str {
90 match self {
91 SegBoards::Main => "main",
92 SegBoards::Slot0 => "slot0",
93 SegBoards::Slot1 => "slot1",
94 SegBoards::Slot2 => "slot2",
95 SegBoards::Slot3 => "slot3",
96 SegBoards::Slot4 => "slot4",
97 SegBoards::Slot5 => "slot5",
98 SegBoards::Slot6 => "slot6",
99 SegBoards::Slot7 => "slot7",
100 }
101 }
102
103 /// Parse a token. `None` is a token this build does not know — from a device on
104 /// a newer minor, which is legal and must never be a parse failure.
105 pub fn from_token(s: &str) -> Option<Self> {
106 Some(match s {
107 "main" => SegBoards::Main,
108 "slot0" => SegBoards::Slot0,
109 "slot1" => SegBoards::Slot1,
110 "slot2" => SegBoards::Slot2,
111 "slot3" => SegBoards::Slot3,
112 "slot4" => SegBoards::Slot4,
113 "slot5" => SegBoards::Slot5,
114 "slot6" => SegBoards::Slot6,
115 "slot7" => SegBoards::Slot7,
116 _ => return None,
117 })
118 }
119}
120
121/// A mode token, 1:1 with the contract's `of:` list. One enum for every argument that
122/// takes this value set — `adio.mode` declares it twice and two identical types would be
123/// two things to keep in step.
124#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
125#[non_exhaustive]
126pub enum ChMode {
127 /// The contract token `off`.
128 Off,
129
130 /// The contract token `in`.
131 In,
132
133 /// The contract token `out`.
134 Out,
135
136 /// The contract token `adc`.
137 Adc,
138
139 /// The contract token `dac`.
140 Dac,
141}
142
143impl ChMode {
144 /// The contract token, 1:1 with contract.yaml.
145 pub const fn token(self) -> &'static str {
146 match self {
147 ChMode::Off => "off",
148 ChMode::In => "in",
149 ChMode::Out => "out",
150 ChMode::Adc => "adc",
151 ChMode::Dac => "dac",
152 }
153 }
154
155 /// Parse a token. `None` is a token this build does not know — from a device on
156 /// a newer minor, which is legal and must never be a parse failure.
157 pub fn from_token(s: &str) -> Option<Self> {
158 Some(match s {
159 "off" => ChMode::Off,
160 "in" => ChMode::In,
161 "out" => ChMode::Out,
162 "adc" => ChMode::Adc,
163 "dac" => ChMode::Dac,
164 _ => return None,
165 })
166 }
167}
168
169/// The reply to `sys.hello`.
170///
171/// Handshake. fw/gw are the firmware and gateware git shas (8 hex) — equal when both came from one
172/// build. The identity REGISTERS carry the same gateware sha pre-boot; the device DNA is not on
173/// this command (it is AXI-side, reachable via the human `kv id`, and on `sys.challenge`). `tiers`
174/// lists the tiers a session of THIS BUILD can reach, comma-joined in rank order: `public` alone
175/// means the build has no unlock and no factory command; `public,service,factory` means every tier
176/// is behind `sys.unlock`. A station tool refuses a build whose `tiers` lacks `factory` rather than
177/// failing midway.
178#[derive(Clone, Debug)]
179pub struct SysHello {
180 /// The reply's `proto` value — declared `u8`.
181 pub proto: u8,
182
183 /// The reply's `cmdset` value — declared `str`.
184 pub cmdset: String,
185
186 /// The reply's `kdi` value — declared `str`.
187 pub kdi: String,
188
189 /// The reply's `board_id` value — declared `u32`.
190 pub board_id: u32,
191
192 /// The reply's `fw` value — declared `str`.
193 pub fw: String,
194
195 /// The reply's `gw` value — declared `str`.
196 pub gw: String,
197
198 /// The reply's `tiers` value — declared `str`.
199 pub tiers: String,
200}
201
202impl SysHello {
203 fn parse(r: &Reply) -> Result<Self, Error> {
204 Ok(Self {
205 proto: uint(r, "proto")?,
206 cmdset: text(r, "cmdset")?,
207 kdi: text(r, "kdi")?,
208 board_id: uint(r, "board_id")?,
209 fw: text(r, "fw")?,
210 gw: text(r, "gw")?,
211 tiers: text(r, "tiers")?,
212 })
213 }
214}
215
216/// One entry of the `id.boards` reply's `boards` list — declared `[{addr: u8, serial: str}]`.
217#[derive(Clone, Debug)]
218pub struct IdBoardsEntry {
219 /// The entry's `addr` value — declared `u8`.
220 pub addr: u8,
221
222 /// The entry's `serial` value — declared `str`.
223 pub serial: String,
224}
225
226impl IdBoardsEntry {
227 fn parse(v: &Value) -> Result<Self, Error> {
228 Ok(Self {
229 addr: uint(v, "addr")?,
230 serial: text(v, "serial")?,
231 })
232 }
233}
234
235/// The reply to `id.boards`.
236///
237/// The Serial of every Board the device can see on one I2C segment: `main` is the main bus, `slotN`
238/// is module mux channel N. Board-ignorant by design — the device scans 7-bit addresses 0x50..0x57,
239/// reads 64 bytes at register 0 with a 16-bit register address, keeps the blocks that carry a valid
240/// identity record (the internal `board_record` layout), and returns the Serial string with the
241/// address it was found at. A NAK from an EEPROM address is "no Board there", never an error; a
242/// blank EEPROM (all 0xFF or all 0x00) is "no record" and is omitted; only a stuck bus is reported
243/// — and `i2c_nak` can only mean the mux itself (`addr` 0x77) refused the channel select. One
244/// segment per call so at most 8 entries, and the reply always fits `max_body_bytes`. On a `slot`
245/// segment the device holds the mux on that channel for the transaction and restores what the power
246/// sequencer expects. Every other record field is unreachable below the factory tier.
247#[derive(Clone, Debug)]
248pub struct IdBoards {
249 /// The reply's `boards` value — declared `[{addr: u8, serial: str}]`.
250 pub boards: Vec<IdBoardsEntry>,
251}
252
253impl IdBoards {
254 fn parse(r: &Reply) -> Result<Self, Error> {
255 Ok(Self {
256 boards: objects(r, "boards", IdBoardsEntry::parse)?,
257 })
258 }
259}
260
261/// The reply to `power.status`.
262///
263/// Read the power tree, writing nothing. present = module-present bitmask from the most recent
264/// sequence pass (a raw detect read is NOT equivalent — after a pass those bits are outputs driving
265/// the DCDC enables). reverify = the periodic re-verify thread is enabled.
266#[derive(Clone, Debug)]
267pub struct PowerStatus {
268 /// The reply's `present` value — declared `u8`.
269 pub present: u8,
270
271 /// The reply's `reverify` value — declared `bool`.
272 pub reverify: bool,
273}
274
275impl PowerStatus {
276 fn parse(r: &Reply) -> Result<Self, Error> {
277 Ok(Self {
278 present: uint(r, "present")?,
279 reverify: flag(r, "reverify")?,
280 })
281 }
282}
283
284/// The reply to `power.up`.
285///
286/// Run the rail sequence. Stim stays off. Level-set: safe to retry.
287#[derive(Clone, Debug)]
288pub struct PowerUp {
289 /// The reply's `ok` value — declared `bool`.
290 pub ok: bool,
291
292 /// The reply's `present` value — declared `u8`.
293 pub present: u8,
294}
295
296impl PowerUp {
297 fn parse(r: &Reply) -> Result<Self, Error> {
298 Ok(Self {
299 ok: flag(r, "ok")?,
300 present: uint(r, "present")?,
301 })
302 }
303}
304
305/// The reply to `adio.mode`.
306///
307/// Set a slot's two channel modes (I2C mux + CH_MODE, kept coherent).
308#[derive(Clone, Debug)]
309pub struct AdioMode {
310 /// The reply's `slot` value — declared `u8`.
311 pub slot: u8,
312
313 /// The reply's `ch_mode` value — declared `u16`.
314 pub ch_mode: u16,
315}
316
317impl AdioMode {
318 fn parse(r: &Reply) -> Result<Self, Error> {
319 Ok(Self {
320 slot: uint(r, "slot")?,
321 ch_mode: uint(r, "ch_mode")?,
322 })
323 }
324}
325
326/// The reply to `adio.fb`.
327///
328/// Cross-channel loopback tie. Independent of either channel's DIRECTION and of CH_MODE, and re-
329/// asserted with the expander, so setting a mode never silently drops a tie. The muxes make it a
330/// SELECT, not a strap: with the tie on, a channel routes to the other channel instead of to its
331/// jack.
332#[derive(Clone, Debug)]
333pub struct AdioFb {
334 /// The reply's `slot` value — declared `u8`.
335 pub slot: u8,
336
337 /// The reply's `fb` value — declared `u8`.
338 pub fb: u8,
339}
340
341impl AdioFb {
342 fn parse(r: &Reply) -> Result<Self, Error> {
343 Ok(Self {
344 slot: uint(r, "slot")?,
345 fb: uint(r, "fb")?,
346 })
347 }
348}
349
350/// The reply to `adio.dout`.
351///
352/// Drive the digital outputs (bit0 CH1, bit1 CH2) and echo the RAW pad readback, so one call is
353/// both a stimulus and its measurement. A non-zero mask is refused on an absent slot: driving a pin
354/// high there back-powers the module rail. Note the pin only moves if that channel's CH_MODE is
355/// out, and a driven channel reads 0 on its own TTL lane by design -- read the OTHER channel,
356/// through the tie.
357#[derive(Clone, Debug)]
358pub struct AdioDout {
359 /// The reply's `slot` value — declared `u8`.
360 pub slot: u8,
361
362 /// The reply's `dout` value — declared `u8`.
363 pub dout: u8,
364
365 /// The reply's `din` value — declared `u8`.
366 pub din: u8,
367}
368
369impl AdioDout {
370 fn parse(r: &Reply) -> Result<Self, Error> {
371 Ok(Self {
372 slot: uint(r, "slot")?,
373 dout: uint(r, "dout")?,
374 din: uint(r, "din")?,
375 })
376 }
377}
378
379/// The reply to `adio.adc`.
380///
381/// n is range-checked, never silently clamped (the human `kv adio adc` clamps). valid\[i\] mirrors
382/// each sample's valid bit — a code with valid=false is meaningless.
383#[derive(Clone, Debug)]
384pub struct AdioAdc {
385 /// The reply's `slot` value — declared `u8`.
386 pub slot: u8,
387
388 /// The reply's `ch` value — declared `u8`.
389 pub ch: u8,
390
391 /// The reply's `codes` value — declared `u16[]`.
392 pub codes: Vec<u16>,
393
394 /// The reply's `valid` value — declared `bool[]`.
395 pub valid: Vec<bool>,
396}
397
398impl AdioAdc {
399 fn parse(r: &Reply) -> Result<Self, Error> {
400 Ok(Self {
401 slot: uint(r, "slot")?,
402 ch: uint(r, "ch")?,
403 codes: uints(r, "codes")?,
404 valid: flags(r, "valid")?,
405 })
406 }
407}
408
409/// Every published command, typed. Implemented for `Device` below.
410pub trait Commands {
411 /// Handshake. fw/gw are the firmware and gateware git shas (8 hex) — equal when both came from
412 /// one build. The identity REGISTERS carry the same gateware sha pre-boot; the device DNA is
413 /// not on this command (it is AXI-side, reachable via the human `kv id`, and on
414 /// `sys.challenge`). `tiers` lists the tiers a session of THIS BUILD can reach, comma-joined in
415 /// rank order: `public` alone means the build has no unlock and no factory command;
416 /// `public,service,factory` means every tier is behind `sys.unlock`. A station tool refuses a
417 /// build whose `tiers` lacks `factory` rather than failing midway.
418 fn sys_hello(&mut self) -> Result<SysHello, Error>;
419
420 /// The Serial of every Board the device can see on one I2C segment: `main` is the main bus,
421 /// `slotN` is module mux channel N. Board-ignorant by design — the device scans 7-bit addresses
422 /// 0x50..0x57, reads 64 bytes at register 0 with a 16-bit register address, keeps the blocks
423 /// that carry a valid identity record (the internal `board_record` layout), and returns the
424 /// Serial string with the address it was found at. A NAK from an EEPROM address is "no Board
425 /// there", never an error; a blank EEPROM (all 0xFF or all 0x00) is "no record" and is omitted;
426 /// only a stuck bus is reported — and `i2c_nak` can only mean the mux itself (`addr` 0x77)
427 /// refused the channel select. One segment per call so at most 8 entries, and the reply always
428 /// fits `max_body_bytes`. On a `slot` segment the device holds the mux on that channel for the
429 /// transaction and restores what the power sequencer expects. Every other record field is
430 /// unreachable below the factory tier.
431 fn id_boards(&mut self, seg: SegBoards) -> Result<IdBoards, Error>;
432
433 /// Read the power tree, writing nothing. present = module-present bitmask from the most recent
434 /// sequence pass (a raw detect read is NOT equivalent — after a pass those bits are outputs
435 /// driving the DCDC enables). reverify = the periodic re-verify thread is enabled.
436 fn power_status(&mut self) -> Result<PowerStatus, Error>;
437
438 /// Run the rail sequence. Stim stays off. Level-set: safe to retry.
439 fn power_up(&mut self) -> Result<PowerUp, Error>;
440
441 /// Set a slot's two channel modes (I2C mux + CH_MODE, kept coherent).
442 fn adio_mode(&mut self, slot: u8, ch1: ChMode, ch2: ChMode) -> Result<AdioMode, Error>;
443
444 /// Cross-channel loopback tie. Independent of either channel's DIRECTION and of CH_MODE, and
445 /// re-asserted with the expander, so setting a mode never silently drops a tie. The muxes make
446 /// it a SELECT, not a strap: with the tie on, a channel routes to the other channel instead of
447 /// to its jack.
448 fn adio_fb(&mut self, slot: u8, on: u8) -> Result<AdioFb, Error>;
449
450 /// Drive the digital outputs (bit0 CH1, bit1 CH2) and echo the RAW pad readback, so one call is
451 /// both a stimulus and its measurement. A non-zero mask is refused on an absent slot: driving a
452 /// pin high there back-powers the module rail. Note the pin only moves if that channel's
453 /// CH_MODE is out, and a driven channel reads 0 on its own TTL lane by design -- read the OTHER
454 /// channel, through the tie.
455 fn adio_dout(&mut self, slot: u8, mask: u8) -> Result<AdioDout, Error>;
456
457 /// n is range-checked, never silently clamped (the human `kv adio adc` clamps). valid\[i\]
458 /// mirrors each sample's valid bit — a code with valid=false is meaningless.
459 fn adio_adc(&mut self, slot: u8, ch: u8, n: Option<u8>) -> Result<AdioAdc, Error>;
460}
461
462impl Commands for Device {
463 fn sys_hello(&mut self) -> Result<SysHello, Error> {
464 let reply = checked(self.raw_cmd("sys.hello", &[])?)?;
465 SysHello::parse(&reply)
466 }
467
468 fn id_boards(&mut self, seg: SegBoards) -> Result<IdBoards, Error> {
469 let args: Vec<String> = vec![seg.token().to_string()];
470 let args: Vec<&str> = args.iter().map(String::as_str).collect();
471 let reply = checked(self.raw_cmd("id.boards", &args)?)?;
472 IdBoards::parse(&reply)
473 }
474
475 fn power_status(&mut self) -> Result<PowerStatus, Error> {
476 let reply = checked(self.raw_cmd("power.status", &[])?)?;
477 PowerStatus::parse(&reply)
478 }
479
480 fn power_up(&mut self) -> Result<PowerUp, Error> {
481 let reply = checked(self.raw_cmd("power.up", &[])?)?;
482 PowerUp::parse(&reply)
483 }
484
485 fn adio_mode(&mut self, slot: u8, ch1: ChMode, ch2: ChMode) -> Result<AdioMode, Error> {
486 if slot > 7 {
487 return Err(Error::Host(HostErr::HostUnsafeArg));
488 }
489 let args: Vec<String> = vec![
490 slot.to_string(),
491 ch1.token().to_string(),
492 ch2.token().to_string(),
493 ];
494 let args: Vec<&str> = args.iter().map(String::as_str).collect();
495 let reply = checked(self.raw_cmd("adio.mode", &args)?)?;
496 AdioMode::parse(&reply)
497 }
498
499 fn adio_fb(&mut self, slot: u8, on: u8) -> Result<AdioFb, Error> {
500 if slot > 7 {
501 return Err(Error::Host(HostErr::HostUnsafeArg));
502 }
503 if on > 1 {
504 return Err(Error::Host(HostErr::HostUnsafeArg));
505 }
506 let args: Vec<String> = vec![slot.to_string(), on.to_string()];
507 let args: Vec<&str> = args.iter().map(String::as_str).collect();
508 let reply = checked(self.raw_cmd("adio.fb", &args)?)?;
509 AdioFb::parse(&reply)
510 }
511
512 fn adio_dout(&mut self, slot: u8, mask: u8) -> Result<AdioDout, Error> {
513 if slot > 7 {
514 return Err(Error::Host(HostErr::HostUnsafeArg));
515 }
516 if mask > 3 {
517 return Err(Error::Host(HostErr::HostUnsafeArg));
518 }
519 let args: Vec<String> = vec![slot.to_string(), mask.to_string()];
520 let args: Vec<&str> = args.iter().map(String::as_str).collect();
521 let reply = checked(self.raw_cmd("adio.dout", &args)?)?;
522 AdioDout::parse(&reply)
523 }
524
525 fn adio_adc(&mut self, slot: u8, ch: u8, n: Option<u8>) -> Result<AdioAdc, Error> {
526 if slot > 7 {
527 return Err(Error::Host(HostErr::HostUnsafeArg));
528 }
529 if ch > 1 {
530 return Err(Error::Host(HostErr::HostUnsafeArg));
531 }
532 if let Some(n) = n {
533 if !(1..=16).contains(&n) {
534 return Err(Error::Host(HostErr::HostUnsafeArg));
535 }
536 }
537 let mut args: Vec<String> = vec![slot.to_string(), ch.to_string()];
538 if let Some(n) = n {
539 args.push(n.to_string());
540 }
541 let args: Vec<&str> = args.iter().map(String::as_str).collect();
542 let reply = checked(self.raw_cmd("adio.adc", &args)?)?;
543 AdioAdc::parse(&reply)
544 }
545}
546
547// Deliberately without typed methods: `sys.claim`, `sys.release`, `sys.challenge`, `sys.unlock`.
548// Every one is `scope: session` — OPTIONAL, so a build may legally answer `unknown_cmd` to any of
549// them and a host proceeds (kdi/contract.yaml:476-478). A typed method would read as a promise
550// every build keeps. Their argument shapes ARE published (the unlock's grant is `tier nonce dna
551// sig`, see the contract), and they stay in `COMMANDS` above, so `Device::raw_cmd` drives one
552// positionally in the declared order.
553
554// ───────────────────────────────────────────────────────────────────── reply decoding
555//
556// A missing or ill-typed key is an ERROR, never a default. A device on a NEWER minor may ADD keys
557// — that is what makes a minor additive, and nothing here rejects an unknown one — but a reply
558// missing a key this contract declares is not from the device this build thinks it is, and
559// `unwrap_or_default` would hand the bench a present-mask of 0: "no modules fitted",
560// indistinguishable from the truth.
561
562fn bad(key: &str, want: &str) -> Error {
563 io_err(
564 ErrorKind::InvalidData,
565 format!("reply key `{key}` is not {want}"),
566 )
567}
568
569/// A whole reply and one object inside it (an entry of a list-valued key) are read alike.
570trait Fields {
571 fn field(&self, key: &str) -> Option<&Value>;
572}
573
574impl Fields for Reply {
575 fn field(&self, key: &str) -> Option<&Value> {
576 self.get(key)
577 }
578}
579
580impl Fields for Value {
581 fn field(&self, key: &str) -> Option<&Value> {
582 self.get(key)
583 }
584}
585
586fn at<'a>(r: &'a impl Fields, key: &str) -> Result<&'a Value, Error> {
587 r.field(key).ok_or_else(|| bad(key, "present in the reply"))
588}
589
590/// Width-checked, never truncating: the device declares `present` as a u8 and a `v as u8` on a
591/// wider value would silently report a different power tree than the one that answered.
592fn uint<T: TryFrom<u64>>(r: &impl Fields, key: &str) -> Result<T, Error> {
593 let v = at(r, key)?
594 .as_u64()
595 .ok_or_else(|| bad(key, "an unsigned integer"))?;
596 T::try_from(v).map_err(|_| bad(key, "in range for its declared width"))
597}
598
599fn flag(r: &impl Fields, key: &str) -> Result<bool, Error> {
600 at(r, key)?.as_bool().ok_or_else(|| bad(key, "a bool"))
601}
602
603fn text(r: &impl Fields, key: &str) -> Result<String, Error> {
604 Ok(at(r, key)?
605 .as_str()
606 .ok_or_else(|| bad(key, "a string"))?
607 .to_string())
608}
609
610fn uints<T: TryFrom<u64>>(r: &impl Fields, key: &str) -> Result<Vec<T>, Error> {
611 at(r, key)?
612 .as_array()
613 .ok_or_else(|| bad(key, "an array"))?
614 .iter()
615 .map(|v| {
616 let n = v
617 .as_u64()
618 .ok_or_else(|| bad(key, "an array of unsigned integers"))?;
619 T::try_from(n).map_err(|_| bad(key, "in range for its declared width"))
620 })
621 .collect()
622}
623
624fn flags(r: &impl Fields, key: &str) -> Result<Vec<bool>, Error> {
625 at(r, key)?
626 .as_array()
627 .ok_or_else(|| bad(key, "an array"))?
628 .iter()
629 .map(|v| v.as_bool().ok_or_else(|| bad(key, "an array of bools")))
630 .collect()
631}
632
633fn object(r: &impl Fields, key: &str) -> Result<Value, Error> {
634 Ok(at(r, key)?.clone())
635}
636
637/// A list of records, each parsed by the generated entry type. An element that is not an
638/// object is an error for the same reason a missing key is: it is not the declared reply.
639fn objects<T>(
640 r: &impl Fields,
641 key: &str,
642 parse: fn(&Value) -> Result<T, Error>,
643) -> Result<Vec<T>, Error> {
644 at(r, key)?
645 .as_array()
646 .ok_or_else(|| bad(key, "an array"))?
647 .iter()
648 .map(|v| {
649 if !v.is_object() {
650 return Err(bad(key, "an array of objects"));
651 }
652 parse(v)
653 })
654 .collect()
655}
656
657/// A refusal reaches a TYPED caller as `Err`, while `Device::raw_cmd` still returns it as data
658/// (lib.rs:12-15). The difference is what was asked for: `raw_cmd` hands back a `Reply` whose `rc`
659/// the caller is obliged to read, but a reply that says `not_present` contains no `AdioAdc`, and
660/// parsing one out of the absent keys would invent codes that were never sampled.
661fn checked(r: Reply) -> Result<Reply, Error> {
662 if r.ok() {
663 Ok(r)
664 } else {
665 Err(Error::Device(r))
666 }
667}