On Sun, 16 Nov 2025 14:50:39 GMT, Igor Rudenko <[email protected]> wrote:

>> Logic for creating IndexOutOfBoundsException in MemorySegment is reworked:
>> - separate logic of checking bounds and constructing exception messages for 
>> both `access` and `slice` cases 
>> - idea presented in 
>> [JDK-8288534](https://bugs.openjdk.org/browse/JDK-8288534) slightly reworked 
>> with preservation of the original approach
>
> Igor Rudenko has updated the pull request incrementally with one additional 
> commit since the last revision:
> 
>   Adjust to TestMergeStoresMemorySegment.java requirements

Previously, AMSI implemented `BiFunction<String, List<Number>, 
RuntimeException>`, but now that there are two different ways of generating 
exceptions, we need something else. I think the concept of having the AMSI 
implement interfaces is a good way of expressing a zero-allocation-on-check 
invariant in all situations.

Another alternative, compared to the proposed way, would be to create two new 
private interfaces, perhaps called `RangeCheckingExceptionFormatter` and 
`SliceCheckingExceptionFormatter`. Here is a sketch which I am certain can be 
improved:


interface ExceptionFormatter extends BiFunction<String, List<Number>, 
RuntimeException> {
    MemorySegment segment();
}

interface RangeCheckingExceptionFormatter extends ExceptionFormatter {

    @Override
    default RuntimeException apply(String s, List<Number> numbers) {
        long offset = numbers.get(0).longValue();
        long length = segment().byteSize() - numbers.get(1).longValue() + 1;
        return new IndexOutOfBoundsException(String.format("... <range text> 
... on segment %s; new offset = %d; new length = %d",
                segment(), offset, length));
    }
}

interface SliceCheckingExceptionFormatter extends ExceptionFormatter {
    @Override
    default RuntimeException apply(String s, List<Number> numbers) {
        long offset = numbers.get(0).longValue();
        long length = segment().byteSize() - numbers.get(1).longValue() + 1;
        return new IndexOutOfBoundsException(String.format("... <slice text> 
... on segment %s; new offset = %d; new length = %d",
                segment(), offset, length));
    }
}


Then we can let AMSI implement these interfaces and trivially implement 
`ExceptionFormatter::segment` by returning `this`. Then, when we need an 
exception formatter in the two distinct cases, we just cast `this` to the 
appropriate formatter type. 

Maybe there is a better way, but I think you get the underlying idea. What do 
you think?

-------------

PR Comment: https://git.openjdk.org/jdk/pull/28124#issuecomment-3540957760

Reply via email to