1use std::collections::{HashMap, HashSet};
20
21use bytes::Bytes;
22use viva_genapi_xml::{Addressing, PortKind};
23
24use super::NodeMap;
25use crate::nodes::{Node, node_addressing};
26use crate::{GenApiError, RegisterIo};
27
28#[derive(Clone, Default, PartialEq, Eq)]
39pub struct ChunkData {
40 chunks: Vec<(u64, Bytes)>,
41}
42
43impl ChunkData {
44 pub fn new() -> Self {
46 Self::default()
47 }
48
49 pub fn push(&mut self, id: u64, data: Bytes) {
51 self.chunks.push((id, data));
52 }
53
54 pub fn get(&self, id: u64) -> Option<&Bytes> {
56 self.chunks
57 .iter()
58 .find(|(chunk, _)| *chunk == id)
59 .map(|(_, data)| data)
60 }
61
62 pub fn iter(&self) -> impl Iterator<Item = (u64, &Bytes)> {
64 self.chunks.iter().map(|(id, data)| (*id, data))
65 }
66
67 pub fn ids(&self) -> impl Iterator<Item = u64> + '_ {
69 self.chunks.iter().map(|(id, _)| *id)
70 }
71
72 pub fn len(&self) -> usize {
74 self.chunks.len()
75 }
76
77 pub fn is_empty(&self) -> bool {
79 self.chunks.is_empty()
80 }
81}
82
83impl FromIterator<(u64, Bytes)> for ChunkData {
84 fn from_iter<I: IntoIterator<Item = (u64, Bytes)>>(iter: I) -> Self {
85 Self {
86 chunks: iter.into_iter().collect(),
87 }
88 }
89}
90
91impl std::fmt::Debug for ChunkData {
93 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
94 f.debug_map()
95 .entries(
96 self.chunks
97 .iter()
98 .map(|(id, data)| (format!("{id:#x}"), data.len())),
99 )
100 .finish()
101 }
102}
103
104#[derive(Default)]
106pub(crate) struct Attached {
107 pub(crate) chunks: ChunkData,
108 pub(crate) events: HashMap<u64, Bytes>,
109}
110
111impl std::fmt::Debug for Attached {
112 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
113 let mut events: Vec<(String, usize)> = self
114 .events
115 .iter()
116 .map(|(id, data)| (format!("{id:#x}"), data.len()))
117 .collect();
118 events.sort();
119 f.debug_struct("Attached")
120 .field("chunks", &self.chunks)
121 .field("events", &events)
122 .finish()
123 }
124}
125
126pub(crate) enum Location<'a> {
128 Device { address: u64, len: u32 },
130 Data {
132 port: &'a str,
133 bytes: &'a Bytes,
134 offset: i64,
136 len: u32,
137 from_end: bool,
139 },
140}
141
142enum Route<'a> {
144 Device,
145 Chunk { port: &'a str, id: u64 },
146 Event { port: &'a str, id: u64 },
147}
148
149impl NodeMap {
150 pub fn attach_chunks(&mut self, chunks: &ChunkData) {
158 self.attached.chunks = chunks.clone();
159 self.invalidate_ports(|kind| matches!(kind, PortKind::Chunk { .. }));
160 }
161
162 pub fn detach_chunks(&mut self) {
165 self.attached.chunks = ChunkData::default();
166 self.invalidate_ports(|kind| matches!(kind, PortKind::Chunk { .. }));
167 }
168
169 pub fn attach_event(&mut self, event_id: u64, data: Bytes) {
179 self.attached.events.insert(event_id, data);
180 self.invalidate_ports(|kind| *kind == PortKind::Event { event_id });
181 }
182
183 pub fn detach_events(&mut self) {
185 self.attached.events.clear();
186 self.invalidate_ports(|kind| matches!(kind, PortKind::Event { .. }));
187 }
188
189 pub fn ports(&self) -> Vec<(&str, PortKind)> {
191 let mut ports: Vec<(&str, PortKind)> = self
192 .ports
193 .iter()
194 .map(|(name, kind)| (name.as_str(), *kind))
195 .collect();
196 ports.sort_by(|a, b| a.0.cmp(b.0));
197 ports
198 }
199
200 pub fn port_features(&self, port: &str) -> Vec<&str> {
209 let features: HashSet<&str> = self
210 .nodes
211 .values()
212 .filter_map(|node| match node {
213 Node::Category(cat) => Some(cat.children.iter().map(String::as_str)),
214 _ => None,
215 })
216 .flatten()
217 .collect();
218 let mut seen: HashSet<&str> = HashSet::new();
219 let mut pending: Vec<&str> = self.dependents(port).iter().map(String::as_str).collect();
220 while let Some(name) = pending.pop() {
221 if !seen.insert(name) {
222 continue;
223 }
224 pending.extend(self.dependents(name).iter().map(String::as_str));
225 }
226 let mut out: Vec<&str> = seen
227 .into_iter()
228 .filter(|name| features.contains(name) && self.nodes.contains_key(*name))
229 .collect();
230 out.sort_unstable();
231 out
232 }
233
234 pub(super) fn link_port_dependents(&mut self) {
238 let mut links: Vec<(String, String)> = Vec::new();
239 for node in self.nodes.values() {
240 let Some(port) = node_addressing(node).and_then(Addressing::port) else {
241 continue;
242 };
243 if matches!(
244 self.ports.get(port),
245 Some(PortKind::Chunk { .. } | PortKind::Event { .. })
246 ) {
247 links.push((port.to_string(), node.name().to_string()));
248 }
249 }
250 for (port, node) in links {
251 let list = self.dependents.entry(port).or_default();
252 if !list.contains(&node) {
253 list.push(node);
254 }
255 }
256 }
257
258 fn invalidate_ports(&self, which: impl Fn(&PortKind) -> bool) {
259 for (name, kind) in &self.ports {
260 if which(kind) {
261 self.invalidate_dependents(name);
262 }
263 }
264 self.bump_generation();
265 }
266
267 fn route<'a>(
271 &'a self,
272 node: &str,
273 addressing: &'a Addressing,
274 ) -> Result<Route<'a>, GenApiError> {
275 let Some(port) = addressing.port() else {
276 return Ok(Route::Device);
277 };
278 match self.ports.get(port) {
279 Some(PortKind::Device) => Ok(Route::Device),
280 Some(PortKind::Chunk { chunk_id }) => Ok(Route::Chunk {
281 port,
282 id: *chunk_id,
283 }),
284 Some(PortKind::Event { event_id }) => Ok(Route::Event {
285 port,
286 id: *event_id,
287 }),
288 None if port.eq_ignore_ascii_case("Device") => Ok(Route::Device),
289 _ => Err(GenApiError::UnknownPort {
290 node: node.to_string(),
291 port: port.to_string(),
292 }),
293 }
294 }
295
296 pub(crate) fn locate<'a>(
302 &'a self,
303 node: &str,
304 addressing: &'a Addressing,
305 io: &dyn RegisterIo,
306 ) -> Result<Location<'a>, GenApiError> {
307 let (port, bytes, from_end) = match self.route(node, addressing)? {
308 Route::Device => {
309 let (address, len) = self.resolve_device_address(node, addressing, io)?;
310 return Ok(Location::Device { address, len });
311 }
312 Route::Chunk { port, id } => (port, self.attached.chunks.get(id), true),
313 Route::Event { port, id } => (port, self.attached.events.get(&id), false),
314 };
315 let bytes = bytes.ok_or_else(|| GenApiError::NotAttached {
316 node: node.to_string(),
317 port: port.to_string(),
318 })?;
319 let (offset, len) = self.resolve_address(node, addressing, io)?;
320 Ok(Location::Data {
321 port,
322 bytes,
323 offset: offset as i64,
327 len,
328 from_end,
329 })
330 }
331
332 pub(crate) fn locate_for_write(
335 &self,
336 node: &str,
337 addressing: &Addressing,
338 io: &dyn RegisterIo,
339 ) -> Result<(u64, u32), GenApiError> {
340 match self.route(node, addressing)? {
341 Route::Device => self.resolve_device_address(node, addressing, io),
342 Route::Chunk { port, .. } | Route::Event { port, .. } => {
343 Err(GenApiError::PortNotWritable {
344 node: node.to_string(),
345 port: port.to_string(),
346 })
347 }
348 }
349 }
350
351 pub(crate) fn read_location(
353 &self,
354 node: &str,
355 location: &Location<'_>,
356 io: &dyn RegisterIo,
357 ) -> Result<Vec<u8>, GenApiError> {
358 match *location {
359 Location::Device { address, len } => io.read(address, len as usize),
360 Location::Data {
361 port,
362 bytes,
363 offset,
364 len,
365 from_end,
366 } => slice_port_data(node, port, bytes, offset, len, from_end).map(<[u8]>::to_vec),
367 }
368 }
369}
370
371fn slice_port_data<'a>(
376 node: &str,
377 port: &str,
378 bytes: &'a [u8],
379 offset: i64,
380 len: u32,
381 from_end: bool,
382) -> Result<&'a [u8], GenApiError> {
383 let size = bytes.len();
384 let out_of_range = || GenApiError::PortOutOfRange {
385 node: node.to_string(),
386 port: port.to_string(),
387 offset,
388 len,
389 size,
390 };
391 let start = if offset < 0 {
392 if !from_end {
393 return Err(out_of_range());
394 }
395 let back = usize::try_from(offset.unsigned_abs()).map_err(|_| out_of_range())?;
396 size.checked_sub(back).ok_or_else(out_of_range)?
397 } else {
398 usize::try_from(offset).map_err(|_| out_of_range())?
399 };
400 let end = start
401 .checked_add(len as usize)
402 .filter(|end| *end <= size)
403 .ok_or_else(out_of_range)?;
404 Ok(&bytes[start..end])
405}
406
407#[cfg(test)]
408mod tests {
409 use super::*;
410
411 #[test]
412 fn a_negative_offset_counts_from_the_end_of_a_chunk() {
413 let data = [1u8, 2, 3, 4, 5, 6, 7, 8];
414 assert_eq!(
415 slice_port_data("n", "p", &data, -4, 4, true).expect("in range"),
416 &[5, 6, 7, 8]
417 );
418 assert_eq!(
419 slice_port_data("n", "p", &data, -8, 2, true).expect("in range"),
420 &[1, 2]
421 );
422 }
423
424 #[test]
425 fn out_of_range_is_an_error_not_a_panic() {
426 let data = [0u8; 8];
427 for (offset, len, from_end) in [
428 (-9, 1, true),
429 (-4, 8, true),
430 (-1, 1, false),
431 (7, 2, false),
432 (8, 1, false),
433 (i64::MIN, 4, true),
434 (i64::MAX, 4, true),
435 (0, u32::MAX, true),
436 ] {
437 let err = slice_port_data("n", "p", &data, offset, len, from_end)
438 .expect_err("outside the data");
439 assert!(
440 matches!(err, GenApiError::PortOutOfRange { size: 8, .. }),
441 "{err}"
442 );
443 }
444 }
445
446 #[test]
447 fn chunk_data_reads_the_first_chunk_with_an_id() {
448 let chunks: ChunkData = [
449 (1, Bytes::from_static(b"one")),
450 (2, Bytes::from_static(b"two")),
451 (1, Bytes::from_static(b"again")),
452 ]
453 .into_iter()
454 .collect();
455 assert_eq!(chunks.get(1).map(|b| &b[..]), Some(&b"one"[..]));
456 assert_eq!(chunks.get(3), None);
457 assert_eq!(chunks.ids().collect::<Vec<_>>(), vec![1, 2, 1]);
458 assert_eq!(format!("{chunks:?}"), r#"{"0x1": 3, "0x2": 3, "0x1": 5}"#);
459 }
460}