3
3
#include <stdlib.h>
4
4
#include <zstd.h>
5
5
6
+ ErlNifTSDKey zstdDecompressContextKey ;
7
+ ErlNifTSDKey zstdCompressContextKey ;
8
+
6
9
static ERL_NIF_TERM zstd_nif_compress (ErlNifEnv * env , int argc , const ERL_NIF_TERM argv []) {
7
10
ErlNifBinary bin , ret_bin ;
8
11
size_t buff_size , compressed_size ;
9
12
unsigned int compression_level ;
10
13
14
+ ZSTD_CCtx * ctx = (ZSTD_CCtx * )enif_tsd_get (zstdCompressContextKey );
15
+ if (!ctx ) {
16
+ ctx = ZSTD_createCCtx ();
17
+ enif_tsd_set (zstdCompressContextKey , ctx );
18
+ }
19
+
11
20
if (!enif_inspect_binary (env , argv [0 ], & bin )
12
21
|| !enif_get_uint (env , argv [1 ], & compression_level )
13
22
|| compression_level > ZSTD_maxCLevel ())
@@ -18,7 +27,7 @@ static ERL_NIF_TERM zstd_nif_compress(ErlNifEnv* env, int argc, const ERL_NIF_TE
18
27
if (!enif_alloc_binary (buff_size , & ret_bin ))
19
28
return enif_make_atom (env , "error" );
20
29
21
- compressed_size = ZSTD_compress ( ret_bin .data , buff_size , bin .data , bin .size , compression_level );
30
+ compressed_size = ZSTD_compressCCtx ( ctx , ret_bin .data , buff_size , bin .data , bin .size , compression_level );
22
31
if (ZSTD_isError (compressed_size ))
23
32
return enif_make_atom (env , "error" );
24
33
@@ -34,14 +43,20 @@ static ERL_NIF_TERM zstd_nif_decompress(ErlNifEnv* env, int argc, const ERL_NIF_
34
43
ErlNifBinary bin ;
35
44
unsigned long long uncompressed_size ;
36
45
46
+ ZSTD_DCtx * ctx = (ZSTD_DCtx * )enif_tsd_get (zstdDecompressContextKey );
47
+ if (!ctx ) {
48
+ ctx = ZSTD_createDCtx ();
49
+ enif_tsd_set (zstdDecompressContextKey , ctx );
50
+ }
51
+
37
52
if (!enif_inspect_binary (env , argv [0 ], & bin ))
38
53
return enif_make_badarg (env );
39
54
40
55
uncompressed_size = ZSTD_getDecompressedSize (bin .data , bin .size );
41
56
42
57
outp = enif_make_new_binary (env , uncompressed_size , & out );
43
58
44
- if (ZSTD_decompress ( outp , uncompressed_size , bin .data , bin .size ) != uncompressed_size )
59
+ if (ZSTD_decompressDCtx ( ctx , outp , uncompressed_size , bin .data , bin .size ) != uncompressed_size )
45
60
return enif_make_atom (env , "error" );
46
61
47
62
return out ;
@@ -52,4 +67,11 @@ static ErlNifFunc nif_funcs[] = {
52
67
{"decompress" , 1 , zstd_nif_decompress }
53
68
};
54
69
55
- ERL_NIF_INIT (zstd , nif_funcs , NULL , NULL , NULL , NULL );
70
+ static int load (ErlNifEnv * env , void * * priv_data , ERL_NIF_TERM load_info )
71
+ {
72
+ enif_tsd_key_create ("zstd_decompress_context_key" , & zstdDecompressContextKey );
73
+ enif_tsd_key_create ("zstd_compress_context_key" , & zstdCompressContextKey );
74
+ return 0 ;
75
+ }
76
+
77
+ ERL_NIF_INIT (zstd , nif_funcs , load , NULL , NULL , NULL );
0 commit comments