-
Notifications
You must be signed in to change notification settings - Fork 313
/
util.c
3282 lines (2963 loc) · 90.8 KB
/
util.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/
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#define R_USE_SIGNALS 1
#include <Defn.h>
#include <Internal.h>
#include <R_ext/Print.h>
#include <ctype.h> /* for isspace */
#include <float.h> /* for DBL_MAX */
#include <R_ext/Itermacros.h> /* for ITERATE_BY_REGION */
#undef COMPILING_R
#define R_imax2(x, y) ((x < y) ? y : x)
#include <Print.h>
#ifdef HAVE_SYS_TYPES_H
# include <sys/types.h> // for size_t
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <stdarg.h>
#ifdef Win32
void R_UTF8fixslash(char *s);
void R_wfixslash(wchar_t *s);
#endif
#ifdef __cplusplus
#include "Clinkage.h"
extern "C" {
#endif
#if defined FC_LEN_T
# include <stddef.h>
void F77_SYMBOL(rwarnc)(char *msg, int *nchar, FC_LEN_T msg_len);
NORET void F77_SYMBOL(rexitc)(char *msg, int *nchar, FC_LEN_T msg_len);
#else
void F77_SYMBOL(rwarnc)(char *msg, int *nchar);
NORET void F77_SYMBOL(rexitc)(char *msg, int *nchar);
#endif
#ifdef __cplusplus
}
#endif
#include <rlocale.h>
/* Many small functions are included from ../include/Rinlinedfuns.h */
int nrows(SEXP s) // ~== NROW(.) in R
{
SEXP t;
if (isVector(s) || isList(s)) {
t = getAttrib(s, R_DimSymbol);
if (t == R_NilValue) return LENGTH(s);
return INTEGER(t)[0];
}
else if (isDataFrame(s)) {
return nrows(CAR(s));
}
else error(_("object is not a matrix"));
return -1;
}
int ncols(SEXP s) // ~== NCOL(.) in R
{
SEXP t;
if (isVector(s) || isList(s)) {
t = getAttrib(s, R_DimSymbol);
if (t == R_NilValue) return 1;
if (LENGTH(t) >= 2) return INTEGER(t)[1];
/* This is a 1D (or possibly 0D array) */
return 1;
}
else if (isDataFrame(s)) {
return length(s);
}
else error(_("object is not a matrix"));
return -1;/*NOTREACHED*/
}
#ifdef UNUSED
const static char type_msg[] = "invalid type passed to internal function\n";
void internalTypeCheck(SEXP call, SEXP s, SEXPTYPE type)
{
if (TYPEOF(s) != type) {
if (call)
errorcall(call, type_msg);
else
error(type_msg);
}
}
#endif
const static char * const truenames[] = {
"T",
"True",
"TRUE",
"true",
(char *) NULL,
};
const static char * const falsenames[] = {
"F",
"False",
"FALSE",
"false",
(char *) NULL,
};
SEXP asChar(SEXP x)
{
if (isVectorAtomic(x) && XLENGTH(x) >= 1) {
int w, d, e, wi, di, ei;
char buf[MAXELTSIZE]; /* Probably 100 would suffice */
switch (TYPEOF(x)) {
case LGLSXP:
if (LOGICAL(x)[0] == NA_LOGICAL)
return NA_STRING;
if (LOGICAL(x)[0])
snprintf(buf, MAXELTSIZE, "TRUE");
else
snprintf(buf, MAXELTSIZE, "FALSE");
return mkChar(buf);
case INTSXP:
if (INTEGER(x)[0] == NA_INTEGER)
return NA_STRING;
snprintf(buf, MAXELTSIZE, "%d", INTEGER(x)[0]);
return mkChar(buf);
case REALSXP:
PrintDefaults();
formatReal(REAL(x), 1, &w, &d, &e, 0);
return mkChar(EncodeReal0(REAL(x)[0], w, d, e, OutDec));
case CPLXSXP:
PrintDefaults();
formatComplex(COMPLEX(x), 1, &w, &d, &e, &wi, &di, &ei, 0);
return mkChar(EncodeComplex(COMPLEX(x)[0], w, d, e, wi, di, ei, OutDec));
case STRSXP:
return STRING_ELT(x, 0);
default:
return NA_STRING;
}
} else if(TYPEOF(x) == CHARSXP) {
return x;
} else if(TYPEOF(x) == SYMSXP)
return PRINTNAME(x);
return NA_STRING;
}
Rboolean isUnordered(SEXP s)
{
return (TYPEOF(s) == INTSXP
&& inherits(s, "factor")
&& !inherits(s, "ordered"));
}
Rboolean isOrdered(SEXP s)
{
return (TYPEOF(s) == INTSXP
&& inherits(s, "factor")
&& inherits(s, "ordered"));
}
Rboolean R_isTRUE(SEXP x)
{
if (TYPEOF(x) == LGLSXP && XLENGTH(x) == 1) {
int val = LOGICAL(x)[0];
return val != NA_LOGICAL && val;
}
return FALSE;
}
const static struct {
const char * const str;
const int type;
}
TypeTable[] = {
{ "NULL", NILSXP }, /* real types */
{ "symbol", SYMSXP },
{ "pairlist", LISTSXP },
{ "closure", CLOSXP },
{ "environment", ENVSXP },
{ "promise", PROMSXP },
{ "language", LANGSXP },
{ "special", SPECIALSXP },
{ "builtin", BUILTINSXP },
{ "char", CHARSXP },
{ "logical", LGLSXP },
{ "integer", INTSXP },
{ "double", REALSXP }, /*- "real", for R <= 0.61.x */
{ "complex", CPLXSXP },
{ "character", STRSXP },
{ "...", DOTSXP },
{ "any", ANYSXP },
{ "expression", EXPRSXP },
{ "list", VECSXP },
{ "externalptr", EXTPTRSXP },
{ "bytecode", BCODESXP },
{ "weakref", WEAKREFSXP },
{ "raw", RAWSXP },
{ "S4", S4SXP },
{ "object", OBJSXP }, /* == S4SXP */
/* aliases : */
{ "numeric", REALSXP },
{ "name", SYMSXP },
{ (char *)NULL, -1 }
};
SEXPTYPE str2type(const char *s)
{
int i;
for (i = 0; TypeTable[i].str; i++) {
if (!strcmp(s, TypeTable[i].str))
return (SEXPTYPE) TypeTable[i].type;
}
/* SEXPTYPE is an unsigned int, so the compiler warns us w/o the cast. */
return (SEXPTYPE) -1;
}
static struct {
const char *cstrName;
SEXP rcharName;
SEXP rstrName;
SEXP rsymName;
} Type2Table[MAX_NUM_SEXPTYPE];
static int findTypeInTypeTable(SEXPTYPE t)
{
for (int i = 0; TypeTable[i].str; i++)
if (TypeTable[i].type == t) return i;
return -1;
}
// called from main.c
attribute_hidden
void InitTypeTables(void) {
/* Type2Table */
for (int type = 0; type < MAX_NUM_SEXPTYPE; type++) {
int j = findTypeInTypeTable(type);
if (j != -1) {
const char *cstr = TypeTable[j].str;
SEXP rchar = PROTECT(mkChar(cstr));
SEXP rstr = ScalarString(rchar);
MARK_NOT_MUTABLE(rstr);
R_PreserveObject(rstr);
SEXP rsym = install(cstr);
Type2Table[type].cstrName = cstr;
Type2Table[type].rcharName = rchar;
Type2Table[type].rstrName = rstr;
Type2Table[type].rsymName = rsym;
UNPROTECT(1); /* rchar */
} else {
Type2Table[type].cstrName = NULL;
Type2Table[type].rcharName = NULL;
Type2Table[type].rstrName = NULL;
Type2Table[type].rsymName = NULL;
}
}
}
SEXP type2str_nowarn(SEXPTYPE t) /* returns a CHARSXP */
{
// if (t >= 0 && t < MAX_NUM_SEXPTYPE) { /* branch not really needed */
SEXP res = Type2Table[t].rcharName;
if (res != NULL) return res;
// }
return R_NilValue;
}
SEXP type2str(SEXPTYPE t) /* returns a CHARSXP */
{
SEXP s = type2str_nowarn(t);
if (s != R_NilValue) {
return s;
}
warning(_("type %d is unimplemented in '%s'"), t, "type2str");
char buf[50];
snprintf(buf, 50, "unknown type #%d", t);
return mkChar(buf);
}
SEXP type2rstr(SEXPTYPE t) /* returns a STRSXP */
{
// if (t < MAX_NUM_SEXPTYPE) {
SEXP res = Type2Table[t].rstrName;
if (res != NULL) return res;
// }
error(_("type %d is unimplemented in '%s'"), t,
"type2ImmutableScalarString");
return R_NilValue; /* for -Wall */
}
const char *type2char(SEXPTYPE t) /* returns a char* */
{
// if (t >=0 && t < MAX_NUM_SEXPTYPE) { /* branch not really needed */
const char * res = Type2Table[t].cstrName;
if (res != NULL) return res;
// }
warning(_("type %d is unimplemented in '%s'"), t, "type2char");
static char buf[50];
snprintf(buf, 50, "unknown type #%d", t);
return buf;
}
#ifdef USE_TYPE2CHAR_2
const char *R_typeToChar2(SEXP x, SEXPTYPE t) {
return (t != OBJSXP)
? type2char(t)
: (IS_S4_OBJECT(x) ? "S4" : "object");
}
#endif
const char *R_typeToChar(SEXP x) {
// = type2char() but distinguishing {S4, object}
if(TYPEOF(x) == OBJSXP)
return IS_S4_OBJECT(x) ? "S4" : "object";
else
return type2char(TYPEOF(x));
}
#ifdef UNUSED
NORET SEXP type2symbol(SEXPTYPE t)
{
// if (t >= 0 && t < MAX_NUM_SEXPTYPE) { /* branch not really needed */
SEXP res = Type2Table[t].rsymName;
if (res != NULL) return res;
// }
error(_("type %d is unimplemented in '%s'"), t, "type2symbol");
}
#endif
attribute_hidden NORET
void UNIMPLEMENTED_TYPEt(const char *s, SEXPTYPE t)
{
int i;
for (i = 0; TypeTable[i].str; i++) {
if (TypeTable[i].type == t)
error(_("unimplemented type '%s' in '%s'\n"), TypeTable[i].str, s);
}
error(_("unimplemented type (%d) in '%s'\n"), t, s);
}
NORET void UNIMPLEMENTED_TYPE(const char *s, SEXP x)
{
UNIMPLEMENTED_TYPEt(s, TYPEOF(x));
}
# include <R_ext/Riconv.h>
# include <sys/param.h>
# include <errno.h>
/* Previous versions of R (< 2.3.0) assumed wchar_t was in Unicode
(and it commonly is). These functions do not. */
# ifdef WORDS_BIGENDIAN
static const char UCS2ENC[] = "UCS-2BE";
# else
static const char UCS2ENC[] = "UCS-2LE";
# endif
/*
* out=NULL returns the number of the MBCS chars
*/
/* Note: this does not terminate out, as all current uses are to look
* at 'out' a wchar at a time, and sometimes just one char.
*/
size_t mbcsToUcs2(const char *in, R_ucs2_t *out, int nout, int enc)
{
void *cd = NULL ;
const char *i_buf;
char *o_buf;
size_t i_len, o_len, status, wc_len;
/* out length */
wc_len = (enc == CE_UTF8)? utf8towcs(NULL, in, 0) : mbstowcs(NULL, in, 0);
if (out == NULL || (int)wc_len < 0) return wc_len;
if ((void*)-1 == (cd = Riconv_open(UCS2ENC, (enc == CE_UTF8) ? "UTF-8": "")))
return (size_t) -1;
i_buf = (char *)in;
i_len = strlen(in); /* not including terminator */
o_buf = (char *)out;
o_len = ((size_t) nout) * sizeof(R_ucs2_t);
status = Riconv(cd, &i_buf, (size_t *)&i_len, &o_buf, (size_t *)&o_len);
int serrno = errno;
Riconv_close(cd);
if (status == (size_t)-1) {
switch(serrno){
case EINVAL:
return (size_t) -2;
case EILSEQ:
return (size_t) -1;
case E2BIG:
break;
default:
errno = EILSEQ;
return (size_t) -1;
}
}
return wc_len; /* status would be better? */
}
#include <wctype.h>
/* This one is not in Rinternals.h, but is used in internet module */
Rboolean isBlankString(const char *s)
{
if(mbcslocale) {
wchar_t wc; size_t used; mbstate_t mb_st;
mbs_init(&mb_st);
// This does not allow for surrogate pairs, but all blanks are in BMP
while( (used = Mbrtowc(&wc, s, R_MB_CUR_MAX, &mb_st)) ) {
if(!iswspace((wint_t) wc)) return FALSE;
s += used;
}
} else
while (*s)
if (!isspace((int)*s++)) return FALSE;
return TRUE;
}
Rboolean StringBlank(SEXP x)
{
if (x == R_NilValue) return TRUE;
else return CHAR(x)[0] == '\0';
}
/* Function to test whether a string is a true value */
Rboolean StringTrue(const char *name)
{
int i;
for (i = 0; truenames[i]; i++)
if (!strcmp(name, truenames[i]))
return TRUE;
return FALSE;
}
Rboolean StringFalse(const char *name)
{
int i;
for (i = 0; falsenames[i]; i++)
if (!strcmp(name, falsenames[i]))
return TRUE;
return FALSE;
}
/* used in bind.c and options.c */
attribute_hidden SEXP EnsureString(SEXP s)
{
switch(TYPEOF(s)) {
case SYMSXP:
s = PRINTNAME(s);
break;
case STRSXP:
s = STRING_ELT(s, 0);
break;
case CHARSXP:
break;
case NILSXP:
s = R_BlankString;
break;
default:
error(_("invalid tag in name extraction"));
}
return s;
}
// NB: have checkArity(a,b) := Rf_checkArityCall(a,b,call)
void Rf_checkArityCall(SEXP op, SEXP args, SEXP call)
{
if (PRIMARITY(op) >= 0 && PRIMARITY(op) != length(args)) {
/* FIXME: ngettext reguires unsigned long, but %u would seem appropriate */
if (PRIMINTERNAL(op))
error(ngettext("%d argument passed to .Internal(%s) which requires %d",
"%d arguments passed to .Internal(%s) which requires %d",
(unsigned long) length(args)),
length(args), PRIMNAME(op), PRIMARITY(op));
else
errorcall(call,
ngettext("%d argument passed to '%s' which requires %d",
"%d arguments passed to '%s' which requires %d",
(unsigned long) length(args)),
length(args), PRIMNAME(op), PRIMARITY(op));
}
}
attribute_hidden void Rf_check1arg(SEXP arg, SEXP call, const char *formal)
{
SEXP tag = TAG(arg);
if (tag == R_NilValue) return;
const char *supplied = CHAR(PRINTNAME(tag));
size_t ns = strlen(supplied);
if (ns > strlen(formal) || strncmp(supplied, formal, ns))
errorcall(call, _("supplied argument name '%s' does not match '%s'"),
supplied, formal);
}
SEXP nthcdr(SEXP s, int n)
{
if (isList(s) || isLanguage(s) || isDataFrame(s) || TYPEOF(s) == DOTSXP ) {
while( n-- > 0 ) {
if (s == R_NilValue)
error(_("'nthcdr' list shorter than %d"), n);
s = CDR(s);
}
return s;
}
else error(_("'nthcdr' needs a list to CDR down"));
return R_NilValue;/* for -Wall */
}
/* Destructively removes R_NilValue ('NULL') elements from a pairlist. */
attribute_hidden /* would need to be in an installed header if not hidden */
SEXP R_listCompact(SEXP s, Rboolean keep_initial) {
if(!keep_initial)
// skip initial NULL values
while (s != R_NilValue && CAR(s) == R_NilValue)
s = CDR(s);
SEXP val = s;
SEXP prev = s;
while (s != R_NilValue) {
s = CDR(s);
if (CAR(s) == R_NilValue) // skip it
SETCDR(prev, CDR(s));
else
prev = s;
}
return val;
}
/* This is a primitive (with no arguments) */
attribute_hidden SEXP do_nargs(SEXP call, SEXP op, SEXP args, SEXP rho)
{
RCNTXT *cptr;
int nargs = NA_INTEGER;
checkArity(op, args);
for (cptr = R_GlobalContext; cptr != NULL; cptr = cptr->nextcontext) {
if ((cptr->callflag & CTXT_FUNCTION) && cptr->cloenv == rho) {
nargs = length(cptr->promargs);
break;
}
}
return ScalarInteger(nargs);
}
/* formerly used in subscript.c, in Utils.h
Does not know about long vectors ....
Commented out 2024-02
attribute_hidden void setIVector(int * vec, int len, int val)
{
for (int i = 0; i < len; i++) vec[i] = val;
}
*/
/* unused in R, in Utils.h, may have been used in Rcpp at some point,
but not any more (as per Nov. 2018).
Does not know about long vectors ....
RcppClassic has its own version.
Commented out 2024-02
attribute_hidden void setRVector(double * vec, int len, double val)
{
for (int i = 0; i < len; i++) vec[i] = val;
}
*/
/* unused in R, in Defn.h, formerly remapped in Rinternals.h
Unused in R.
Does not know about long vectors ....
Commented out 2024-02
void setSVector(SEXP * vec, int len, SEXP val)
{
for (int i = 0; i < len; i++) vec[i] = val;
}
*/
attribute_hidden Rboolean isFree(SEXP val)
{
SEXP t;
for (t = R_FreeSEXP; t != R_NilValue; t = CAR(t))
if (val == t)
return TRUE;
return FALSE;
}
/* Debugging functions (hence the d-prefix). */
/* These are intended to be called interactively from */
/* a debugger such as gdb, so you don't have to remember */
/* the names of the data structure components. */
attribute_hidden int dtype(SEXP q)
{
return((int)TYPEOF(q));
}
attribute_hidden SEXP dcar(SEXP l)
{
return(CAR(l));
}
attribute_hidden SEXP dcdr(SEXP l)
{
return(CDR(l));
}
static void isort_with_index(int *x, int *indx, int n)
{
int i, j, h, iv, v;
for (h = 1; h <= n / 9; h = 3 * h + 1);
for (; h > 0; h /= 3)
for (i = h; i < n; i++) {
v = x[i]; iv = indx[i];
j = i;
while (j >= h && x[j - h] > v)
{ x[j] = x[j - h]; indx[j] = indx[j-h]; j -= h; }
x[j] = v; indx[j] = iv;
}
}
// body(x) without attributes "srcref", "srcfile", "wholeSrcref" :
// NOTE: Callers typically need PROTECT(R_body_no_src(.))
attribute_hidden SEXP R_body_no_src(SEXP x) {
SEXP b = PROTECT(duplicate(BODY_EXPR(x)));
/* R's removeSource() works *recursively* on the body()
in ../library/utils/R/sourceutils.R but that seems unneeded (?) */
setAttrib(b, R_SrcrefSymbol, R_NilValue);
setAttrib(b, R_SrcfileSymbol, R_NilValue);
setAttrib(b, R_WholeSrcrefSymbol, R_NilValue);
UNPROTECT(1);
return b;
}
/* merge(xinds, yinds, all.x, all.y) */
/* xinds, yinds are along x and y rows matching into the (numeric)
common indices, with 0 for non-matches.
all.x and all.y are boolean.
The return value is a list with 4 elements (xi, yi, x.alone, y.alone),
which are index vectors for rows of x or y.
*/
attribute_hidden SEXP do_merge(SEXP call, SEXP op, SEXP args, SEXP rho)
{
SEXP xi, yi, ansx, ansy, ans;
int nx = 0, ny = 0, i, j, k, nx_lone = 0, ny_lone = 0;
int all_x = 0, all_y = 0, ll = 0/* "= 0" : for -Wall */;
int nnx, nny;
checkArity(op, args);
xi = CAR(args);
// NB: long vectors are not supported for input
if ( !isInteger(xi) || !(nx = LENGTH(xi)) )
error(_("invalid '%s' argument"), "xinds");
yi = CADR(args);
if ( !isInteger(yi) || !(ny = LENGTH(yi)) )
error(_("invalid '%s' argument"), "yinds");
if(!LENGTH(ans = CADDR(args)) || NA_LOGICAL == (all_x = asLogical(ans)))
error(_("'all.x' must be TRUE or FALSE"));
if(!LENGTH(ans = CADDDR(args))|| NA_LOGICAL == (all_y = asLogical(ans)))
error(_("'all.y' must be TRUE or FALSE"));
/* 0. sort the indices */
int *ix = (int *) R_alloc((size_t) nx, sizeof(int));
int *iy = (int *) R_alloc((size_t) ny, sizeof(int));
for(i = 0; i < nx; i++) ix[i] = i+1;
for(i = 0; i < ny; i++) iy[i] = i+1;
isort_with_index(INTEGER(xi), ix, nx);
isort_with_index(INTEGER(yi), iy, ny);
/* 1. determine result sizes */
for (i = 0; i < nx; i++)
if (INTEGER(xi)[i] > 0) break;
nx_lone = i;
for (i = 0; i < ny; i++)
if (INTEGER(yi)[i] > 0) break;
ny_lone = i;
double dnans = 0;
for (i = nx_lone, j = ny_lone; i < nx; i = nnx, j = nny) {
int tmp = INTEGER(xi)[i];
for(nnx = i; nnx < nx; nnx++) if(INTEGER(xi)[nnx] != tmp) break;
/* the next is not in theory necessary,
since we have the common values only */
for(; j < ny; j++) if(INTEGER(yi)[j] >= tmp) break;
for(nny = j; nny < ny; nny++) if(INTEGER(yi)[nny] != tmp) break;
/* printf("i %d nnx %d j %d nny %d\n", i, nnx, j, nny); */
dnans += ((double)(nnx-i))*(nny-j);
}
if (dnans > R_XLEN_T_MAX)
error(_("number of rows in the result exceeds maximum vector length"));
R_xlen_t nans = (int) dnans;
/* 2. allocate and store result components */
const char *nms[] = {"xi", "yi", "x.alone", "y.alone", ""};
ans = PROTECT(mkNamed(VECSXP, nms));
ansx = allocVector(INTSXP, nans); SET_VECTOR_ELT(ans, 0, ansx);
ansy = allocVector(INTSXP, nans); SET_VECTOR_ELT(ans, 1, ansy);
if(all_x) {
SEXP x_lone = allocVector(INTSXP, nx_lone);
SET_VECTOR_ELT(ans, 2, x_lone);
for (i = 0, ll = 0; i < nx_lone; i++)
INTEGER(x_lone)[ll++] = ix[i];
}
if(all_y) {
SEXP y_lone = allocVector(INTSXP, ny_lone);
SET_VECTOR_ELT(ans, 3, y_lone);
for (i = 0, ll = 0; i < ny_lone; i++)
INTEGER(y_lone)[ll++] = iy[i];
}
for (i = nx_lone, j = ny_lone, k = 0; i < nx; i = nnx, j = nny) {
int tmp = INTEGER(xi)[i];
for(nnx = i; nnx < nx; nnx++) if(INTEGER(xi)[nnx] != tmp) break;
for(; j < ny; j++) if(INTEGER(yi)[j] >= tmp) break;
for(nny = j; nny < ny; nny++) if(INTEGER(yi)[nny] != tmp) break;
for(int i0 = i; i0 < nnx; i0++)
for(int j0 = j; j0 < nny; j0++) {
INTEGER(ansx)[k] = ix[i0];
INTEGER(ansy)[k++] = iy[j0];
}
}
UNPROTECT(1);
return ans;
}
/* Functions for getting and setting the working directory. */
#ifdef Win32
# define WIN32_LEAN_AND_MEAN 1
# include <windows.h>
#endif
/* uses R_alloc */
SEXP static intern_getwd(void)
{
SEXP rval = R_NilValue;
#ifdef Win32
{
DWORD res = GetCurrentDirectoryW(0, NULL);
if (res > 0) {
wchar_t *wbuf = (wchar_t*)R_alloc(res, sizeof(wchar_t));
DWORD res1 = GetCurrentDirectoryW(res, wbuf);
if (res1 <= 0 || res1 >= res)
return R_NilValue;
size_t needed = wcstoutf8(NULL, wbuf, (size_t)INT_MAX + 2);
char *buf = R_alloc(needed + 1, 1);
wcstoutf8(buf, wbuf, needed + 1);
R_UTF8fixslash(buf);
PROTECT(rval = allocVector(STRSXP, 1));
SET_STRING_ELT(rval, 0, mkCharCE(buf, CE_UTF8));
UNPROTECT(1);
}
}
#else
char buf[4*R_PATH_MAX+1];
char *res = getcwd(buf, R_PATH_MAX); /* can return NULL */
if(res) rval = mkString(buf);
#endif
return(rval);
}
attribute_hidden SEXP do_getwd(SEXP call, SEXP op, SEXP args, SEXP rho)
{
checkArity(op, args);
return(intern_getwd());
}
#if defined(Win32) && defined(_MSC_VER)
# include <direct.h> /* for chdir, via io.h */
#endif
attribute_hidden SEXP do_setwd(SEXP call, SEXP op, SEXP args, SEXP rho)
{
SEXP s = R_NilValue, wd = R_NilValue; /* -Wall */
checkArity(op, args);
if (!isPairList(args) || !isValidString(s = CAR(args)))
error(_("character argument expected"));
if (STRING_ELT(s, 0) == NA_STRING)
error(_("missing value is invalid"));
/* get current directory to return */
PROTECT(wd = intern_getwd());
#ifdef Win32
{
const wchar_t *path = filenameToWchar(STRING_ELT(s, 0), TRUE);
if(_wchdir(path) < 0)
error(_("cannot change working directory"));
}
#else
{
const char *path
= R_ExpandFileName(translateCharFP(STRING_ELT(s, 0)));
if(chdir(path) < 0)
error(_("cannot change working directory"));
}
#endif
UNPROTECT(1); /* wd */
return(wd);
}
/* remove portion of path before file separator if one exists */
#ifdef Win32
attribute_hidden SEXP do_basename(SEXP call, SEXP op, SEXP args, SEXP rho)
{
SEXP ans, s = R_NilValue; /* -Wall */
const char *pp;
int i, n;
checkArity(op, args);
if (TYPEOF(s = CAR(args)) != STRSXP)
error(_("a character vector argument expected"));
PROTECT(ans = allocVector(STRSXP, n = LENGTH(s)));
for(i = 0; i < n; i++) {
if (STRING_ELT(s, i) == NA_STRING)
SET_STRING_ELT(ans, i, NA_STRING);
else {
pp = R_ExpandFileNameUTF8(trCharUTF8(STRING_ELT(s, i)));
size_t ll = strlen(pp);
/* remove trailing file separator(s) */
while(ll && (pp[ll-1] == '\\' || pp[ll-1] == '/')) ll--;
size_t ff = ll;
/* find start of file part */
while(ff && (pp[ff-1] != '\\' && pp[ff-1] != '/')) ff--;
SET_STRING_ELT(ans, i, mkCharLenCE(pp+ff, ll-ff, CE_UTF8));
}
}
UNPROTECT(1);
return(ans);
}
#else
attribute_hidden SEXP do_basename(SEXP call, SEXP op, SEXP args, SEXP rho)
{
SEXP ans, s = R_NilValue; /* -Wall */
const char fsp = FILESEP[0];
const char *pp;
int i, n;
checkArity(op, args);
if (TYPEOF(s = CAR(args)) != STRSXP)
error(_("a character vector argument expected"));
PROTECT(ans = allocVector(STRSXP, n = LENGTH(s)));
for(i = 0; i < n; i++) {
if (STRING_ELT(s, i) == NA_STRING)
SET_STRING_ELT(ans, i, NA_STRING);
else {
pp = R_ExpandFileName(translateCharFP(STRING_ELT(s, i)));
size_t ll = strlen(pp);
if (ll > R_PATH_MAX - 1)
error(_("path too long"));
/* remove trailing file separator(s) */
while(ll && pp[ll-1] == fsp) ll--;
size_t ff = ll;
/* find start of file part */
while(ff && pp[ff-1] != fsp) ff--;
SET_STRING_ELT(ans, i, mkCharLenCE(pp+ff, (int)(ll-ff), CE_NATIVE));
}
}
UNPROTECT(1);
return(ans);
}
#endif
/* remove portion of path after last file separator if one exists, else
return "."
*/
#ifdef Win32
static SEXP root_dir_on_drive(char d)
{
char buf[3];
buf[0] = d;
buf[1] = ':';
buf[2] = '/';
return mkCharLenCE(buf, 3, CE_UTF8);
}
attribute_hidden SEXP do_dirname(SEXP call, SEXP op, SEXP args, SEXP rho)
{
SEXP ans, s = R_NilValue; /* -Wall */
char *buf;
const char *pp;
int i, n;
checkArity(op, args);
if (TYPEOF(s = CAR(args)) != STRSXP)
error(_("a character vector argument expected"));
PROTECT(ans = allocVector(STRSXP, n = LENGTH(s)));
for(i = 0; i < n; i++) {
if (STRING_ELT(s, i) == NA_STRING)
SET_STRING_ELT(ans, i, NA_STRING);
else {
pp = R_ExpandFileNameUTF8(trCharUTF8(STRING_ELT(s, i)));
size_t ll = strlen(pp);
if (ll) {
buf = (char *)R_alloc(ll + 1, sizeof(char));
memcpy(buf, pp, ll + 1);
R_UTF8fixslash(buf);
/* remove trailing file separator(s) */
while (ll && buf[ll-1] == '/') ll--;
if (ll == 2 && buf[1] == ':' && buf[2]) {
SET_STRING_ELT(ans, i, root_dir_on_drive(buf[0]));
continue;
}
if (!ll) { /* only separators, not share */
SET_STRING_ELT(ans, i, mkCharLenCE("/", 1, CE_UTF8));
continue;
}
/* remove file part */
while(ll && buf[ll-1] != '\\' && buf[ll-1] != '/') ll--;
if (!ll) { /* only file part, not share */
/* FIXME: dirname of D: is ., is this good behavior? */
SET_STRING_ELT(ans, i, mkChar("."));
continue;
}
/* remove separator(s) after directory part */
while(ll && buf[ll-1] == '/') ll--;
if (ll == 2 && buf[1] == ':' && buf[2]) {
SET_STRING_ELT(ans, i, root_dir_on_drive(buf[0]));
continue;
}
if (!ll) /* only single part, not share */
SET_STRING_ELT(ans, i, mkCharLenCE("/", 1, CE_UTF8));
else if (ll == 2 && buf[0] == '\\' && buf[1] == '\\'
&& buf[2] == '/') {
/* network share with extra slashes */
SET_STRING_ELT(ans, i, mkCharLenCE("/", 1, CE_UTF8));
} else
SET_STRING_ELT(ans, i, mkCharLenCE(buf, ll, CE_UTF8));
} else
/* empty pathname is invalid, but returned */
SET_STRING_ELT(ans, i, mkChar(""));
}
}
UNPROTECT(1);
return(ans);
}