-
Notifications
You must be signed in to change notification settings - Fork 16
/
Redis.cpp
1088 lines (899 loc) · 42.1 KB
/
Redis.cpp
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
// RcppRedis -- Rcpp bindings to Hiredis for some Redis functionality
//
// Copyright (C) 2013 - 2023 Dirk Eddelbuettel
// Portions Copyright (C) 2013 Wush Wu
// Portions Copyright (C) 2013 William Pleasant
// Portions Copyright (C) 2015 Russell S. Pierce
// Portions Copyright (C) 2022 Bryan W. Lewis
//
// This file is part of RcppRedis
//
// RcppRedis 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.
//
// RcppRedis 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 RcppRedis. If not, see <http://www.gnu.org/licenses/>.
// simple C++ class to host a stateful connection to redis
//
// uses hiredis library which provides a basic C API to redis
//
// initially forked from Wush Wu's Rhiredis
// slowly adding some more Redis functions
// trying to figure out if we want
// -- R serialization for interop with rredis
// -- 'native' serialization for interop with redis-cli
// or possibly both
//
// We do use 'binary' serialization for faster processing
//
// Dirk Eddelbuettel, 2013 - 2023
// [[Rcpp::depends(BH)]]
#include <Rcpp/Rcpp>
#include <hiredis/hiredis.h> // we check in configure for this
#include <RApiSerializeAPI.h> // provides C API with serialization for R
#include <sys/time.h> // for struct timeval
#ifdef HAVE_MSGPACK
#include <msgpack.hpp>
#endif
// A simple and lightweight class -- with just a simple private member variable
// We could add some more member variables to cache the last call, status, ...
class Redis {
private:
redisContext *prc_; // private pointer to redis context
// set up a connection to Redis on the given machine and port
void init(std::string host="127.0.0.1", int port=6379,
std::string auth="", double timeout=0.0) {
if (timeout == 0.0) { // icky float equality
prc_ = redisConnect(host.c_str(), port);
} else {
int second = static_cast<int>(timeout);
int microseconds = static_cast<int>(1000000*(timeout - second));
struct timeval timeoutStruct = { second, microseconds };
prc_ = redisConnectWithTimeout(host.c_str(), port, timeoutStruct);
}
if (prc_->err) {
Rcpp::stop(std::string("Redis connection error: ") + std::string(prc_->errstr));
}
if (auth != "") {
redisReply *reply =
static_cast<redisReply*>(redisCommandNULLSafe(prc_, ("AUTH " + auth).c_str()));
if (reply->type == REDIS_REPLY_ERROR) {
freeReplyObject(reply);
Rcpp::stop(std::string("Redis authentication error."));
}
freeReplyObject(reply);
}
}
void nullReplyCheck(redisReply *reply) {
if (reply == NULL) {
Rcpp::stop("Recieved NULL reply; potential connection loss with Redis");
}
}
void *redisCommandNULLSafe(redisContext *c, const char *format, ...) {
va_list myargs;
va_start(myargs, format);
redisReply *reply =
static_cast<redisReply*>(redisvCommand(c, format, myargs));
nullReplyCheck(reply);
return reply;
}
void *redisCommandArgvNULLSafe(redisContext *c, int argc, const char **argv, const size_t *argvlen) {
redisReply *reply =
static_cast<redisReply*>(redisCommandArgv(c, argc, argv, argvlen));
nullReplyCheck(reply);
return reply;
}
// This function was originally contributed by William Pleasant
// It switches according to the return type
SEXP extract_reply(redisReply *reply){
switch(reply->type) {
case REDIS_REPLY_STRING:
case REDIS_REPLY_STATUS:
return Rcpp::wrap(std::string(reply->str));
case REDIS_REPLY_ERROR: {
std::string errorMessage = std::string(reply->str);
freeReplyObject(reply);
Rcpp::stop(errorMessage);
}
case REDIS_REPLY_INTEGER: {
// cast to double to avoid INT_MAX overflow
return Rcpp::wrap(static_cast<double>(reply->integer));
}
case REDIS_REPLY_NIL: {
return R_NilValue;
}
case REDIS_REPLY_ARRAY: {
return extract_array(reply);
}
default:
Rcpp::stop("Unknown type");
}
return R_NilValue; // makes 'g++ -Wall -pedantic' happy
}
// for vector results (of any type), fill a list (as a list type can contain
// different basic types and we switch later over these
Rcpp::List extract_array(redisReply *node) {
Rcpp::List retlist(node->elements);
for(unsigned int i = 0;i < node->elements;i++) {
retlist[i] = extract_reply(node->element[i]);
}
return retlist;
}
// helper function
std::string replyTypeToString(const redisReply *reply) {
switch(reply->type) {
case REDIS_REPLY_STRING: return std::string("string");
case REDIS_REPLY_STATUS: return std::string("status");
case REDIS_REPLY_INTEGER: return std::string("integer");
case REDIS_REPLY_ERROR: return std::string("error");
case REDIS_REPLY_NIL: return std::string("nil");
case REDIS_REPLY_ARRAY: return std::string("array");
default: return std::string("unknown");
}
}
enum { replyString_t = 0, replyStatus_t, replyInteger_t, replyError_t,
replyNil_t, replyArray_t };
int replyTypeToInteger(const redisReply *reply) {
switch(reply->type) {
case REDIS_REPLY_STRING: return replyString_t;
case REDIS_REPLY_STATUS: return replyStatus_t;
case REDIS_REPLY_INTEGER: return replyInteger_t;
case REDIS_REPLY_ERROR: return replyError_t;
case REDIS_REPLY_NIL: return replyNil_t;
case REDIS_REPLY_ARRAY: return replyArray_t;
default: return -1;
}
}
void checkReplyType(const redisReply *reply, int replyType) {
if (replyType != replyTypeToInteger(reply)) {
Rcpp::stop(std::string("Wrong reply type, got ") + replyTypeToString(reply));
}
}
public:
Redis(std::string host, int port, std::string auth, int timeout) { init(host, port, auth, timeout); }
Redis(std::string host, int port, std::string auth) { init(host, port, auth); }
Redis(std::string host, int port) { init(host, port); }
Redis(std::string host) { init(host); }
Redis() { init(); }
// could create new functions to (re-)connect with given host and port etc pp
~Redis() {
redisFree(prc_);
prc_ = NULL; // just to be on the safe side
}
// execute given string
SEXP exec(std::string cmd) {
redisReply *reply =
static_cast<redisReply*>(redisCommandNULLSafe(prc_, cmd.c_str()));
SEXP rep = extract_reply(reply);
freeReplyObject(reply);
return(rep);
}
SEXP execv(std::vector<std::string> cmd) {
std::vector<const char*> cmdv(cmd.size());
std::vector<size_t> cmdlen(cmd.size());
for (unsigned int i=0; i < cmd.size(); ++i) {
cmdv[i] = cmd[i].c_str();
cmdlen[i] = cmd[i].size();
}
redisReply *reply =
static_cast<redisReply*>(redisCommandArgvNULLSafe(prc_, cmd.size(),
&(cmdv[0]), &(cmdlen[0])));
SEXP rep = extract_reply(reply);
freeReplyObject(reply);
return(rep);
}
// redis ping -- see if server is alive and responding
SEXP ping(void) {
redisReply *reply = static_cast<redisReply*>(redisCommandNULLSafe(prc_, "PING"));
SEXP rep = extract_reply(reply);
freeReplyObject(reply);
return(rep);
}
// redis exists -- get the number of keys matching the request
SEXP exists(std::string key) {
return(exec("EXISTS " + key));
}
// redis expire -- expire key after numeric seconds, use expire and round
SEXP expire(std::string key, double seconds) {
std::string secs = std::to_string(static_cast<int32_t>(std::round(seconds)));
return(exec("EXPIRE " + key + " " + secs));
}
// redis pexpire -- expire key after numeric milliseconds, use pexpire and round
SEXP pexpire(std::string key, double milliseconds) {
std::string ms = std::to_string(static_cast<int32_t>(std::round(milliseconds)));
return(exec("EXPIRE " + key + " " + ms));
}
// redis set -- serializes to R internal format
std::string set(std::string key, SEXP s) {
// if raw, use as is else serialize to raw
Rcpp::RawVector x = (TYPEOF(s) == RAWSXP) ? s : serializeToRaw(s);
// uses binary protocol, see hiredis doc at github
redisReply *reply =
static_cast<redisReply*>(redisCommandNULLSafe(prc_, "SET %s %b",
key.c_str(), x.begin(), x.size()));
std::string res(reply->str);
freeReplyObject(reply);
return(res);
}
// redis get -- deserializes from R format
SEXP get(std::string key) {
SEXP obj;
redisReply *reply =
static_cast<redisReply*>(redisCommandNULLSafe(prc_, "GET %s", key.c_str()));
if (replyTypeToInteger(reply) == replyNil_t) {
obj = R_NilValue;
} else {
int nc = reply->len;
Rcpp::RawVector res(nc);
memcpy(res.begin(), reply->str, nc);
obj = unserializeFromRaw(res);
}
freeReplyObject(reply);
return(obj);
}
// redis hset -- serializes to R internal format
int hset(std::string key, std::string field, SEXP s) {
// if raw, use as is else serialize to raw
Rcpp::RawVector x = (TYPEOF(s) == RAWSXP) ? s : serializeToRaw(s);
// uses binary protocol, see hiredis doc at github
redisReply *reply =
static_cast<redisReply*>(redisCommandNULLSafe(prc_, "HSET %s %s %b",
key.c_str(), field.c_str(), x.begin(), x.size()));
checkReplyType(reply, replyInteger_t); // ensure we got integer
int res = reply->integer;
freeReplyObject(reply);
return(res);
}
// redis hget -- deserializes from R format
SEXP hget(std::string key, std::string field) {
redisReply *reply =
static_cast<redisReply*>(redisCommandNULLSafe(prc_, "HGET %s %s",
key.c_str(), field.c_str()));
int nc = reply->len;
Rcpp::RawVector res(nc);
memcpy(res.begin(), reply->str, nc);
freeReplyObject(reply);
SEXP obj = unserializeFromRaw(res);
return(obj);
}
// redis hexists -- returns int
int hexists(std::string key, std::string field) {
redisReply *reply =
static_cast<redisReply*>(redisCommandNULLSafe(prc_, "HEXISTS %s %s",
key.c_str(), field.c_str()));
checkReplyType(reply, replyInteger_t); // ensure we got integer
int res = reply->integer;
freeReplyObject(reply);
return(res);
}
// redis hdel -- returns int
int hdel(std::string key, std::string field) {
redisReply *reply =
static_cast<redisReply*>(redisCommandNULLSafe(prc_, "HDEL %s %s",
key.c_str(), field.c_str()));
checkReplyType(reply, replyInteger_t); // ensure we got integer
int res = reply->integer;
freeReplyObject(reply);
return(res);
}
// redis hlen -- returns int
int hlen(std::string key) {
redisReply *reply =
static_cast<redisReply*>(redisCommandNULLSafe(prc_, "HLEN %s", key.c_str()));
checkReplyType(reply, replyInteger_t); // ensure we got integer
int res = reply->integer;
freeReplyObject(reply);
return(res);
}
// redis hkeys -- returns character vector
SEXP hkeys(std::string key) {
redisReply *reply =
static_cast<redisReply*>(redisCommandNULLSafe(prc_, "HKEYS %s", key.c_str()));
unsigned int nc = reply->elements;
Rcpp::CharacterVector vec(nc);
for (unsigned int i = 0; i < nc; i++) {
vec[i] = reply->element[i]->str;
}
freeReplyObject(reply);
return(vec);
}
// redis hgetall -- returns a list
Rcpp::List hgetall(std::string key) {
redisReply *reply =
static_cast<redisReply*>(redisCommandNULLSafe(prc_, "HGETALL %s", key.c_str()));
unsigned int nc = reply->elements;
Rcpp::List vec(nc/2);
Rcpp::CharacterVector keys(nc/2);
// 0, 2, 4 are names, 1, 3, 5 are values
for (unsigned int i = 0; i < nc/2; i++) {
keys[i] = reply->element[i*2]->str;
int valueidx = i*2+1;
int vlen = reply->element[valueidx]->len;
Rcpp::RawVector res(vlen);
memcpy(res.begin(), reply->element[valueidx]->str, vlen);
SEXP obj = unserializeFromRaw(res);
vec[i] = obj;
}
vec.names() = keys;
freeReplyObject(reply);
return(vec);
}
// redis sadd -- serializes to R internal format
SEXP sadd(std::string key, SEXP s) {
// if raw, use as is else serialize to raw
Rcpp::RawVector x = (TYPEOF(s) == RAWSXP) ? s : serializeToRaw(s);
const char* cmdv[3] = {"SADD", key.c_str(), reinterpret_cast<char*>(x.begin())};
size_t cmdlen[3] = {4, key.length(), static_cast<size_t>(x.size())};
// uses binary protocol, see hiredis doc at github
redisReply *reply =
static_cast<redisReply*>(redisCommandArgvNULLSafe(prc_, 3, cmdv, cmdlen));
SEXP rep = extract_reply(reply);
freeReplyObject(reply);
return(rep);
}
// redis srem -- serializes to R internal format
SEXP srem(std::string key, SEXP s) {
// if raw, use as is else serialize to raw
Rcpp::RawVector x = (TYPEOF(s) == RAWSXP) ? s : serializeToRaw(s);
const char* cmdv[3] = {"SREM", key.c_str(), reinterpret_cast<char*>(x.begin())};
size_t cmdlen[3] = {4, key.length(), static_cast<size_t>(x.size())};
// uses binary protocol, see hiredis doc at github
redisReply *reply =
static_cast<redisReply*>(redisCommandArgvNULLSafe(prc_, 3, cmdv, cmdlen));
SEXP rep = extract_reply(reply);
freeReplyObject(reply);
return(rep);
}
// redis smembers -- deserializes from R format
Rcpp::List smembers(std::string key) {
redisReply *reply =
static_cast<redisReply*>(redisCommandNULLSafe(prc_, "SMEMBERS %s", key.c_str()));
unsigned int len = reply->elements;
Rcpp::List x(len);
for (unsigned int i = 0; i < len; i++) {
int nc = reply->element[i]->len;
Rcpp::RawVector res(nc);
memcpy(res.begin(), reply->element[i]->str, nc);
SEXP obj = unserializeFromRaw(res);
x[i] = obj;
}
freeReplyObject(reply);
return(x);
}
// redis keys -- returns character vector
SEXP keys(std::string regexp) {
redisReply *reply =
static_cast<redisReply*>(redisCommandNULLSafe(prc_, "KEYS %s", regexp.c_str()));
unsigned int nc = reply->elements;
Rcpp::CharacterVector vec(nc);
for (unsigned int i = 0; i < nc; i++) {
vec[i] = reply->element[i]->str;
}
freeReplyObject(reply);
return(vec);
}
// redis ltrim: trim list so that it contains only the range of elements specified
SEXP ltrim(std::string key, int start, int end) {
redisReply *reply =
static_cast<redisReply*>(redisCommandNULLSafe(prc_, "LTRIM %s %d %d",
key.c_str(), start, end));
SEXP rep = extract_reply(reply);
return(rep);
}
// redis lrange: get list from start to end -- with R serialization
Rcpp::List lrange(std::string key, int start, int end) {
redisReply *reply =
static_cast<redisReply*>(redisCommandNULLSafe(prc_, "LRANGE %s %d %d",
key.c_str(), start, end));
unsigned int len = reply->elements;
//Rcpp::Rcout << "Seeing " << len << " elements\n";
Rcpp::List x(len);
for (unsigned int i = 0; i < len; i++) {
//Rcpp::Rcout << " Seeing size " << reply->element[i]->len << "\n";
int nc = reply->element[i]->len;
Rcpp::RawVector res(nc);
memcpy(res.begin(), reply->element[i]->str, nc);
SEXP obj = unserializeFromRaw(res);
x[i] = obj;
}
freeReplyObject(reply);
return(x);
}
// redis llen: get list length
double llen(std::string key) {
redisReply *reply =
static_cast<redisReply*>(redisCommandNULLSafe(prc_, "LLEN %s", key.c_str()));
checkReplyType(reply, replyInteger_t); // ensure we got int
double res = static_cast<double>(reply->integer); // a 'long long' would overflow int
freeReplyObject(reply);
return(res);
}
// Some "R-serialization" functions below
// redis "lpop from" -- with R serialization
SEXP lpop(std::string key) {
SEXP obj;
std::string res;
redisReply *reply =
static_cast<redisReply*>(redisCommandNULLSafe(prc_, "LPOP %s", key.c_str()));
if (replyTypeToInteger(reply) == replyNil_t) {
obj = R_NilValue;
} else {
checkReplyType(reply, replyString_t); // ensure we got string
int nc = reply->len;
Rcpp::RawVector res(nc);
memcpy(res.begin(), reply->str, nc);
obj = unserializeFromRaw(res);
}
return(obj);
}
// redis "rpop from" -- with R serialization
SEXP rpop(std::string key) {
SEXP obj;
std::string res;
redisReply *reply =
static_cast<redisReply*>(redisCommandNULLSafe(prc_, "RPOP %s", key.c_str()));
if (replyTypeToInteger(reply) == replyNil_t) {
obj = R_NilValue;
} else {
checkReplyType(reply, replyString_t); // ensure we got string
int nc = reply->len;
Rcpp::RawVector res(nc);
memcpy(res.begin(), reply->str, nc);
obj = unserializeFromRaw(res);
}
return(obj);
}
// redis "prepend to list" -- with R serialization
SEXP lpush(std::string key, SEXP s) {
// if raw, use as is else serialize to raw
Rcpp::RawVector x = (TYPEOF(s) == RAWSXP) ? s : serializeToRaw(s);
// uses binary protocol, see hiredis doc at github
redisReply *reply =
static_cast<redisReply*>(redisCommandNULLSafe(prc_, "LPUSH %s %b",
key.c_str(), x.begin(),
x.size()*szdb));
SEXP rep = extract_reply(reply);
freeReplyObject(reply);
return(rep);
}
// redis "append to list" -- with R serialization
SEXP rpush(std::string key, SEXP s) {
// if raw, use as is else serialize to raw
Rcpp::RawVector x = (TYPEOF(s) == RAWSXP) ? s : serializeToRaw(s);
// uses binary protocol, see hiredis doc at github
redisReply *reply =
static_cast<redisReply*>(redisCommandNULLSafe(prc_, "RPUSH %s %b",
key.c_str(), x.begin(),
x.size()*szdb));
SEXP rep = extract_reply(reply);
freeReplyObject(reply);
return(rep);
}
// Some "non-R-serialzation" functions below
// used in functions below
static const unsigned int szdb = sizeof(double);
// redis set a string without deserializes from R format [as set() above does]
std::string setString(std::string key, std::string value) {
redisReply *reply =
static_cast<redisReply*>(redisCommandNULLSafe(prc_, "SET %s %s",
key.c_str(), value.c_str()));
std::string res(reply->str);
freeReplyObject(reply);
return(res);
}
// redis get a string without deserializes from R format [as get() above does]
std::string getString(std::string key) {
redisReply *reply =
static_cast<redisReply*>(redisCommandNULLSafe(prc_, "GET %s", key.c_str()));
std::string res(reply->str);
freeReplyObject(reply);
return(res);
}
// redis "set a vector" -- without R serialization, without attributes, ...
std::string setVector(std::string key, Rcpp::NumericVector x) {
redisReply *reply =
static_cast<redisReply*>(redisCommandNULLSafe(prc_, "SET %s %b",
key.c_str(), x.begin(),
x.size()*szdb));
std::string res(reply->str);
freeReplyObject(reply);
return(res);
}
// redis "get a vector" -- without R serialization, without attributes, ...
Rcpp::NumericVector getVector(std::string key) {
redisReply *reply =
static_cast<redisReply*>(redisCommandNULLSafe(prc_, "GET %s", key.c_str()));
int nc = reply->len;
Rcpp::NumericVector x(nc/szdb);
memcpy(x.begin(), reply->str, nc);
freeReplyObject(reply);
return(x);
}
// redis "get from list from start to end" -- without R serialization
// assume numerical vectors, doesn't test all that well
Rcpp::List listRange(std::string key, int start, int end) {
redisReply *reply =
static_cast<redisReply*>(redisCommandNULLSafe(prc_, "LRANGE %s %d %d",
key.c_str(), start, end));
//Rcpp::Rcout << "listRange got type: " << replyTypeToString(reply) << "\n";
checkReplyType(reply, replyArray_t); // ensure we got array
unsigned int len = reply->elements;
Rcpp::List x(len);
for (unsigned int i = 0; i < len; i++) {
checkReplyType(reply->element[i], replyString_t); // ensure we got [binary] string
int nc = reply->element[i]->len;
Rcpp::NumericVector v(nc/szdb);
memcpy(v.begin(), reply->element[i]->str, nc);
x[i] = v;
}
freeReplyObject(reply);
return(x);
}
// redis "get from list from start to end" as matrix -- without R serialization
Rcpp::NumericMatrix listToMatrix(Rcpp::List Z) {
unsigned int n = Z.size();
int k = Rcpp::NumericVector(Z[0]).size();
Rcpp::NumericMatrix X(n, k);
for (unsigned int i = 0; i < n; i++) {
Rcpp::NumericVector z(Z[i]);
if (z.size() != k) Rcpp::stop("Wrong dimension");
X.row(i) = z;
}
return(X);
}
// redis "lpop from" -- without R serialization
std::string listLPop(std::string key) {
redisReply *reply =
static_cast<redisReply*>(redisCommandNULLSafe(prc_, "LPOP %s", key.c_str()));
std::string res;
if (replyTypeToInteger(reply) == replyNil_t) {
res = "(nil)";
} else {
checkReplyType(reply, replyString_t); // ensure we got string
res = reply->str;
}
freeReplyObject(reply);
return(res);
}
// redis "prepend to list" -- without R serialization
// as above: pure vector, no attributes, ...
std::string listLPush(std::string key, Rcpp::NumericVector x) {
// uses binary protocol, see hiredis doc at github
redisReply *reply =
static_cast<redisReply*>(redisCommandNULLSafe(prc_, "LPUSH %s %b",
key.c_str(), x.begin(),
x.size()*szdb));
//std::string res(reply->str);
std::string res = "";
freeReplyObject(reply);
return(res);
}
// redis "append to list" -- without R serialization
// as above: pure vector, no attributes, ...
std::string listRPush(std::string key, Rcpp::NumericVector x) {
// uses binary protocol, see hiredis doc at github
redisReply *reply =
static_cast<redisReply*>(redisCommandNULLSafe(prc_, "RPUSH %s %b",
key.c_str(), x.begin(),
x.size()*szdb));
//std::string res(reply->str);
std::string res = "";
freeReplyObject(reply);
return(res);
}
// redis "zadd" -- insert score and matrix row (without R serialization)
// by convention, the first element of each row vector is the score value
double zadd(std::string key, Rcpp::NumericMatrix x) {
double res = 0;
for (int i=0; i<x.nrow(); i++) {
Rcpp::NumericVector y = x.row(i);
// uses binary protocol, see hiredis doc at github
redisReply *reply =
static_cast<redisReply*>(redisCommandNULLSafe(prc_, "ZADD %s %f %b",
key.c_str(),
y[0],
y.begin(), y.size()*szdb));
checkReplyType(reply, replyInteger_t); // ensure we got array
res += static_cast<double>(reply->integer); // a 'long long' would overflow int
freeReplyObject(reply);
}
return(res);
}
// redis "zrange" (withscores) -- retrieve vectors from index [min, max] (without R serial.)
Rcpp::NumericMatrix zrange(std::string key, int min, int max) {
// uses binary protocol, see hiredis doc at github
redisReply *reply =
static_cast<redisReply*>(redisCommandNULLSafe(prc_, "ZRANGE %s %d %d",
key.c_str(), min, max));
checkReplyType(reply, replyArray_t); // ensure we got array
unsigned int rows = reply->elements;
unsigned int cols = reply->element[0]->len; // assumes all row have same nb of cols
Rcpp::NumericMatrix x(rows, cols/szdb); // and that all elements are type double
for (unsigned int i = 0; i < rows; i++) {
checkReplyType(reply->element[i], replyString_t); // ensure we got [binary] string
Rcpp::NumericVector v(cols/szdb);
memcpy(v.begin(), reply->element[i]->str, cols);
x.row(i) = v;
}
freeReplyObject(reply);
return(x);
}
// redis "zrangebyscore" -- retrieve vectors for score in [min, max] (without R serial.)
Rcpp::NumericMatrix zrangebyscore(std::string key, double min, double max) {
// uses binary protocol, see hiredis doc at github
redisReply *reply =
static_cast<redisReply*>(redisCommandNULLSafe(prc_,
"ZRANGEBYSCORE %s %f %f",
key.c_str(), min, max));
checkReplyType(reply, replyArray_t); // ensure we got array
unsigned int rows = reply->elements;
unsigned int cols = reply->element[0]->len; // assumes all row have same nb of cols
Rcpp::NumericMatrix x(rows, cols/szdb); // and that all elements are type double
for (unsigned int i = 0; i < rows; i++) {
checkReplyType(reply->element[i], replyString_t); // ensure we got [binary] string
Rcpp::NumericVector v(cols/szdb);
memcpy(v.begin(), reply->element[i]->str, cols);
x.row(i) = v;
}
freeReplyObject(reply);
return(x);
}
// redis "zremrangebyscore" -- remove elements in [min, max]
Rcpp::NumericVector zremrangebyscore(Rcpp::CharacterVector keyvec, double min, double max) {
int n = keyvec.size();
Rcpp::NumericVector res(n);
for (int i=0; i<n; i++) {
std::string key(keyvec[i]);
// uses binary protocol, see hiredis doc at github
redisReply *reply =
static_cast<redisReply*>(redisCommandNULLSafe(prc_,
"ZREMRANGEBYSCORE %s %f %f",
key.c_str(), min, max));
checkReplyType(reply, replyInteger_t); // ensure we got array
res[i] = static_cast<double>(reply->integer); // a 'long long' would overflow int
freeReplyObject(reply);
}
return(res);
}
// redis "zcard" -- number of members in sorted set
double zcard(std::string key) {
// uses binary protocol, see hiredis doc at github
redisReply *reply =
static_cast<redisReply*>(redisCommandNULLSafe(prc_,
"ZCARD %s", key.c_str()));
checkReplyType(reply, replyInteger_t); // ensure we got integer
double res = static_cast<double>(reply->integer); // a 'long long' would overflow int
freeReplyObject(reply);
return(res);
}
// redis "zcount" -- counter members in set with scores in given range
double zcount(std::string key, double min, double max) {
redisReply *reply =
static_cast<redisReply*>(redisCommandNULLSafe(prc_,
"ZCOUNT %s %f %f",
key.c_str(), min, max));
checkReplyType(reply, replyInteger_t); // ensure we got array
double res = static_cast<double>(reply->integer); // a 'long long' would overflow int
freeReplyObject(reply);
return(res);
}
// redis "get from list from start to end" -- without R serialization
// assume strings numerical vectors, doesn't test all that well
Rcpp::CharacterVector listRangeAsStrings(std::string key, int start, int end) {
// uses binary protocol, see hiredis doc at github
redisReply *reply =
static_cast<redisReply*>(redisCommandNULLSafe(prc_, "LRANGE %s %d %d",
key.c_str(), start, end));
//Rcpp::Rcout << "listRange got type: " << replyTypeToString(reply) << "\n";
checkReplyType(reply, replyArray_t); // ensure we got array
unsigned int len = reply->elements;
Rcpp::CharacterVector x(len);
for (unsigned int i = 0; i < len; i++) {
checkReplyType(reply->element[i], replyString_t); // ensure we got [binary] string
x[i] = reply->element[i]->str;
}
freeReplyObject(reply);
return(x);
}
#ifdef HAVE_MSGPACK
Rcpp::NumericMatrix msgPackMatrix(std::string key, int start, int end) {
redisReply *reply =
static_cast<redisReply*>(redisCommandNULLSafe(prc_, "LRANGE %s %d %d",
key.c_str(), start, end));
std::vector<double> row;
std::vector<std::vector<double> > vecs;
checkReplyType(reply, replyArray_t); // ensure we got array
unsigned int rows = reply->elements;
for (unsigned int i = 0; i < rows; i++) {
checkReplyType(reply->element[i], replyString_t); // ensure we got [binary] string
//x[i] = reply->element[i]->str;
msgpack::unpacked result;
msgpack::unpack(result, (char*)reply->element[i]->str, reply->element[i]->len);
// deserialized object is valid during the msgpack::unpacked instance alive.
msgpack::object deserialized = result.get();
// msgpack::object supports ostream.
//Rcpp::Rcout << deserialized << std::endl;
deserialized.convert(row);
vecs.push_back(row);
}
unsigned int cols = vecs[0].size();
Rcpp::NumericMatrix m(rows, cols);
for (unsigned int i=0; i<rows; i++) {
for (unsigned int j=0; j<cols; j++) {
m(i,j) = vecs[i][j];
}
}
freeReplyObject(reply);
return(m);
}
Rcpp::NumericMatrix msgPackZMatrix(std::string key, double min, double max) {
redisReply *reply = static_cast<redisReply*>(redisCommandNULLSafe(prc_, "ZRANGEBYSCORE %s %f %f", key.c_str(), min, max));
std::vector<double> row;
std::vector<std::vector<double> > vecs;
//checkReplyType(reply, replyArray_t); // ensure we got array
unsigned int rows = reply->elements;
for (unsigned int i = 0; i < rows; i++) {
//checkReplyType(reply->element[i], replyString_t); // ensure we got [binary] string
//x[i] = reply->element[i]->str;
msgpack::unpacked result;
msgpack::unpack(result, (char*)reply->element[i]->str, reply->element[i]->len);
// deserialized object is valid during the msgpack::unpacked instance alive.
msgpack::object deserialized = result.get();
// msgpack::object supports ostream.
//Rcpp::Rcout << deserialized << std::endl;
deserialized.convert(row);
vecs.push_back(row);
}
unsigned int cols = vecs[0].size();
Rcpp::NumericMatrix m(rows, cols);
for (unsigned int i=0; i<rows; i++) {
for (unsigned int j=0; j<cols; j++) {
m(i,j) = vecs[i][j];
}
}
freeReplyObject(reply);
return(m);
}
#endif
// redis quit -- exit the server
SEXP quit(void) {
redisReply *reply = static_cast<redisReply*>(redisCommandNULLSafe(prc_, "QUIT"));
SEXP rep = extract_reply(reply);
freeReplyObject(reply);
return(rep);
}
// cf. hiredis redisGetReply, blocking read of pub/sub message
SEXP listen(std::string type) {
redisReply *reply;
redisGetReply(prc_, (void **)&reply);
unsigned int nc = reply->elements;
Rcpp::List vec(nc);
for (unsigned int i = 0; i < nc; i++) {
if(i < 2) {
vec[i] = extract_reply(reply->element[i]);
} else
{
if(type == "string") {
vec[i] = Rcpp::wrap(std::string(reply->element[i]->str));
goto end;
}
int vlen = reply->element[i]->len;
Rcpp::RawVector res(vlen);
memcpy(res.begin(), reply->element[i]->str, vlen);
if(type == "raw") {
vec[i] = res;
} else {
vec[i] = unserializeFromRaw(res);
}
}
}
end:
freeReplyObject(reply);
return(vec);
}
// redis subscribe to one or more channels
SEXP subscribe_proto(Rcpp::CharacterVector channels, const char * type) {
int n = channels.size();
Rcpp::List vec(n);
for (int i=0; i<n; i++) {
std::string key(channels[i]);
redisReply *reply =
static_cast<redisReply*>(redisCommandNULLSafe(prc_,
"%s %s",
type, key.c_str()));
vec[i] = extract_reply(reply);
freeReplyObject(reply);
}
return(vec);
}
SEXP subscribe(Rcpp::CharacterVector channels) {
return(subscribe_proto(channels, "SUBSCRIBE"));
}
SEXP psubscribe(Rcpp::CharacterVector channels) {
return(subscribe_proto(channels, "PSUBSCRIBE"));
}
SEXP unsubscribe(Rcpp::CharacterVector channels) {
return(subscribe_proto(channels, "UNSUBSCRIBE"));
}
// redis publish -- serializes to R internal format
SEXP publish(std::string channel, SEXP s) {
// if raw, use as is else serialize to raw
Rcpp::RawVector x = (TYPEOF(s) == RAWSXP) ? s : serializeToRaw(s);
// uses binary protocol, see hiredis doc at github