forked from ocaml/Zarith
-
Notifications
You must be signed in to change notification settings - Fork 0
/
caml_z.c
3078 lines (2913 loc) · 78.5 KB
/
caml_z.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
Implementation of Z module.
This file is part of the Zarith library
http://forge.ocamlcore.org/projects/zarith .
It is distributed under LGPL 2 licensing, with static linking exception.
See the LICENSE file included in the distribution.
Copyright (c) 2010-2011 Antoine Miné, Abstraction project.
Abstraction is part of the LIENS (Laboratoire d'Informatique de l'ENS),
a joint laboratory by:
CNRS (Centre national de la recherche scientifique, France),
ENS (École normale supérieure, Paris, France),
INRIA Rocquencourt (Institut national de recherche en informatique, France).
*/
/*---------------------------------------------------
INCLUDES
---------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <stdint.h>
#ifdef HAS_GMP
#include <gmp.h>
#endif
#ifdef HAS_MPIR
#include <mpir.h>
#endif
#include "z_features.h"
#include "zarith.h"
#ifdef __cplusplus
extern "C" {
#endif
#include <caml/mlvalues.h>
#include <caml/memory.h>
#include <caml/alloc.h>
#include <caml/fail.h>
#include <caml/custom.h>
#include <caml/intext.h>
#include <caml/callback.h>
#include <caml/intext.h>
#ifdef Z_OCAML_HASH
#include <caml/hash.h>
#endif
#define inline __inline
#ifdef _MSC_VER
#include <float.h>
#endif
/*---------------------------------------------------
CONFIGURATION
---------------------------------------------------*/
/* Whether to enable native (i.e. non-mpn_) operations and output
ocaml integers when possible.
Highly recommended.
*/
#define Z_FAST_PATH 1
#define Z_USE_NATINT 1
/* Sanity checks. */
#define Z_PERFORM_CHECK 0
/* Enable performance counters.
Prints some info on stdout at exit.
*/
/*
#define Z_PERF_COUNTER 0
now set by configure
*/
/* whether to use custom blocks (supporting serialization, comparison &
hashing) instead of abstract tags
*/
#define Z_CUSTOM_BLOCK 1
/* whether the "compare_ext" operation over custom blocks is supported.
This operation is required for OCaml's generic comparisons to
operate properly over values of type Z.t.
The compare_ext operation is supported in OCaml since version 3.12.1.
*/
/*
#define Z_OCAML_COMPARE_EXT 0
now set by configure
*/
/*---------------------------------------------------
DATA STRUCTURES
---------------------------------------------------*/
/*
we assume that:
- intnat is a signed integer type
- mp_limb_t is an unsigned integer type
- sizeof(intnat) == sizeof(mp_limb_t) == either 4 or 8
*/
#ifdef _WIN64
#define PRINTF_LIMB "I64"
#else
#define PRINTF_LIMB "l"
#endif
/*
A z object x can be:
- either an ocaml int
- or a block with abstract or custom tag and containing:
. a 1 value header containing the sign Z_SIGN(x) and the size Z_SIZE(x)
. Z_SIZE(x) mp_limb_t
Invariant:
- if the number fits in an int, it is stored in an int, not a block
- if the number is stored in a block, then Z_SIZE(x) >= 1 and
the most significant limb Z_LIMB(x)[Z_SIZE(x)] is not 0
*/
/* a sign is always denoted as 0 (+) or Z_SIGN_MASK (-) */
#ifdef ARCH_SIXTYFOUR
#define Z_SIGN_MASK 0x8000000000000000
#define Z_SIZE_MASK 0x7fffffffffffffff
#else
#define Z_SIGN_MASK 0x80000000
#define Z_SIZE_MASK 0x7fffffff
#endif
#if Z_CUSTOM_BLOCK
#define Z_HEAD(x) (*((value*)Data_custom_val((x))))
#define Z_LIMB(x) ((mp_limb_t*)Data_custom_val((x)) + 1)
#else
#define Z_HEAD(x) (Field((x),0))
#define Z_LIMB(x) ((mp_limb_t*)&(Field((x),1)))
#endif
#define Z_SIGN(x) (Z_HEAD((x)) & Z_SIGN_MASK)
#define Z_SIZE(x) (Z_HEAD((x)) & Z_SIZE_MASK)
/* bounds of an Ocaml int */
#ifdef ARCH_SIXTYFOUR
#define Z_MAX_INT 0x3fffffffffffffff
#define Z_MIN_INT (-0x4000000000000000)
#else
#define Z_MAX_INT 0x3fffffff
#define Z_MIN_INT (-0x40000000)
#endif
#define Z_FITS_INT(v) ((v) >= Z_MIN_INT && (v) <= Z_MAX_INT)
/* Z_MAX_INT may not be representable exactly as a double => we use a
lower approximation to be safe
*/
#ifdef ARCH_SIXTYFOUR
#define Z_MAX_INT_FL 0x3ffffffffffff000
#define Z_MIN_INT_FL (-Z_MAX_INT_FL)
#else
#define Z_MAX_INT_FL Z_MAX_INT
#define Z_MIN_INT_FL Z_MIN_INT
#endif
/* safe bounds to avoid overflow in multiplication */
#ifdef ARCH_SIXTYFOUR
#define Z_MAX_HINT 0x3fffffff
#else
#define Z_MAX_HINT 0x3fff
#endif
#define Z_MIN_HINT (-Z_MAX_HINT)
#define Z_FITS_HINT(v) ((v) >= Z_MIN_HINT && (v) <= Z_MAX_HINT)
/* hi bit of OCaml int32, int64 & nativeint */
#define Z_HI_INT32 0x80000000
#define Z_HI_INT64 0x8000000000000000LL
#ifdef ARCH_SIXTYFOUR
#define Z_HI_INTNAT Z_HI_INT64
#define Z_HI_INT 0x4000000000000000
#else
#define Z_HI_INTNAT Z_HI_INT32
#define Z_HI_INT 0x40000000
#endif
/* safe bounds for the length of a base n string fitting in a native
int. Defined as the result of (n - 2) log_base(2) with n = 64 or
32.
*/
#ifdef ARCH_SIXTYFOUR
#define Z_BASE16_LENGTH_OP 15
#define Z_BASE10_LENGTH_OP 18
#define Z_BASE8_LENGTH_OP 20
#define Z_BASE2_LENGTH_OP 62
#else
#define Z_BASE16_LENGTH_OP 7
#define Z_BASE10_LENGTH_OP 9
#define Z_BASE8_LENGTH_OP 10
#define Z_BASE2_LENGTH_OP 30
#endif
#define Z_LIMB_BITS (8 * sizeof(mp_limb_t))
/* performance counters */
unsigned long ml_z_ops = 0;
unsigned long ml_z_slow = 0;
unsigned long ml_z_ops_as = 0;
#if Z_PERF_COUNTER
#define Z_MARK_OP ml_z_ops++
#define Z_MARK_SLOW ml_z_slow++
#else
#define Z_MARK_OP
#define Z_MARK_SLOW
#endif
/*---------------------------------------------------
UTILITIES
---------------------------------------------------*/
extern struct custom_operations ml_z_custom_ops;
static double ml_z_2p32; /* 2 ^ 32 in double */
#if Z_PERFORM_CHECK
/* for debugging: dump a mp_limb_t array */
static void ml_z_dump(const char* msg, mp_limb_t* p, mp_size_t sz)
{
mp_size_t i;
printf("%s %i: ",msg,(int)sz);
for (i = 0; i < sz; i++)
#ifdef ARCH_SIXTYFOUR
printf("%08" PRINTF_LIMB "x ",p[i]);
#else
printf("%04" PRINTF_LIMB "x ",p[i]);
#endif
printf("\n");
fflush(stdout);
}
#endif
#if Z_PERFORM_CHECK
/* for debugging: check invariant */
void ml_z_check(const char* fn, int line, const char* arg, value v)
{
mp_size_t sz;
if (Is_block(v)) {
#if Z_CUSTOM_BLOCK
if (Custom_ops_val(v) != &ml_z_custom_ops) {
printf("ml_z_check: wrong custom block for %s at %s:%i.\n",
arg, fn, line);
exit(1);
}
sz = Wosize_val(v) - 1;
#else
sz = Wosize_val(v);
#endif
if (Z_SIZE(v) + 2 > sz) {
printf("ml_z_check: invalid block size (%i / %i) for %s at %s:%i.\n",
(int)Z_SIZE(v), (int)sz,
arg, fn, line);
exit(1);
}
if ((mp_size_t) Z_LIMB(v)[sz - 2] != (mp_size_t)(0xDEADBEEF ^ (sz - 2))) {
printf("ml_z_check: corrupted block for %s at %s:%i.\n",
arg, fn, line);
exit(1);
}
if (Z_SIZE(v) && Z_LIMB(v)[Z_SIZE(v)-1]) return;
#if !Z_USE_NATINT
if (!Z_SIZE(v)) {
if (Z_SIGN(v)) {
printf("ml_z_check: invalid sign of 0 for %s at %s:%i.\n",
arg, fn, line);
exit(1);
}
return;
}
if (Z_SIZE(v) <= 1 && Z_LIMB(v)[0] <= Z_MAX_INT) {
printf("ml_z_check: unreduced argument for %s at %s:%i.\n", arg, fn, line);
ml_z_dump("offending argument: ", Z_LIMB(v), Z_SIZE(v));
exit(1);
}
#endif
printf("ml_z_check failed for %s at %s:%i.\n", arg, fn, line);
ml_z_dump("offending argument: ", Z_LIMB(v), Z_SIZE(v));
exit(1);
}
}
#endif
/* for debugging */
#if Z_PERFORM_CHECK
#define Z_CHECK(v) ml_z_check(__FUNCTION__, __LINE__, #v, v)
#else
#define Z_CHECK(v)
#endif
/* allocates z object block with space for sz mp_limb_t;
does not set the header
*/
#if !Z_PERFORM_CHECK
/* inlined allocation */
#if Z_CUSTOM_BLOCK
#define ml_z_alloc(sz) \
caml_alloc_custom(&ml_z_custom_ops, (1 + (sz)) * sizeof(value), 0, 1)
#else
#define ml_z_alloc(sz) \
caml_alloc(1 + (sz), Abstract_tag);
#endif
#else
/* out-of-line allocation, inserting a canary after the last limb */
static value ml_z_alloc(mp_size_t sz)
{
value v;
#if Z_CUSTOM_BLOCK
v = caml_alloc_custom(&ml_z_custom_ops, (1 + sz + 1) * sizeof(value), 0, 1);
#else
v = caml_alloc(1 + sz + 1, Abstract_tag);
#endif
Z_LIMB(v)[sz] = 0xDEADBEEF ^ sz;
return v;
}
#endif
/* duplicates the caml block src */
static inline void ml_z_cpy_limb(mp_limb_t* dst, mp_limb_t* src, mp_size_t sz)
{
memcpy(dst, src, sz * sizeof(mp_limb_t));
}
/* duplicates the mp_limb_t array src */
static inline mp_limb_t* ml_z_dup_limb(mp_limb_t* src, mp_size_t sz)
{
mp_limb_t* r = (mp_limb_t*) malloc(sz * sizeof(mp_limb_t));
memcpy(r, src, sz * sizeof(mp_limb_t));
return r;
}
#ifdef _MSC_VER
#define MAYBE_UNUSED
#else
#define MAYBE_UNUSED (void)
#endif
/* given a z object, define:
- ptr_arg: a pointer to the first mp_limb_t
- size_arg: the number of mp-limb_t
- sign_arg: the sign of the number
if arg is an int, it is converted to a 1-limb number
*/
#define Z_DECL(arg) \
mp_limb_t loc_##arg, *ptr_##arg; \
mp_size_t size_##arg; \
intnat sign_##arg; \
MAYBE_UNUSED loc_##arg; \
MAYBE_UNUSED ptr_##arg; \
MAYBE_UNUSED size_##arg; \
MAYBE_UNUSED sign_##arg;
#define Z_ARG(arg) \
if (Is_long(arg)) { \
intnat n = Long_val(arg); \
loc_##arg = n < 0 ? -n : n; \
sign_##arg = n & Z_SIGN_MASK; \
size_##arg = n != 0; \
ptr_##arg = &loc_##arg; \
} \
else { \
size_##arg = Z_SIZE(arg); \
sign_##arg = Z_SIGN(arg); \
ptr_##arg = Z_LIMB(arg); \
}
/* After an allocation, a heap-allocated Z argument may have moved and
its ptr_arg pointer can be invalid. Reset the ptr_arg pointer to
its correct value. */
#define Z_REFRESH(arg) \
if (! Is_long(arg)) ptr_##arg = Z_LIMB(arg);
/* computes the actual size of the z object r and updates its header,
either returns r or, if the number is small enough, an int
*/
static value ml_z_reduce(value r, mp_size_t sz, intnat sign)
{
while (sz > 0 && !Z_LIMB(r)[sz-1]) sz--;
#if Z_USE_NATINT
if (!sz) return Val_long(0);
if (sz <= 1 && Z_LIMB(r)[0] <= Z_MAX_INT) {
if (sign) return Val_long(-Z_LIMB(r)[0]);
else return Val_long(Z_LIMB(r)[0]);
}
#else
if (!sz) sign = 0;
#endif
Z_HEAD(r) = sz | sign;
return r;
}
static void ml_z_raise_overflow()
{
caml_raise_constant(*caml_named_value("ml_z_overflow"));
}
#define ml_z_raise_divide_by_zero() \
caml_raise_zero_divide()
/*---------------------------------------------------
CONVERSION FUNCTIONS
---------------------------------------------------*/
CAMLprim value ml_z_of_int(value v)
{
#if Z_USE_NATINT
Z_MARK_OP;
return v;
#else
intnat x;
value r;
Z_MARK_OP;
Z_MARK_SLOW;
x = Long_val(v);
r = ml_z_alloc(1);
if (x > 0) { Z_HEAD(r) = 1; Z_LIMB(r)[0] = x; }
else if (x < 0) { Z_HEAD(r) = 1 | Z_SIGN_MASK; Z_LIMB(r)[0] = -x; }
else Z_HEAD(r) = 0;
Z_CHECK(r);
return r;
#endif
}
CAMLprim value ml_z_of_nativeint(value v)
{
intnat x;
value r;
Z_MARK_OP;
x = Nativeint_val(v);
#if Z_USE_NATINT
if (Z_FITS_INT(x)) return Val_long(x);
#endif
Z_MARK_SLOW;
r = ml_z_alloc(1);
if (x > 0) { Z_HEAD(r) = 1; Z_LIMB(r)[0] = x; }
else if (x < 0) { Z_HEAD(r) = 1 | Z_SIGN_MASK; Z_LIMB(r)[0] = -x; }
else Z_HEAD(r) = 0;
Z_CHECK(r);
return r;
}
CAMLprim value ml_z_of_int32(value v)
{
int32_t x;
Z_MARK_OP;
x = Int32_val(v);
#if Z_USE_NATINT && defined(ARCH_SIXTYFOUR)
return Val_long(x);
#else
#if Z_USE_NATINT
if (Z_FITS_INT(x)) return Val_long(x);
#endif
{
value r;
Z_MARK_SLOW;
r = ml_z_alloc(1);
if (x > 0) { Z_HEAD(r) = 1; Z_LIMB(r)[0] = x; }
else if (x < 0) { Z_HEAD(r) = 1 | Z_SIGN_MASK; Z_LIMB(r)[0] = -(mp_limb_t)x; }
else Z_HEAD(r) = 0;
Z_CHECK(r);
return r;
}
#endif
}
CAMLprim value ml_z_of_int64(value v)
{
int64_t x;
value r;
Z_MARK_OP;
x = Int64_val(v);
#if Z_USE_NATINT
if (Z_FITS_INT(x)) return Val_long(x);
#endif
Z_MARK_SLOW;
#ifdef ARCH_SIXTYFOUR
r = ml_z_alloc(1);
if (x > 0) { Z_HEAD(r) = 1; Z_LIMB(r)[0] = x; }
else if (x < 0) { Z_HEAD(r) = 1 | Z_SIGN_MASK; Z_LIMB(r)[0] = -x; }
else Z_HEAD(r) = 0;
#else
{
mp_limb_t sign;
r = ml_z_alloc(2);
if (x >= 0) { sign = 0; }
else { sign = Z_SIGN_MASK; x = -x; }
Z_LIMB(r)[0] = x;
Z_LIMB(r)[1] = x >> 32;
r = ml_z_reduce(r, 2, sign);
}
#endif
Z_CHECK(r);
return r;
}
CAMLprim value ml_z_of_float(value v)
{
double x;
int exp;
int64_t y, m;
value r;
Z_MARK_OP;
x = Double_val(v);
#if Z_USE_NATINT
if (x >= Z_MIN_INT_FL && x <= Z_MAX_INT_FL) return Val_long((intnat) x);
#endif
Z_MARK_SLOW;
#ifdef ARCH_ALIGN_INT64
memcpy(&y, (void *) v, 8);
#else
y = *((int64_t*)v);
#endif
exp = ((y >> 52) & 0x7ff) - 1023; /* exponent */
if (exp < 0) return(Val_long(0));
if (exp == 1024) ml_z_raise_overflow(); /* NaN or infinity */
m = (y & 0x000fffffffffffffLL) | 0x0010000000000000LL; /* mantissa */
if (exp <= 52) {
m >>= 52-exp;
#ifdef ARCH_SIXTYFOUR
r = Val_long((x >= 0.) ? m : -m);
#else
r = ml_z_alloc(2);
Z_LIMB(r)[0] = m;
Z_LIMB(r)[1] = m >> 32;
r = ml_z_reduce(r, 2, (x >= 0.) ? 0 : Z_SIGN_MASK);
#endif
}
else {
int c1 = (exp-52) / Z_LIMB_BITS;
int c2 = (exp-52) % Z_LIMB_BITS;
mp_size_t i;
#ifdef ARCH_SIXTYFOUR
r = ml_z_alloc(c1 + 2);
for (i = 0; i < c1; i++) Z_LIMB(r)[i] = 0;
Z_LIMB(r)[c1] = m << c2;
Z_LIMB(r)[c1+1] = c2 ? (m >> (64-c2)) : 0;
r = ml_z_reduce(r, c1 + 2, (x >= 0.) ? 0 : Z_SIGN_MASK);
#else
r = ml_z_alloc(c1 + 3);
for (i = 0; i < c1; i++) Z_LIMB(r)[i] = 0;
Z_LIMB(r)[c1] = m << c2;
Z_LIMB(r)[c1+1] = m >> (32-c2);
Z_LIMB(r)[c1+2] = c2 ? (m >> (64-c2)) : 0;
r = ml_z_reduce(r, c1 + 3, (x >= 0.) ? 0 : Z_SIGN_MASK);
#endif
}
Z_CHECK(r);
return r;
}
CAMLprim value ml_z_of_substring_base(value b, value v, value offset, value length)
{
CAMLparam1(v);
CAMLlocal1(r);
intnat ofs = Long_val(offset);
intnat len = Long_val(length);
/* make sure the ofs/length make sense */
if (ofs < 0
|| len < 0
|| (intnat)caml_string_length(v) < ofs + len)
caml_invalid_argument("Z.of_substring_base: invalid offset or length");
/* process the string */
char *d = String_val(v) + ofs;
char *end = d + len;
mp_size_t i, sz, sz2;
mp_limb_t sign = 0;
intnat base = Long_val(b);
/* We allow [d] to advance beyond [end] while parsing the prefix:
sign, base, and/or leading zeros.
This simplifies the code, and reading these locations is safe since
we don't progress beyond a terminating null character.
At the end of the prefix, if we ran past the end, we return 0.
*/
/* get optional sign */
if (*d == '-') { sign ^= Z_SIGN_MASK; d++; }
if (*d == '+') d++;
/* get optional base */
if (!base) {
base = 10;
if (*d == '0') {
d++;
if (*d == 'o' || *d == 'O') { base = 8; d++; }
else if (*d == 'x' || *d == 'X') { base = 16; d++; }
else if (*d == 'b' || *d == 'B') { base = 2; d++; }
}
}
if (base < 2 || base > 16)
caml_invalid_argument("Z.of_substring_base: base must be between 2 and 16");
while (*d == '0') d++;
/* sz is the length of the substring that has not been consumed above. */
sz = end - d;
#if Z_USE_NATINT
if (sz <= 0) {
/* "+", "-", "0x" are parsed as 0. */
r = Val_long(0);
}
/* Process common case (fits into a native integer) */
else if ((base == 10 && sz <= Z_BASE10_LENGTH_OP)
|| (base == 16 && sz <= Z_BASE16_LENGTH_OP)
|| (base == 8 && sz <= Z_BASE8_LENGTH_OP)
|| (base == 2 && sz <= Z_BASE2_LENGTH_OP)) {
Z_MARK_OP;
intnat ret = 0;
for (i = 0; i < sz; i++) {
int digit = 0;
if (d[i] >= '0' && d[i] <= '9') digit = d[i] - '0';
else if (d[i] >= 'a' && d[i] <= 'f') digit = d[i] - 'a' + 10;
else if (d[i] >= 'A' && d[i] <= 'F') digit = d[i] - 'A' + 10;
else caml_invalid_argument("Z.of_substring_base: invalid digit");
if (digit >= base)
caml_invalid_argument("Z.of_substring_base: invalid digit");
ret = ret * base + digit;
}
r = Val_long(ret * (sign ? -1 : 1));
} else
#endif
{
/* converts to sequence of digits */
char* dd = (char*)malloc(sz+1);
strncpy(dd,d,sz);
/* make sure that dd is nul terminated */
dd[sz] = 0;
for (i = 0; i < sz; i++) {
if (dd[i] >= '0' && dd[i] <= '9') dd[i] -= '0';
else if (dd[i] >= 'a' && dd[i] <= 'f') dd[i] -= 'a' - 10;
else if (dd[i] >= 'A' && dd[i] <= 'F') dd[i] -= 'A' - 10;
else caml_invalid_argument("Z.of_substring_base: invalid digit");
if (dd[i] >= base)
caml_invalid_argument("Z.of_substring_base: invalid digit");
}
r = ml_z_alloc(1 + sz / (2 * sizeof(mp_limb_t)));
sz2 = mpn_set_str(Z_LIMB(r), (unsigned char*)dd, sz, base);
r = ml_z_reduce(r, sz2, sign);
free(dd);
}
Z_CHECK(r);
CAMLreturn(r);
}
CAMLprim value ml_z_to_int(value v)
{
intnat x;
Z_DECL(v);
Z_MARK_OP;
Z_CHECK(v);
if (Is_long(v)) return v;
Z_MARK_SLOW;
Z_ARG(v);
if (size_v > 1) ml_z_raise_overflow();
if (!size_v) return Val_long(0);
x = *ptr_v;
if (sign_v) {
if ((uintnat)x > Z_HI_INT) ml_z_raise_overflow();
x = -x;
}
else {
if ((uintnat)x >= Z_HI_INT) ml_z_raise_overflow();
}
return Val_long(x);
}
CAMLprim value ml_z_to_nativeint(value v)
{
intnat x;
Z_DECL(v);
Z_MARK_OP;
Z_CHECK(v);
if (Is_long(v)) return caml_copy_nativeint(Long_val(v));
Z_MARK_SLOW;
Z_ARG(v);
if (size_v > 1) ml_z_raise_overflow();
if (!size_v) x = 0;
else {
x = *ptr_v;
if (sign_v) {
if ((uintnat)x > Z_HI_INTNAT) ml_z_raise_overflow();
x = -x;
}
else {
if ((uintnat)x >= Z_HI_INTNAT) ml_z_raise_overflow();
}
}
return caml_copy_nativeint(x);
}
CAMLprim value ml_z_to_int32(value v)
{
intnat x;
Z_DECL(v);
Z_MARK_OP;
Z_CHECK(v);
if (Is_long(v)) {
x = Long_val(v);
#ifdef ARCH_SIXTYFOUR
if (x >= (intnat)Z_HI_INT32 || x < -(intnat)Z_HI_INT32)
ml_z_raise_overflow();
#endif
return caml_copy_int32(x);
}
else {
Z_ARG(v);
Z_MARK_SLOW;
if (size_v > 1) ml_z_raise_overflow();
if (!size_v) x = 0;
else {
x = *ptr_v;
if (sign_v) {
if ((uintnat)x > Z_HI_INT32) ml_z_raise_overflow();
x = -x;
}
else {
if ((uintnat)x >= Z_HI_INT32) ml_z_raise_overflow();
}
}
return caml_copy_int32(x);
}
}
CAMLprim value ml_z_to_int64(value v)
{
int64_t x = 0;
Z_DECL(v);
Z_MARK_OP;
Z_CHECK(v);
if (Is_long(v)) return caml_copy_int64(Long_val(v));
Z_MARK_SLOW;
Z_ARG(v);
switch (size_v) {
case 0: x = 0; break;
case 1: x = ptr_v[0]; break;
#ifndef ARCH_SIXTYFOUR
case 2: x = ptr_v[0] | ((uint64_t)ptr_v[1] << 32); break;
#endif
default: ml_z_raise_overflow(); break;
}
if (sign_v) {
if ((uint64_t)x > Z_HI_INT64) ml_z_raise_overflow();
x = -x;
}
else {
if ((uint64_t)x >= Z_HI_INT64) ml_z_raise_overflow();
}
return caml_copy_int64(x);
}
/* XXX: characters that do not belong to the format are ignored, this departs
from the classic printf behavior (it copies them in the output)
*/
CAMLprim value ml_z_format(value f, value v)
{
CAMLparam2(f,v);
Z_DECL(v);
const char tab[2][16] =
{ { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' },
{ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' } };
char* buf, *dst;
mp_size_t i, size_dst, max_size;
value r;
char* fmt = String_val(f);
int base = 10; /* base */
int cas = 0; /* uppercase X / lowercase x */
int width = 0;
int alt = 0; /* alternate # */
int dir = 0; /* right / left adjusted */
char sign = 0; /* sign char */
char pad = ' '; /* padding char */
char *prefix = "";
Z_MARK_OP;
Z_CHECK(v);
Z_ARG(v);
Z_MARK_SLOW;
/* parse format */
while (*fmt == '%') fmt++;
for (; ; fmt++) {
if (*fmt == '#') alt = 1;
else if (*fmt == '0') pad = '0';
else if (*fmt == '-') dir = 1;
else if (*fmt == ' ' || *fmt == '+') sign = *fmt;
else break;
}
if (sign_v) sign = '-';
for (;*fmt>='0' && *fmt<='9';fmt++)
width = 10*width + *fmt-'0';
switch (*fmt) {
case 'i': case 'd': case 'u': break;
case 'b': base = 2; if (alt) prefix = "0b"; break;
case 'o': base = 8; if (alt) prefix = "0o"; break;
case 'x': base = 16; if (alt) prefix = "0x"; cas = 1; break;
case 'X': base = 16; if (alt) prefix = "0X"; break;
default: caml_invalid_argument("Z.format: invalid format");
}
if (dir) pad = ' ';
/* get digits */
/* we need space for sign + prefix + digits + 1 + padding + terminal 0 */
max_size = 1 + 2 + Z_LIMB_BITS * size_v + 1 + 2 * width + 1;
buf = (char*) malloc(max_size);
dst = buf + 1 + 2 + width;
if (!size_v) {
size_dst = 1;
*dst = '0';
}
else {
mp_limb_t* copy_v = ml_z_dup_limb(ptr_v, size_v);
size_dst = mpn_get_str((unsigned char*)dst, base, copy_v, size_v);
if (dst + size_dst >= buf + max_size)
caml_failwith("Z.format: internal error");
free(copy_v);
while (size_dst && !*dst) { dst++; size_dst--; }
for (i = 0; i < size_dst; i++)
dst[i] = tab[cas][ (int) dst[i] ];
}
/* add prefix, sign & padding */
if (pad == ' ') {
if (dir) {
/* left alignment */
for (i = strlen(prefix); i > 0; i--, size_dst++)
*(--dst) = prefix[i-1];
if (sign) { *(--dst) = sign; size_dst++; }
for (; size_dst < width; size_dst++)
dst[size_dst] = pad;
}
else {
/* right alignment, space padding */
for (i = strlen(prefix); i > 0; i--, size_dst++)
*(--dst) = prefix[i-1];
if (sign) { *(--dst) = sign; size_dst++; }
for (; size_dst < width; size_dst++) *(--dst) = pad;
}
}
else {
/* right alignment, non-space padding */
width -= strlen(prefix) + (sign ? 1 : 0);
for (; size_dst < width; size_dst++) *(--dst) = pad;
for (i = strlen(prefix); i > 0; i--, size_dst++)
*(--dst) = prefix[i-1];
if (sign) { *(--dst) = sign; size_dst++; }
}
dst[size_dst] = 0;
if (dst < buf || dst + size_dst >= buf + max_size)
caml_failwith("Z.format: internal error");
r = caml_copy_string(dst);
free(buf);
CAMLreturn(r);
}
#ifdef ARCH_SIXTYFOUR
#define BITS_PER_WORD 64
#else
#define BITS_PER_WORD 32
#endif
CAMLprim value ml_z_extract(value arg, value off, value len)
{
intnat o, l, x;
mp_size_t sz, c1, c2, csz, i;
mp_limb_t cr;
value r;
Z_DECL(arg);
Z_MARK_OP;
MAYBE_UNUSED x;
o = Long_val(off);
l = Long_val(len);
if (o < 0) caml_invalid_argument("Z.extract: negative bit offset");
if (l <= 0) caml_invalid_argument("Z.extract: non-positive bit length");
#if Z_USE_NATINT
/* Fast path */
if (Is_long(arg)) {
x = Long_val(arg);
/* Shift away low "o" bits. If "o" too big, just replicate sign bit. */
if (o >= BITS_PER_WORD) o = BITS_PER_WORD - 1;
x = x >> o;
/* Extract "l" low bits, if "l" is small enough */
if (l < BITS_PER_WORD - 1) {
x = x & (((intnat)1 << l) - 1);
return Val_long(x);
} else {
/* If x >= 0, the extraction of "l" low bits keeps x unchanged. */
if (x >= 0) return Val_long(x);
/* If x < 0, fall through slow path */
}
}
#endif
Z_MARK_SLOW;
{
CAMLparam1(arg);
Z_ARG(arg);
sz = (l + Z_LIMB_BITS - 1) / Z_LIMB_BITS;
r = ml_z_alloc(sz + 1);
Z_REFRESH(arg);
c1 = o / Z_LIMB_BITS;
c2 = o % Z_LIMB_BITS;
/* shift or copy */
csz = size_arg - c1;
if (csz > sz + 1) csz = sz + 1;
cr = 0;
if (csz > 0) {
if (c2) cr = mpn_rshift(Z_LIMB(r), ptr_arg + c1, csz, c2);
else ml_z_cpy_limb(Z_LIMB(r), ptr_arg + c1, csz);
}
else csz = 0;
/* 0-pad */
for (i = csz; i < sz; i++)
Z_LIMB(r)[i] = 0;
/* 2's complement */
if (sign_arg) {
for (i = 0; i < sz; i++)
Z_LIMB(r)[i] = ~Z_LIMB(r)[i];
/* carry (cr=0 if all shifted-out bits are 0) */
for (i = 0; !cr && i < c1 && i < size_arg; i++)
cr = ptr_arg[i];
if (!cr) mpn_add_1(Z_LIMB(r), Z_LIMB(r), sz, 1);
}
/* mask out high bits */
l %= Z_LIMB_BITS;
if (l) Z_LIMB(r)[sz-1] &= ((uintnat)(intnat)-1) >> (Z_LIMB_BITS - l);
r = ml_z_reduce(r, sz, 0);
CAMLreturn(r);
}
}
/* NOTE: the sign is not stored */
CAMLprim value ml_z_to_bits(value arg)
{
CAMLparam1(arg);
CAMLlocal1(r);
Z_DECL(arg);
mp_size_t i;
unsigned char* p;
Z_MARK_OP;
Z_MARK_SLOW;
Z_ARG(arg);
r = caml_alloc_string(size_arg * sizeof(mp_limb_t));
Z_REFRESH(arg);
p = (unsigned char*) String_val(r);
memset(p, 0, size_arg * sizeof(mp_limb_t));
for (i = 0; i < size_arg; i++) {
mp_limb_t x = ptr_arg[i];
*(p++) = x;
*(p++) = x >> 8;
*(p++) = x >> 16;
*(p++) = x >> 24;
#ifdef ARCH_SIXTYFOUR
*(p++) = x >> 32;
*(p++) = x >> 40;
*(p++) = x >> 48;
*(p++) = x >> 56;
#endif
}
CAMLreturn(r);
}
CAMLprim value ml_z_of_bits(value arg)
{
CAMLparam1(arg);
CAMLlocal1(r);
mp_size_t sz, szw;
mp_size_t i = 0;
mp_limb_t x;
unsigned char* p;
Z_MARK_OP;
Z_MARK_SLOW;
sz = caml_string_length(arg);
szw = (sz + sizeof(mp_limb_t) - 1) / sizeof(mp_limb_t);
r = ml_z_alloc(szw);
p = (unsigned char*) String_val(arg);
/* all limbs but last */
if (szw > 1) {
for (; i < szw - 1; i++) {
x = *(p++);
x |= ((mp_limb_t) *(p++)) << 8;
x |= ((mp_limb_t) *(p++)) << 16;
x |= ((mp_limb_t) *(p++)) << 24;
#ifdef ARCH_SIXTYFOUR
x |= ((mp_limb_t) *(p++)) << 32;
x |= ((mp_limb_t) *(p++)) << 40;
x |= ((mp_limb_t) *(p++)) << 48;
x |= ((mp_limb_t) *(p++)) << 56;
#endif