2025-09-27 10:12:44 +02:00
|
|
|
/**
|
|
|
|
|
* This file is part of the Fun programming language.
|
|
|
|
|
* https://hanez.org/project/fun/
|
|
|
|
|
*
|
|
|
|
|
* Copyright 2025 Johannes Findeisen <you@hanez.org>
|
|
|
|
|
* Licensed under the terms of the ISC license.
|
|
|
|
|
* https://opensource.org/license/isc-license-txt
|
|
|
|
|
*/
|
|
|
|
|
|
2025-09-16 12:38:47 +02:00
|
|
|
case OP_SCLAMP: {
|
2025-09-28 23:56:45 +02:00
|
|
|
/* Saturating clamp to signed N-bit range: [-2^(N-1) .. 2^(N-1)-1] */
|
2025-09-16 12:38:47 +02:00
|
|
|
Value v = pop_value(vm);
|
|
|
|
|
int bits = inst.operand;
|
2025-09-28 23:56:45 +02:00
|
|
|
int64_t vi = (v.type == VAL_INT) ? v.i : 0;
|
2025-09-16 12:38:47 +02:00
|
|
|
|
2025-09-28 23:56:45 +02:00
|
|
|
int64_t smin, smax;
|
2025-09-16 12:38:47 +02:00
|
|
|
if (bits <= 0) {
|
2025-09-28 23:56:45 +02:00
|
|
|
smin = 0; smax = 0;
|
|
|
|
|
} else if (bits >= 63) {
|
|
|
|
|
/* cover full int64_t domain for 63+ bits */
|
|
|
|
|
smin = INT64_MIN;
|
|
|
|
|
smax = INT64_MAX;
|
2025-09-16 12:38:47 +02:00
|
|
|
} else {
|
2025-09-28 23:56:45 +02:00
|
|
|
smin = -(1LL << (bits - 1));
|
|
|
|
|
smax = (1LL << (bits - 1)) - 1LL;
|
2025-09-16 12:38:47 +02:00
|
|
|
}
|
|
|
|
|
|
2025-09-28 23:56:45 +02:00
|
|
|
if (vi < smin) vi = smin;
|
|
|
|
|
else if (vi > smax) vi = smax;
|
|
|
|
|
|
|
|
|
|
push_value(vm, make_int(vi));
|
2025-09-16 12:38:47 +02:00
|
|
|
free_value(v);
|
|
|
|
|
break;
|
|
|
|
|
}
|