11use std:: fs;
2- use std:: io:: { BufReader , ErrorKind , Write } ;
2+ use std:: io:: { ErrorKind , Write } ;
33use std:: path:: PathBuf ;
44
55use serde:: { Deserialize , Serialize } ;
66
77use crate :: errors:: StoreError ;
88use crate :: records:: Check ;
99
10+ #[ cfg( feature = "compression" ) ]
11+ use zstd;
12+
1013/// The filename of the database, in [DB_PATH]
1114pub const DB_NAME : & str = "netpulse.store" ;
1215/// Path to the database of netpulse (combine with [DB_NAME])
1316pub const DB_PATH : & str = "/var/lib/netpulse" ;
17+ #[ cfg( feature = "compression" ) ]
18+ pub const ZSTD_COMPRESSION_LEVEL : i32 = 4 ;
19+ pub const ENV_PATH : & str = "NETPULSE_STORE_PATH" ;
1420
1521#[ derive( Debug , PartialEq , Eq , Hash , Deserialize , Serialize ) ]
1622pub struct Store {
@@ -19,7 +25,13 @@ pub struct Store {
1925
2026impl Store {
2127 pub fn path ( ) -> PathBuf {
22- PathBuf :: from ( format ! ( "{DB_PATH}/{DB_NAME}" ) )
28+ if let Some ( var) = std:: env:: var_os ( ENV_PATH ) {
29+ let mut p = PathBuf :: from ( var) ;
30+ p. push ( DB_NAME ) ;
31+ p
32+ } else {
33+ PathBuf :: from ( format ! ( "{DB_PATH}/{DB_NAME}" ) )
34+ }
2335 }
2436
2537 fn new ( ) -> Self {
@@ -33,7 +45,7 @@ impl Store {
3345 . expect ( "the store path has no parent directory" ) ,
3446 ) ?;
3547
36- let mut file = match fs:: File :: options ( )
48+ let file = match fs:: File :: options ( )
3749 . read ( false )
3850 . write ( true )
3951 . append ( false )
@@ -46,8 +58,13 @@ impl Store {
4658
4759 let store = Store :: new ( ) ;
4860
49- file. write_all ( & bincode:: serialize ( & store) ?) ?;
50- file. flush ( ) ?;
61+ #[ cfg( feature = "compression" ) ]
62+ let mut writer = zstd:: Encoder :: new ( file, ZSTD_COMPRESSION_LEVEL ) ?;
63+ #[ cfg( not( feature = "compression" ) ) ]
64+ let mut writer = file;
65+
66+ writer. write_all ( & bincode:: serialize ( & store) ?) ?;
67+ writer. flush ( ) ?;
5168 Ok ( store)
5269 }
5370
@@ -78,7 +95,10 @@ impl Store {
7895 } ,
7996 } ;
8097
81- let reader = BufReader :: new ( file) ;
98+ #[ cfg( feature = "compression" ) ]
99+ let reader = zstd:: Decoder :: new ( file) ?;
100+ #[ cfg( not( feature = "compression" ) ) ]
101+ let mut reader = file;
82102
83103 Ok ( bincode:: deserialize_from ( reader) ?)
84104 }
@@ -100,8 +120,13 @@ impl Store {
100120 } ,
101121 } ;
102122
103- file. write_all ( & bincode:: serialize ( & self ) ?) ?;
104- file. flush ( ) ?;
123+ #[ cfg( feature = "compression" ) ]
124+ let mut writer = zstd:: Encoder :: new ( file, ZSTD_COMPRESSION_LEVEL ) ?;
125+ #[ cfg( not( feature = "compression" ) ) ]
126+ let mut writer = file;
127+
128+ writer. write_all ( & bincode:: serialize ( & self ) ?) ?;
129+ writer. flush ( ) ?;
105130 Ok ( ( ) )
106131 }
107132
0 commit comments