-
Notifications
You must be signed in to change notification settings - Fork 3
/
r-snappy.c
108 lines (95 loc) · 2.36 KB
/
r-snappy.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
/*
* ========================================================================
*
* Filename: r-snappy.c
*
* Description: Google snappy R binding.
*
* Created: 08/29/2013 16:30:59 PM
*
* Author: luliang (lulyon), [email protected]
* Company: ICT ( Institute Of Computing Technology, CAS )
*
* ========================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <R.h>
#include <Rdefines.h>
#include "snappy/snappy-c.h"
SEXP rsnappy_compress(SEXP v)
{
SEXP ans = R_NilValue;
PROTECT(v = AS_CHARACTER(v));
const char* src = CHAR(STRING_ELT(v, 0));
size_t src_len = strlen(src);
size_t dst_max_size = snappy_max_compressed_length(src_len);
char* dst = R_alloc(dst_max_size, sizeof(char));
if (dst != NULL) {
if (snappy_compress(src, src_len, dst,
&dst_max_size) == SNAPPY_OK) {
PROTECT(ans = NEW_CHARACTER(1));
SET_STRING_ELT(ans, 0, mkCharLen(dst, dst_max_size));
UNPROTECT(2);
return ans;
}
else {
printf("Error: snappy_compress fails.\n");
UNPROTECT(1);
return ans;
}
}
printf("Error: R_alloc fails.\n");
UNPROTECT(1);
return ans;
}
SEXP rsnappy_uncompress(SEXP v)
{
SEXP ans = R_NilValue;
PROTECT(v = AS_CHARACTER(v));
const char* src = CHAR(STRING_ELT(v, 0));
size_t src_len = strlen(src);
size_t dst_max_size = 0;
if (snappy_uncompressed_length(src, src_len, &dst_max_size)
!= SNAPPY_OK) {
printf("Error: snappy_uncompressed_length fails.\n");
return ans;
}
char* dst = R_alloc(dst_max_size, sizeof(char));
if (dst != NULL) {
if (snappy_uncompress(src, src_len, dst,
&dst_max_size) == SNAPPY_OK) {
PROTECT(ans = NEW_CHARACTER(1));
SET_STRING_ELT(ans, 0, mkCharLen(dst, dst_max_size));
UNPROTECT(2);
return ans;
}
else {
printf("Error: snappy_uncompress fails.\n");
UNPROTECT(1);
return ans;
}
}
printf("Error: R_alloc fails.\n");
UNPROTECT(1);
return ans;
}
SEXP rsnappy_validate_compressed_buffer(SEXP v)
{
SEXP ans;
PROTECT(v = AS_CHARACTER(v));
const char* src = CHAR(STRING_ELT(v, 0));
size_t src_len = strlen(src);
if(snappy_validate_compressed_buffer(src, src_len) == SNAPPY_OK) {
PROTECT(ans = NEW_LOGICAL(1));
int *ians = LOGICAL(ans);
*ians = TRUE;
UNPROTECT(2);
return ans;
}
PROTECT(ans = NEW_LOGICAL(1));
int *ians = LOGICAL(ans);
*ians = FALSE;
UNPROTECT(2);
return ans;
}