Skip to content

Commit 95cba36

Browse files
authored
Merge pull request #54 from mblsha/patch-1
Add "Validating attribute values" section to user_doc
2 parents 0da3b92 + 168534b commit 95cba36

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

user_guide.adoc

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -310,6 +310,47 @@ definitely not recommended in real-life specs):
310310
NOTE: There's no need to specify `type` or `size` for fixed contents
311311
data — it all comes naturally from the `contents`.
312312

313+
[[valid-values]]
314+
=== Validating attribute values
315+
316+
To ensure attributes in your data structures adhere to expected formats and ranges, Kaitai Struct provides a mechanism for validating attribute values using the `valid` key. This key allows you to define constraints for values, enhancing the robustness of your specifications. Here's how you can enforce these constraints:
317+
318+
* `eq` (or directly `valid: value`): Ensures the attribute value exactly matches the given value.
319+
* `min`: Specifies the minimum valid value for the attribute.
320+
* `max`: Specifies the maximum valid value for the attribute.
321+
* `any-of`: Defines a list of acceptable values, one of which the attribute must match.
322+
* `expr`: An expression that evaluates to true for the attribute to be considered valid.
323+
324+
For most cases, the direct `valid: value` shortcut is preferred for its simplicity, effectively functioning as `valid/eq`.
325+
326+
[source,yaml]
327+
----
328+
seq:
329+
- id: exact_value
330+
type: u1
331+
valid: 0x42 # Shortcut for eq: The only valid value is 0x42
332+
333+
- id: bounded_value
334+
type: u2
335+
valid:
336+
min: 100 # Value must be at least 100
337+
max: 200 # and at most 200
338+
339+
- id: enum_value
340+
type: u4
341+
valid:
342+
any-of: [3, 5, 7] # Value must be one of 3, 5, or 7
343+
344+
- id: calculated_value
345+
type: u4
346+
valid:
347+
expr: _ % 2 == 0 # Value must be even
348+
----
349+
350+
When a value does not meet the specified criteria, Kaitai Struct raises a validation error, halting further parsing. This preemptive measure ensures the data being parsed is within the expected domain, providing a first layer of error handling.
351+
352+
NOTE: The actual implementation of validation checks is language-dependent and may vary in behavior and supported features across different target languages.
353+
313354
[[var-length-struct]]
314355
=== Variable-length structures
315356

0 commit comments

Comments
 (0)