| 1 | // Test for https://github.com/vlang/v/issues/27508 |
| 2 | // `error_sentinel` is a reusable, allocation-free `IError` (a cached const, like |
| 3 | // `none`), for hot stateless/"not found" error paths in `!T` functions. |
| 4 | |
| 5 | fn find(x int) !int { |
| 6 | if x < 0 { |
| 7 | return error_sentinel |
| 8 | } |
| 9 | return x |
| 10 | } |
| 11 | |
| 12 | fn test_error_sentinel_is_returned_as_error() { |
| 13 | mut misses := 0 |
| 14 | for i := -3; i < 3; i++ { |
| 15 | v := find(i) or { |
| 16 | misses++ |
| 17 | continue |
| 18 | } |
| 19 | assert v == i |
| 20 | } |
| 21 | assert misses == 3 |
| 22 | } |
| 23 | |
| 24 | fn test_error_sentinel_message() { |
| 25 | if _ := find(-1) { |
| 26 | assert false |
| 27 | } else { |
| 28 | assert err.msg() == 'error' |
| 29 | assert err.code() == 0 |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | fn test_error_sentinel_is_stable_identity() { |
| 34 | // Every call returns the same cached const instance (no per-call allocation). |
| 35 | a := error_sentinel |
| 36 | b := error_sentinel |
| 37 | assert a.msg() == b.msg() |
| 38 | assert a is MessageError |
| 39 | } |
| 40 | |