/
robj.rs
1661 lines (1501 loc) · 49.7 KB
/
robj.rs
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 object handling.
//!
//! See. https://cran.r-project.org/doc/manuals/R-exts.html
//!
//! Fundamental principals:
//!
//! * Any function that can break the protection mechanism is unsafe.
//! * Users should be able to do almost everything without using libR_sys.
//! * The interface should be friendly to R users without Rust experience.
use libR_sys::*;
use std::os::raw;
use crate::logical::*;
use crate::wrapper::*;
use crate::AnyError;
use ndarray::prelude::*;
/// Wrapper for an R S-expression pointer (SEXP).
///
/// As much as possible we wish to make this object safe (ie. no segfaults).
///
/// If you avoid using unsafe functions it is more likely that you will avoid
/// panics and segfaults. We will take great trouble to ensure that this
/// is true.
///
pub enum Robj {
/// This object owns the SEXP and must free it.
Owned(SEXP),
/// This object references a SEXP such as an input parameter.
Borrowed(SEXP),
/// This object references a SEXP owned by libR.
Sys(SEXP),
}
pub const TRUE: bool = true;
pub const FALSE: bool = false;
pub const NULL: () = ();
impl Clone for Robj {
fn clone(&self) -> Self {
self.duplicate()
}
}
impl Default for Robj {
fn default() -> Self {
Robj::from(())
}
}
pub trait FromRobj<'a>: Sized {
fn from_robj(_robj: &'a Robj) -> Result<Self, &'static str> {
Err("unable to convert value from R object")
}
}
macro_rules! impl_prim_from_robj {
($t: ty) => {
impl<'a> FromRobj<'a> for $t {
fn from_robj(robj: &'a Robj) -> Result<Self, &'static str> {
if let Some(v) = robj.as_i32_slice() {
if v.len() == 0 {
Err("zero length vector")
} else {
Ok(v[0] as Self)
}
} else if let Some(v) = robj.as_f64_slice() {
if v.len() == 0 {
Err("zero length vector")
} else {
Ok(v[0] as Self)
}
} else {
Err("unable to convert R object to primitive")
}
}
}
};
}
impl_prim_from_robj!(u8);
impl_prim_from_robj!(u16);
impl_prim_from_robj!(u32);
impl_prim_from_robj!(u64);
impl_prim_from_robj!(i8);
impl_prim_from_robj!(i16);
impl_prim_from_robj!(i32);
impl_prim_from_robj!(i64);
impl_prim_from_robj!(f32);
impl_prim_from_robj!(f64);
impl<'a> FromRobj<'a> for &'a str {
fn from_robj(robj: &'a Robj) -> Result<Self, &'static str> {
if let Some(s) = robj.as_str() {
Ok(s)
} else {
Err("not a string object")
}
}
}
impl<'a> FromRobj<'a> for String {
fn from_robj(robj: &'a Robj) -> Result<Self, &'static str> {
if let Some(s) = robj.as_str() {
Ok(s.to_string())
} else {
Err("not a string object")
}
}
}
impl<'a> FromRobj<'a> for Vec<i32> {
fn from_robj(robj: &'a Robj) -> Result<Self, &'static str> {
if let Some(v) = robj.as_i32_slice() {
Ok(Vec::from(v))
} else {
Err("not an integer or logical vector")
}
}
}
impl<'a> FromRobj<'a> for Vec<f64> {
fn from_robj(robj: &'a Robj) -> Result<Self, &'static str> {
if let Some(v) = robj.as_f64_slice() {
Ok(Vec::from(v))
} else {
Err("not a floating point vector")
}
}
}
/// Input Numeric vector parameter.
/// Note we don't accept mutable R objects as parameters
/// but you can make this behaviour using unsafe code.
impl<'a, T> FromRobj<'a> for ArrayView1<'a, T>
where
Robj: AsTypedSlice<T>,
{
fn from_robj(robj: &'a Robj) -> Result<Self, &'static str> {
if let Some(v) = robj.as_typed_slice() {
Ok(ArrayView1::<'a, T>::from(v))
} else {
Err("not a floating point vector")
}
}
}
/// Pass-through Robj conversion.
impl<'a> FromRobj<'a> for Robj {
fn from_robj(robj: &'a Robj) -> Result<Self, &'static str> {
Ok(unsafe { new_borrowed(robj.get()) })
}
}
impl Robj {
/// Get a copy of the underlying SEXP.
/// Note: this is unsafe.
pub unsafe fn get(&self) -> SEXP {
match self {
Robj::Owned(sexp) => *sexp,
Robj::Borrowed(sexp) => *sexp,
Robj::Sys(sexp) => *sexp,
}
}
/// Get a copy of the underlying SEXP for mutable types.
/// This is valid only for owned objects as we are not
/// permitted to modify parameters or system objects.
pub unsafe fn get_mut(&mut self) -> Option<SEXP> {
match self {
Robj::Owned(sexp) => Some(*sexp),
Robj::Borrowed(_) => None,
Robj::Sys(_) => None,
}
}
/// Get the XXXSXP type of the object.
pub fn sexptype(&self) -> u32 {
unsafe { TYPEOF(self.get()) as u32 }
}
/// Get the extended length of the object.
pub fn len(&self) -> usize {
unsafe { Rf_xlength(self.get()) as usize }
}
/// Get a read-only reference to the content of an integer or logical vector.
pub fn as_i32_slice(&self) -> Option<&[i32]> {
self.as_typed_slice()
}
/// Get a read-only reference to the content of an integer or logical vector.
pub fn as_logical_slice(&self) -> Option<&[Bool]> {
self.as_typed_slice()
}
/// Get a read-only reference to the content of a double vector.
pub fn as_f64_slice(&self) -> Option<&[f64]> {
self.as_typed_slice()
}
/// Get a read-only reference to the content of an integer or logical vector.
pub fn as_u8_slice(&self) -> Option<&[u8]> {
self.as_typed_slice()
}
/// Get a read-write reference to the content of an integer or logical vector.
pub fn as_i32_slice_mut(&mut self) -> Option<&mut [i32]> {
self.as_typed_slice_mut()
}
/// Get a read-write reference to the content of a double vector.
pub fn as_f64_slice_mut(&mut self) -> Option<&mut [f64]> {
self.as_typed_slice_mut()
}
/// Get a read-write reference to the content of an integer or logical vector.
pub fn as_u8_slice_mut(&mut self) -> Option<&mut [u8]> {
self.as_typed_slice_mut()
}
/// Get an iterator over a pairlist.
pub fn pairlist_iter(&self) -> Option<ListIter> {
match self.sexptype() {
LISTSXP | LANGSXP | DOTSXP => unsafe {
Some(ListIter {
list_elem: self.get(),
})
},
_ => None,
}
}
/// Get an iterator over an unnamed list.
pub fn list_iter(&self) -> Option<VecIter> {
match self.sexptype() {
VECSXP | EXPRSXP | WEAKREFSXP => unsafe {
Some(VecIter {
vector: self.get(),
i: 0,
len: self.len(),
})
},
_ => None,
}
}
/// Get an iterator over a string vector.
pub fn str_iter(&self) -> Option<StrIter> {
match self.sexptype() {
STRSXP => unsafe {
Some(StrIter {
vector: self.get(),
i: 0,
len: self.len(),
})
},
_ => None,
}
}
/// Get a read-only reference to a char, symbol or string type.
pub fn as_str(&self) -> Option<&str> {
unsafe {
match self.sexptype() {
STRSXP => {
if self.len() == 0 {
None
} else {
Some(to_str(R_CHAR(STRING_ELT(self.get(), 0)) as *const u8))
}
}
CHARSXP => Some(to_str(R_CHAR(self.get()) as *const u8)),
SYMSXP => Some(to_str(R_CHAR(PRINTNAME(self.get())) as *const u8)),
_ => None,
}
}
}
/// Evaluate the expression and return an error or an R object.
pub fn eval(&self) -> Result<Robj, AnyError> {
unsafe {
let mut error: raw::c_int = 0;
let res = R_tryEval(self.get(), R_GlobalEnv, &mut error as *mut raw::c_int);
if error != 0 {
Err(AnyError::from("R eval error"))
} else {
Ok(Robj::from(res))
}
}
}
/// Evaluate the expression and return NULL or an R object.
pub fn eval_blind(&self) -> Robj {
unsafe {
let mut error: raw::c_int = 0;
let res = R_tryEval(self.get(), R_GlobalEnv, &mut error as *mut raw::c_int);
if error != 0 {
Robj::from(())
} else {
Robj::from(res)
}
}
}
/// Parse a string into an R executable object
pub fn parse(code: &str) -> Result<Robj, AnyError> {
unsafe {
use libR_sys::*;
let mut status = 0_u32;
let status_ptr = &mut status as *mut u32;
let code: Robj = code.into();
let parsed = Robj::from(R_ParseVector(code.get(), -1, status_ptr, R_NilValue));
match status {
1 => Ok(parsed),
_ => Err(AnyError::from("parse_error")),
}
}
}
/// Parse a string into an R executable object and run it.
pub fn eval_string(code: &str) -> Result<Robj, AnyError> {
let expr = Robj::parse(code)?;
let mut res = Robj::from(());
if let Some(iter) = expr.list_iter() {
for lang in iter {
res = lang.eval()?;
}
}
Ok(res)
}
/// Unprotect an object - assumes a transfer of ownership.
/// This is unsafe because the object pointer may be left dangling.
pub unsafe fn unprotected(self) -> Robj {
match self {
Robj::Owned(sexp) => {
R_ReleaseObject(sexp);
Robj::Borrowed(sexp)
}
_ => self,
}
}
/// Return true if the object is owned by this wrapper.
/// If so, it will be released when the wrapper drops.
pub fn is_owned(&self) -> bool {
match self {
Robj::Owned(_) => true,
_ => false,
}
}
}
pub trait AsTypedSlice<T> {
fn as_typed_slice(&self) -> Option<&[T]> {
None
}
fn as_typed_slice_mut(&mut self) -> Option<&mut [T]> {
None
}
}
macro_rules! make_typed_slice {
($type: ty, $fn: tt, $($sexp: tt),* ) => {
impl AsTypedSlice<$type> for Robj {
fn as_typed_slice(&self) -> Option<&[$type]> {
match self.sexptype() {
$( $sexp )|* => {
unsafe {
let ptr = $fn(self.get()) as *const $type;
Some(std::slice::from_raw_parts(ptr, self.len()))
}
}
_ => None
}
}
fn as_typed_slice_mut(&mut self) -> Option<&mut [$type]> {
match self.sexptype() {
$( $sexp )|* => {
unsafe {
let ptr = $fn(self.get()) as *mut $type;
Some(std::slice::from_raw_parts_mut(ptr, self.len()))
}
}
_ => None
}
}
}
}
}
make_typed_slice!(Bool, INTEGER, LGLSXP);
make_typed_slice!(i32, INTEGER, INTSXP);
make_typed_slice!(f64, REAL, REALSXP);
make_typed_slice!(u8, RAW, RAWSXP);
///////////////////////////////////////////////////////////////
/// The following impls wrap specific Rinternals.h symbols.
///
#[allow(non_snake_case)]
impl Robj {
/// The "global" environment
pub fn globalEnv() -> Robj {
unsafe { new_sys(R_GlobalEnv) }
}
/// An empty environment at the root of the environment tree
pub fn emptyEnv() -> Robj {
unsafe { new_sys(R_EmptyEnv) }
}
/// The base environment; formerly R_NilValue
pub fn baseEnv() -> Robj {
unsafe { new_sys(R_BaseEnv) }
}
/// The (fake) namespace for base
pub fn baseNamespace() -> Robj {
unsafe { new_sys(R_BaseNamespace) }
}
/// for registered namespaces
pub fn namespaceRegistry() -> Robj {
unsafe { new_sys(R_NamespaceRegistry) }
}
/// Current srcref, for debuggers
pub fn srcref() -> Robj {
unsafe { new_sys(R_Srcref) }
}
/// The nil object
pub fn nilValue() -> Robj {
unsafe { new_sys(R_NilValue) }
}
/// Unbound marker
pub fn unboundValue() -> Robj {
unsafe { new_sys(R_UnboundValue) }
}
/// Missing argument marker
pub fn missingArg() -> Robj {
unsafe { new_sys(R_MissingArg) }
}
/* Not supported by older R versions.
/// To be found in BC interp. state (marker)
pub fn inBCInterpreter() -> Robj { unsafe { new_sys(R_InBCInterpreter) }}
/// Use current expression (marker)
pub fn currentExpression() -> Robj { unsafe { new_sys(R_CurrentExpression) }}
/// character"
pub fn asCharacterSymbol() -> Robj { unsafe { new_sys(R_AsCharacterSymbol) }}
*/
/// "base"
pub fn baseSymbol() -> Robj {
unsafe { new_sys(R_BaseSymbol) }
}
/// "{"
pub fn braceSymbol() -> Robj {
unsafe { new_sys(R_BraceSymbol) }
}
/// "[["
pub fn bracket2Symbol() -> Robj {
unsafe { new_sys(R_Bracket2Symbol) }
}
/// "["
pub fn bracketSymbol() -> Robj {
unsafe { new_sys(R_BracketSymbol) }
}
/// "class"
pub fn classSymbol() -> Robj {
unsafe { new_sys(R_ClassSymbol) }
}
/// ".Device"
pub fn deviceSymbol() -> Robj {
unsafe { new_sys(R_DeviceSymbol) }
}
/// "dimnames"
pub fn dimNamesSymbol() -> Robj {
unsafe { new_sys(R_DimNamesSymbol) }
}
/// "dim"
pub fn dimSymbol() -> Robj {
unsafe { new_sys(R_DimSymbol) }
}
/// "$"
pub fn dollarSymbol() -> Robj {
unsafe { new_sys(R_DollarSymbol) }
}
/// "..."
pub fn dotsSymbol() -> Robj {
unsafe { new_sys(R_DotsSymbol) }
}
/// pub fn dropSymbol() -> Robj { unsafe { new_sys(R_DropSymbol) }}"drop"
pub fn doubleColonSymbol() -> Robj {
unsafe { new_sys(R_DoubleColonSymbol) }
} //
/// ".Last.value"
pub fn lastvalueSymbol() -> Robj {
unsafe { new_sys(R_LastvalueSymbol) }
}
/// "levels"
pub fn levelsSymbol() -> Robj {
unsafe { new_sys(R_LevelsSymbol) }
}
/// "mode"
pub fn modeSymbol() -> Robj {
unsafe { new_sys(R_ModeSymbol) }
}
/// "na.rm"
pub fn naRmSymbol() -> Robj {
unsafe { new_sys(R_NaRmSymbol) }
}
/// "name"
pub fn nameSymbol() -> Robj {
unsafe { new_sys(R_NameSymbol) }
}
/// "names"
pub fn namesSymbol() -> Robj {
unsafe { new_sys(R_NamesSymbol) }
}
/// _NAMESPACE__."
pub fn namespaceEnvSymbol() -> Robj {
unsafe { new_sys(R_NamespaceEnvSymbol) }
}
/// "package"
pub fn packageSymbol() -> Robj {
unsafe { new_sys(R_PackageSymbol) }
}
/// "previous"
pub fn previousSymbol() -> Robj {
unsafe { new_sys(R_PreviousSymbol) }
}
/// "quote"
pub fn quoteSymbol() -> Robj {
unsafe { new_sys(R_QuoteSymbol) }
}
/// "row.names"
pub fn rowNamesSymbol() -> Robj {
unsafe { new_sys(R_RowNamesSymbol) }
}
/// ".Random.seed"
pub fn seedsSymbol() -> Robj {
unsafe { new_sys(R_SeedsSymbol) }
}
/// "sort.list"
pub fn sortListSymbol() -> Robj {
unsafe { new_sys(R_SortListSymbol) }
}
/// "source"
pub fn sourceSymbol() -> Robj {
unsafe { new_sys(R_SourceSymbol) }
}
/// "spec"
pub fn specSymbol() -> Robj {
unsafe { new_sys(R_SpecSymbol) }
}
/// "tsp"
pub fn tspSymbol() -> Robj {
unsafe { new_sys(R_TspSymbol) }
}
/// ":::"
pub fn tripleColonSymbol() -> Robj {
unsafe { new_sys(R_TripleColonSymbol) }
}
/// ".defined"
pub fn dot_defined() -> Robj {
unsafe { new_sys(R_dot_defined) }
}
/// ".Method"
pub fn dot_Method() -> Robj {
unsafe { new_sys(R_dot_Method) }
}
/// "packageName"
pub fn dot_packageName() -> Robj {
unsafe { new_sys(R_dot_packageName) }
} //
/// ".target"
pub fn dot_target() -> Robj {
unsafe { new_sys(R_dot_target) }
}
/* fix version issues.
/// ".Generic"
pub fn dot_Generic() -> Robj { unsafe { new_sys(R_dot_Generic) }}
*/
/// NA_STRING as a CHARSXP
pub fn naString() -> Robj {
unsafe { new_sys(R_NaString) }
}
/// "" as a CHARSXP
pub fn blankString() -> Robj {
unsafe { new_sys(R_BlankString) }
}
/// as a STRSXP
pub fn blankScalarString() -> Robj {
unsafe { new_sys(R_BlankScalarString) }
}
}
///////////////////////////////////////////////////////////////
/// The following impls wrap specific Rinternals.h functions.
///
#[allow(non_snake_case)]
impl Robj {
/// Return true if this is the null object.
pub fn isNull(&self) -> bool {
unsafe { Rf_isNull(self.get()) != 0 }
}
/// Return true if this is a symbol.
pub fn isSymbol(&self) -> bool {
unsafe { Rf_isSymbol(self.get()) != 0 }
}
/// Return true if this is a boolean (logical) vector
pub fn isLogical(&self) -> bool {
unsafe { Rf_isLogical(self.get()) != 0 }
}
/// Return true if this is a real (f64) vector.
pub fn isReal(&self) -> bool {
unsafe { Rf_isReal(self.get()) != 0 }
}
/// Return true if this is a complex vector.
pub fn isComplex(&self) -> bool {
unsafe { Rf_isComplex(self.get()) != 0 }
}
/// Return true if this is an expression.
pub fn isExpression(&self) -> bool {
unsafe { Rf_isExpression(self.get()) != 0 }
}
/// Return true if this is an environment.
pub fn isEnvironment(&self) -> bool {
unsafe { Rf_isEnvironment(self.get()) != 0 }
}
/// Return true if this is a string.
pub fn isString(&self) -> bool {
unsafe { Rf_isString(self.get()) != 0 }
}
/// Return true if this is an object.
pub fn isObject(&self) -> bool {
unsafe { Rf_isObject(self.get()) != 0 }
}
/// Get the source ref.
pub fn getCurrentSrcref(val: i32) -> Robj {
unsafe { new_owned(R_GetCurrentSrcref(val as raw::c_int)) }
}
/// Get the source filename.
pub fn getSrcFilename(&self) -> Robj {
unsafe { new_owned(R_GetSrcFilename(self.get())) }
}
/// Convert to a string vector.
pub fn asChar(&self) -> Robj {
unsafe { new_owned(Rf_asChar(self.get())) }
}
/// Convert to vectors of many kinds.
pub fn coerceVector(&self, sexptype: u32) -> Robj {
unsafe { new_owned(Rf_coerceVector(self.get(), sexptype as SEXPTYPE)) }
}
/// Convert a pairlist (LISTSXP) to a vector list (VECSXP).
pub fn pairToVectorList(&self) -> Robj {
unsafe { new_owned(Rf_PairToVectorList(self.get())) }
}
/// Convert a vector list (VECSXP) to a pair list (LISTSXP)
pub fn vectorToPairList(&self) -> Robj {
unsafe { new_owned(Rf_VectorToPairList(self.get())) }
}
/// Assign an integer to each unique string and return a "factor".
pub fn asCharacterFactor(&self) -> Robj {
unsafe { new_owned(Rf_asCharacterFactor(self.get())) }
}
/// Get a scalar boolean value
pub fn asLogical(&self) -> bool {
unsafe { Rf_asLogical(self.get()) != 0 }
}
/// Get a scalar 32 bit integer value
pub fn asInteger(&self) -> i32 {
unsafe { Rf_asInteger(self.get()) as i32 }
}
/// Get a 64 bit double value
pub fn asReal(&self) -> f64 {
unsafe { Rf_asReal(self.get()) as f64 }
}
/// Allocate a matrix object (see NumericMatrix etc.)
pub fn allocMatrix(sexptype: SEXPTYPE, rows: i32, cols: i32) -> Robj {
unsafe { new_owned(Rf_allocMatrix(sexptype, rows, cols)) }
}
/* TODO:
int Rf_asLogical2(SEXP x, int checking, SEXP call, SEXP rho);
Rcomplex Rf_asComplex(SEXP x);
void Rf_addMissingVarsToNewEnv(SEXP, SEXP);
SEXP Rf_alloc3DArray(SEXPTYPE, int, int, int);
SEXP Rf_allocArray(SEXPTYPE, SEXP);
SEXP Rf_allocFormalsList2(SEXP sym1, SEXP sym2);
SEXP Rf_allocFormalsList3(SEXP sym1, SEXP sym2, SEXP sym3);
SEXP Rf_allocFormalsList4(SEXP sym1, SEXP sym2, SEXP sym3, SEXP sym4);
SEXP Rf_allocFormalsList5(SEXP sym1, SEXP sym2, SEXP sym3, SEXP sym4, SEXP sym5);
SEXP Rf_allocFormalsList6(SEXP sym1, SEXP sym2, SEXP sym3, SEXP sym4, SEXP sym5, SEXP sym6);
SEXP Rf_allocList(int);
SEXP Rf_allocS4Object(void);
SEXP Rf_allocSExp(SEXPTYPE);
SEXP Rf_allocVector3(SEXPTYPE, R_xlen_t, R_allocator_t*);
R_xlen_t Rf_any_duplicated(SEXP x, Rboolean from_last);
R_xlen_t Rf_any_duplicated3(SEXP x, SEXP incomp, Rboolean from_last);
SEXP Rf_applyClosure(SEXP, SEXP, SEXP, SEXP, SEXP);
SEXP Rf_arraySubscript(int, SEXP, SEXP, SEXP (*)(SEXP,SEXP), SEXP (*)(SEXP, int), SEXP);
SEXP Rf_classgets(SEXP, SEXP);
SEXP Rf_cons(SEXP, SEXP);
SEXP Rf_fixSubset3Args(SEXP, SEXP, SEXP, SEXP*);
void Rf_copyMatrix(SEXP, SEXP, Rboolean);
void Rf_copyListMatrix(SEXP, SEXP, Rboolean);
void Rf_copyMostAttrib(SEXP, SEXP);
void Rf_copyVector(SEXP, SEXP);
int Rf_countContexts(int, int);
SEXP Rf_CreateTag(SEXP);
void Rf_defineVar(SEXP, SEXP, SEXP);
SEXP Rf_dimgets(SEXP, SEXP);
SEXP Rf_dimnamesgets(SEXP, SEXP);
SEXP Rf_DropDims(SEXP);
*/
/// Compatible way to duplicate an object. Use obj.clone() instead
/// for Rust compaitibility.
pub fn duplicate(&self) -> Self {
unsafe { new_owned(Rf_duplicate(self.get())) }
}
/*
SEXP Rf_shallow_duplicate(SEXP);
SEXP R_duplicate_attr(SEXP);
SEXP R_shallow_duplicate_attr(SEXP);
SEXP Rf_lazy_duplicate(SEXP);
SEXP Rf_duplicated(SEXP, Rboolean);
Rboolean R_envHasNoSpecialSymbols(SEXP);
SEXP Rf_eval(SEXP, SEXP);
SEXP Rf_ExtractSubset(SEXP, SEXP, SEXP);
SEXP Rf_findFun(SEXP, SEXP);
SEXP Rf_findFun3(SEXP, SEXP, SEXP);
void Rf_findFunctionForBody(SEXP);
SEXP Rf_findVar(SEXP, SEXP);
SEXP Rf_findVarInFrame(SEXP, SEXP);
SEXP Rf_findVarInFrame3(SEXP, SEXP, Rboolean);
SEXP Rf_getAttrib(SEXP, SEXP);
SEXP Rf_GetArrayDimnames(SEXP);
SEXP Rf_GetColNames(SEXP);
void Rf_GetMatrixDimnames(SEXP, SEXP*, SEXP*, const char**, const char**);
SEXP Rf_GetOption(SEXP, SEXP);
SEXP Rf_GetOption1(SEXP);
int Rf_FixupDigits(SEXP, warn_type);
int Rf_FixupWidth (SEXP, warn_type);
int Rf_GetOptionDigits(void);
int Rf_GetOptionWidth(void);
SEXP Rf_GetRowNames(SEXP);
void Rf_gsetVar(SEXP, SEXP, SEXP);
SEXP Rf_install(const char *);
SEXP Rf_installChar(SEXP);
SEXP Rf_installNoTrChar(SEXP);
SEXP Rf_installTrChar(SEXP);
SEXP Rf_installDDVAL(int i);
SEXP Rf_installS3Signature(const char *, const char *);
Rboolean Rf_isFree(SEXP);
Rboolean Rf_isOrdered(SEXP);
Rboolean Rf_isUnmodifiedSpecSym(SEXP sym, SEXP env);
Rboolean Rf_isUnordered(SEXP);
Rboolean Rf_isUnsorted(SEXP, Rboolean);
SEXP Rf_lengthgets(SEXP, R_len_t);
SEXP Rf_xlengthgets(SEXP, R_xlen_t);
SEXP R_lsInternal(SEXP, Rboolean);
SEXP R_lsInternal3(SEXP, Rboolean, Rboolean);
SEXP Rf_match(SEXP, SEXP, int);
SEXP Rf_matchE(SEXP, SEXP, int, SEXP);
SEXP Rf_namesgets(SEXP, SEXP);
SEXP Rf_mkChar(const char *);
SEXP Rf_mkCharLen(const char *, int);
Rboolean Rf_NonNullStringMatch(SEXP, SEXP);
*/
/// Number of columns of a matrix
pub fn ncols(&self) -> usize {
unsafe { Rf_ncols(self.get()) as usize }
}
/// Number of rows of a matrix
pub fn nrows(&self) -> usize {
unsafe { Rf_nrows(self.get()) as usize }
}
/*SEXP Rf_nthcdr(SEXP, int);
Rboolean Rf_pmatch(SEXP, SEXP, Rboolean);
Rboolean Rf_psmatch(const char *, const char *, Rboolean);
void Rf_PrintValue(SEXP);
void Rf_printwhere(void);
void Rf_readS3VarsFromFrame(SEXP, SEXP*, SEXP*, SEXP*, SEXP*, SEXP*, SEXP*);
SEXP Rf_setAttrib(SEXP, SEXP, SEXP);
void Rf_setSVector(SEXP*, int, SEXP);
void Rf_setVar(SEXP, SEXP, SEXP);
SEXP Rf_stringSuffix(SEXP, int);
SEXPTYPE Rf_str2type(const char *);
Rboolean Rf_StringBlank(SEXP);
SEXP Rf_substitute(SEXP,SEXP);
SEXP Rf_topenv(SEXP, SEXP);
const char * Rf_translateChar(SEXP);
const char * Rf_translateChar0(SEXP);
const char * Rf_translateCharUTF8(SEXP);
const char * Rf_type2char(SEXPTYPE);
SEXP Rf_type2rstr(SEXPTYPE);
SEXP Rf_type2str(SEXPTYPE);
SEXP Rf_type2str_nowarn(SEXPTYPE);
SEXP R_GetCurrentEnv();
Rboolean Rf_isS4(SEXP);
SEXP Rf_asS4(SEXP, Rboolean, int);
SEXP Rf_S3Class(SEXP);
int Rf_isBasicClass(const char *);
Rboolean R_cycle_detected(SEXP s, SEXP child);
u32 Rf_getCharCE(SEXP);
SEXP Rf_mkCharCE(const char *, cetype_t);
SEXP Rf_mkCharLenCE(const char *, int, cetype_t);
SEXP R_forceAndCall(SEXP e, int n, SEXP rho);
*/
/// Internal function used to implement #[extendr] impl
pub unsafe fn makeExternalPtr<T>(p: *mut T, tag: Robj, prot: Robj) -> Self {
new_owned(R_MakeExternalPtr(
p as *mut ::std::os::raw::c_void,
tag.get(),
prot.get(),
))
}
/// Internal function used to implement #[extendr] impl
pub unsafe fn externalPtrAddr<T>(&self) -> *mut T {
R_ExternalPtrAddr(self.get()) as *mut T
}
/// Internal function used to implement #[extendr] impl
pub unsafe fn externalPtrTag(&self) -> Self {
new_borrowed(R_ExternalPtrTag(self.get()))
}
/// Internal function used to implement #[extendr] impl
pub unsafe fn externalPtrProtected(&self) -> Self {
new_borrowed(R_ExternalPtrProtected(self.get()))
}
pub unsafe fn registerCFinalizer(&self, func: R_CFinalizer_t) {
R_RegisterCFinalizer(self.get(), func);
}
// SEXP R_ExternalPtrTag(SEXP s);
// SEXP R_ExternalPtrProtected(SEXP s);
// void R_ClearExternalPtr(SEXP s);
// void R_SetExternalPtrAddr(SEXP s, void *p);
// void R_SetExternalPtrTag(SEXP s, SEXP tag);
// void R_SetExternalPtrProtected(SEXP s, SEXP p);
/*
SEXP R_MakeWeakRef(SEXP key, SEXP val, SEXP fin, Rboolean onexit);
SEXP R_MakeWeakRefC(SEXP key, SEXP val, R_CFinalizer_t fin, Rboolean onexit);
SEXP R_WeakRefKey(SEXP w);
SEXP R_WeakRefValue(SEXP w);
void R_RunWeakRefFinalizer(SEXP w);
SEXP R_PromiseExpr(SEXP);
SEXP R_ClosureExpr(SEXP);
SEXP R_BytecodeExpr(SEXP e);
SEXP R_bcEncode(SEXP);
SEXP R_bcDecode(SEXP);
void R_registerBC(SEXP, SEXP);
Rboolean R_checkConstants(Rboolean);
Rboolean R_BCVersionOK(SEXP);
void R_RestoreHashCount(SEXP rho);
Rboolean R_IsPackageEnv(SEXP rho);
SEXP R_PackageEnvName(SEXP rho);
SEXP R_FindPackageEnv(SEXP info);
Rboolean R_IsNamespaceEnv(SEXP rho);
SEXP R_NamespaceEnvSpec(SEXP rho);
SEXP R_FindNamespace(SEXP info);
void R_LockEnvironment(SEXP env, Rboolean bindings);
Rboolean R_EnvironmentIsLocked(SEXP env);
void R_LockBinding(SEXP sym, SEXP env);
void R_unLockBinding(SEXP sym, SEXP env);
void R_MakeActiveBinding(SEXP sym, SEXP fun, SEXP env);
Rboolean R_BindingIsLocked(SEXP sym, SEXP env);
Rboolean R_BindingIsActive(SEXP sym, SEXP env);
Rboolean R_HasFancyBindings(SEXP rho);
*/
/// Read-only access to attribute list.
// fn attrib(&self) -> Robj {
// unsafe {new_borrowed(ATTRIB(self.get()))}
// }
/// Copy a vector and resize it.
/// See. https://github.com/hadley/r-internals/blob/master/vectors.md
pub fn xlengthgets(&self, new_len: usize) -> Result<Robj, AnyError> {
unsafe {
if self.isVector() {
Ok(new_owned(Rf_xlengthgets(self.get(), new_len as R_xlen_t)))
} else {
Err(AnyError::from("xlengthgets: Not a vector type"))
}
}
}
/// Allocated an owned object of a certain type.
pub fn allocVector(sexptype: u32, len: usize) -> Robj {
unsafe { new_owned(Rf_allocVector(sexptype, len as R_xlen_t)) }
}
/// Return true if two arrays have identical dims.
pub fn conformable(a: &Robj, b: &Robj) -> bool {
unsafe { Rf_conformable(a.get(), b.get()) != 0 }
}
/// Borrow an element from a list.
pub fn elt(&self, index: usize) -> Robj {
unsafe { Robj::from(Rf_elt(self.get(), index as raw::c_int)) }
}
//Rboolean Rf_inherits(SEXP, const char *);
/// Return true if this is an array.
pub fn isArray(&self) -> bool {
unsafe { Rf_isArray(self.get()) != 0 }
}
/// Return true if this is factor.
pub fn isFactor(&self) -> bool {
unsafe { Rf_isFactor(self.get()) != 0 }
}
/// Return true if this is a data frame.
pub fn isFrame(&self) -> bool {
unsafe { Rf_isFrame(self.get()) != 0 }
}
/// Return true if this is a function.
pub fn isFunction(&self) -> bool {
unsafe { Rf_isFunction(self.get()) != 0 }
}
/// Return true if this is an integer vector.
pub fn isInteger(&self) -> bool {
unsafe { Rf_isInteger(self.get()) != 0 }
}
/// Return true if this is a language object.
pub fn isLanguage(&self) -> bool {
unsafe { Rf_isLanguage(self.get()) != 0 }
}
/// Return true if this is a vector list.
pub fn isList(&self) -> bool {
unsafe { Rf_isList(self.get()) != 0 }
}
/// Return true if this is a matrix.
pub fn isMatrix(&self) -> bool {
unsafe { Rf_isMatrix(self.get()) != 0 }
}
/// Return true if this is a vector list or null.
pub fn isNewList(&self) -> bool {
unsafe { Rf_isNewList(self.get()) != 0 }
}
/// Return true if this is a numeric vector but not a factor.
pub fn isNumber(&self) -> bool {
unsafe { Rf_isNumber(self.get()) != 0 }
}
/// Return true if this is a numeric vector but not a factor or complex.
pub fn isNumeric(&self) -> bool {
unsafe { Rf_isNumeric(self.get()) != 0 }
}
/// Return true if this is a pairlist.
pub fn isPairList(&self) -> bool {
unsafe { Rf_isPairList(self.get()) != 0 }
}
/// Return true if this is a primitive function.
pub fn isPrimitive(&self) -> bool {
unsafe { Rf_isPrimitive(self.get()) != 0 }