|
| 1 | +--- |
| 2 | +title: Slice Range |
| 3 | +parent: Examples |
| 4 | +nav_order: 3 |
| 5 | +permalink: /examples/slice-range/ |
| 6 | +description: Plain refinements with aliases for valid index ranges and slice lengths. |
| 7 | +--- |
| 8 | + |
| 9 | +# Slice Range |
| 10 | + |
| 11 | +This example models a small utility for working with array slices. It uses plain refinements and aliases with multiple parameters to encode reusable range checks. |
| 12 | + |
| 13 | +```java |
| 14 | +import liquidjava.specification.*; |
| 15 | + |
| 16 | +@RefinementAlias("Length(int n) { n >= 0 }") |
| 17 | +@RefinementAlias("ValidIndex(int i, int size) { 0 <= i && i < size }") |
| 18 | +@RefinementAlias("ValidRange(int start, int end, int size) { 0 <= start && start <= end && end <= size }") |
| 19 | +public class SliceRange { |
| 20 | + @Refinement("Length(_) && _ == end - start") |
| 21 | + public static int sliceLength( |
| 22 | + @Refinement("Length(size)") int size, |
| 23 | + int start, |
| 24 | + @Refinement("ValidRange(start, end, size)") int end |
| 25 | + ) { |
| 26 | + return end - start; |
| 27 | + } |
| 28 | + |
| 29 | + @Refinement("ValidIndex(_, size)") |
| 30 | + public static int lastIndex(@Refinement("size > 0") int size) { |
| 31 | + return size - 1; |
| 32 | + } |
| 33 | + |
| 34 | + @Refinement("Length(_) && _ == index + 1") |
| 35 | + public static int prefixLength( |
| 36 | + @Refinement("Length(size)") int size, |
| 37 | + @Refinement("ValidIndex(index, size)") int index |
| 38 | + ) { |
| 39 | + return index + 1; |
| 40 | + } |
| 41 | +} |
| 42 | +``` |
| 43 | + |
| 44 | +```java |
| 45 | +int size = 10; |
| 46 | +int part = SliceRange.sliceLength(size, 2, 6); |
| 47 | +int last = SliceRange.lastIndex(size); |
| 48 | +int prefix = SliceRange.prefixLength(size, 4); |
| 49 | +``` |
| 50 | + |
| 51 | +```java |
| 52 | +SliceRange.sliceLength(10, 7, 3); // Refinement Error |
| 53 | +``` |
| 54 | + |
| 55 | +```java |
| 56 | +SliceRange.prefixLength(10, 10); // Refinement Error |
| 57 | +``` |
| 58 | + |
| 59 | +The aliases capture the key domain concepts for working with slices: |
| 60 | +- `Length` says lengths are non-negative |
| 61 | +- `ValidIndex` says an index is valid if it is within the bounds of the size |
| 62 | +- `ValidRange` says a range is valid if it starts and ends within the bounds of the size, and the start is not after the end |
0 commit comments