1 /* This code in included by number.s.c to generate integer conversion
2 functions like scm_to_int and scm_from_int. It is only for
3 unsigned types, see conv-integer.i.c for the signed variant.
6 /* You need to define the following macros before including this
7 template. They are undefined at the end of this file to giove a
8 clean slate for the next inclusion.
10 TYPE - the integral type to be converted
11 TYPE_MIN - the smallest representable number of TYPE, typically 0.
12 TYPE_MAX - the largest representable number of TYPE
13 SIZEOF_TYPE - the size of TYPE, equal to "sizeof (TYPE)" but
14 in a form that can be computed by the preprocessor.
15 When this number is 0, the preprocessor is not used
16 to select which code to compile; the most general
19 SCM_TO_TYPE_PROTO(arg), SCM_FROM_TYPE_PROTO(arg)
20 - These two macros should expand into the prototype
21 for the two defined functions, without the return
27 SCM_TO_TYPE_PROTO (SCM val
)
29 if (SCM_I_INUMP (val
))
31 scm_t_signed_bits n
= SCM_I_INUM (val
);
33 && ((scm_t_uintmax
)n
) >= TYPE_MIN
&& ((scm_t_uintmax
)n
) <= TYPE_MAX
)
38 scm_i_range_error (val
,
39 scm_from_unsigned_integer (TYPE_MIN
),
40 scm_from_unsigned_integer (TYPE_MAX
));
44 else if (SCM_BIGP (val
))
46 if (TYPE_MAX
<= SCM_MOST_POSITIVE_FIXNUM
)
48 else if (TYPE_MAX
<= ULONG_MAX
)
50 if (mpz_fits_ulong_p (SCM_I_BIG_MPZ (val
)))
52 unsigned long n
= mpz_get_ui (SCM_I_BIG_MPZ (val
));
53 #if SIZEOF_TYPE != 0 && SIZEOF_TYPE > SCM_SIZEOF_LONG
57 if (n
>= TYPE_MIN
&& n
<= TYPE_MAX
)
72 if (mpz_sgn (SCM_I_BIG_MPZ (val
)) < 0)
75 if (mpz_sizeinbase (SCM_I_BIG_MPZ (val
), 2)
76 > CHAR_BIT
*sizeof (TYPE
))
79 mpz_export (&n
, &count
, 1, sizeof (TYPE
), 0, 0, SCM_I_BIG_MPZ (val
));
81 if (n
>= TYPE_MIN
&& n
<= TYPE_MAX
)
90 scm_wrong_type_arg_msg (NULL
, 0, val
, "exact integer");
96 SCM_FROM_TYPE_PROTO (TYPE val
)
98 #if SIZEOF_TYPE != 0 && SIZEOF_TYPE < SIZEOF_SCM_T_BITS
99 return SCM_I_MAKINUM (val
);
101 if (SCM_POSFIXABLE (val
))
102 return SCM_I_MAKINUM (val
);
103 else if (val
<= ULONG_MAX
)
104 return scm_i_ulong2big (val
);
107 SCM z
= scm_double_cell (scm_tc16_big
, 0, 0, 0);
108 mpz_init (SCM_I_BIG_MPZ (z
));
109 mpz_import (SCM_I_BIG_MPZ (z
), 1, 1, sizeof (TYPE
), 0, 0, &val
);
119 #undef SCM_TO_TYPE_PROTO
120 #undef SCM_FROM_TYPE_PROTO