-
Notifications
You must be signed in to change notification settings - Fork 306
/
unique.c
2655 lines (2379 loc) · 68.8 KB
/
unique.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
/*
* R : A Computer Language for Statistical Data Analysis
* Copyright (C) 1997--2024 The R Core Team
* Copyright (C) 1995, 1996 Robert Gentleman and Ross Ihaka
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, a copy is available at
* https://www.R-project.org/Licenses/
*/
/* This is currently restricted to vectors of length < 2^30 */
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#define R_USE_SIGNALS 1
#include <Defn.h>
#include <Internal.h>
#include <R_ext/Altrep.h>
#include <R_ext/Itermacros.h>
/* inline version of function R_NaN_is_R_NA defined in arithmetic.c */
/* may not be needed if LTO is enabled */
#define R_NaN_is_R_NA R_NaN_is_R_NA_inline
static R_INLINE int R_NaN_is_R_NA_inline(double x)
{
#ifdef WORDS_BIGENDIAN
static const int lw = 1;
#else /* !WORDS_BIGENDIAN */
static const int lw = 0;
#endif /* WORDS_BIGENDIAN */
union {
double value;
unsigned int word[2];
} y;
y.value = x;
return y.word[lw] == 1954;
}
#define NIL -1
#define ARGUSED(x) LEVELS(x)
#define SET_ARGUSED(x,v) SETLEVELS(x,v)
/* interval at which to check interrupts */
#define NINTERRUPT 1000000
typedef size_t hlen;
/* Hash function and equality test for keys */
typedef struct _HashData HashData;
struct _HashData {
int K;
hlen M;
R_xlen_t nmax;
#ifdef LONG_VECTOR_SUPPORT
Rboolean isLong;
#endif
hlen (*hash)(SEXP, R_xlen_t, HashData *);
int (*equal)(SEXP, R_xlen_t, SEXP, R_xlen_t);
SEXP HashTable;
int nomatch;
Rboolean useUTF8;
Rboolean useCache;
Rboolean useCloEnv;
Rboolean extptrAsRef;
Rboolean inHashtab;
};
#define HTDATA_INT(d) (INTEGER0((d)->HashTable))
#define HTDATA_DBL(d) (REAL0((d)->HashTable))
/*
Integer keys are hashed via a random number generator
based on Knuth's recommendations. The high order K bits
are used as the hash code.
NB: lots of this code relies on M being a power of two and
on silent integer overflow mod 2^32.
<FIXME> Integer keys are wasteful for logical and raw vectors, but
the tables are small in that case. It would be much easier to
implement long vectors, though.
*/
/* Currently the hash table is implemented as a (signed) integer
array. So there are two 31-bit restrictions, the length of the
array and the values. The values are initially NIL (-1). O-based
indices are inserted by isDuplicated, and invalidated by setting
to NA_INTEGER.
*/
static hlen scatter(unsigned int key, HashData *d)
{
return 3141592653U * key >> (32 - d->K);
}
static hlen lhash(SEXP x, R_xlen_t indx, HashData *d)
{
int xi = LOGICAL_ELT(x, indx);
if (xi == NA_LOGICAL) return 2U;
return (hlen) xi;
}
static R_INLINE hlen ihash(SEXP x, R_xlen_t indx, HashData *d)
{
int xi = INTEGER_ELT(x, indx);
if (xi == NA_INTEGER) return 0;
return scatter((unsigned int) xi, d);
}
/* We use unions here because Solaris gcc -O2 has trouble with
casting + incrementing pointers. We use tests here, but R currently
assumes int is 4 bytes and double is 8 bytes.
*/
union foo {
double d;
unsigned int u[2];
};
static R_INLINE hlen rhash(SEXP x, R_xlen_t indx, HashData *d)
{
/* There is a problem with signed 0s under IEC60559 */
double xi = REAL_ELT(x, indx);
double tmp = (xi == 0.0) ? 0.0 : xi;
/* need to use both 32-byte chunks or endianness is an issue */
/* we want all NaNs except NA equal, and all NAs equal */
if (R_IsNA(tmp)) tmp = NA_REAL;
else if (R_IsNaN(tmp)) tmp = R_NaN;
#if 2*SIZEOF_INT == SIZEOF_DOUBLE
{
union foo tmpu;
tmpu.d = tmp;
return scatter(tmpu.u[0] + tmpu.u[1], d);
}
#else
return scatter(*((unsigned int *) (&tmp)), d);
#endif
}
static Rcomplex unify_complex_na(Rcomplex z) {
Rcomplex ans;
ans.r = (z.r == 0.0) ? 0.0 : z.r;
ans.i = (z.i == 0.0) ? 0.0 : z.i;
if (R_IsNA(ans.r) || R_IsNA(ans.i))
ans.r = ans.i = NA_REAL;
else if (R_IsNaN(ans.r) || R_IsNaN(ans.i))
ans.r = ans.i = R_NaN;
return ans;
}
static hlen chash(SEXP x, R_xlen_t indx, HashData *d)
{
Rcomplex tmp = unify_complex_na(COMPLEX_ELT(x, indx));
#if 2*SIZEOF_INT == SIZEOF_DOUBLE
{
unsigned int u;
union foo tmpu;
tmpu.d = tmp.r;
u = tmpu.u[0] ^ tmpu.u[1];
tmpu.d = tmp.i;
u ^= tmpu.u[0] ^ tmpu.u[1];
return scatter(u, d);
}
#else
return scatter((*((unsigned int *)(&tmp.r)) ^
(*((unsigned int *)(&tmp.i)))), d);
#endif
}
/* Pointer hashing as used here isn't entirely portable (we do it in
several other places, sometimes in slightly different ways) but it
could be made so by computing a unique value based on the
allocation page and position in the page.
Pointer hashes will not be valid if serialized and unserialized in
another process.
Hash values are int, For 64bit pointers, we do (upper ^ lower) */
static R_INLINE unsigned int PTRHASH(void *x)
{
intptr_t z = (intptr_t) x;
unsigned int z1 = (unsigned int)(z & 0xffffffff), z2 = 0;
#if SIZEOF_LONG == 8
z2 = (unsigned int)(z/0x100000000L);
#endif
return z1 ^ z2;
}
/* Hash CHARSXP by address. */
static R_INLINE hlen cshash(SEXP x, R_xlen_t indx, HashData *d)
{
return scatter(PTRHASH(STRING_ELT(x, indx)), d);
}
static R_INLINE hlen shash(SEXP x, R_xlen_t indx, HashData *d)
{
unsigned int k;
const char *p;
if (d->inHashtab) {
SEXP xi = STRING_ELT(x, indx);
int noTrans = (IS_BYTES(xi) || IS_ASCII(xi)) ? TRUE : FALSE;
if (d->useCache && noTrans)
return scatter(PTRHASH(xi), d);
const void *vmax = vmaxget();
p = noTrans ? CHAR(xi) : translateCharUTF8(xi);
k = 0;
while (*p++)
/* multiplier was 8 but 11 isn't a power of 2 */
k = 11 * k + (unsigned int) *p;
vmaxset(vmax); /* discard any memory used by translateChar */
return scatter(k, d);
}
if(!d->useUTF8 && d->useCache) return cshash(x, indx, d);
const void *vmax = vmaxget();
/* Not having d->useCache really should not happen anymore. */
p = translateCharUTF8(STRING_ELT(x, indx));
k = 0;
while (*p++)
k = 11 * k + (unsigned int) *p; /* was 8 but 11 isn't a power of 2 */
vmaxset(vmax); /* discard any memory used by translateChar */
return scatter(k, d);
}
static int lequal(SEXP x, R_xlen_t i, SEXP y, R_xlen_t j)
{
if (i < 0 || j < 0) return 0;
return (LOGICAL_ELT(x, i) == LOGICAL_ELT(y, j));
}
static R_INLINE int iequal(SEXP x, R_xlen_t i, SEXP y, R_xlen_t j)
{
if (i < 0 || j < 0) return 0;
return (INTEGER_ELT(x, i) == INTEGER_ELT(y, j));
}
/* BDR 2002-1-17 We don't want NA and other NaNs to be equal */
static R_INLINE int requal(SEXP x, R_xlen_t i, SEXP y, R_xlen_t j)
{
if (i < 0 || j < 0) return 0;
double xi = REAL_ELT(x, i);
double yj = REAL_ELT(y, j);
if (!ISNAN(xi) && !ISNAN(yj))
return (xi == yj);
else if (R_IsNA(xi) && R_IsNA(yj)) return 1;
else if (R_IsNaN(xi) && R_IsNaN(yj)) return 1;
else return 0;
}
/* This is differentiating {NA,1}, {NA,0}, {NA, NaN}, {NA, NA},
* but R's print() and format() render all as "NA" */
static int cplx_eq(Rcomplex x, Rcomplex y)
{
if (!ISNAN(x.r) && !ISNAN(x.i) && !ISNAN(y.r) && !ISNAN(y.i))
return x.r == y.r && x.i == y.i;
else if (R_IsNA(x.r) || R_IsNA(x.i)) // x is NA
return (R_IsNA(y.r) || R_IsNA(y.i)) ? 1 : 0;
else if (R_IsNA(y.r) || R_IsNA(y.i)) // y is NA but x is not
return 0;
// else : none is NA but there's at least one NaN; hence ISNAN(.) == R_IsNaN(.)
return
(((ISNAN(x.r) && ISNAN(y.r)) || (!ISNAN(x.r) && !ISNAN(y.r) && x.r == y.r)) && // Re
((ISNAN(x.i) && ISNAN(y.i)) || (!ISNAN(x.i) && !ISNAN(y.i) && x.i == y.i)) // Im
) ? 1 : 0;
}
static int cequal(SEXP x, R_xlen_t i, SEXP y, R_xlen_t j)
{
if (i < 0 || j < 0) return 0;
return cplx_eq(COMPLEX_ELT(x, i), COMPLEX_ELT(y, j));
}
static R_INLINE int sequal(SEXP x, R_xlen_t i, SEXP y, R_xlen_t j)
{
if (i < 0 || j < 0) return 0;
SEXP xi = STRING_ELT(x, i);
SEXP yj = STRING_ELT(y, j);
/* Two strings which have the same address must be the same,
so avoid looking at the contents */
if (xi == yj) return 1;
/* Then if either is NA the other cannot be */
/* Once all CHARSXPs are cached, Seql will handle this */
if (xi == NA_STRING || yj == NA_STRING)
return 0;
/* another pre-test to avoid the call to Seql */
if (IS_CACHED(xi) && IS_CACHED(yj) && ENC_KNOWN(xi) == ENC_KNOWN(yj))
return 0;
return Seql(xi, yj);
}
static hlen rawhash(SEXP x, R_xlen_t indx, HashData *d)
{
return (hlen) RAW_ELT(x, indx);
}
static int rawequal(SEXP x, R_xlen_t i, SEXP y, R_xlen_t j)
{
if (i < 0 || j < 0) return 0;
return (RAW_ELT(x, i) == RAW_ELT(y, j));
}
static hlen vhash_one(SEXP _this, HashData *d);
static hlen vhash(SEXP x, R_xlen_t indx, HashData *d)
{
SEXP _this = VECTOR_ELT(x, indx);
return vhash_one(_this, d);
}
static hlen vhash_one(SEXP _this, HashData *d)
{
/* Handle environments by pointer hashing. Previously,
environments were hashed based only on length, which is not
very effective and could be expensive to compute. */
if (TYPEOF(_this) == ENVSXP)
return scatter(PTRHASH(_this), d);
int i;
unsigned int key = OBJECT(_this) + 2*TYPEOF(_this) + 100U*(unsigned int) length(_this);
/* maybe we should also look at attributes, but that slows us down */
switch (TYPEOF(_this)) {
case LGLSXP:
/* This is not too clever: pack into 32-bits and then scatter? */
for(i = 0; i < LENGTH(_this); i++) {
key ^= lhash(_this, i, d);
key *= 97;
}
break;
case INTSXP:
for(i = 0; i < LENGTH(_this); i++) {
key ^= ihash(_this, i, d);
key *= 97;
}
break;
case REALSXP:
for(i = 0; i < LENGTH(_this); i++) {
key ^= rhash(_this, i, d);
key *= 97;
}
break;
case CPLXSXP:
for(i = 0; i < LENGTH(_this); i++) {
key ^= chash(_this, i, d);
key *= 97;
}
break;
case STRSXP:
for(i = 0; i < LENGTH(_this); i++) {
key ^= shash(_this, i, d);
key *= 97;
}
break;
case RAWSXP:
for(i = 0; i < LENGTH(_this); i++) {
key ^= scatter((unsigned int)rawhash(_this, i, d), d);
key *= 97;
}
break;
case EXPRSXP:
case VECSXP:
R_CheckStack();
for(i = 0; i < LENGTH(_this); i++) {
key ^= vhash(_this, i, d);
key *= 97;
}
break;
case LANGSXP:
case LISTSXP:
R_CheckStack();
/* all attributes are ignored */
/* might be good to consider environments on formulas */
for (SEXP next = _this; next != R_NilValue; next = CDR(next)) {
key ^= vhash_one(CAR(next), d);
key *= 97;
}
break;
case CLOSXP:
/* all attributes are ignored */
key ^= vhash_one(BODY_EXPR(_this), d);
key *= 97;
if (d->useCloEnv) {
key ^= vhash_one(CLOENV(_this), d);
key *= 97;
}
break;
case SYMSXP:
key *= PTRHASH(_this);
key *= 97;
break;
case CHARSXP:
if(!d->useUTF8 && d->useCache) key *= PTRHASH(_this);
/**** otherwise, do nothing for now */
/* this should only happen in C-leve hash tables */
/* eventually this should do what shash does */
key *= 97;
break;
case EXTPTRSXP:
if (d->extptrAsRef)
key ^= PTRHASH(_this);
else
/* identical() considers only the EXTPTR_PTR values ... */
key ^= PTRHASH(EXTPTR_PTR(_this));
key *= 97;
break;
default:
break;
}
return scatter(key, d);
}
static int vequal(SEXP x, R_xlen_t i, SEXP y, R_xlen_t j)
{
if (i < 0 || j < 0) return 0;
return R_compute_identical(VECTOR_ELT(x, i), VECTOR_ELT(y, j), 0);
}
/*
Choose M to be the smallest power of 2
not less than 2*n and set K = log2(M).
Need K >= 1 and hence M >= 2, and 2^M < 2^31-1, hence n <= 2^29.
Dec 2004: modified from 4*n to 2*n, since in the worst case we have
a 50% full table, and that is still rather efficient -- see
R. Sedgewick (1998) Algorithms in C++ 3rd edition p.606.
*/
static void MKsetup(R_xlen_t n, HashData *d, R_xlen_t nmax)
{
#ifdef LONG_VECTOR_SUPPORT
/* M = 2^32 is safe, hence n <= 2^31 -1 */
if(n < 0) /* protect against overflow to -ve */
error(_("length %lld is too large for hashing"), (long long)n);
#else
if(n < 0 || n >= 1073741824) /* protect against overflow to -ve */
error(_("length %d is too large for hashing"), n);
#endif
if (nmax != NA_INTEGER && nmax != 1) n = nmax;
size_t n2 = 2U * (size_t) n;
d->M = 2;
d->K = 1;
while (d->M < n2) {
d->M *= 2;
d->K++;
}
d->nmax = n;
}
#define IMAX 4294967296L
static void HashTableSetup(SEXP x, HashData *d, R_xlen_t nmax)
{
d->useUTF8 = FALSE;
d->useCache = TRUE;
switch (TYPEOF(x)) {
case LGLSXP:
d->hash = lhash;
d->equal = lequal;
d->nmax = d->M = 4;
d->K = 2; /* unused */
break;
case INTSXP:
{
d->hash = ihash;
d->equal = iequal;
#ifdef LONG_VECTOR_SUPPORT
R_xlen_t nn = XLENGTH(x);
if (nn > IMAX) nn = IMAX;
MKsetup(nn, d, nmax);
#else
MKsetup(LENGTH(x), d, nmax);
#endif
}
break;
case REALSXP:
d->hash = rhash;
d->equal = requal;
MKsetup(XLENGTH(x), d, nmax);
break;
case CPLXSXP:
d->hash = chash;
d->equal = cequal;
MKsetup(XLENGTH(x), d, nmax);
break;
case STRSXP:
d->hash = shash;
d->equal = sequal;
MKsetup(XLENGTH(x), d, nmax);
break;
case RAWSXP:
d->hash = rawhash;
d->equal = rawequal;
d->nmax = d->M = 256;
d->K = 8; /* unused */
break;
case VECSXP:
d->hash = vhash;
d->equal = vequal;
MKsetup(XLENGTH(x), d, nmax);
break;
default:
UNIMPLEMENTED_TYPE("HashTableSetup", x);
}
#ifdef LONG_VECTOR_SUPPORT
d->isLong = IS_LONG_VEC(x);
if (d->isLong) {
d->HashTable = allocVector(REALSXP, (R_xlen_t) d->M);
for (R_xlen_t i = 0; i < d->M; i++) HTDATA_DBL(d)[i] = NIL;
} else
#endif
{
d->HashTable = allocVector(INTSXP, (R_xlen_t) d->M);
for (R_xlen_t i = 0; i < d->M; i++) HTDATA_INT(d)[i] = NIL;
}
}
/* Open address hashing */
/* Collision resolution is by linear probing */
/* The table is guaranteed large so this is sufficient */
static int isDuplicated(SEXP x, R_xlen_t indx, HashData *d)
{
#ifdef LONG_VECTOR_SUPPORT
if (d->isLong) {
double *h = HTDATA_DBL(d);
hlen i = d->hash(x, indx, d);
while (h[i] != NIL) {
if (d->equal(x, (R_xlen_t) h[i], x, indx))
return h[i] >= 0 ? 1 : 0;
i = (i + 1) % d->M;
}
if (d->nmax-- < 0) error("hash table is full");
h[i] = (double) indx;
} else
#endif
{
int *h = HTDATA_INT(d);
hlen i = d->hash(x, indx, d);
while (h[i] != NIL) {
if (d->equal(x, h[i], x, indx))
return h[i] >= 0 ? 1 : 0;
i = (i + 1) % d->M;
}
if (d->nmax-- < 0) error("hash table is full");
h[i] = (int) indx;
}
return 0;
}
static Rboolean duplicatedInit(SEXP x, HashData *d)
{
Rboolean stop = FALSE;
if(TYPEOF(x) == STRSXP) {
R_xlen_t i, n = XLENGTH(x);
for(i = 0; i < n; i++) {
if(IS_BYTES(STRING_ELT(x, i))) {
d->useUTF8 = FALSE;
stop = TRUE;
break;
}
if(ENC_KNOWN(STRING_ELT(x, i))) {
d->useUTF8 = TRUE;
}
/* uncached strings are currently not properly supported */
if(!IS_CACHED(STRING_ELT(x, i))) {
d->useCache = FALSE;
stop = TRUE;
break;
}
}
} else if (TYPEOF(x) == VECSXP || TYPEOF(x) == EXPRSXP) {
R_xlen_t i, n = XLENGTH(x);
for(i = 0; i < n; i++)
if (duplicatedInit(VECTOR_ELT(x, i), d)) {
stop = TRUE;
break;
}
} else if (TYPEOF(x) == LANGSXP || TYPEOF(x) == LISTSXP) {
for(SEXP head = x; head != R_NilValue; head = CDR(head))
if (duplicatedInit(CAR(head), d)) {
stop = TRUE;
break;
}
} else if (TYPEOF(x) == CLOSXP) {
if (duplicatedInit(BODY_EXPR(x), d))
stop = TRUE;
}
return stop;
}
static void removeEntry(SEXP table, SEXP x, R_xlen_t indx, HashData *d)
{
#ifdef LONG_VECTOR_SUPPORT
if (d->isLong) {
double *h = HTDATA_DBL(d);
hlen i = d->hash(x, indx, d);
while (h[i] >= 0) {
if (d->equal(table, (R_xlen_t) h[i], x, indx)) {
h[i] = NA_INTEGER; /* < 0, only index values are inserted */
return;
}
i = (i + 1) % d->M;
}
} else
#endif
{
int *h = HTDATA_INT(d);
hlen i = d->hash(x, indx, d);
while (h[i] >= 0) {
if (d->equal(table, h[i], x, indx)) {
h[i] = NA_INTEGER; /* < 0, only index values are inserted */
return;
}
i = (i + 1) % d->M;
}
}
}
#define DUPLICATED_INIT \
HashData data = { 0 }; \
HashTableSetup(x, &data, nmax); \
data.useUTF8 = FALSE; data.useCache = TRUE; \
duplicatedInit(x, &data);
/* used in scan() */
SEXP duplicated(SEXP x, Rboolean from_last)
{
SEXP ans;
int *v, nmax = NA_INTEGER;
if (!isVector(x)) error(_("'duplicated' applies only to vectors"));
R_xlen_t i, n = XLENGTH(x);
DUPLICATED_INIT;
PROTECT(data.HashTable);
PROTECT(ans = allocVector(LGLSXP, n));
v = LOGICAL(ans);
if(from_last)
for (i = n-1; i >= 0; i--) {
// if ((i+1) % NINTERRUPT == 0) R_CheckUserInterrupt();
v[i] = isDuplicated(x, i, &data);
}
else
for (i = 0; i < n; i++) {
// if ((i+1) % NINTERRUPT == 0) R_CheckUserInterrupt();
v[i] = isDuplicated(x, i, &data);
}
UNPROTECT(2);
return ans;
}
attribute_hidden R_xlen_t sorted_real_count_NANs(SEXP x) {
R_xlen_t n = XLENGTH(x);
if(n == 0)
return 0;
if(n == 1)
return ISNAN(REAL_ELT(x, 0));
int sorted = REAL_IS_SORTED(x);
if(!KNOWN_SORTED(sorted)) /* this should never happen! */
error("sorted_real_count_NANs got unsorted vector: this should not happen");
double rtmp;
R_xlen_t ret, nanpos, lowedge, highedge;
int nas1st = KNOWN_NA_1ST(sorted);
rtmp = nas1st ? REAL_ELT(x, 0) : REAL_ELT(x, n - 1);
if(!ISNAN(rtmp))
return 0;
if((nas1st && ISNAN(REAL_ELT(x, n - 1))) ||
(!nas1st && ISNAN(REAL_ELT(x, 0))))
return n;
nanpos = n / 2;
lowedge = 0;
highedge = n - 1;
#define FIND_NAN_EDGE(yes, no, final) do { \
while(highedge > lowedge + 1) { \
rtmp = REAL_ELT(x, nanpos); \
if(ISNAN(rtmp)) \
yes; \
else \
no; \
nanpos = (highedge + lowedge) / 2; \
} \
ret = final; \
} while(0)
if(nas1st) {
FIND_NAN_EDGE(lowedge = nanpos, highedge = nanpos, lowedge + 1);
} else {
FIND_NAN_EDGE(highedge = nanpos, lowedge = nanpos, n - highedge);
}
return ret;
}
#undef FIND_NAN_EDGE
#define DUP_DO_ONE(x, y, ind) do { \
if(x == y) \
v[ind] = TRUE; \
else \
v[ind] = FALSE; \
} while(0)
static SEXP sorted_Duplicated(SEXP x, Rboolean from_last, int nmax)
{
// n guaranteed >= 2 from calling function (Duplicated)
R_xlen_t n = XLENGTH(x), numnas, na_left = -1, startpos;
SEXP ans = PROTECT(allocVector(LGLSXP, n));
int *v = LOGICAL(ans), itmp, sorted;
double rtmp;
Rboolean seen_na = FALSE, seen_nan = FALSE,
nas1st= TRUE;
#define SORTED_DUP_NONNANS(start, niter, tmpvar, eetype, vvtype) do { \
if(from_last) { \
v[start + niter] = FALSE; \
tmpvar = vvtype##_ELT(x, start + niter); \
ITERATE_BY_REGION_PARTIAL_REV(x, xptr, idx, nb, eetype, \
vvtype, start, niter, { \
DUP_DO_ONE(xptr[nb - 1], \
tmpvar, \
idx + nb - 1); \
for(R_xlen_t k = nb - 2; k >= 0; k--) { \
DUP_DO_ONE(xptr[k + 1], \
xptr[k], \
idx + k); \
} \
tmpvar = xptr[0]; \
}); \
} else { /* !from_last */ \
v[start] = FALSE; \
tmpvar = vvtype##_ELT(x, start); \
ITERATE_BY_REGION_PARTIAL(x, xptr, idx, nb, eetype, \
vvtype, start + 1, niter, { \
DUP_DO_ONE(xptr[0], tmpvar, \
idx); \
for(R_xlen_t k = 1; k < nb; k++) { \
DUP_DO_ONE(xptr[k], \
xptr[k - 1], \
idx + k); \
} \
tmpvar = xptr[nb - 1]; \
}); \
} \
} while(0)
#define SORTED_DUP_NANS(itype, istart, icond, iter) do { \
ITERATE_BY_REGION_##itype(x, xptr, idx, nb, \
double, REAL, na_left, numnas, { \
for(R_xlen_t i = istart; icond; iter) { \
if(R_NaN_is_R_NA(xptr[i])) { \
v[idx + i] = seen_na; \
seen_na = TRUE; \
} else { \
v[idx + i] = seen_nan; \
seen_nan = TRUE; \
} \
} \
}); \
} while(0)
switch(TYPEOF(x)) {
case INTSXP:
sorted = INTEGER_IS_SORTED(x);
if(!KNOWN_SORTED(sorted))
error("sorted_Duplicated got unsorted vector: this should not happen");
SORTED_DUP_NONNANS(0, n - 1, itmp, int, INTEGER);
break;
case REALSXP:
sorted = REAL_IS_SORTED(x);
if(!KNOWN_SORTED(sorted))
error("sorted_Duplicated got unsorted vector: this should not happen");
numnas = sorted_real_count_NANs(x);
nas1st = KNOWN_NA_1ST(REAL_IS_SORTED(x));
if(numnas > 0) {
na_left = nas1st ? 0 : n - numnas;
if(from_last) {
SORTED_DUP_NANS(PARTIAL_REV, nb - 1, i >= 0, i--);
} else { // !from_last
SORTED_DUP_NANS(PARTIAL, 0, i < nb, i++);
} // from_last
} // numnas > 0
if(numnas < n) {
startpos = nas1st ? numnas : 0;
SORTED_DUP_NONNANS(startpos, n - numnas - 1, rtmp, double, REAL);
}
break;
default:
error("sorted_Duplicated got unsupported type %d: this should not happen", TYPEOF(x));
}
UNPROTECT(1); //ans
return ans;
}
#undef SORTED_DUP_NONNANS
#undef SORTED_DUP_NANS
#undef DUP_DO_ONE
/* to add sorted fastpass support for new SEXP types modify sorted_Duplicated
and sorted_any_Duplicated then add them here */
#define DUP_KNOWN_SORTED(x) \
((TYPEOF(x) == INTSXP && KNOWN_SORTED(INTEGER_IS_SORTED(x))) || \
(TYPEOF(x) == REALSXP && KNOWN_SORTED(REAL_IS_SORTED(x))))
static SEXP Duplicated(SEXP x, Rboolean from_last, int nmax)
{
SEXP ans;
int *v;
if (!isVector(x)) error(_("'duplicated' applies only to vectors"));
R_xlen_t i, n = XLENGTH(x);
if(n == 0)
return allocVector(LGLSXP, 0);
else if (n == 1)
return ScalarLogical(FALSE);
if(DUP_KNOWN_SORTED(x)) {
return sorted_Duplicated(x, from_last, nmax);
}
DUPLICATED_INIT;
PROTECT(data.HashTable);
PROTECT(ans = allocVector(LGLSXP, n));
v = LOGICAL(ans);
if(from_last)
for (i = n-1; i >= 0; i--) {
// if ((i+1) % NINTERRUPT == 0) R_CheckUserInterrupt();
v[i] = isDuplicated(x, i, &data);
}
else
for (i = 0; i < n; i++) {
// if ((i+1) % NINTERRUPT == 0) R_CheckUserInterrupt();
v[i] = isDuplicated(x, i, &data);
}
UNPROTECT(2);
return ans;
}
attribute_hidden R_xlen_t sorted_any_duplicated(SEXP x, Rboolean from_last) {
int itmp, sorted;
double rtmp;
Rboolean seen_na = FALSE, seen_nan = FALSE, na1st = FALSE;
#define SORTED_ANYDUP_NONNANS_FROM_LAST(start, count, tmpvar, eetype, vvtype) do { \
if (count > 1) { \
tmpvar = vvtype##_ELT(x, start + count - 1); \
ITERATE_BY_REGION_PARTIAL_REV(x, xptr, idx, nb, eetype, vvtype, \
start, count - 1, { \
if(xptr[nb - 1] == tmpvar) { \
return idx + nb; \
} \
for(R_xlen_t k = nb - 2; k >= 0; k--) { \
if(xptr[k + 1] == xptr[k]) { \
return idx + k + 1; \
} \
} \
tmpvar = xptr[0]; \
}); \
} \
} while(0)
#define SORTED_ANYDUP_NONNANS_FROM_FIRST(start, count, tmpvar, eetype, vvtype) do { \
if (count > 1) { \
tmpvar = vvtype##_ELT(x, start); \
ITERATE_BY_REGION_PARTIAL(x, xptr, idx, nb, eetype, \
vvtype, start + 1, count - 1, { \
if(xptr[0] == tmpvar) { \
return idx + 1; \
} \
for(R_xlen_t k = 1; k < nb; k++) { \
if(xptr[k] == xptr[k - 1]) { \
return idx + k + 1; \
} \
} \
tmpvar = xptr[nb - 1]; \
}); \
} \
} while(0)
#define SORTED_ANYDUP_NANS(start, count, itype, istart, icond, iter) do { \
if (count > 1) { \
ITERATE_BY_REGION_##itype(x, xptr, idx, nb, double, REAL, \
start, count, { \
for(R_xlen_t i = istart; icond; iter) { \
if(R_NaN_is_R_NA(xptr[i])) { \
if(seen_na) { \
return idx + i + 1; \
} else { \
seen_na = TRUE; \
} \
} else { \
if(seen_nan) { \
return idx + i + 1; \
} else { \
seen_nan = TRUE; \
} \
} \
} \
}); \
} \
} while(0)
switch(TYPEOF(x)) {
case INTSXP:
sorted = INTEGER_IS_SORTED(x);
if(!KNOWN_SORTED(sorted))
error("sorted_any_duplicated got unsorted vector: this should not happen");
if(from_last) {
SORTED_ANYDUP_NONNANS_FROM_LAST(0, XLENGTH(x), itmp, int, INTEGER);
} else {
SORTED_ANYDUP_NONNANS_FROM_FIRST(0, XLENGTH(x), itmp, int, INTEGER);
}
break;
case REALSXP:
sorted = REAL_IS_SORTED(x);
if(!KNOWN_SORTED(sorted))
error("sorted_any_duplicated got unsorted vector: this should not happen");
R_xlen_t numnas = sorted_real_count_NANs(x), napivot;
napivot = XLENGTH(x) - numnas;
na1st = KNOWN_NA_1ST(sorted);
if(from_last) {
if(na1st) {
SORTED_ANYDUP_NONNANS_FROM_LAST(numnas, napivot, rtmp, double,
REAL);
SORTED_ANYDUP_NANS(0, numnas, PARTIAL_REV, nb - 1, i >=0, i--);
} else {
SORTED_ANYDUP_NANS(napivot, numnas, PARTIAL_REV, nb - 1, i >= 0,
i--);
SORTED_ANYDUP_NONNANS_FROM_LAST(0, napivot, rtmp, double, REAL);
}
} else { // !from_last
if(na1st) {
SORTED_ANYDUP_NANS(0, numnas, PARTIAL, 0, i < nb, i++);
SORTED_ANYDUP_NONNANS_FROM_FIRST(numnas, napivot, rtmp, double,
REAL);
} else {
SORTED_ANYDUP_NONNANS_FROM_FIRST(0, napivot, rtmp, double,
REAL);
SORTED_ANYDUP_NANS(napivot, numnas, PARTIAL, 0, i < nb, i++);
}
} //from_last
break;
default:
error("sorted_Duplicated got unsupported type %d: this should not happen", TYPEOF(x));
}
return 0;
}
#undef SORTED_ANYDUP_NONNANS_FROM_LAST
#undef SORTED_ANYDUP_NONNANS_FRO_FIRST
#undef SORTED_ANYDUP_NANS
/* simpler version of the above : return 1-based index of first, or 0 : */
R_xlen_t any_duplicated(SEXP x, Rboolean from_last)
{
R_xlen_t result = 0;
int nmax = NA_INTEGER;
if (!isVector(x)) error(_("'duplicated' applies only to vectors"));
R_xlen_t i, n = XLENGTH(x);
if(DUP_KNOWN_SORTED(x)) {
return sorted_any_duplicated(x, from_last);
}
DUPLICATED_INIT;
PROTECT(data.HashTable);
if(from_last) {
for (i = n-1; i >= 0; i--) {
if(isDuplicated(x, i, &data)) { result = ++i; break; }
}
} else {
for (i = 0; i < n; i++) {
if(isDuplicated(x, i, &data)) { result = ++i; break; }