-
Notifications
You must be signed in to change notification settings - Fork 21
/
XS.xs
5687 lines (5399 loc) · 172 KB
/
XS.xs
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
#define PERL_NO_GET_CONTEXT 1 /* Define at top for more efficiency. */
#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"
#include "multicall.h" /* only works in 5.6 and newer */
#include <stdio.h> /* For fileno and stdout */
#define NEED_newCONSTSUB
#define NEED_newRV_noinc
#define NEED_sv_2pv_flags
#define NEED_HvNAME_get
#include "ppport.h"
#define FUNC_gcd_ui 1
#define FUNC_isqrt 1
#define FUNC_ipow 1
#define FUNC_popcnt 1
#define FUNC_is_strong_pseudoprime 1
#include "ptypes.h"
#include "cache.h"
#include "sieve.h"
#include "sieve_cluster.h"
#include "util.h"
#include "primality.h"
#include "lucas_seq.h"
#include "factor.h"
#include "totients.h"
#include "lehmer.h"
#include "lmo.h"
#include "legendre_phi.h"
#include "aks.h"
#include "constants.h"
#include "mulmod.h"
#include "entropy.h"
#include "csprng.h"
#include "random_prime.h"
#include "perfect_powers.h"
#include "prime_powers.h"
#include "ramanujan_primes.h"
#include "semi_primes.h"
#include "twin_primes.h"
#include "almost_primes.h"
#include "omega_primes.h"
#include "prime_counts.h"
#include "prime_sums.h"
#include "powerfree.h"
#include "powerful.h"
#include "lucky_numbers.h"
#include "rootmod.h"
#include "real.h"
#include "ds_iset.h"
#ifdef FACTORING_HARNESSES
#include <sys/time.h>
static double my_difftime (struct timeval * start, struct timeval * end) {
double secs, usecs;
if (start->tv_sec == end->tv_sec) {
secs = 0;
usecs = end->tv_usec - start->tv_usec;
} else {
usecs = 1000000 - start->tv_usec;
secs = end->tv_sec - (start->tv_sec + 1);
usecs += end->tv_usec;
if (usecs >= 1000000) {
usecs -= 1000000;
secs += 1;
}
}
return secs + usecs / 1000000.;
}
#endif
#if BITS_PER_WORD == 64
#if defined(_MSC_VER)
#include <stdlib.h>
#define strtoull _strtoui64
#define strtoll _strtoi64
#endif
#define PSTRTOULL(str, end, base) strtoull (str, end, base)
#define PSTRTOLL(str, end, base) strtoll (str, end, base)
#else
#define PSTRTOULL(str, end, base) strtoul (str, end, base)
#define PSTRTOLL(str, end, base) strtol (str, end, base)
#endif
#if defined(_MSC_VER) && !defined(strtold)
#define strtold strtod
#endif
#if PERL_REVISION <= 5 && PERL_VERSION <= 6 && BITS_PER_WORD == 64
/* Workaround perl 5.6 UVs and bigints */
#define my_svuv(sv) PSTRTOULL(SvPV_nolen(sv), NULL, 10)
#define my_sviv(sv) PSTRTOLL(SvPV_nolen(sv), NULL, 10)
#elif PERL_REVISION <= 5 && PERL_VERSION < 14 && BITS_PER_WORD == 64
/* Workaround RT 49569 in Math::BigInt::FastCalc (pre 5.14.0) */
/* TODO: Math::BigInt::Pari has the same problem with negs pre-5.18.0 */
#define my_svuv(sv) ( (!SvROK(sv)) ? SvUV(sv) : PSTRTOULL(SvPV_nolen(sv),NULL,10) )
#define my_sviv(sv) ( (!SvROK(sv)) ? SvIV(sv) : PSTRTOLL(SvPV_nolen(sv),NULL,10) )
#else
#define my_svuv(sv) SvUV(sv)
#define my_sviv(sv) SvIV(sv)
#endif
#if PERL_REVISION >=5 && PERL_VERSION >= 9 && PERL_SUBVERSION >= 4
#define SVf_MAGTEST SVf_ROK
#else
#define SVf_MAGTEST SVf_AMAGIC
#endif
#define SVNUMTEST(n) \
((SvFLAGS(n) & (SVf_IOK | SVf_MAGTEST | SVs_GMG )) == SVf_IOK)
/* multicall compatibility stuff */
#if (PERL_REVISION <= 5 && PERL_VERSION < 7) || !defined(dMULTICALL)
# define USE_MULTICALL 0 /* Too much trouble to work around it */
#else
# define USE_MULTICALL 1
#endif
#if PERL_VERSION < 13 || (PERL_VERSION == 13 && PERL_SUBVERSION < 9)
# define FIX_MULTICALL_REFCOUNT \
if (CvDEPTH(multicall_cv) > 1) SvREFCNT_inc(multicall_cv);
#else
# define FIX_MULTICALL_REFCOUNT
#endif
#ifndef CvISXSUB
# define CvISXSUB(cv) CvXSUB(cv)
#endif
/* Not right, but close */
#if !defined cxinc && ( (PERL_VERSION == 8 && PERL_SUBVERSION >= 1) || (PERL_VERSION == 10 && PERL_SUBVERSION <= 1) )
# define cxinc() Perl_cxinc(aTHX)
#endif
#if PERL_VERSION < 17 || (PERL_VERSION == 17 && PERL_SUBVERSION < 7)
# define SvREFCNT_dec_NN(sv) SvREFCNT_dec(sv)
#endif
#if BITS_PER_WORD == 32
static const unsigned int uvmax_maxlen = 10;
static const unsigned int ivmax_maxlen = 10;
static const char uvmax_str[] = "4294967295";
/* static const char ivmax_str[] = "2147483648"; */
static const char ivmin_str[] = "2147483648";
#else
static const unsigned int uvmax_maxlen = 20;
static const unsigned int ivmax_maxlen = 19;
static const char uvmax_str[] = "18446744073709551615";
/* static const char ivmax_str[] = "9223372036854775808"; */
static const char ivmin_str[] = "9223372036854775808";
#endif
#define MY_CXT_KEY "Math::Prime::Util::API_guts"
#define CINTS 100
typedef struct {
HV* MPUroot;
HV* MPUGMP;
HV* MPUPP;
SV* const_int[CINTS+1]; /* -1, 0, 1, ..., 99 */
void* randcxt; /* per-thread csprng context */
uint16_t forcount;
char forexit;
} my_cxt_t;
START_MY_CXT
static int _is_sv_bigint(pTHX_ SV* n)
{
if (sv_isobject(n)) {
const char *hvname = HvNAME_get(SvSTASH(SvRV(n)));
if (hvname != 0) {
if (strEQ(hvname, "Math::BigInt") || strEQ(hvname, "Math::BigFloat") ||
strEQ(hvname, "Math::GMPz") || strEQ(hvname, "Math::GMP") ||
strEQ(hvname, "Math::GMPq") || strEQ(hvname, "Math::AnyNum") ||
strEQ(hvname, "Math::Pari") || strEQ(hvname, "Math::BigInt::Lite"))
return 1;
}
}
return 0;
}
/* Is this a pedantically valid integer?
* Croaks if undefined or invalid.
* Returns 0 if it is an object or a string too large for a UV.
* Returns 1 if it is good to process by XS.
*/
static int _validate_int(pTHX_ SV* n, int negok)
{
const char* mustbe = (negok) ? "must be an integer" : "must be a non-negative integer";
const char* maxstr;
char* ptr;
STRLEN i, len, maxlen;
int ret, isbignum = 0, isneg = 0;
/* TODO: magic, grok_number, etc. */
if (SVNUMTEST(n)) { /* If defined as number, use it */
if (SvIsUV(n) || SvIVX(n) >= 0) return 1; /* The normal case */
if (negok) return -1;
else croak("Parameter '%" SVf "' %s", n, mustbe);
}
if (sv_isobject(n)) {
isbignum = _is_sv_bigint(aTHX_ n);
if (!isbignum) return 0;
}
/* Without being very careful, don't process magic variables here */
if (SvGAMAGIC(n) && !isbignum) return 0;
if (!SvOK(n)) croak("Parameter must be defined");
ptr = SvPV_nomg(n, len); /* Includes stringifying bigints */
if (len == 0 || ptr == 0) croak("Parameter %s", mustbe);
if (ptr[0] == '-' && negok) {
isneg = 1; ptr++; len--; /* Read negative sign */
} else if (ptr[0] == '+') {
ptr++; len--; /* Allow a single plus sign */
}
ret = isneg ? -1 : 1;
maxlen = isneg ? ivmax_maxlen : uvmax_maxlen;
maxstr = isneg ? ivmin_str : uvmax_str; /* ivmin_str is intentional */
if (len == 0 || !isDIGIT(ptr[0]))
croak("Parameter '%" SVf "' %s", n, mustbe);
while (len > 0 && *ptr == '0') /* Strip all leading zeros */
{ ptr++; len--; }
if (len > maxlen)
return 0; /* Huge number, don't even look at it */
for (i = 0; i < len; i++) /* Ensure all characters are digits */
if (!isDIGIT(ptr[i]))
croak("Parameter '%" SVf "' %s", n, mustbe);
if (len < maxlen) /* Valid small integer */
return ret;
for (i = 0; i < maxlen; i++) { /* Check if in range */
if (ptr[i] < maxstr[i]) return ret;
if (ptr[i] > maxstr[i]) return 0;
}
return ret; /* value = UV_MAX/UV_MIN. That's ok */
}
#define IFLAG_ANY 0x00000000U
#define IFLAG_POS 0x00000001U /* Must be non-negative */
#define IFLAG_NONZERO 0x00000002U /* Must not be zero */
#define IFLAG_ABS 0x00000004U /* Absolute value returned */
#define IFLAG_IV 0x00000008U /* Value returned as IV */
static int _validate_and_set(UV* val, pTHX_ SV* svn, uint32_t mask) {
UV n = 0;
int negok = !(mask & IFLAG_POS);
int status = _validate_int(aTHX_ svn, negok);
if (status == 1) {
n = my_svuv(svn);
#if 0 /* _validate_int already does this */
} else if (status == -1 && (mask & IFLAG_POS)) {
croak("parameter must be a non-negative integer");
#endif
} else if (status == -1) {
if (mask & IFLAG_ABS) {
n = (UV)(-(my_sviv(svn)));
status = 1;
} else {
n = (UV)my_sviv(svn);
}
}
if (status != 0 && (mask & IFLAG_NONZERO) && n == 0)
croak("Parameter '%" SVf "' must be a positive integer", svn);
/* If they want an IV returned, verify it fits. */
if (status == 1 && (mask & IFLAG_IV) && n > (UV)IV_MAX)
status = 0;
if (status != 0)
*val = n;
return status;
}
static UV neg_iv(UV n) {
if ((IV)n == IV_MIN) return (UV_MAX >> 1) + 1;
else return (UV) (-(IV)n);
}
/* Given 'a' and astatus (-1 means 'a' is an IV), properly mod with n */
static void _mod_with(UV *a, int astatus, UV n) {
if (n == 0) return;
if (astatus != -1) {
*a %= n;
} else {
UV r = neg_iv(*a) % n;
*a = (r == 0) ? 0 : n-r;
}
}
#define VCALL_ROOT 0x0
#define VCALL_PP 0x1
#define VCALL_GMP 0x2
/* Call a Perl sub to handle work for us. */
static int _vcallsubn(pTHX_ I32 flags, I32 stashflags, const char* name, int nargs, int minversion)
{
GV* gv = NULL;
dMY_CXT;
Size_t namelen = strlen(name);
/* If given a GMP function, and GMP enabled, and function exists, use it. */
int use_gmp = stashflags & VCALL_GMP && _XS_get_callgmp() && _XS_get_callgmp() >= minversion;
assert(!(stashflags & ~(VCALL_PP|VCALL_GMP)));
if (use_gmp && hv_exists(MY_CXT.MPUGMP,name,namelen)) {
GV ** gvp = (GV**)hv_fetch(MY_CXT.MPUGMP,name,namelen,0);
if (gvp) gv = *gvp;
}
if (!gv && (stashflags & VCALL_PP))
perl_require_pv("Math/Prime/Util/PP.pm");
if (!gv) {
GV ** gvp = (GV**)hv_fetch(stashflags & VCALL_PP? MY_CXT.MPUPP : MY_CXT.MPUroot, name,namelen,0);
if (gvp) gv = *gvp;
}
/* use PL_stack_sp in PUSHMARK macro directly it will be read after
the possible mark stack extend */
PUSHMARK(PL_stack_sp-nargs);
/* no PUTBACK bc we didn't move global SP */
return call_sv((SV*)gv, flags);
}
#define _vcallsub(func) (void)_vcallsubn(aTHX_ G_SCALAR, VCALL_ROOT, func, items,0)
#define _vcallsub_with_gmp(ver,func) (void)_vcallsubn(aTHX_ G_SCALAR, VCALL_GMP|VCALL_PP, func, items,(int)(100*(ver)))
#define _vcallsub_with_pp(func) (void)_vcallsubn(aTHX_ G_SCALAR, VCALL_PP, func, items,0)
/* #define _vcallsub_with_gmpobj(ver,func) (void)_vcallsubn(aTHX_ G_SCALAR, (PERL_REVISION >= 5 && PERL_VERSION > 8) ? VCALL_GMP|VCALL_PP : VCALL_PP, func, items,(int)(100*(ver))) */
#define _vcallsub_with_gmpobj(ver,func) _vcallsub_with_gmp(ver,func)
#if 0
static int _vcallgmpsubn(pTHX_ I32 flags, const char* name, int nargs, int minversion)
{
Size_t namelen = strlen(name);
int gmpver = _XS_get_callgmp();
dMY_CXT;
if (gmpver && gmpver >= minversion && hv_exists(MY_CXT.MPUGMP,name,namelen)) {
GV ** gvp = (GV**)hv_fetch(MY_CXT.MPUGMP,name,namelen,0);
if (gvp) {
GV* gv = *gvp;
PUSHMARK(PL_stack_sp-nargs);
return call_sv((SV*)gv, flags);
}
}
return 0;
}
#endif
/* In my testing, this constant return works fine with threads, but to be
* correct (see perlxs) one has to make a context, store separate copies in
* each one, then retrieve them from a struct using a hash index. This
* defeats the purpose if only done once. */
#define RETURN_NPARITY(ret) \
do { int r_ = ret; \
dMY_CXT; \
if (r_ >= -1 && r_<CINTS) { ST(0) = MY_CXT.const_int[r_+1]; XSRETURN(1); } \
else { XSRETURN_IV(r_); } \
} while (0)
#define PUSH_NPARITY(ret) \
do { int r_ = ret; \
if (r_ >= -1 && r_<CINTS) { PUSHs( MY_CXT.const_int[r_+1] ); } \
else { PUSHs(sv_2mortal(newSViv(r_))); } \
} while (0)
static void objectify_result(pTHX_ SV* input, SV* output) {
/* Leave unchanged: undef, objects, small integers */
if (!SvOK(output) || sv_isobject(output) || SVNUMTEST(output))
return;
/* If they didn't give us a bigint, then try to be smart */
if (!input || !sv_isobject(input)) {
(void)_vcallsubn(aTHX_ G_SCALAR, VCALL_ROOT, "_to_bigint_if_needed", 1, 0);
} else {
const char *iname = HvNAME_get(SvSTASH(SvRV(input)));
if (strEQ(iname, "Math::BigInt")) {
(void)_vcallsubn(aTHX_ G_SCALAR, VCALL_ROOT, "_to_bigint", 1, 0);
} else if (strEQ(iname, "Math::GMPz")) {
(void)_vcallsubn(aTHX_ G_SCALAR, VCALL_ROOT, "_to_gmpz", 1, 0);
} else if (strEQ(iname, "Math::GMP")) {
(void)_vcallsubn(aTHX_ G_SCALAR, VCALL_ROOT, "_to_gmp", 1, 0);
} else { /* Return it as: ref(input)->new(result) */
dSP; (void)POPs; ENTER; PUSHMARK(SP);
XPUSHs(sv_2mortal(newSVpv(iname, 0))); XPUSHs(output);
PUTBACK; call_method("new", G_SCALAR); LEAVE;
}
}
}
static SV* call_sv_to_func(pTHX_ SV* r, const char* name) {
dSP; ENTER; PUSHMARK(SP);
XPUSHs(r);
PUTBACK;
call_pv(name, G_SCALAR);
SPAGAIN;
r = POPs;
PUTBACK; LEAVE;
return r;
}
static SV* sv_to_bigint(pTHX_ SV* r) {
return call_sv_to_func(aTHX_ r, "Math::Prime::Util::_to_bigint");
}
static SV* sv_to_bigint_abs(pTHX_ SV* r) {
return call_sv_to_func(aTHX_ r, "Math::Prime::Util::_to_bigint_abs");
}
static SV* sv_to_bigint_nonneg(pTHX_ SV* r) {
return call_sv_to_func(aTHX_ r, "Math::Prime::Util::_to_bigint_nonneg");
}
#define RETURN_128(hi,lo) \
do { char str[40]; \
int slen = to_string_128(str, hi, lo); \
ST(0) = sv_to_bigint( aTHX_ sv_2mortal(newSVpv(str,slen)) ); \
XSRETURN(1); } while(0)
#define CREATE_AV(av) \
do { \
av = newAV(); \
{ \
SV * retsv = sv_2mortal(newRV_noinc( (SV*) av )); \
PUSHs(retsv); \
PUTBACK; \
SP = NULL; /* never use SP again, poison */ \
} \
} while(0)
static int arrayref_to_digit_array(pTHX_ UV** ret, AV* av, int base)
{
int len, i;
UV *r, carry = 0;
if (SvTYPE((SV*)av) != SVt_PVAV)
croak("fromdigits first argument must be a string or array reference");
len = 1 + av_len(av);
New(0, r, len, UV);
for (i = len-1; i >= 0; i--) {
SV** psvd = av_fetch(av, i, 0);
if (_validate_and_set(r+i, aTHX_ *psvd, IFLAG_ANY) != 1) break;
r[i] += carry;
if (r[i] >= (UV)base && i > 0) {
carry = r[i] / base;
r[i] -= carry * base;
} else {
carry = 0;
}
}
if (i >= 0) {
Safefree(r);
return -1;
}
/* printf("array is ["); for(i=0;i<len;i++)printf("%lu,",r[i]); printf("]\n"); */
*ret = r;
return len;
}
static int arrayref_to_iv_array(pTHX_ IV** ret, SV* sva, const char* fstr)
{
AV *av;
int len, i;
if ((!SvROK(sva)) || (SvTYPE(SvRV(sva)) != SVt_PVAV))
croak("%s argument must be an array reference", fstr);
av = (AV*) SvRV(sva);
len = av_len(av);
*ret = 0;
if (len >= 0) {
UV val;
IV *r;
New(0, r, len+1, IV);
for (i = 0; i <= len; i++) {
SV **iv = av_fetch(av, i, 0);
if (iv==0 || _validate_and_set(&val, aTHX_ *iv, IFLAG_ANY|IFLAG_IV) == 0)
break;
r[i] = (IV)val;
}
if (i <= len) {
Safefree(r);
return -2;
}
*ret = r;
}
return len;
}
static int arrayref_to_int_array(pTHX_ unsigned long *retlen, UV** ret, SV* sva, const char* fstr)
{
AV *av;
int len, i, istatus, sflag;
UV val, *r;
if ((!SvROK(sva)) || (SvTYPE(SvRV(sva)) != SVt_PVAV))
croak("%s argument must be an array reference", fstr);
av = (AV*) SvRV(sva);
len = av_len(av);
if (len < 0) {
*retlen = 0; *ret = 0; return 1;
}
sflag = 0;
New(0, r, len+1, UV);
for (i = 0; i <= len; i++) {
SV **iv = av_fetch(av, i, 0);
if (iv == 0) break;
istatus = _validate_and_set(&val, aTHX_ *iv, IFLAG_ANY);
if (val > (UV)IV_MAX) {
sflag |= ((istatus == 1) ? 1 : 2);
if (sflag == 3) istatus = 0;
}
if (istatus == 0) break;
r[i] = val;
}
if (i <= len) {
Safefree(r);
*retlen = 0; *ret = 0; return 0;
}
*retlen = len+1;
*ret = r;
return ((sflag == 2) ? -1 : 1);
}
/* Status -1 for IVs, 1 for UVs, 0 for failed (overflow or bigints) */
static iset_t arrayref_to_iset(pTHX_ int *status, SV* sva, const char* fstr)
{
UV *r;
unsigned long len;
iset_t s;
/* Doing this in two steps is much faster than one, probably caching. */
*status = arrayref_to_int_array(aTHX_ &len, &r, sva, fstr);
s = iset_create_from_array(r, len, *status);
Safefree(r);
return s;
}
static int _compare_array_refs(pTHX_ SV* a, SV* b)
{
AV *ava, *avb;
int i, alen, blen;
if ( ((!SvROK(a)) || (SvTYPE(SvRV(a)) != SVt_PVAV)) ||
((!SvROK(b)) || (SvTYPE(SvRV(b)) != SVt_PVAV)) )
return -1;
ava = (AV*) SvRV(a);
avb = (AV*) SvRV(b);
alen = av_len(ava);
blen = av_len(avb);
if (alen != blen)
return 0;
for (i = 0; i <= alen; i++) {
SV** iva = av_fetch(ava, i, 0);
SV** ivb = av_fetch(avb, i, 0);
SV *sva, *svb;
int res;
if (!iva || !ivb) return -1;
sva = *iva;
svb = *ivb;
if (!SvOK(sva) && !SvOK(svb)) /* Two undefs are fine. */
continue;
if (!SvOK(sva) || !SvOK(svb)) /* One undef isn't ok. */
return 0;
/* Hashes, I/O, etc. are not ok. */
if (SvTYPE(sva) >= SVt_PVAV || SvTYPE(svb) >= SVt_PVAV)
return -1;
/* One of them is a non-object reference */
if ( (SvROK(sva) && !sv_isobject(sva)) ||
(SvROK(svb) && !sv_isobject(svb)) ) {
/* Always error if either one is not an array reference. */
if ( (SvROK(sva) && SvTYPE(SvRV(sva)) != SVt_PVAV) ||
(SvROK(svb) && SvTYPE(SvRV(svb)) != SVt_PVAV) )
return -1;
/* One reference, one non-reference = not equal */
if (SvROK(sva) != SvROK(svb))
return 0;
/* Now we know both are array references. Compare. */
res = _compare_array_refs(aTHX_ sva, svb);
if (res == 1) continue;
return res;
}
/* Common case: two simple integers */
if ( SVNUMTEST(sva) && SVNUMTEST(svb)
&& (SvTYPE(sva) == SVt_IV || SvTYPE(sva) == SVt_PVIV)
&& (SvTYPE(svb) == SVt_IV || SvTYPE(svb) == SVt_PVIV) ) {
UV va = my_svuv(sva), vb = my_svuv(svb);
if (va != vb) return 0;
continue;
}
/* This function is more useful if we allow more than strictly integers */
{ /* Compare the string representation */
STRLEN alen, blen;
const char* stra = SvPV(sva, alen);
const char* strb = SvPV(svb, blen);
if (alen != blen || strcmp(stra,strb) != 0)
return 0;
}
}
return 1;
}
static void csprng_init_seed(void* ctx) {
unsigned char* data;
New(0, data, 64, unsigned char);
get_entropy_bytes(64, data);
csprng_seed(ctx, 64, data);
Safefree(data);
}
static void _comb_init(UV* cm, UV k, int derangement) {
UV i;
cm[0] = UV_MAX;
for (i = 0; i < k; i++)
cm[i] = k-i;
if (derangement && k >= 2) { /* Make derangements start deranged */
for (i = 0; i < k; i++)
cm[k-i-1] = (i&1) ? i : i+2;
if (k & 1) {
cm[0] = k-2;
cm[1] = k;
}
}
}
static int _comb_iterate(UV* cm, UV k, UV n, int ix) {
UV i, j, m;
if (ix == 0) {
if (cm[0]++ < n) return 0; /* Increment last value */
for (i = 1; i < k && cm[i] >= n-i; i++) ; /* Find next index to incr */
if (i >= k) return 1; /* Done! */
cm[i]++; /* Increment this one */
while (i-- > 0) cm[i] = cm[i+1] + 1; /* Set the rest */
} else if (ix == 1) {
for (j = 1; j < k && cm[j] > cm[j-1]; j++) ; /* Find last decrease */
if (j >= k) return 1; /* Done! */
for (m = 0; cm[j] > cm[m]; m++) ; /* Find next greater */
{ UV t = cm[j]; cm[j] = cm[m]; cm[m] = t; } /* Swap */
for (i = j-1, m = 0; m < i; i--, m++) /* Reverse the end */
{ UV t = cm[i]; cm[i] = cm[m]; cm[m] = t; }
} else {
REDERANGE:
for (j = 1; j < k && cm[j] > cm[j-1]; j++) ; /* Find last decrease */
if (j >= k) return 1; /* Done! */
for (m = 0; cm[j] > cm[m]; m++) ; /* Find next greater */
{ UV t = cm[j]; cm[j] = cm[m]; cm[m] = t; } /* Swap */
if (cm[j] == k-j) goto REDERANGE; /* Skip? */
for (i = j-1, m = 0; m < i; i--, m++) /* Reverse the end */
{ UV t = cm[i]; cm[i] = cm[m]; cm[m] = t; }
for (i = 0; i < k; i++) /* Check deranged */
if (cm[k-i-1]-1 == i)
break;
if (i != k) goto REDERANGE;
}
return 0;
}
MODULE = Math::Prime::Util PACKAGE = Math::Prime::Util
PROTOTYPES: ENABLE
BOOT:
{
int i;
SV * sv = newSViv(BITS_PER_WORD);
HV * stash = gv_stashpv("Math::Prime::Util", TRUE);
newCONSTSUB(stash, "_XS_prime_maxbits", sv);
{
MY_CXT_INIT;
MY_CXT.MPUroot = stash;
MY_CXT.MPUGMP = gv_stashpv("Math::Prime::Util::GMP", TRUE);
MY_CXT.MPUPP = gv_stashpv("Math::Prime::Util::PP", TRUE);
for (i = 0; i <= CINTS; i++) {
MY_CXT.const_int[i] = newSViv(i-1);
SvREADONLY_on(MY_CXT.const_int[i]);
}
New(0, MY_CXT.randcxt, csprng_context_size(), char);
csprng_init_seed(MY_CXT.randcxt);
MY_CXT.forcount = 0;
MY_CXT.forexit = 0;
}
}
#if defined(USE_ITHREADS) && defined(MY_CXT_KEY)
void
CLONE(...)
PREINIT:
int i;
PPCODE:
{
MY_CXT_CLONE; /* possible declaration */
MY_CXT.MPUroot = gv_stashpv("Math::Prime::Util", TRUE);
MY_CXT.MPUGMP = gv_stashpv("Math::Prime::Util::GMP", TRUE);
MY_CXT.MPUPP = gv_stashpv("Math::Prime::Util::PP", TRUE);
/* These should be shared between threads, but that's dodgy. */
for (i = 0; i <= CINTS; i++) {
MY_CXT.const_int[i] = newSViv(i-1);
SvREADONLY_on(MY_CXT.const_int[i]);
}
/* Make a new CSPRNG context for this thread */
New(0, MY_CXT.randcxt, csprng_context_size(), char);
csprng_init_seed(MY_CXT.randcxt);
/* NOTE: There is no thread destroy, so these never get freed... */
MY_CXT.forcount = 0;
MY_CXT.forexit = 0;
}
return; /* skip implicit PUTBACK, returning @_ to caller, more efficient*/
#endif
void
END(...)
PREINIT:
dMY_CXT;
int i;
PPCODE:
_prime_memfreeall();
MY_CXT.MPUroot = NULL;
MY_CXT.MPUGMP = NULL;
MY_CXT.MPUPP = NULL;
for (i = 0; i <= CINTS; i++) {
SV * const sv = MY_CXT.const_int[i];
MY_CXT.const_int[i] = NULL;
SvREFCNT_dec_NN(sv);
} /* stashes are owned by stash tree, no refcount on them in MY_CXT */
Safefree(MY_CXT.randcxt); MY_CXT.randcxt = 0;
return; /* skip implicit PUTBACK, returning @_ to caller, more efficient*/
void csrand(IN SV* seed = 0)
PREINIT:
unsigned char* data;
STRLEN size;
dMY_CXT;
PPCODE:
if (items == 0) {
csprng_init_seed(MY_CXT.randcxt);
} else if (_XS_get_secure()) {
croak("secure option set, manual seeding disabled");
} else {
data = (unsigned char*) SvPV(seed, size);
csprng_seed(MY_CXT.randcxt, size, data);
}
if (_XS_get_callgmp() >= 42) _vcallsub("_csrand_p");
return;
UV srand(IN UV seedval = 0)
PREINIT:
dMY_CXT;
CODE:
if (_XS_get_secure())
croak("secure option set, manual seeding disabled");
if (items == 0)
get_entropy_bytes(sizeof(UV), (unsigned char*) &seedval);
csprng_srand(MY_CXT.randcxt, seedval);
if (_XS_get_callgmp() >= 42) _vcallsub("_srand_p");
RETVAL = seedval;
OUTPUT:
RETVAL
UV irand()
ALIAS:
irand64 = 1
PREINIT:
dMY_CXT;
CODE:
if (ix == 0)
RETVAL = irand32(MY_CXT.randcxt);
else
#if BITS_PER_WORD >= 64
RETVAL = irand64(MY_CXT.randcxt);
#else /* TODO: should irand64 on 32-bit perl (1) croak, (2) return 32-bits */
RETVAL = irand32(MY_CXT.randcxt);
#endif
OUTPUT:
RETVAL
NV drand(NV m = 0.0)
ALIAS:
rand = 1
PREINIT:
dMY_CXT;
CODE:
PERL_UNUSED_VAR(ix);
RETVAL = drand64(MY_CXT.randcxt);
if (m != 0) RETVAL *= m;
OUTPUT:
RETVAL
SV* random_bytes(IN UV n)
PREINIT:
char* sptr;
dMY_CXT;
CODE:
RETVAL = newSV(n == 0 ? 1 : n);
SvPOK_only(RETVAL);
SvCUR_set(RETVAL, n);
sptr = SvPVX(RETVAL);
csprng_rand_bytes(MY_CXT.randcxt, n, (unsigned char*)sptr);
sptr[n] = '\0';
OUTPUT:
RETVAL
SV* entropy_bytes(IN UV n)
PREINIT:
char* sptr;
CODE:
RETVAL = newSV(n == 0 ? 1 : n);
SvPOK_only(RETVAL);
SvCUR_set(RETVAL, n);
sptr = SvPVX(RETVAL);
get_entropy_bytes(n, (unsigned char*)sptr);
sptr[n] = '\0';
OUTPUT:
RETVAL
UV _is_csprng_well_seeded()
ALIAS:
_XS_get_verbose = 1
_XS_get_callgmp = 2
_XS_get_secure = 3
_XS_set_secure = 4
_get_forexit = 5
_start_for_loop = 6
_get_prime_cache_size = 7
CODE:
switch (ix) {
case 0: { dMY_CXT; RETVAL = is_csprng_well_seeded(MY_CXT.randcxt); } break;
case 1: RETVAL = _XS_get_verbose(); break;
case 2: RETVAL = _XS_get_callgmp(); break;
case 3: RETVAL = _XS_get_secure(); break;
case 4: _XS_set_secure(); RETVAL = 1; break;
case 5: { dMY_CXT; RETVAL = MY_CXT.forexit; } break;
case 6: { dMY_CXT; MY_CXT.forcount++; RETVAL = MY_CXT.forexit; MY_CXT.forexit = 0; } break;
case 7:
default: RETVAL = get_prime_cache(0,0); break;
}
OUTPUT:
RETVAL
bool _validate_integer(SV* svn)
ALIAS:
_validate_integer_nonneg = 1
_validate_integer_positive = 2
_validate_integer_abs = 3
PREINIT:
uint32_t mask;
int status;
UV n;
CODE:
/* Flag: 0 neg ok, 1 neg err, 2 zero or neg err, 3 abs */
switch (ix) {
case 0: mask = IFLAG_ANY; break;
case 1: mask = IFLAG_POS; break;
case 2: mask = IFLAG_POS | IFLAG_NONZERO; break;
case 3: mask = IFLAG_ABS; break;
default: croak("_validate_integer unknown flag value");
}
status = _validate_and_set(&n, aTHX_ svn, mask);
if (status != 0) {
#if PERL_REVISION <= 5 && PERL_VERSION < 8 && BITS_PER_WORD == 64
sv_setpviv(svn, n);
#else
if (status == 1) sv_setuv(svn, n);
else sv_setiv(svn, n);
#endif
} else { /* Status 0 = bigint */
if (mask & IFLAG_ABS) {
/* TODO: if given a positive bigint, no need for this */
sv_setsv(svn, sv_to_bigint_abs(aTHX_ svn));
} else if (mask & IFLAG_POS) {
if (!_is_sv_bigint(aTHX_ svn))
sv_setsv(svn, sv_to_bigint_nonneg(aTHX_ svn));
} else {
if (!_is_sv_bigint(aTHX_ svn))
sv_setsv(svn, sv_to_bigint(aTHX_ svn));
}
}
RETVAL = TRUE;
OUTPUT:
RETVAL
void prime_memfree()
PREINIT:
dMY_CXT;
PPCODE:
prime_memfree();
/* (void) _vcallgmpsubn(aTHX_ G_VOID|G_DISCARD, "_GMP_memfree", 0, 49); */
if (MY_CXT.MPUPP != NULL) _vcallsub_with_pp("prime_memfree");
return;
void
prime_precalc(IN UV n)
ALIAS:
_XS_set_verbose = 1
_XS_set_callgmp = 2
_end_for_loop = 3
PPCODE:
PUTBACK; /* SP is never used again, the 3 next func calls are tailcall
friendly since this XSUB has nothing to do after the 3 calls return */
switch (ix) {
case 0: prime_precalc(n); break;
case 1: _XS_set_verbose(n); break;
case 2: _XS_set_callgmp(n); break;
case 3:
default: { dMY_CXT; MY_CXT.forcount--; MY_CXT.forexit = n; } break;
}
return; /* skip implicit PUTBACK */
void prime_count(IN SV* svlo, IN SV* svhi = 0)
ALIAS:
semiprime_count = 1
twin_prime_count = 2
ramanujan_prime_count = 3
perfect_power_count = 4
prime_power_count = 5
lucky_count = 6
PREINIT:
UV lo = 0, hi, count = 0;
PPCODE:
if ((items == 1 && _validate_and_set(&hi, aTHX_ svlo, IFLAG_POS)) ||
(items == 2 && _validate_and_set(&lo, aTHX_ svlo, IFLAG_POS) && _validate_and_set(&hi, aTHX_ svhi, IFLAG_POS))) {
if (lo <= hi) {
switch (ix) {
case 0: count = prime_count_range(lo, hi); break;
case 1: count = semiprime_count_range(lo, hi); break;
case 2: count = twin_prime_count_range(lo, hi); break;
case 3: count = ramanujan_prime_count_range(lo, hi); break;
case 4: count = perfect_power_count_range(lo, hi); break;
case 5: count = prime_power_count_range(lo, hi); break;
case 6: count = lucky_count_range(lo, hi); break;
}
}
XSRETURN_UV(count);
}
switch (ix) {
case 0: _vcallsubn(aTHX_ GIMME_V, VCALL_ROOT, "_generic_prime_count", items, 0); break;
case 1: _vcallsub_with_pp("semiprime_count"); break;
case 2: _vcallsub_with_pp("twin_prime_count"); break;
case 3: _vcallsub_with_pp("ramanujan_prime_count"); break;
case 4: _vcallsub_with_gmpobj(0.53,"perfect_power_count"); break;
case 5: _vcallsub_with_gmpobj(0.53,"prime_power_count"); break;
case 6: _vcallsub_with_pp("lucky_count"); break;
}
return;
void prime_count_upper(IN SV* svn)
ALIAS:
prime_count_lower = 1
prime_count_approx = 2
prime_power_count_upper = 3
prime_power_count_lower = 4
prime_power_count_approx = 5
perfect_power_count_upper = 6
perfect_power_count_lower = 7
perfect_power_count_approx = 8
ramanujan_prime_count_upper = 9
ramanujan_prime_count_lower = 10
ramanujan_prime_count_approx = 11
twin_prime_count_approx = 12
semiprime_count_approx = 13
lucky_count_upper = 14
lucky_count_lower = 15
lucky_count_approx = 16
PREINIT:
UV n, ret;
PPCODE:
if (_validate_and_set(&n, aTHX_ svn, IFLAG_POS)) {
switch (ix) {
case 0: ret = prime_count_upper(n); break;
case 1: ret = prime_count_lower(n); break;
case 2: ret = prime_count_approx(n); break;
case 3: ret = prime_power_count_upper(n); break;
case 4: ret = prime_power_count_lower(n); break;
case 5: ret = prime_power_count_approx(n); break;
case 6: ret = perfect_power_count_upper(n); break;
case 7: ret = perfect_power_count_lower(n); break;
case 8: ret = perfect_power_count_approx(n); break;
case 9: ret = ramanujan_prime_count_upper(n); break;
case 10: ret = ramanujan_prime_count_lower(n); break;
case 11: ret = ramanujan_prime_count_approx(n); break;
case 12: ret = twin_prime_count_approx(n); break;
case 13: ret = semiprime_count_approx(n); break;
case 14: ret = lucky_count_upper(n); break;
case 15: ret = lucky_count_lower(n); break;
case 16:
default: ret = lucky_count_approx(n); break;
}
XSRETURN_UV(ret);
}
switch (ix) {
case 0: _vcallsub_with_pp("prime_count_upper"); break;
case 1: _vcallsub_with_pp("prime_count_lower"); break;
case 2: _vcallsub_with_pp("prime_count_approx"); break;
case 3: _vcallsub_with_pp("prime_power_count_upper"); break;
case 4: _vcallsub_with_pp("prime_power_count_lower"); break;
case 5: _vcallsub_with_pp("prime_power_count_approx"); break;
case 6: _vcallsub_with_pp("perfect_power_count_upper"); break;
case 7: _vcallsub_with_pp("perfect_power_count_lower"); break;
case 8: _vcallsub_with_pp("perfect_power_count_approx"); break;
case 9: _vcallsub_with_pp("ramanujan_prime_count_upper"); break;
case 10: _vcallsub_with_pp("ramanujan_prime_count_lower"); break;
case 11: _vcallsub_with_pp("ramanujan_prime_count_approx"); break;
case 12: _vcallsub_with_pp("twin_prime_count_approx"); break;