1
0
Fork 0
forked from fun/fun
fun/src/vm/sclamp.c

34 lines
888 B
C
Raw Normal View History

/**
* 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: {
/* 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;
int64_t vi = (v.type == VAL_INT) ? v.i : 0;
2025-09-16 12:38:47 +02:00
int64_t smin, smax;
2025-09-16 12:38:47 +02:00
if (bits <= 0) {
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 {
smin = -(1LL << (bits - 1));
smax = (1LL << (bits - 1)) - 1LL;
2025-09-16 12:38:47 +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;
}