1use asdf_yaml::{Document, NodeData, NodeId};
12
13use crate::core::datatype::{ByteOrder, Datatype, ScalarType, parse_shape_with_star};
14use crate::error::{Result, err};
15
16#[derive(Clone, PartialEq, Debug)]
18pub enum Source {
19 Block(usize),
21 LastBlock,
26 External(String),
28 Inline(NodeId),
30}
31
32#[derive(Default, Debug)]
34struct InlineTypes {
35 has_string: bool,
36 has_float: bool,
37 has_signed: bool,
38 int_min: i64,
39 uint_max: u64,
40}
41
42pub fn infer_inline_datatype(doc: &Document, node: NodeId) -> ScalarType {
49 let mut seen = InlineTypes::default();
50 survey_inline(doc, node, &mut seen);
51
52 if seen.has_string {
53 return ScalarType::Unknown;
54 }
55 if seen.has_float {
56 return ScalarType::Float64;
57 }
58 if !seen.has_signed && seen.uint_max == 0 && seen.int_min == 0 {
59 return ScalarType::Bool8;
61 }
62 if seen.has_signed {
63 if seen.int_min >= i64::from(i8::MIN) && seen.uint_max <= i8::MAX as u64 {
64 return ScalarType::Int8;
65 }
66 if seen.int_min >= i64::from(i16::MIN) && seen.uint_max <= i16::MAX as u64 {
67 return ScalarType::Int16;
68 }
69 if seen.int_min >= i64::from(i32::MIN) && seen.uint_max <= i32::MAX as u64 {
70 return ScalarType::Int32;
71 }
72 return ScalarType::Int64;
73 }
74 if seen.uint_max <= u64::from(u8::MAX) {
75 ScalarType::Uint8
76 } else if seen.uint_max <= u64::from(u16::MAX) {
77 ScalarType::Uint16
78 } else if seen.uint_max <= u64::from(u32::MAX) {
79 ScalarType::Uint32
80 } else {
81 ScalarType::Uint64
82 }
83}
84
85fn survey_inline(doc: &Document, node: NodeId, seen: &mut InlineTypes) {
87 survey_inline_bounded(doc, node, seen, 0, &mut inline_budget(doc));
88}
89
90const MAX_INLINE_DEPTH: usize = 64;
95
96fn inline_budget(doc: &Document) -> u64 {
105 (doc.node_count() as u64).saturating_mul(8).max(1024)
106}
107
108fn survey_inline_bounded(
109 doc: &Document,
110 node: NodeId,
111 seen: &mut InlineTypes,
112 depth: usize,
113 budget: &mut u64,
114) {
115 if depth > MAX_INLINE_DEPTH || *budget == 0 {
116 return;
117 }
118 *budget -= 1;
119
120 let resolved = doc.resolve(node);
121 if let Some(items) = doc.sequence_items(resolved).map(<[_]>::to_vec) {
122 for item in items {
123 survey_inline_bounded(doc, item, seen, depth + 1, budget);
124 }
125 return;
126 }
127
128 let Some(text) = doc.resolved(resolved).as_str() else {
129 return;
130 };
131 let style = match &doc.resolved(resolved).data {
132 NodeData::Scalar { style, .. } => *style,
133 _ => return,
134 };
135
136 match asdf_yaml::resolve(text, style, asdf_yaml::Schema::Libasdf) {
137 asdf_yaml::Resolved::Uint(v, _) => seen.uint_max = seen.uint_max.max(v),
138 asdf_yaml::Resolved::Int(v, _) => {
139 seen.has_signed = true;
140 seen.int_min = seen.int_min.min(v);
141 if v > 0 {
142 seen.uint_max = seen.uint_max.max(v as u64);
143 }
144 }
145 asdf_yaml::Resolved::Double(_) => seen.has_float = true,
146 asdf_yaml::Resolved::String => seen.has_string = true,
147 _ => {}
148 }
149}
150
151#[derive(Clone, PartialEq, Debug)]
153pub enum Mask {
154 Value(String),
156 Array(NodeId),
158}
159
160#[derive(Clone, PartialEq, Debug)]
162pub struct Ndarray {
163 pub source: Source,
165 pub shape: Vec<Option<u64>>,
168 pub datatype: Datatype,
170 pub byteorder: ByteOrder,
172 pub offset: u64,
174 pub strides: Option<Vec<i64>>,
176 pub mask: Option<Mask>,
178}
179
180impl Ndarray {
181 pub fn parse(doc: &Document, id: NodeId) -> Result<Self> {
183 let node = doc.resolved(id);
184
185 if matches!(node.data, NodeData::Sequence { .. }) {
187 let data = doc.resolve(id);
188 return Ok(Ndarray {
189 source: Source::Inline(data),
190 shape: infer_inline_shape(doc, data),
191 datatype: Datatype::scalar(infer_inline_datatype(doc, data)),
194 byteorder: ByteOrder::Default,
195 offset: 0,
196 strides: None,
197 mask: None,
198 });
199 }
200
201 if !matches!(node.data, NodeData::Mapping { .. }) {
202 return Err(err!(InvalidArgument, "ndarray must be a mapping or a sequence"));
203 }
204
205 let source = match (doc.mapping_get(id, "source"), doc.mapping_get(id, "data")) {
206 (Some(src), _) => parse_source(doc, src)?,
207 (None, Some(data)) => Source::Inline(doc.resolve(data)),
208 (None, None) => {
209 return Err(err!(
210 InvalidArgument,
211 "ndarray has neither a 'source' nor a 'data' key"
212 ));
213 }
214 };
215
216 let shape = match doc.mapping_get(id, "shape") {
217 Some(s) => parse_shape_with_star(doc, s)?,
218 None => match &source {
219 Source::Inline(node) => infer_inline_shape(doc, *node),
221 _ => Vec::new(),
222 },
223 };
224
225 let datatype = match doc.mapping_get(id, "datatype") {
226 Some(d) => Datatype::parse(doc, d)?,
227 None => match &source {
230 Source::Inline(node) => Datatype::scalar(infer_inline_datatype(doc, *node)),
231 _ => Datatype::default(),
232 },
233 };
234
235 let byteorder = doc
236 .mapping_get(id, "byteorder")
237 .and_then(|b| doc.resolved(b).as_str().map(ByteOrder::from_name))
238 .unwrap_or(ByteOrder::Default);
239
240 let offset = doc
241 .mapping_get(id, "offset")
242 .and_then(|o| doc.resolved(o).as_str().and_then(|s| s.parse().ok()))
243 .unwrap_or(0);
244
245 let strides = match doc.mapping_get(id, "strides") {
246 None => None,
247 Some(s) => {
248 let items = doc
249 .sequence_items(s)
250 .ok_or_else(|| err!(InvalidArgument, "strides must be a sequence"))?;
251 let mut out = Vec::with_capacity(items.len());
252 for item in items {
253 let text = doc
254 .resolved(*item)
255 .as_str()
256 .ok_or_else(|| err!(InvalidArgument, "stride entry is not a scalar"))?;
257 out.push(text.parse::<i64>().map_err(|_| {
258 err!(InvalidArgument, "stride entry is not an integer: {text}")
259 })?);
260 }
261 Some(out)
262 }
263 };
264
265 let mask = doc.mapping_get(id, "mask").map(|m| {
266 let n = doc.resolved(m);
267 match n.data {
268 NodeData::Mapping { .. } | NodeData::Sequence { .. } => Mask::Array(doc.resolve(m)),
269 _ => Mask::Value(n.as_str().unwrap_or_default().to_string()),
270 }
271 });
272
273 Ok(Ndarray { source, shape, datatype, byteorder, offset, strides, mask })
274 }
275
276 #[deny(clippy::arithmetic_side_effects)]
281 pub fn resolved_shape(&self, block_bytes: Option<u64>) -> Result<Vec<u64>> {
282 let item = self.datatype.item_size();
283 let mut out = Vec::with_capacity(self.shape.len());
284
285 for (idx, dim) in self.shape.iter().enumerate() {
286 match dim {
287 Some(d) => out.push(*d),
288 None => {
289 let bytes = block_bytes.ok_or_else(|| {
290 err!(
291 InvalidArgument,
292 "shape dimension {idx} is '*' but no block size is available"
293 )
294 })?;
295 #[allow(
296 clippy::arithmetic_side_effects,
297 reason = "idx indexes self.shape, so idx + 1 is at most its length"
298 )]
299 let row: u64 = self.shape[idx + 1..]
300 .iter()
301 .map(|d| d.unwrap_or(1))
302 .product::<u64>()
303 .max(1);
304 let row_bytes = row.checked_mul(item).filter(|b| *b != 0).ok_or_else(|| {
305 err!(InvalidArgument, "cannot size a '*' dimension with a zero-width row")
306 })?;
307 #[allow(
308 clippy::arithmetic_side_effects,
309 reason = "row_bytes was filtered non-zero just above"
310 )]
311 out.push(bytes / row_bytes);
312 }
313 }
314 }
315 Ok(out)
316 }
317
318 pub fn len(&self, block_bytes: Option<u64>) -> Result<u64> {
325 element_count(&self.resolved_shape(block_bytes)?)
326 }
327
328 pub fn is_empty(&self, block_bytes: Option<u64>) -> Result<bool> {
330 Ok(self.len(block_bytes)? == 0)
331 }
332
333 pub fn nbytes(&self, block_bytes: Option<u64>) -> Result<u64> {
335 self.len(block_bytes)?
336 .checked_mul(self.datatype.item_size())
337 .ok_or_else(|| err!(OverLimit, "array's size in bytes does not fit in 64 bits"))
338 }
339
340 #[deny(clippy::arithmetic_side_effects)]
346 pub fn c_strides(shape: &[u64], item_size: u64) -> Option<Vec<i64>> {
347 let mut strides = vec![0i64; shape.len()];
348 let mut acc = i64::try_from(item_size).ok()?;
349 for idx in (0..shape.len()).rev() {
350 strides[idx] = acc;
351 acc = acc.checked_mul(i64::try_from(shape[idx]).ok()?)?;
352 }
353 Some(strides)
354 }
355}
356
357fn parse_source(doc: &Document, id: NodeId) -> Result<Source> {
359 let node = doc.resolved(id);
360 let text =
361 node.as_str().ok_or_else(|| err!(InvalidArgument, "ndarray source must be a scalar"))?;
362
363 let quoted = node.scalar_style().is_some_and(|s| s.is_quoted());
365 if !quoted && let Ok(index) = text.parse::<i64>() {
366 return Ok(if index == -1 {
367 Source::LastBlock
368 } else if index < 0 {
369 return Err(err!(
373 InvalidArgument,
374 "negative ndarray source {index} other than -1 is not supported"
375 ));
376 } else {
377 Source::Block(index as usize)
378 });
379 }
380 Ok(Source::External(text.to_string()))
381}
382
383#[deny(clippy::arithmetic_side_effects)]
391pub fn element_count(shape: &[u64]) -> Result<u64> {
392 let mut count: u64 = 1;
393 for dim in shape {
394 count = count.checked_mul(*dim).ok_or_else(|| {
395 err!(OverLimit, "shape {shape:?} has more elements than 64 bits hold")
396 })?;
397 }
398 Ok(count)
399}
400
401fn infer_inline_shape(doc: &Document, id: NodeId) -> Vec<Option<u64>> {
403 let mut shape = Vec::new();
404 let mut current = id;
405 while let Some(items) = doc.sequence_items(current) {
413 if shape.len() >= MAX_INLINE_DEPTH {
414 break;
415 }
416 shape.push(Some(items.len() as u64));
417 match items.first() {
418 Some(first) => {
419 let next = doc.resolve(*first);
420 if next == current {
421 break;
422 }
423 current = next;
424 }
425 None => break,
426 }
427 }
428 shape
429}
430
431#[cfg(test)]
432mod tests {
433 use super::*;
434
435 #[test]
438 fn an_inline_arrays_datatype_is_inferred_from_its_values() {
439 let cases = [
440 ("[[0, 1, 2], [3, 4, 5]]", ScalarType::Uint8),
441 ("[0, 255]", ScalarType::Uint8),
442 ("[0, 256]", ScalarType::Uint16),
443 ("[0, 70000]", ScalarType::Uint32),
444 ("[0, 5000000000]", ScalarType::Uint64),
445 ("[-1, 1]", ScalarType::Int8),
446 ("[-200, 1]", ScalarType::Int16),
447 ("[-70000, 1]", ScalarType::Int32),
448 ("[-5000000000, 1]", ScalarType::Int64),
449 ("[1, 2.5]", ScalarType::Float64),
451 ("[-1, 200]", ScalarType::Int16),
453 ("['a', 'b']", ScalarType::Unknown),
455 ("[true, false]", ScalarType::Bool8),
456 ];
457
458 for (data, expected) in cases {
459 let doc = asdf_yaml::parse_document(&format!("a: {data}\n")).unwrap();
460 let root = doc.root().unwrap();
461 let node = doc.mapping_get(root, "a").unwrap();
462 assert_eq!(infer_inline_datatype(&doc, node), expected, "{data}");
463 }
464 }
465
466 #[test]
468 fn the_shorthand_form_infers_both_shape_and_type() {
469 let doc = asdf_yaml::parse_document("a: [[0, 1, 2], [3, 4, 5], [6, 7, 8]]\n").unwrap();
470 let root = doc.root().unwrap();
471 let nd = Ndarray::parse(&doc, doc.mapping_get(root, "a").unwrap()).unwrap();
472
473 assert_eq!(nd.resolved_shape(None).unwrap(), vec![3, 3]);
474 assert_eq!(nd.datatype.scalar, ScalarType::Uint8);
475 assert!(matches!(nd.source, Source::Inline(_)));
476 }
477 use crate::core::datatype::ScalarType;
478 use asdf_yaml::parse_document;
479
480 fn parse_nd(yaml: &str) -> Result<Ndarray> {
481 let doc = parse_document(yaml).unwrap();
482 let root = doc.root().unwrap();
483 let nd = doc.mapping_get(root, "a").unwrap();
484 Ndarray::parse(&doc, nd)
485 }
486
487 #[test]
488 fn parses_a_block_backed_array() {
489 let nd = parse_nd(
490 "a:\n source: 0\n datatype: float64\n shape: [1024, 1024]\n byteorder: little\n",
491 )
492 .unwrap();
493 assert_eq!(nd.source, Source::Block(0));
494 assert_eq!(nd.datatype.scalar, ScalarType::Float64);
495 assert_eq!(nd.byteorder, ByteOrder::Little);
496 assert_eq!(nd.resolved_shape(None).unwrap(), vec![1024, 1024]);
497 assert_eq!(nd.len(None).unwrap(), 1024 * 1024);
498 assert_eq!(nd.nbytes(None).unwrap(), 1024 * 1024 * 8);
499 }
500
501 #[test]
502 fn parses_a_view_with_offset_and_strides() {
503 let nd = parse_nd(
505 "a:\n source: 0\n shape: [256, 256]\n datatype: float64\n \
506 byteorder: little\n strides: [8192, 8]\n offset: 2099200\n",
507 )
508 .unwrap();
509 assert_eq!(nd.offset, 2099200);
510 assert_eq!(nd.strides, Some(vec![8192, 8]));
511 }
512
513 #[test]
514 fn parses_inline_data_under_a_data_key() {
515 let nd = parse_nd("a:\n data: [1, 2, 3, 4]\n datatype: int64\n shape: [4]\n").unwrap();
516 assert!(matches!(nd.source, Source::Inline(_)));
517 assert_eq!(nd.resolved_shape(None).unwrap(), vec![4]);
518 }
519
520 #[test]
521 fn parses_the_bare_sequence_shorthand() {
522 let nd = parse_nd("a: [[1, 0, 0], [0, 1, 0], [0, 0, 1]]\n").unwrap();
524 assert!(matches!(nd.source, Source::Inline(_)));
525 assert_eq!(nd.resolved_shape(None).unwrap(), vec![3, 3]);
526 }
527
528 #[test]
529 fn infers_nested_inline_shape() {
530 let nd = parse_nd("a:\n data: [[1, 2, 3], [4, 5, 6]]\n").unwrap();
531 assert_eq!(nd.resolved_shape(None).unwrap(), vec![2, 3]);
532 }
533
534 #[test]
535 fn an_external_source_is_a_uri() {
536 let nd = parse_nd(
537 "a:\n source: external.asdf\n shape: [4]\n datatype: int8\n byteorder: little\n",
538 )
539 .unwrap();
540 assert_eq!(nd.source, Source::External("external.asdf".into()));
541 }
542
543 #[test]
544 fn a_quoted_numeric_source_is_still_a_uri() {
545 let nd =
547 parse_nd("a:\n source: '0'\n shape: [4]\n datatype: int8\n byteorder: little\n")
548 .unwrap();
549 assert_eq!(nd.source, Source::External("0".into()));
550 }
551
552 #[test]
553 fn source_minus_one_is_the_last_block() {
554 let nd =
555 parse_nd("a:\n source: -1\n shape: ['*']\n datatype: int64\n byteorder: little\n")
556 .unwrap();
557 assert_eq!(nd.source, Source::LastBlock);
558 }
559
560 #[test]
561 fn a_star_dimension_is_sized_from_the_block() {
562 let nd = parse_nd(
563 "a:\n source: -1\n shape: ['*', 4]\n datatype: int64\n byteorder: little\n",
564 )
565 .unwrap();
566 assert_eq!(nd.shape, vec![None, Some(4)]);
567
568 assert_eq!(nd.resolved_shape(Some(320)).unwrap(), vec![10, 4]);
570 assert_eq!(nd.resolved_shape(Some(330)).unwrap(), vec![10, 4]);
572 assert!(nd.resolved_shape(None).is_err());
574 }
575
576 #[test]
577 fn parses_both_mask_forms() {
578 let nd = parse_nd(
579 "a:\n source: 0\n shape: [4]\n datatype: float64\n byteorder: little\n mask: -999\n",
580 )
581 .unwrap();
582 assert_eq!(nd.mask, Some(Mask::Value("-999".into())));
583
584 let nd = parse_nd(
585 "a:\n source: 0\n shape: [4]\n datatype: float64\n byteorder: little\n \
586 mask:\n source: 1\n shape: [4]\n datatype: bool8\n",
587 )
588 .unwrap();
589 assert!(matches!(nd.mask, Some(Mask::Array(_))));
590 }
591
592 #[test]
593 fn rejects_an_ndarray_with_no_data_at_all() {
594 assert!(parse_nd("a:\n shape: [4]\n datatype: int8\n").is_err());
595 }
596
597 #[test]
598 fn c_strides_are_row_major() {
599 assert_eq!(Ndarray::c_strides(&[2, 3], 8), Some(vec![24, 8]));
601 assert_eq!(Ndarray::c_strides(&[4], 4), Some(vec![4]));
602 assert_eq!(Ndarray::c_strides(&[2, 3, 4], 1), Some(vec![12, 4, 1]));
603 assert_eq!(Ndarray::c_strides(&[u64::MAX / 2, 4, 4], 8), None);
606 }
607
608 #[test]
609 fn compound_arrays_size_by_record() {
610 let nd = parse_nd(
611 "a:\n source: 0\n shape: [64]\n byteorder: little\n \
612 datatype:\n - name: x\n datatype: float64\n \
613 - name: y\n datatype: float64\n",
614 )
615 .unwrap();
616 assert!(nd.datatype.is_structured());
617 assert_eq!(nd.datatype.item_size(), 16);
618 assert_eq!(nd.nbytes(None).unwrap(), 64 * 16);
619 }
620}