Commit 9e8049d143ac2a64352af7806b5660310a4b8461

Authored by Hayk
1 parent bd79d63d

Apply clang format to codebase

.clang-format 0 → 100644
  1 +---
  2 +Language: Cpp
  3 +# BasedOnStyle: LLVM
  4 +AccessModifierOffset: -2
  5 +AlignAfterOpenBracket: true
  6 +AlignEscapedNewlinesLeft: false
  7 +AlignOperands: true
  8 +AlignTrailingComments: true
  9 +AllowAllParametersOfDeclarationOnNextLine: true
  10 +AllowShortBlocksOnASingleLine: false
  11 +AllowShortCaseLabelsOnASingleLine: false
  12 +AllowShortIfStatementsOnASingleLine: false
  13 +AllowShortLoopsOnASingleLine: false
  14 +AllowShortFunctionsOnASingleLine: All
  15 +AlwaysBreakAfterDefinitionReturnType: false
  16 +AlwaysBreakTemplateDeclarations: false
  17 +AlwaysBreakBeforeMultilineStrings: false
  18 +BreakBeforeBinaryOperators: None
  19 +BreakBeforeTernaryOperators: true
  20 +BreakConstructorInitializersBeforeComma: false
  21 +BinPackParameters: true
  22 +BinPackArguments: true
  23 +ColumnLimit: 100
  24 +ConstructorInitializerAllOnOneLineOrOnePerLine: false
  25 +ConstructorInitializerIndentWidth: 4
  26 +DerivePointerAlignment: false
  27 +ExperimentalAutoDetectBinPacking: false
  28 +IndentCaseLabels: false
  29 +IndentWrappedFunctionNames: false
  30 +IndentFunctionDeclarationAfterType: false
  31 +MaxEmptyLinesToKeep: 1
  32 +KeepEmptyLinesAtTheStartOfBlocks: true
  33 +NamespaceIndentation: None
  34 +ObjCBlockIndentWidth: 2
  35 +ObjCSpaceAfterProperty: false
  36 +ObjCSpaceBeforeProtocolList: true
  37 +PenaltyBreakBeforeFirstCallParameter: 19
  38 +PenaltyBreakComment: 300
  39 +PenaltyBreakString: 1000
  40 +PenaltyBreakFirstLessLess: 120
  41 +PenaltyExcessCharacter: 1000000
  42 +PenaltyReturnTypeOnItsOwnLine: 60
  43 +PointerAlignment: Right
  44 +SpacesBeforeTrailingComments: 1
  45 +Cpp11BracedListStyle: true
  46 +Standard: Cpp11
  47 +IndentWidth: 2
  48 +TabWidth: 8
  49 +UseTab: Never
  50 +BreakBeforeBraces: Attach
  51 +SpacesInParentheses: false
  52 +SpacesInSquareBrackets: false
  53 +SpacesInAngles: false
  54 +SpaceInEmptyParentheses: false
  55 +SpacesInCStyleCastParentheses: false
  56 +SpaceAfterCStyleCast: false
  57 +SpacesInContainerLiterals: true
  58 +SpaceBeforeAssignmentOperators: true
  59 +ContinuationIndentWidth: 4
  60 +CommentPragmas: '^ IWYU pragma:'
  61 +ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH ]
  62 +SpaceBeforeParens: ControlStatements
  63 +DisableFormat: false
  64 +...
  65 +
... ...
include/redox/client.hpp
... ... @@ -54,14 +54,13 @@ static const std::string REDIS_DEFAULT_PATH = "/var/run/redis/redis.sock";
54 54 class Redox {
55 55  
56 56 public:
57   -
58 57 // Connection states
59 58 static const int NOT_YET_CONNECTED = 0; // Starting state
60   - static const int CONNECTED = 1; // Successfully connected
61   - static const int DISCONNECTED = 2; // Successfully disconnected
62   - static const int CONNECT_ERROR = 3; // Error connecting
63   - static const int DISCONNECT_ERROR = 4; // Disconnected on error
64   - static const int INIT_ERROR = 5; // Failed to init data structures
  59 + static const int CONNECTED = 1; // Successfully connected
  60 + static const int DISCONNECTED = 2; // Successfully disconnected
  61 + static const int CONNECT_ERROR = 3; // Error connecting
  62 + static const int DISCONNECT_ERROR = 4; // Disconnected on error
  63 + static const int INIT_ERROR = 5; // Failed to init data structures
65 64  
66 65 // ------------------------------------------------
67 66 // Core public API
... ... @@ -70,10 +69,7 @@ public:
70 69 /**
71 70 * Constructor. Optionally specify a log stream and a log level.
72 71 */
73   - Redox(
74   - std::ostream& log_stream = std::cout,
75   - log::Level log_level = log::Warning
76   - );
  72 + Redox(std::ostream &log_stream = std::cout, log::Level log_level = log::Warning);
77 73  
78 74 /**
79 75 * Disconnects from the Redis server, shuts down the event loop, and cleans up.
... ... @@ -89,7 +85,7 @@ public:
89 85 * is off.
90 86 *
91 87 * Implementation note: When enabled, the event thread calls libev's ev_run in a
92   - * loop with the EVRUN_NOWAIT flag.
  88 + * loop with the EVRUN_NOWAIT flag.
93 89 */
94 90 void noWait(bool state);
95 91  
... ... @@ -97,18 +93,15 @@ public:
97 93 * Connects to Redis over TCP and starts an event loop in a separate thread. Returns
98 94 * true once everything is ready, or false on failure.
99 95 */
100   - bool connect(
101   - const std::string& host = REDIS_DEFAULT_HOST,
102   - const int port = REDIS_DEFAULT_PORT,
103   - std::function<void(int)> connection_callback = nullptr);
  96 + bool connect(const std::string &host = REDIS_DEFAULT_HOST, const int port = REDIS_DEFAULT_PORT,
  97 + std::function<void(int)> connection_callback = nullptr);
104 98  
105 99 /**
106 100 * Connects to Redis over a unix socket and starts an event loop in a separate
107 101 * thread. Returns true once everything is ready, or false on failure.
108 102 */
109   - bool connectUnix(
110   - const std::string& path = REDIS_DEFAULT_PATH,
111   - std::function<void(int)> connection_callback = nullptr);
  103 + bool connectUnix(const std::string &path = REDIS_DEFAULT_PATH,
  104 + std::function<void(int)> connection_callback = nullptr);
112 105  
113 106 /**
114 107 * Disconnect from Redis, shut down the event loop, then return. A simple
... ... @@ -134,16 +127,14 @@ public:
134 127 * memory for it is automatically freed when the callback returns.
135 128 */
136 129  
137   - template<class ReplyT>
138   - void command(
139   - const std::vector<std::string>& cmd,
140   - const std::function<void(Command<ReplyT>&)>& callback = nullptr
141   - );
  130 + template <class ReplyT>
  131 + void command(const std::vector<std::string> &cmd,
  132 + const std::function<void(Command<ReplyT> &)> &callback = nullptr);
142 133  
143 134 /**
144 135 * Asynchronously runs a command and ignores any errors or replies.
145 136 */
146   - void command(const std::vector<std::string>& cmd);
  137 + void command(const std::vector<std::string> &cmd);
147 138  
148 139 /**
149 140 * Synchronously runs a command, returning the Command object only once
... ... @@ -151,14 +142,13 @@ public:
151 142 * calling .free() on the returned Command object.
152 143 */
153 144  
154   - template<class ReplyT>
155   - Command<ReplyT>& commandSync(const std::vector<std::string>& cmd);
  145 + template <class ReplyT> Command<ReplyT> &commandSync(const std::vector<std::string> &cmd);
156 146  
157 147 /**
158 148 * Synchronously runs a command, returning only once a reply is received
159 149 * or there's an error. Returns true on successful reply, false on error.
160 150 */
161   - bool commandSync(const std::vector<std::string>& cmd);
  151 + bool commandSync(const std::vector<std::string> &cmd);
162 152  
163 153 /**
164 154 * Creates an asynchronous command that is run every [repeat] seconds,
... ... @@ -167,13 +157,10 @@ public:
167 157 * on the returned Command object.
168 158 */
169 159  
170   - template<class ReplyT>
171   - Command<ReplyT>& commandLoop(
172   - const std::vector<std::string>& cmd,
173   - const std::function<void(Command<ReplyT>&)>& callback,
174   - double repeat,
175   - double after = 0.0
176   - );
  160 + template <class ReplyT>
  161 + Command<ReplyT> &commandLoop(const std::vector<std::string> &cmd,
  162 + const std::function<void(Command<ReplyT> &)> &callback,
  163 + double repeat, double after = 0.0);
177 164  
178 165 /**
179 166 * Creates an asynchronous command that is run once after a given
... ... @@ -182,12 +169,9 @@ public:
182 169 * after the callback returns.
183 170 */
184 171  
185   - template<class ReplyT>
186   - void commandDelayed(
187   - const std::vector<std::string>& cmd,
188   - const std::function<void(Command<ReplyT>&)>& callback,
189   - double after
190   - );
  172 + template <class ReplyT>
  173 + void commandDelayed(const std::vector<std::string> &cmd,
  174 + const std::function<void(Command<ReplyT> &)> &callback, double after);
191 175  
192 176 // ------------------------------------------------
193 177 // Utility methods
... ... @@ -197,13 +181,13 @@ public:
197 181 * Given a vector of strings, returns a string of the concatenated elements, separated
198 182 * by the delimiter. Useful for printing out a command string from a vector.
199 183 */
200   - static std::string vecToStr(const std::vector<std::string>& vec, const char delimiter = ' ');
  184 + static std::string vecToStr(const std::vector<std::string> &vec, const char delimiter = ' ');
201 185  
202 186 /**
203 187 * Given a command string, returns a vector of strings by splitting the input by
204 188 * the delimiter. Useful for turning a string input into a command.
205 189 */
206   - static std::vector<std::string> strToVec(const std::string& s, const char delimiter = ' ');
  190 + static std::vector<std::string> strToVec(const std::string &s, const char delimiter = ' ');
207 191  
208 192 // ------------------------------------------------
209 193 // Command wrapper methods for convenience only
... ... @@ -213,32 +197,32 @@ public:
213 197 * Redis GET command wrapper - return the value for the given key, or throw
214 198 * an exception if there is an error. Blocking call.
215 199 */
216   - std::string get(const std::string& key);
  200 + std::string get(const std::string &key);
217 201  
218 202 /**
219 203 * Redis SET command wrapper - set the value for the given key. Return
220 204 * true if succeeded, false if error. Blocking call.
221 205 */
222   - bool set(const std::string& key, const std::string& value);
  206 + bool set(const std::string &key, const std::string &value);
223 207  
224 208 /**
225 209 * Redis DEL command wrapper - delete the given key. Return true if succeeded,
226 210 * false if error. Blocking call.
227 211 */
228   - bool del(const std::string& key);
  212 + bool del(const std::string &key);
229 213  
230 214 /**
231 215 * Redis PUBLISH command wrapper - publish the given message to all subscribers.
232 216 * Non-blocking call.
233 217 */
234   - void publish(const std::string& topic, const std::string& msg);
  218 + void publish(const std::string &topic, const std::string &msg);
235 219  
236 220 // ------------------------------------------------
237 221 // Public members
238 222 // ------------------------------------------------
239 223  
240 224 // Hiredis context, left public to allow low-level access
241   - redisAsyncContext * ctx_;
  225 + redisAsyncContext *ctx_;
242 226  
243 227 // TODO make these private
244 228 // Redox server over TCP
... ... @@ -252,7 +236,6 @@ public:
252 236 log::Logger logger_;
253 237  
254 238 private:
255   -
256 239 // ------------------------------------------------
257 240 // Private methods
258 241 // ------------------------------------------------
... ... @@ -262,14 +245,10 @@ private:
262 245  
263 246 // One stop shop for creating commands. The base of all public
264 247 // methods that run commands.
265   - template<class ReplyT>
266   - Command<ReplyT>& createCommand(
267   - const std::vector<std::string>& cmd,
268   - const std::function<void(Command<ReplyT>&)>& callback = nullptr,
269   - double repeat = 0.0,
270   - double after = 0.0,
271   - bool free_memory = true
272   - );
  248 + template <class ReplyT>
  249 + Command<ReplyT> &createCommand(const std::vector<std::string> &cmd,
  250 + const std::function<void(Command<ReplyT> &)> &callback = nullptr,
  251 + double repeat = 0.0, double after = 0.0, bool free_memory = true);
273 252  
274 253 // Setup code for the constructors
275 254 // Return true on success, false on failure
... ... @@ -277,54 +256,48 @@ private:
277 256 bool initHiredis();
278 257  
279 258 // Callbacks invoked on server connection/disconnection
280   - static void connectedCallback(const redisAsyncContext* c, int status);
281   - static void disconnectedCallback(const redisAsyncContext* c, int status);
  259 + static void connectedCallback(const redisAsyncContext *c, int status);
  260 + static void disconnectedCallback(const redisAsyncContext *c, int status);
282 261  
283 262 // Main event loop, run in a separate thread
284 263 void runEventLoop();
285 264  
286 265 // Return the command map corresponding to the templated reply type
287   - template<class ReplyT>
288   - std::unordered_map<long, Command<ReplyT>*>& getCommandMap();
  266 + template <class ReplyT> std::unordered_map<long, Command<ReplyT> *> &getCommandMap();
289 267  
290 268 // Return the given Command from the relevant command map, or nullptr if not there
291   - template<class ReplyT>
292   - Command<ReplyT>* findCommand(long id);
  269 + template <class ReplyT> Command<ReplyT> *findCommand(long id);
293 270  
294 271 // Send all commands in the command queue to the server
295   - static void processQueuedCommands(struct ev_loop* loop, ev_async* async, int revents);
  272 + static void processQueuedCommands(struct ev_loop *loop, ev_async *async, int revents);
296 273  
297 274 // Process the command with the given ID. Return true if the command had the
298 275 // templated type, and false if it was not in the command map of that type.
299   - template<class ReplyT>
300   - bool processQueuedCommand(long id);
  276 + template <class ReplyT> bool processQueuedCommand(long id);
301 277  
302 278 // Callback given to libev for a Command's timer watcher, to be processed in
303 279 // a deferred or looping state
304   - template<class ReplyT>
305   - static void submitCommandCallback(struct ev_loop* loop, ev_timer* timer, int revents);
  280 + template <class ReplyT>
  281 + static void submitCommandCallback(struct ev_loop *loop, ev_timer *timer, int revents);
306 282  
307 283 // Submit an asynchronous command to the Redox server. Return
308 284 // true if succeeded, false otherwise.
309   - template<class ReplyT>
310   - static bool submitToServer(Command<ReplyT>* c);
  285 + template <class ReplyT> static bool submitToServer(Command<ReplyT> *c);
311 286  
312 287 // Callback given to hiredis to invoke when a reply is received
313   - template<class ReplyT>
314   - static void commandCallback(redisAsyncContext* ctx, void* r, void* privdata);
  288 + template <class ReplyT>
  289 + static void commandCallback(redisAsyncContext *ctx, void *r, void *privdata);
315 290  
316 291 // Free all commands in the commands_to_free_ queue
317   - static void freeQueuedCommands(struct ev_loop* loop, ev_async* async, int revents);
  292 + static void freeQueuedCommands(struct ev_loop *loop, ev_async *async, int revents);
318 293  
319 294 // Free the command with the given ID. Return true if the command had the templated
320 295 // type, and false if it was not in the command map of that type.
321   - template<class ReplyT>
322   - bool freeQueuedCommand(long id);
  296 + template <class ReplyT> bool freeQueuedCommand(long id);
323 297  
324 298 // Invoked by Command objects when they are completed. Removes them
325 299 // from the command map.
326   - template<class ReplyT>
327   - void deregisterCommand(const long id) {
  300 + template <class ReplyT> void deregisterCommand(const long id) {
328 301 std::lock_guard<std::mutex> lg1(command_map_guard_);
329 302 getCommandMap<ReplyT>().erase(id);
330 303 commands_deleted_ += 1;
... ... @@ -334,8 +307,7 @@ private:
334 307 long freeAllCommands();
335 308  
336 309 // Helper function for freeAllCommands to access a specific command map
337   - template<class ReplyT>
338   - long freeAllCommandsOfType();
  310 + template <class ReplyT> long freeAllCommandsOfType();
339 311  
340 312 // ------------------------------------------------
341 313 // Private members
... ... @@ -350,15 +322,15 @@ private:
350 322 std::function<void(int)> user_connection_callback_;
351 323  
352 324 // Dynamically allocated libev event loop
353   - struct ev_loop* evloop_;
  325 + struct ev_loop *evloop_;
354 326  
355 327 // No-wait mode for high-performance
356 328 std::atomic_bool nowait_ = {false};
357 329  
358 330 // Asynchronous watchers
359 331 ev_async watcher_command_; // For processing commands
360   - ev_async watcher_stop_; // For breaking the loop
361   - ev_async watcher_free_; // For freeing commands
  332 + ev_async watcher_stop_; // For breaking the loop
  333 + ev_async watcher_free_; // For freeing commands
362 334  
363 335 // Track of Command objects allocated. Also provides unique Command IDs.
364 336 std::atomic_long commands_created_ = {0};
... ... @@ -374,7 +346,7 @@ private:
374 346  
375 347 // Variable and CV to know when the event loop stops running
376 348 std::atomic_bool to_exit_ = {false}; // Signal to exit
377   - std::atomic_bool exited_ = {false}; // Event thread exited
  349 + std::atomic_bool exited_ = {false}; // Event thread exited
378 350 std::mutex exit_waiter_lock_;
379 351 std::condition_variable exit_waiter_;
380 352  
... ... @@ -385,15 +357,16 @@ private:
385 357 // template<class ReplyT>
386 358 // std::unordered_map<long, Command<ReplyT>*> commands_;
387 359 // ---------
388   - std::unordered_map<long, Command<redisReply*>*> commands_redis_reply_;
389   - std::unordered_map<long, Command<std::string>*> commands_string_;
390   - std::unordered_map<long, Command<char*>*> commands_char_p_;
391   - std::unordered_map<long, Command<int>*> commands_int_;
392   - std::unordered_map<long, Command<long long int>*> commands_long_long_int_;
393   - std::unordered_map<long, Command<std::nullptr_t>*> commands_null_;
394   - std::unordered_map<long, Command<std::vector<std::string>>*> commands_vector_string_;
395   - std::unordered_map<long, Command<std::set<std::string>>*> commands_set_string_;
396   - std::unordered_map<long, Command<std::unordered_set<std::string>>*> commands_unordered_set_string_;
  360 + std::unordered_map<long, Command<redisReply *> *> commands_redis_reply_;
  361 + std::unordered_map<long, Command<std::string> *> commands_string_;
  362 + std::unordered_map<long, Command<char *> *> commands_char_p_;
  363 + std::unordered_map<long, Command<int> *> commands_int_;
  364 + std::unordered_map<long, Command<long long int> *> commands_long_long_int_;
  365 + std::unordered_map<long, Command<std::nullptr_t> *> commands_null_;
  366 + std::unordered_map<long, Command<std::vector<std::string>> *> commands_vector_string_;
  367 + std::unordered_map<long, Command<std::set<std::string>> *> commands_set_string_;
  368 + std::unordered_map<long, Command<std::unordered_set<std::string>> *>
  369 + commands_unordered_set_string_;
397 370 std::mutex command_map_guard_; // Guards access to all of the above
398 371  
399 372 // Command IDs pending to be sent to the server
... ... @@ -406,36 +379,28 @@ private:
406 379  
407 380 // Commands use this method to deregister themselves from Redox,
408 381 // give it access to private members
409   - template<class ReplyT>
410   - friend void Command<ReplyT>::free();
  382 + template <class ReplyT> friend void Command<ReplyT>::free();
411 383  
412 384 // Access to call disconnectedCallback
413   - template<class ReplyT>
414   - friend void Command<ReplyT>::processReply(redisReply* r);
  385 + template <class ReplyT> friend void Command<ReplyT>::processReply(redisReply *r);
415 386 };
416 387  
417 388 // ------------------------------------------------
418 389 // Implementation of templated methods
419 390 // ------------------------------------------------
420 391  
421   -template<class ReplyT>
422   -Command<ReplyT>& Redox::createCommand(
423   - const std::vector<std::string>& cmd,
424   - const std::function<void(Command<ReplyT>&)>& callback,
425   - double repeat,
426   - double after,
427   - bool free_memory
428   -) {
  392 +template <class ReplyT>
  393 +Command<ReplyT> &Redox::createCommand(const std::vector<std::string> &cmd,
  394 + const std::function<void(Command<ReplyT> &)> &callback,
  395 + double repeat, double after, bool free_memory) {
429 396  
430   - if(!running_) {
  397 + if (!running_) {
431 398 throw std::runtime_error("[ERROR] Need to connect Redox before running commands!");
432 399 }
433 400  
434 401 commands_created_ += 1;
435   - auto* c = new Command<ReplyT>(
436   - this, commands_created_, cmd,
437   - callback, repeat, after, free_memory, logger_
438   - );
  402 + auto *c = new Command<ReplyT>(this, commands_created_, cmd, callback, repeat, after, free_memory,
  403 + logger_);
439 404  
440 405 std::lock_guard<std::mutex> lg(queue_guard_);
441 406 std::lock_guard<std::mutex> lg2(command_map_guard_);
... ... @@ -449,36 +414,27 @@ Command&lt;ReplyT&gt;&amp; Redox::createCommand(
449 414 return *c;
450 415 }
451 416  
452   -template<class ReplyT>
453   -void Redox::command(
454   - const std::vector<std::string>& cmd,
455   - const std::function<void(Command<ReplyT>&)>& callback
456   -) {
  417 +template <class ReplyT>
  418 +void Redox::command(const std::vector<std::string> &cmd,
  419 + const std::function<void(Command<ReplyT> &)> &callback) {
457 420 createCommand(cmd, callback);
458 421 }
459 422  
460   -template<class ReplyT>
461   -Command<ReplyT>& Redox::commandLoop(
462   - const std::vector<std::string>& cmd,
463   - const std::function<void(Command<ReplyT>&)>& callback,
464   - double repeat,
465   - double after
466   -) {
  423 +template <class ReplyT>
  424 +Command<ReplyT> &Redox::commandLoop(const std::vector<std::string> &cmd,
  425 + const std::function<void(Command<ReplyT> &)> &callback,
  426 + double repeat, double after) {
467 427 return createCommand(cmd, callback, repeat, after, false);
468 428 }
469 429  
470   -template<class ReplyT>
471   -void Redox::commandDelayed(
472   - const std::vector<std::string>& cmd,
473   - const std::function<void(Command<ReplyT>&)>& callback,
474   - double after
475   -) {
  430 +template <class ReplyT>
  431 +void Redox::commandDelayed(const std::vector<std::string> &cmd,
  432 + const std::function<void(Command<ReplyT> &)> &callback, double after) {
476 433 createCommand(cmd, callback, 0, after, true);
477 434 }
478 435  
479   -template<class ReplyT>
480   -Command<ReplyT>& Redox::commandSync(const std::vector<std::string>& cmd) {
481   - auto& c = createCommand<ReplyT>(cmd, nullptr, 0, 0, false);
  436 +template <class ReplyT> Command<ReplyT> &Redox::commandSync(const std::vector<std::string> &cmd) {
  437 + auto &c = createCommand<ReplyT>(cmd, nullptr, 0, 0, false);
482 438 c.wait();
483 439 return c;
484 440 }
... ...
include/redox/command.hpp
... ... @@ -42,19 +42,17 @@ class Redox;
42 42 * represent a deferred or looping command, in which case the success or
43 43 * error callbacks are invoked more than once.
44 44 */
45   -template<class ReplyT>
46   -class Command {
  45 +template <class ReplyT> class Command {
47 46  
48 47 public:
49   -
50 48 // Reply codes
51   - static const int NO_REPLY = -1; // No reply yet
52   - static const int OK_REPLY = 0; // Successful reply of the expected type
53   - static const int NIL_REPLY = 1; // Got a nil reply
  49 + static const int NO_REPLY = -1; // No reply yet
  50 + static const int OK_REPLY = 0; // Successful reply of the expected type
  51 + static const int NIL_REPLY = 1; // Got a nil reply
54 52 static const int ERROR_REPLY = 2; // Got an error reply
55   - static const int SEND_ERROR = 3; // Could not send to server
56   - static const int WRONG_TYPE = 4; // Got reply, but it was not the expected type
57   - static const int TIMEOUT = 5; // No reply, timed out
  53 + static const int SEND_ERROR = 3; // Could not send to server
  54 + static const int WRONG_TYPE = 4; // Got reply, but it was not the expected type
  55 + static const int TIMEOUT = 5; // No reply, timed out
58 56  
59 57 /**
60 58 * Returns the reply status of this command.
... ... @@ -94,7 +92,7 @@ public:
94 92 std::string cmd() const;
95 93  
96 94 // Allow public access to constructed data
97   - Redox* const rdx_;
  95 + Redox *const rdx_;
98 96 const long id_;
99 97 const std::vector<std::string> cmd_;
100 98 const double repeat_;
... ... @@ -102,26 +100,22 @@ public:
102 100 const bool free_memory_;
103 101  
104 102 private:
105   -
106   - Command(
107   - Redox* rdx,
108   - long id,
109   - const std::vector<std::string>& cmd,
110   - const std::function<void(Command<ReplyT>&)>& callback,
111   - double repeat, double after,
112   - bool free_memory,
113   - log::Logger& logger
114   - );
  103 + Command(Redox *rdx, long id, const std::vector<std::string> &cmd,
  104 + const std::function<void(Command<ReplyT> &)> &callback, double repeat, double after,
  105 + bool free_memory, log::Logger &logger);
115 106  
116 107 // Handles a new reply from the server
117   - void processReply(redisReply* r);
  108 + void processReply(redisReply *r);
118 109  
119 110 // Invoke a user callback from the reply object. This method is specialized
120 111 // for each ReplyT of Command.
121 112 void parseReplyObject();
122 113  
123 114 // Directly invoke the user callback if it exists
124   - void invoke() { if(callback_) callback_(*this); }
  115 + void invoke() {
  116 + if (callback_)
  117 + callback_(*this);
  118 + }
125 119  
126 120 bool checkErrorReply();
127 121 bool checkNilReply();
... ... @@ -132,10 +126,10 @@ private:
132 126 void freeReply();
133 127  
134 128 // The last server reply
135   - redisReply* reply_obj_ = nullptr;
  129 + redisReply *reply_obj_ = nullptr;
136 130  
137 131 // User callback
138   - const std::function<void(Command<ReplyT>&)> callback_;
  132 + const std::function<void(Command<ReplyT> &)> callback_;
139 133  
140 134 // Place to store the reply value and status.
141 135 ReplyT reply_val_;
... ... @@ -161,13 +155,13 @@ private:
161 155 std::atomic_bool waiting_done_ = {false};
162 156  
163 157 // Passed on from Redox class
164   - log::Logger& logger_;
  158 + log::Logger &logger_;
165 159  
166 160 // Explicitly delete copy constructor and assignment operator,
167 161 // Command objects should never be copied because they hold
168 162 // state with a network resource.
169   - Command(const Command&) = delete;
170   - Command& operator=(const Command&) = delete;
  163 + Command(const Command &) = delete;
  164 + Command &operator=(const Command &) = delete;
171 165  
172 166 friend class Redox;
173 167 };
... ...
include/redox/subscriber.hpp
... ... @@ -27,14 +27,10 @@ namespace redox {
27 27 class Subscriber {
28 28  
29 29 public:
30   -
31 30 /**
32 31 * Constructor. Same as Redox.
33 32 */
34   - Subscriber(
35   - std::ostream& log_stream = std::cout,
36   - log::Level log_level = log::Warning
37   - );
  33 + Subscriber(std::ostream &log_stream = std::cout, log::Level log_level = log::Warning);
38 34  
39 35 /**
40 36 * Cleans up.
... ... @@ -49,19 +45,16 @@ public:
49 45 /**
50 46 * Same as .connect() on a Redox instance.
51 47 */
52   - bool connect(
53   - const std::string& host = REDIS_DEFAULT_HOST,
54   - const int port = REDIS_DEFAULT_PORT,
55   - std::function<void(int)> connection_callback = nullptr) {
  48 + bool connect(const std::string &host = REDIS_DEFAULT_HOST, const int port = REDIS_DEFAULT_PORT,
  49 + std::function<void(int)> connection_callback = nullptr) {
56 50 return rdx_.connect(host, port, connection_callback);
57 51 }
58 52  
59 53 /**
60 54 * Same as .connectUnix() on a Redox instance.
61 55 */
62   - bool connectUnix(
63   - const std::string& path = REDIS_DEFAULT_PATH,
64   - std::function<void(int)> connection_callback = nullptr) {
  56 + bool connectUnix(const std::string &path = REDIS_DEFAULT_PATH,
  57 + std::function<void(int)> connection_callback = nullptr) {
65 58 return rdx_.connectUnix(path, connection_callback);
66 59 }
67 60  
... ... @@ -88,11 +81,10 @@ public:
88 81 * err_callback: invoked on some error state
89 82 */
90 83 void subscribe(const std::string topic,
91   - std::function<void(const std::string&, const std::string&)> msg_callback,
92   - std::function<void(const std::string&)> sub_callback = nullptr,
93   - std::function<void(const std::string&)> unsub_callback = nullptr,
94   - std::function<void(const std::string&, int)> err_callback = nullptr
95   - );
  84 + std::function<void(const std::string &, const std::string &)> msg_callback,
  85 + std::function<void(const std::string &)> sub_callback = nullptr,
  86 + std::function<void(const std::string &)> unsub_callback = nullptr,
  87 + std::function<void(const std::string &, int)> err_callback = nullptr);
96 88  
97 89 /**
98 90 * Subscribe to a topic with a pattern.
... ... @@ -102,11 +94,10 @@ public:
102 94 * err_callback: invoked on some error state
103 95 */
104 96 void psubscribe(const std::string topic,
105   - std::function<void(const std::string&, const std::string&)> msg_callback,
106   - std::function<void(const std::string&)> sub_callback = nullptr,
107   - std::function<void(const std::string&)> unsub_callback = nullptr,
108   - std::function<void(const std::string&, int)> err_callback = nullptr
109   - );
  97 + std::function<void(const std::string &, const std::string &)> msg_callback,
  98 + std::function<void(const std::string &)> sub_callback = nullptr,
  99 + std::function<void(const std::string &)> unsub_callback = nullptr,
  100 + std::function<void(const std::string &, int)> err_callback = nullptr);
110 101  
111 102 /**
112 103 * Unsubscribe from a topic.
... ... @@ -114,8 +105,7 @@ public:
114 105 * err_callback: invoked on some error state
115 106 */
116 107 void unsubscribe(const std::string topic,
117   - std::function<void(const std::string&, int)> err_callback = nullptr
118   - );
  108 + std::function<void(const std::string &, int)> err_callback = nullptr);
119 109  
120 110 /**
121 111 * Unsubscribe from a topic with a pattern.
... ... @@ -123,8 +113,7 @@ public:
123 113 * err_callback: invoked on some error state
124 114 */
125 115 void punsubscribe(const std::string topic,
126   - std::function<void(const std::string&, int)> err_callback = nullptr
127   - );
  116 + std::function<void(const std::string &, int)> err_callback = nullptr);
128 117  
129 118 /**
130 119 * Return the topics that are subscribed() to.
... ... @@ -143,19 +132,16 @@ public:
143 132 }
144 133  
145 134 private:
146   -
147 135 // Base for subscribe and psubscribe
148 136 void subscribeBase(const std::string cmd_name, const std::string topic,
149   - std::function<void(const std::string&, const std::string&)> msg_callback,
150   - std::function<void(const std::string&)> sub_callback = nullptr,
151   - std::function<void(const std::string&)> unsub_callback = nullptr,
152   - std::function<void(const std::string&, int)> err_callback = nullptr
153   - );
  137 + std::function<void(const std::string &, const std::string &)> msg_callback,
  138 + std::function<void(const std::string &)> sub_callback = nullptr,
  139 + std::function<void(const std::string &)> unsub_callback = nullptr,
  140 + std::function<void(const std::string &, int)> err_callback = nullptr);
154 141  
155 142 // Base for unsubscribe and punsubscribe
156 143 void unsubscribeBase(const std::string cmd_name, const std::string topic,
157   - std::function<void(const std::string&, int)> err_callback = nullptr
158   - );
  144 + std::function<void(const std::string &, int)> err_callback = nullptr);
159 145  
160 146 // Underlying Redis client
161 147 Redox rdx_;
... ... @@ -170,10 +156,10 @@ private:
170 156 std::mutex psubscribed_topics_guard_;
171 157  
172 158 // Set of persisting commands, so that we can cancel them
173   - std::set<Command<redisReply*>*> commands_;
  159 + std::set<Command<redisReply *> *> commands_;
174 160  
175 161 // Reference to rdx_.logger_ for convenience
176   - log::Logger& logger_;
  162 + log::Logger &logger_;
177 163  
178 164 // CVs to wait for unsubscriptions
179 165 std::condition_variable cv_unsub_;
... ...
src/client.cpp
... ... @@ -26,63 +26,56 @@ using namespace std;
26 26  
27 27 namespace redox {
28 28  
29   -Redox::Redox(
30   - ostream& log_stream,
31   - log::Level log_level
32   -) : logger_(log_stream, log_level), evloop_(nullptr) {}
  29 +Redox::Redox(ostream &log_stream, log::Level log_level)
  30 + : logger_(log_stream, log_level), evloop_(nullptr) {}
33 31  
34   -bool Redox::connect(
35   - const std::string& host, const int port,
36   - std::function<void(int)> connection_callback
37   -) {
  32 +bool Redox::connect(const string &host, const int port,
  33 + function<void(int)> connection_callback) {
38 34  
39 35 host_ = host;
40 36 port_ = port;
41 37 user_connection_callback_ = connection_callback;
42 38  
43   - if(!initEv()) return false;
  39 + if (!initEv())
  40 + return false;
44 41  
45 42 // Connect over TCP
46 43 ctx_ = redisAsyncConnect(host.c_str(), port);
47 44  
48   - if(!initHiredis()) return false;
  45 + if (!initHiredis())
  46 + return false;
49 47  
50 48 event_loop_thread_ = thread([this] { runEventLoop(); });
51 49  
52 50 // Block until connected and running the event loop, or until
53 51 // a connection error happens and the event loop exits
54 52 unique_lock<mutex> ul(running_waiter_lock_);
55   - running_waiter_.wait(ul, [this] {
56   - return running_.load() || connect_state_ == CONNECT_ERROR;
57   - });
  53 + running_waiter_.wait(ul, [this] { return running_.load() || connect_state_ == CONNECT_ERROR; });
58 54  
59 55 // Return if succeeded
60 56 return connect_state_ == CONNECTED;
61 57 }
62 58  
63   -bool Redox::connectUnix(
64   - const std::string& path,
65   - std::function<void(int)> connection_callback
66   -) {
  59 +bool Redox::connectUnix(const string &path, function<void(int)> connection_callback) {
67 60  
68 61 path_ = path;
69 62 user_connection_callback_ = connection_callback;
70 63  
71   - if(!initEv()) return false;
  64 + if (!initEv())
  65 + return false;
72 66  
73 67 // Connect over unix sockets
74 68 ctx_ = redisAsyncConnectUnix(path.c_str());
75 69  
76   - if(!initHiredis()) return false;
  70 + if (!initHiredis())
  71 + return false;
77 72  
78 73 event_loop_thread_ = thread([this] { runEventLoop(); });
79 74  
80 75 // Block until connected and running the event loop, or until
81 76 // a connection error happens and the event loop exits
82 77 unique_lock<mutex> ul(running_waiter_lock_);
83   - running_waiter_.wait(ul, [this] {
84   - return running_.load() || connect_state_ == CONNECT_ERROR;
85   - });
  78 + running_waiter_.wait(ul, [this] { return running_.load() || connect_state_ == CONNECT_ERROR; });
86 79  
87 80 // Return if succeeded
88 81 return connect_state_ == CONNECTED;
... ... @@ -107,16 +100,20 @@ void Redox::wait() {
107 100 Redox::~Redox() {
108 101  
109 102 // Bring down the event loop
110   - if(running_ == true) { stop(); }
  103 + if (running_ == true) {
  104 + stop();
  105 + }
111 106  
112   - if(event_loop_thread_.joinable()) event_loop_thread_.join();
  107 + if (event_loop_thread_.joinable())
  108 + event_loop_thread_.join();
113 109  
114   - if(evloop_ != nullptr) ev_loop_destroy(evloop_);
  110 + if (evloop_ != nullptr)
  111 + ev_loop_destroy(evloop_);
115 112 }
116 113  
117   -void Redox::connectedCallback(const redisAsyncContext* ctx, int status) {
  114 +void Redox::connectedCallback(const redisAsyncContext *ctx, int status) {
118 115  
119   - Redox* rdx = (Redox*) ctx->data;
  116 + Redox *rdx = (Redox *)ctx->data;
120 117  
121 118 if (status != REDIS_OK) {
122 119 rdx->logger_.fatal() << "Could not connect to Redis: " << ctx->errstr;
... ... @@ -131,12 +128,13 @@ void Redox::connectedCallback(const redisAsyncContext* ctx, int status) {
131 128 }
132 129  
133 130 rdx->connect_waiter_.notify_all();
134   - if(rdx->user_connection_callback_) rdx->user_connection_callback_(rdx->connect_state_);
  131 + if (rdx->user_connection_callback_)
  132 + rdx->user_connection_callback_(rdx->connect_state_);
135 133 }
136 134  
137   -void Redox::disconnectedCallback(const redisAsyncContext* ctx, int status) {
  135 +void Redox::disconnectedCallback(const redisAsyncContext *ctx, int status) {
138 136  
139   - Redox* rdx = (Redox*) ctx->data;
  137 + Redox *rdx = (Redox *)ctx->data;
140 138  
141 139 if (status != REDIS_OK) {
142 140 rdx->logger_.error() << "Disconnected from Redis on error: " << ctx->errstr;
... ... @@ -148,25 +146,26 @@ void Redox::disconnectedCallback(const redisAsyncContext* ctx, int status) {
148 146  
149 147 rdx->stop();
150 148 rdx->connect_waiter_.notify_all();
151   - if(rdx->user_connection_callback_) rdx->user_connection_callback_(rdx->connect_state_);
  149 + if (rdx->user_connection_callback_)
  150 + rdx->user_connection_callback_(rdx->connect_state_);
152 151 }
153 152  
154 153 bool Redox::initEv() {
155 154 signal(SIGPIPE, SIG_IGN);
156 155 evloop_ = ev_loop_new(EVFLAG_AUTO);
157   - if(evloop_ == nullptr) {
  156 + if (evloop_ == nullptr) {
158 157 logger_.fatal() << "Could not create a libev event loop.";
159 158 connect_state_ = INIT_ERROR;
160 159 connect_waiter_.notify_all();
161 160 return false;
162 161 }
163   - ev_set_userdata(evloop_, (void*)this); // Back-reference
  162 + ev_set_userdata(evloop_, (void *)this); // Back-reference
164 163 return true;
165 164 }
166 165  
167 166 bool Redox::initHiredis() {
168 167  
169   - ctx_->data = (void*)this; // Back-reference
  168 + ctx_->data = (void *)this; // Back-reference
170 169  
171 170 if (ctx_->err) {
172 171 logger_.fatal() << "Could not create a hiredis context: " << ctx_->errstr;
... ... @@ -176,7 +175,7 @@ bool Redox::initHiredis() {
176 175 }
177 176  
178 177 // Attach event loop to hiredis
179   - if(redisLibevAttach(evloop_, ctx_) != REDIS_OK) {
  178 + if (redisLibevAttach(evloop_, ctx_) != REDIS_OK) {
180 179 logger_.fatal() << "Could not attach libev event loop to hiredis.";
181 180 connect_state_ = INIT_ERROR;
182 181 connect_waiter_.notify_all();
... ... @@ -184,14 +183,14 @@ bool Redox::initHiredis() {
184 183 }
185 184  
186 185 // Set the callbacks to be invoked on server connection/disconnection
187   - if(redisAsyncSetConnectCallback(ctx_, Redox::connectedCallback) != REDIS_OK) {
  186 + if (redisAsyncSetConnectCallback(ctx_, Redox::connectedCallback) != REDIS_OK) {
188 187 logger_.fatal() << "Could not attach connect callback to hiredis.";
189 188 connect_state_ = INIT_ERROR;
190 189 connect_waiter_.notify_all();
191 190 return false;
192 191 }
193 192  
194   - if(redisAsyncSetDisconnectCallback(ctx_, Redox::disconnectedCallback) != REDIS_OK) {
  193 + if (redisAsyncSetDisconnectCallback(ctx_, Redox::disconnectedCallback) != REDIS_OK) {
195 194 logger_.fatal() << "Could not attach disconnect callback to hiredis.";
196 195 connect_state_ = INIT_ERROR;
197 196 connect_waiter_.notify_all();
... ... @@ -202,12 +201,14 @@ bool Redox::initHiredis() {
202 201 }
203 202  
204 203 void Redox::noWait(bool state) {
205   - if(state) logger_.info() << "No-wait mode enabled.";
206   - else logger_.info() << "No-wait mode disabled.";
  204 + if (state)
  205 + logger_.info() << "No-wait mode enabled.";
  206 + else
  207 + logger_.info() << "No-wait mode disabled.";
207 208 nowait_ = state;
208 209 }
209 210  
210   -void breakEventLoop(struct ev_loop* loop, ev_async* async, int revents) {
  211 +void breakEventLoop(struct ev_loop *loop, ev_async *async, int revents) {
211 212 ev_break(loop, EVBREAK_ALL);
212 213 }
213 214  
... ... @@ -222,7 +223,7 @@ void Redox::runEventLoop() {
222 223 connect_waiter_.wait(ul, [this] { return connect_state_ != NOT_YET_CONNECTED; });
223 224  
224 225 // Handle connection error
225   - if(connect_state_ != CONNECTED) {
  226 + if (connect_state_ != CONNECTED) {
226 227 logger_.warning() << "Did not connect, event loop exiting.";
227 228 exited_ = true;
228 229 running_ = false;
... ... @@ -250,7 +251,7 @@ void Redox::runEventLoop() {
250 251 // Run the event loop, using NOWAIT if enabled for maximum
251 252 // throughput by avoiding any sleeping
252 253 while (!to_exit_) {
253   - if(nowait_) {
  254 + if (nowait_) {
254 255 ev_run(evloop_, EVRUN_NOWAIT);
255 256 } else {
256 257 ev_run(evloop_);
... ... @@ -266,14 +267,15 @@ void Redox::runEventLoop() {
266 267 this_thread::sleep_for(chrono::milliseconds(10));
267 268 ev_run(evloop_, EVRUN_NOWAIT);
268 269  
269   - if(connect_state_ == CONNECTED) redisAsyncDisconnect(ctx_);
  270 + if (connect_state_ == CONNECTED)
  271 + redisAsyncDisconnect(ctx_);
270 272  
271 273 // Run once more to disconnect
272 274 ev_run(evloop_, EVRUN_NOWAIT);
273 275  
274   - if(commands_created_ != commands_deleted_) {
275   - logger_.error() << "All commands were not freed! "
276   - << commands_deleted_ << "/" << commands_created_;
  276 + if (commands_created_ != commands_deleted_) {
  277 + logger_.error() << "All commands were not freed! " << commands_deleted_ << "/"
  278 + << commands_created_;
277 279 }
278 280  
279 281 exited_ = true;
... ... @@ -285,27 +287,26 @@ void Redox::runEventLoop() {
285 287 logger_.info() << "Event thread exited.";
286 288 }
287 289  
288   -template<class ReplyT>
289   -Command<ReplyT>* Redox::findCommand(long id) {
  290 +template <class ReplyT> Command<ReplyT> *Redox::findCommand(long id) {
290 291  
291 292 lock_guard<mutex> lg(command_map_guard_);
292 293  
293   - auto& command_map = getCommandMap<ReplyT>();
  294 + auto &command_map = getCommandMap<ReplyT>();
294 295 auto it = command_map.find(id);
295   - if(it == command_map.end()) return nullptr;
  296 + if (it == command_map.end())
  297 + return nullptr;
296 298 return it->second;
297 299 }
298 300  
299   -template<class ReplyT>
300   -void Redox::commandCallback(redisAsyncContext* ctx, void* r, void* privdata) {
  301 +template <class ReplyT>
  302 +void Redox::commandCallback(redisAsyncContext *ctx, void *r, void *privdata) {
301 303  
302   - Redox* rdx = (Redox*) ctx->data;
  304 + Redox *rdx = (Redox *)ctx->data;
303 305 long id = (long)privdata;
304   - redisReply* reply_obj = (redisReply*) r;
  306 + redisReply *reply_obj = (redisReply *)r;
305 307  
306   - Command<ReplyT>* c = rdx->findCommand<ReplyT>(id);
307   - if(c == nullptr) {
308   -// rdx->logger.warning() << "Couldn't find Command " << id << " in command_map (commandCallback).";
  308 + Command<ReplyT> *c = rdx->findCommand<ReplyT>(id);
  309 + if (c == nullptr) {
309 310 freeReplyObject(reply_obj);
310 311 return;
311 312 }
... ... @@ -313,26 +314,23 @@ void Redox::commandCallback(redisAsyncContext* ctx, void* r, void* privdata) {
313 314 c->processReply(reply_obj);
314 315 }
315 316  
316   -template<class ReplyT>
317   -bool Redox::submitToServer(Command<ReplyT>* c) {
  317 +template <class ReplyT> bool Redox::submitToServer(Command<ReplyT> *c) {
318 318  
319   - Redox* rdx = c->rdx_;
  319 + Redox *rdx = c->rdx_;
320 320 c->pending_++;
321 321  
322 322 // Construct a char** from the vector
323   - vector<const char*> argv;
  323 + vector<const char *> argv;
324 324 transform(c->cmd_.begin(), c->cmd_.end(), back_inserter(argv),
325   - [](const string& s){ return s.c_str(); }
326   - );
  325 + [](const string &s) { return s.c_str(); });
327 326  
328 327 // Construct a size_t* of string lengths from the vector
329 328 vector<size_t> argvlen;
330 329 transform(c->cmd_.begin(), c->cmd_.end(), back_inserter(argvlen),
331   - [](const string& s) { return s.size(); }
332   - );
  330 + [](const string &s) { return s.size(); });
333 331  
334   - if(redisAsyncCommandArgv(rdx->ctx_, commandCallback<ReplyT>, (void*) c->id_,
335   - argv.size(), &argv[0], &argvlen[0]) != REDIS_OK) {
  332 + if (redisAsyncCommandArgv(rdx->ctx_, commandCallback<ReplyT>, (void *)c->id_, argv.size(),
  333 + &argv[0], &argvlen[0]) != REDIS_OK) {
336 334 rdx->logger_.error() << "Could not send \"" << c->cmd() << "\": " << rdx->ctx_->errstr;
337 335 c->reply_status_ = Command<ReplyT>::SEND_ERROR;
338 336 c->invoke();
... ... @@ -342,34 +340,34 @@ bool Redox::submitToServer(Command&lt;ReplyT&gt;* c) {
342 340 return true;
343 341 }
344 342  
345   -template<class ReplyT>
346   -void Redox::submitCommandCallback(struct ev_loop* loop, ev_timer* timer, int revents) {
  343 +template <class ReplyT>
  344 +void Redox::submitCommandCallback(struct ev_loop *loop, ev_timer *timer, int revents) {
347 345  
348   - Redox* rdx = (Redox*) ev_userdata(loop);
  346 + Redox *rdx = (Redox *)ev_userdata(loop);
349 347 long id = (long)timer->data;
350 348  
351   - Command<ReplyT>* c = rdx->findCommand<ReplyT>(id);
352   - if(c == nullptr) {
  349 + Command<ReplyT> *c = rdx->findCommand<ReplyT>(id);
  350 + if (c == nullptr) {
353 351 rdx->logger_.error() << "Couldn't find Command " << id
354   - << " in command_map (submitCommandCallback).";
  352 + << " in command_map (submitCommandCallback).";
355 353 return;
356 354 }
357 355  
358 356 submitToServer<ReplyT>(c);
359 357 }
360 358  
361   -template<class ReplyT>
362   -bool Redox::processQueuedCommand(long id) {
  359 +template <class ReplyT> bool Redox::processQueuedCommand(long id) {
363 360  
364   - Command<ReplyT>* c = findCommand<ReplyT>(id);
365   - if(c == nullptr) return false;
  361 + Command<ReplyT> *c = findCommand<ReplyT>(id);
  362 + if (c == nullptr)
  363 + return false;
366 364  
367   - if((c->repeat_ == 0) && (c->after_ == 0)) {
  365 + if ((c->repeat_ == 0) && (c->after_ == 0)) {
368 366 submitToServer<ReplyT>(c);
369 367  
370 368 } else {
371 369  
372   - c->timer_.data = (void*)c->id_;
  370 + c->timer_.data = (void *)c->id_;
373 371 ev_timer_init(&c->timer_, submitCommandCallback<ReplyT>, c->after_, c->repeat_);
374 372 ev_timer_start(evloop_, &c->timer_);
375 373  
... ... @@ -379,62 +377,64 @@ bool Redox::processQueuedCommand(long id) {
379 377 return true;
380 378 }
381 379  
382   -void Redox::processQueuedCommands(struct ev_loop* loop, ev_async* async, int revents) {
  380 +void Redox::processQueuedCommands(struct ev_loop *loop, ev_async *async, int revents) {
383 381  
384   - Redox* rdx = (Redox*) ev_userdata(loop);
  382 + Redox *rdx = (Redox *)ev_userdata(loop);
385 383  
386 384 lock_guard<mutex> lg(rdx->queue_guard_);
387 385  
388   - while(!rdx->command_queue_.empty()) {
  386 + while (!rdx->command_queue_.empty()) {
389 387  
390 388 long id = rdx->command_queue_.front();
391 389 rdx->command_queue_.pop();
392 390  
393   - if(rdx->processQueuedCommand<redisReply*>(id)) {}
394   - else if(rdx->processQueuedCommand<string>(id)) {}
395   - else if(rdx->processQueuedCommand<char*>(id)) {}
396   - else if(rdx->processQueuedCommand<int>(id)) {}
397   - else if(rdx->processQueuedCommand<long long int>(id)) {}
398   - else if(rdx->processQueuedCommand<nullptr_t>(id)) {}
399   - else if(rdx->processQueuedCommand<vector<string>>(id)) {}
400   - else if(rdx->processQueuedCommand<std::set<string>>(id)) {}
401   - else if(rdx->processQueuedCommand<unordered_set<string>>(id)) {}
402   - else throw runtime_error("Command pointer not found in any queue!");
  391 + if (rdx->processQueuedCommand<redisReply *>(id)) {
  392 + } else if (rdx->processQueuedCommand<string>(id)) {
  393 + } else if (rdx->processQueuedCommand<char *>(id)) {
  394 + } else if (rdx->processQueuedCommand<int>(id)) {
  395 + } else if (rdx->processQueuedCommand<long long int>(id)) {
  396 + } else if (rdx->processQueuedCommand<nullptr_t>(id)) {
  397 + } else if (rdx->processQueuedCommand<vector<string>>(id)) {
  398 + } else if (rdx->processQueuedCommand<std::set<string>>(id)) {
  399 + } else if (rdx->processQueuedCommand<unordered_set<string>>(id)) {
  400 + } else
  401 + throw runtime_error("Command pointer not found in any queue!");
403 402 }
404 403 }
405 404  
406   -void Redox::freeQueuedCommands(struct ev_loop* loop, ev_async* async, int revents) {
  405 +void Redox::freeQueuedCommands(struct ev_loop *loop, ev_async *async, int revents) {
407 406  
408   - Redox* rdx = (Redox*) ev_userdata(loop);
  407 + Redox *rdx = (Redox *)ev_userdata(loop);
409 408  
410 409 lock_guard<mutex> lg(rdx->free_queue_guard_);
411 410  
412   - while(!rdx->commands_to_free_.empty()) {
  411 + while (!rdx->commands_to_free_.empty()) {
413 412 long id = rdx->commands_to_free_.front();
414 413 rdx->commands_to_free_.pop();
415 414  
416   - if(rdx->freeQueuedCommand<redisReply*>(id)) {}
417   - else if(rdx->freeQueuedCommand<string>(id)) {}
418   - else if(rdx->freeQueuedCommand<char*>(id)) {}
419   - else if(rdx->freeQueuedCommand<int>(id)) {}
420   - else if(rdx->freeQueuedCommand<long long int>(id)) {}
421   - else if(rdx->freeQueuedCommand<nullptr_t>(id)) {}
422   - else if(rdx->freeQueuedCommand<vector<string>>(id)) {}
423   - else if(rdx->freeQueuedCommand<std::set<string>>(id)) {}
424   - else if(rdx->freeQueuedCommand<unordered_set<string>>(id)) {}
425   - else {}
  415 + if (rdx->freeQueuedCommand<redisReply *>(id)) {
  416 + } else if (rdx->freeQueuedCommand<string>(id)) {
  417 + } else if (rdx->freeQueuedCommand<char *>(id)) {
  418 + } else if (rdx->freeQueuedCommand<int>(id)) {
  419 + } else if (rdx->freeQueuedCommand<long long int>(id)) {
  420 + } else if (rdx->freeQueuedCommand<nullptr_t>(id)) {
  421 + } else if (rdx->freeQueuedCommand<vector<string>>(id)) {
  422 + } else if (rdx->freeQueuedCommand<std::set<string>>(id)) {
  423 + } else if (rdx->freeQueuedCommand<unordered_set<string>>(id)) {
  424 + } else {
  425 + }
426 426 }
427 427 }
428 428  
429   -template<class ReplyT>
430   -bool Redox::freeQueuedCommand(long id) {
431   - Command<ReplyT>* c = findCommand<ReplyT>(id);
432   - if(c == nullptr) return false;
  429 +template <class ReplyT> bool Redox::freeQueuedCommand(long id) {
  430 + Command<ReplyT> *c = findCommand<ReplyT>(id);
  431 + if (c == nullptr)
  432 + return false;
433 433  
434 434 c->freeReply();
435 435  
436 436 // Stop the libev timer if this is a repeating command
437   - if((c->repeat_ != 0) || (c->after_ != 0)) {
  437 + if ((c->repeat_ != 0) || (c->after_ != 0)) {
438 438 lock_guard<mutex> lg(c->timer_guard_);
439 439 ev_timer_stop(c->rdx_->evloop_, &c->timer_);
440 440 }
... ... @@ -447,33 +447,28 @@ bool Redox::freeQueuedCommand(long id) {
447 447 }
448 448  
449 449 long Redox::freeAllCommands() {
450   - return freeAllCommandsOfType<redisReply*>() +
451   - freeAllCommandsOfType<string>() +
452   - freeAllCommandsOfType<char*>() +
453   - freeAllCommandsOfType<int>() +
454   - freeAllCommandsOfType<long long int>() +
455   - freeAllCommandsOfType<nullptr_t>() +
456   - freeAllCommandsOfType<vector<string>>() +
457   - freeAllCommandsOfType<std::set<string>>() +
458   - freeAllCommandsOfType<unordered_set<string>>();
  450 + return freeAllCommandsOfType<redisReply *>() + freeAllCommandsOfType<string>() +
  451 + freeAllCommandsOfType<char *>() + freeAllCommandsOfType<int>() +
  452 + freeAllCommandsOfType<long long int>() + freeAllCommandsOfType<nullptr_t>() +
  453 + freeAllCommandsOfType<vector<string>>() + freeAllCommandsOfType<std::set<string>>() +
  454 + freeAllCommandsOfType<unordered_set<string>>();
459 455 }
460 456  
461   -template<class ReplyT>
462   -long Redox::freeAllCommandsOfType() {
  457 +template <class ReplyT> long Redox::freeAllCommandsOfType() {
463 458  
464 459 lock_guard<mutex> lg(free_queue_guard_);
465 460 lock_guard<mutex> lg2(queue_guard_);
466 461  
467   - auto& command_map = getCommandMap<ReplyT>();
  462 + auto &command_map = getCommandMap<ReplyT>();
468 463 long len = command_map.size();
469 464  
470   - for(auto& pair : command_map) {
471   - Command<ReplyT>* c = pair.second;
  465 + for (auto &pair : command_map) {
  466 + Command<ReplyT> *c = pair.second;
472 467  
473 468 c->freeReply();
474 469  
475 470 // Stop the libev timer if this is a repeating command
476   - if((c->repeat_ != 0) || (c->after_ != 0)) {
  471 + if ((c->repeat_ != 0) || (c->after_ != 0)) {
477 472 lock_guard<mutex> lg3(c->timer_guard_);
478 473 ev_timer_stop(c->rdx_->evloop_, &c->timer_);
479 474 }
... ... @@ -491,89 +486,95 @@ long Redox::freeAllCommandsOfType() {
491 486 // get_command_map specializations
492 487 // ---------------------------------
493 488  
494   -template<> unordered_map<long, Command<redisReply*>*>&
495   -Redox::getCommandMap<redisReply*>() { return commands_redis_reply_; }
  489 +template <> unordered_map<long, Command<redisReply *> *> &Redox::getCommandMap<redisReply *>() {
  490 + return commands_redis_reply_;
  491 +}
496 492  
497   -template<> unordered_map<long, Command<string>*>&
498   -Redox::getCommandMap<string>() { return commands_string_; }
  493 +template <> unordered_map<long, Command<string> *> &Redox::getCommandMap<string>() {
  494 + return commands_string_;
  495 +}
499 496  
500   -template<> unordered_map<long, Command<char*>*>&
501   -Redox::getCommandMap<char*>() { return commands_char_p_; }
  497 +template <> unordered_map<long, Command<char *> *> &Redox::getCommandMap<char *>() {
  498 + return commands_char_p_;
  499 +}
502 500  
503   -template<> unordered_map<long, Command<int>*>&
504   -Redox::getCommandMap<int>() { return commands_int_; }
  501 +template <> unordered_map<long, Command<int> *> &Redox::getCommandMap<int>() {
  502 + return commands_int_;
  503 +}
505 504  
506   -template<> unordered_map<long, Command<long long int>*>&
507   -Redox::getCommandMap<long long int>() { return commands_long_long_int_; }
  505 +template <> unordered_map<long, Command<long long int> *> &Redox::getCommandMap<long long int>() {
  506 + return commands_long_long_int_;
  507 +}
508 508  
509   -template<> unordered_map<long, Command<nullptr_t>*>&
510   -Redox::getCommandMap<nullptr_t>() { return commands_null_; }
  509 +template <> unordered_map<long, Command<nullptr_t> *> &Redox::getCommandMap<nullptr_t>() {
  510 + return commands_null_;
  511 +}
511 512  
512   -template<> unordered_map<long, Command<vector<string>>*>&
513   -Redox::getCommandMap<vector<string>>() { return commands_vector_string_; }
  513 +template <> unordered_map<long, Command<vector<string>> *> &Redox::getCommandMap<vector<string>>() {
  514 + return commands_vector_string_;
  515 +}
514 516  
515   -template<> unordered_map<long, Command<set<string>>*>&
516   -Redox::getCommandMap<set<string>>() { return commands_set_string_; }
  517 +template <> unordered_map<long, Command<set<string>> *> &Redox::getCommandMap<set<string>>() {
  518 + return commands_set_string_;
  519 +}
517 520  
518   -template<> unordered_map<long, Command<unordered_set<string>>*>&
519   -Redox::getCommandMap<unordered_set<string>>() { return commands_unordered_set_string_; }
  521 +template <>
  522 +unordered_map<long, Command<unordered_set<string>> *> &
  523 +Redox::getCommandMap<unordered_set<string>>() {
  524 + return commands_unordered_set_string_;
  525 +}
520 526  
521 527 // ----------------------------
522 528 // Helpers
523 529 // ----------------------------
524 530  
525   -string Redox::vecToStr(const vector<string>& vec, const char delimiter) {
  531 +string Redox::vecToStr(const vector<string> &vec, const char delimiter) {
526 532 string str;
527   - for(size_t i = 0; i < vec.size() - 1; i++)
  533 + for (size_t i = 0; i < vec.size() - 1; i++)
528 534 str += vec[i] + delimiter;
529   - str += vec[vec.size()-1];
  535 + str += vec[vec.size() - 1];
530 536 return str;
531 537 }
532 538  
533   -vector<string> Redox::strToVec(const string& s, const char delimiter) {
  539 +vector<string> Redox::strToVec(const string &s, const char delimiter) {
534 540 vector<string> vec;
535 541 size_t last = 0;
536 542 size_t next = 0;
537 543 while ((next = s.find(delimiter, last)) != string::npos) {
538   - vec.push_back(s.substr(last, next-last));
  544 + vec.push_back(s.substr(last, next - last));
539 545 last = next + 1;
540 546 }
541 547 vec.push_back(s.substr(last));
542 548 return vec;
543 549 }
544 550  
545   -void Redox::command(const std::vector<std::string>& cmd) {
546   - command<redisReply*>(cmd, nullptr);
547   -}
  551 +void Redox::command(const vector<string> &cmd) { command<redisReply *>(cmd, nullptr); }
548 552  
549   -bool Redox::commandSync(const std::vector<std::string>& cmd) {
550   - auto& c = commandSync<redisReply*>(cmd);
  553 +bool Redox::commandSync(const vector<string> &cmd) {
  554 + auto &c = commandSync<redisReply *>(cmd);
551 555 bool succeeded = c.ok();
552 556 c.free();
553 557 return succeeded;
554 558 }
555 559  
556   -string Redox::get(const string& key) {
  560 +string Redox::get(const string &key) {
557 561  
558   - Command<char*>& c = commandSync<char*>({"GET", key});
559   - if(!c.ok()) {
560   - throw runtime_error("[FATAL] Error getting key " + key + ": Status code " + to_string(c.status()));
  562 + Command<char *> &c = commandSync<char *>({"GET", key});
  563 + if (!c.ok()) {
  564 + throw runtime_error("[FATAL] Error getting key " + key + ": Status code " +
  565 + to_string(c.status()));
561 566 }
562 567 string reply = c.reply();
563 568 c.free();
564 569 return reply;
565 570 };
566 571  
567   -bool Redox::set(const string& key, const string& value) {
568   - return commandSync({"SET", key, value});
569   -}
  572 +bool Redox::set(const string &key, const string &value) { return commandSync({"SET", key, value}); }
570 573  
571   -bool Redox::del(const string& key) {
572   - return commandSync({"DEL", key});
573   -}
  574 +bool Redox::del(const string &key) { return commandSync({"DEL", key}); }
574 575  
575   -void Redox::publish(const string& topic, const string& msg) {
576   - command<redisReply*>({"PUBLISH", topic, msg});
  576 +void Redox::publish(const string &topic, const string &msg) {
  577 + command<redisReply *>({"PUBLISH", topic, msg});
577 578 }
578 579  
579 580 } // End namespace redis
... ...
src/command.cpp
... ... @@ -29,32 +29,27 @@ using namespace std;
29 29  
30 30 namespace redox {
31 31  
32   -template<class ReplyT>
33   -Command<ReplyT>::Command(
34   - Redox* rdx,
35   - long id,
36   - const std::vector<std::string>& cmd,
37   - const std::function<void(Command<ReplyT>&)>& callback,
38   - double repeat, double after, bool free_memory, log::Logger& logger
39   -) : rdx_(rdx), id_(id), cmd_(cmd), repeat_(repeat), after_(after), free_memory_(free_memory),
40   - callback_(callback), last_error_(), logger_(logger) {
  32 +template <class ReplyT>
  33 +Command<ReplyT>::Command(Redox *rdx, long id, const vector<string> &cmd,
  34 + const function<void(Command<ReplyT> &)> &callback, double repeat,
  35 + double after, bool free_memory, log::Logger &logger)
  36 + : rdx_(rdx), id_(id), cmd_(cmd), repeat_(repeat), after_(after), free_memory_(free_memory),
  37 + callback_(callback), last_error_(), logger_(logger) {
41 38 timer_guard_.lock();
42 39 }
43 40  
44   -template<class ReplyT>
45   -void Command<ReplyT>::wait() {
46   - std::unique_lock<std::mutex> lk(waiter_lock_);
  41 +template <class ReplyT> void Command<ReplyT>::wait() {
  42 + unique_lock<mutex> lk(waiter_lock_);
47 43 waiter_.wait(lk, [this]() { return waiting_done_.load(); });
48 44 waiting_done_ = {false};
49 45 }
50 46  
51   -template<class ReplyT>
52   -void Command<ReplyT>::processReply(redisReply* r) {
  47 +template <class ReplyT> void Command<ReplyT>::processReply(redisReply *r) {
53 48  
54 49 last_error_.clear();
55 50 reply_obj_ = r;
56 51  
57   - if(reply_obj_ == nullptr) {
  52 + if (reply_obj_ == nullptr) {
58 53 reply_status_ = ERROR_REPLY;
59 54 last_error_ = "Received null redisReply* from hiredis.";
60 55 logger_.error() << last_error_;
... ... @@ -73,34 +68,35 @@ void Command&lt;ReplyT&gt;::processReply(redisReply* r) {
73 68 waiter_.notify_all();
74 69  
75 70 // Always free the reply object for repeating commands
76   - if(repeat_ > 0) {
  71 + if (repeat_ > 0) {
77 72 freeReply();
78 73  
79 74 } else {
80 75  
81 76 // User calls .free()
82   - if (!free_memory_) return;
  77 + if (!free_memory_)
  78 + return;
83 79  
84 80 // Free non-repeating commands automatically
85 81 // once we receive expected replies
86   - if(pending_ == 0) free();
  82 + if (pending_ == 0)
  83 + free();
87 84 }
88 85 }
89 86  
90 87 // This is the only method in Command that has
91 88 // access to private members of Redox
92   -template<class ReplyT>
93   -void Command<ReplyT>::free() {
  89 +template <class ReplyT> void Command<ReplyT>::free() {
94 90  
95 91 lock_guard<mutex> lg(rdx_->free_queue_guard_);
96 92 rdx_->commands_to_free_.push(id_);
97 93 ev_async_send(rdx_->evloop_, &rdx_->watcher_free_);
98 94 }
99 95  
100   -template<class ReplyT>
101   -void Command<ReplyT>::freeReply() {
  96 +template <class ReplyT> void Command<ReplyT>::freeReply() {
102 97  
103   - if (reply_obj_ == nullptr) return;
  98 + if (reply_obj_ == nullptr)
  99 + return;
104 100  
105 101 freeReplyObject(reply_obj_);
106 102 reply_obj_ = nullptr;
... ... @@ -111,60 +107,55 @@ void Command&lt;ReplyT&gt;::freeReply() {
111 107 * to make sure we don't return a reply while it is being
112 108 * modified.
113 109 */
114   -template<class ReplyT>
115   -ReplyT Command<ReplyT>::reply() {
116   - std::lock_guard<std::mutex> lg(reply_guard_);
  110 +template <class ReplyT> ReplyT Command<ReplyT>::reply() {
  111 + lock_guard<mutex> lg(reply_guard_);
117 112 if (!ok()) {
118 113 logger_.warning() << cmd() << ": Accessing reply value while status != OK.";
119 114 }
120 115 return reply_val_;
121 116 }
122 117  
123   -template<class ReplyT>
124   -std::string Command<ReplyT>::cmd() const {
125   - return rdx_->vecToStr(cmd_);
126   -}
  118 +template <class ReplyT> string Command<ReplyT>::cmd() const { return rdx_->vecToStr(cmd_); }
127 119  
128   -template<class ReplyT>
129   -bool Command<ReplyT>::isExpectedReply(int type) {
  120 +template <class ReplyT> bool Command<ReplyT>::isExpectedReply(int type) {
130 121  
131   - if(reply_obj_->type == type) {
  122 + if (reply_obj_->type == type) {
132 123 reply_status_ = OK_REPLY;
133 124 return true;
134 125 }
135 126  
136   - if(checkErrorReply() || checkNilReply()) return false;
  127 + if (checkErrorReply() || checkNilReply())
  128 + return false;
137 129  
138   - std::stringstream errorMessage;
139   - errorMessage << "Received reply of type " << reply_obj_->type
140   - << ", expected type " << type << ".";
  130 + stringstream errorMessage;
  131 + errorMessage << "Received reply of type " << reply_obj_->type << ", expected type " << type
  132 + << ".";
141 133 last_error_ = errorMessage.str();
142 134 logger_.error() << cmd() << ": " << last_error_;
143 135 reply_status_ = WRONG_TYPE;
144 136 return false;
145 137 }
146 138  
147   -template<class ReplyT>
148   -bool Command<ReplyT>::isExpectedReply(int typeA, int typeB) {
  139 +template <class ReplyT> bool Command<ReplyT>::isExpectedReply(int typeA, int typeB) {
149 140  
150   - if((reply_obj_->type == typeA) || (reply_obj_->type == typeB)) {
  141 + if ((reply_obj_->type == typeA) || (reply_obj_->type == typeB)) {
151 142 reply_status_ = OK_REPLY;
152 143 return true;
153 144 }
154 145  
155   - if(checkErrorReply() || checkNilReply()) return false;
  146 + if (checkErrorReply() || checkNilReply())
  147 + return false;
156 148  
157   - std::stringstream errorMessage;
158   - errorMessage << "Received reply of type " << reply_obj_->type
159   - << ", expected type " << typeA << " or " << typeB << ".";
  149 + stringstream errorMessage;
  150 + errorMessage << "Received reply of type " << reply_obj_->type << ", expected type " << typeA
  151 + << " or " << typeB << ".";
160 152 last_error_ = errorMessage.str();
161 153 logger_.error() << cmd() << ": " << last_error_;
162 154 reply_status_ = WRONG_TYPE;
163 155 return false;
164 156 }
165 157  
166   -template<class ReplyT>
167   -bool Command<ReplyT>::checkErrorReply() {
  158 +template <class ReplyT> bool Command<ReplyT>::checkErrorReply() {
168 159  
169 160 if (reply_obj_->type == REDIS_REPLY_ERROR) {
170 161 if (reply_obj_->str != 0) {
... ... @@ -178,8 +169,7 @@ bool Command&lt;ReplyT&gt;::checkErrorReply() {
178 169 return false;
179 170 }
180 171  
181   -template<class ReplyT>
182   -bool Command<ReplyT>::checkNilReply() {
  172 +template <class ReplyT> bool Command<ReplyT>::checkNilReply() {
183 173  
184 174 if (reply_obj_->type == REDIS_REPLY_NIL) {
185 175 logger_.warning() << cmd() << ": Nil reply.";
... ... @@ -193,74 +183,74 @@ bool Command&lt;ReplyT&gt;::checkNilReply() {
193 183 // Specializations of parseReplyObject for all expected return types
194 184 // ----------------------------------------------------------------------------
195 185  
196   -template<>
197   -void Command<redisReply*>::parseReplyObject() {
198   - if(!checkErrorReply()) reply_status_ = OK_REPLY;
  186 +template <> void Command<redisReply *>::parseReplyObject() {
  187 + if (!checkErrorReply())
  188 + reply_status_ = OK_REPLY;
199 189 reply_val_ = reply_obj_;
200 190 }
201 191  
202   -template<>
203   -void Command<string>::parseReplyObject() {
204   - if(!isExpectedReply(REDIS_REPLY_STRING, REDIS_REPLY_STATUS)) return;
  192 +template <> void Command<string>::parseReplyObject() {
  193 + if (!isExpectedReply(REDIS_REPLY_STRING, REDIS_REPLY_STATUS))
  194 + return;
205 195 reply_val_ = {reply_obj_->str, static_cast<size_t>(reply_obj_->len)};
206 196 }
207 197  
208   -template<>
209   -void Command<char*>::parseReplyObject() {
210   - if(!isExpectedReply(REDIS_REPLY_STRING, REDIS_REPLY_STATUS)) return;
  198 +template <> void Command<char *>::parseReplyObject() {
  199 + if (!isExpectedReply(REDIS_REPLY_STRING, REDIS_REPLY_STATUS))
  200 + return;
211 201 reply_val_ = reply_obj_->str;
212 202 }
213 203  
214   -template<>
215   -void Command<int>::parseReplyObject() {
  204 +template <> void Command<int>::parseReplyObject() {
216 205  
217   - if(!isExpectedReply(REDIS_REPLY_INTEGER)) return;
218   - reply_val_ = (int) reply_obj_->integer;
  206 + if (!isExpectedReply(REDIS_REPLY_INTEGER))
  207 + return;
  208 + reply_val_ = (int)reply_obj_->integer;
219 209 }
220 210  
221   -template<>
222   -void Command<long long int>::parseReplyObject() {
  211 +template <> void Command<long long int>::parseReplyObject() {
223 212  
224   - if(!isExpectedReply(REDIS_REPLY_INTEGER)) return;
  213 + if (!isExpectedReply(REDIS_REPLY_INTEGER))
  214 + return;
225 215 reply_val_ = reply_obj_->integer;
226 216 }
227 217  
228   -template<>
229   -void Command<nullptr_t>::parseReplyObject() {
  218 +template <> void Command<nullptr_t>::parseReplyObject() {
230 219  
231   - if(!isExpectedReply(REDIS_REPLY_NIL)) return;
  220 + if (!isExpectedReply(REDIS_REPLY_NIL))
  221 + return;
232 222 reply_val_ = nullptr;
233 223 }
234 224  
235   -template<>
236   -void Command<vector<string>>::parseReplyObject() {
  225 +template <> void Command<vector<string>>::parseReplyObject() {
237 226  
238   - if(!isExpectedReply(REDIS_REPLY_ARRAY)) return;
  227 + if (!isExpectedReply(REDIS_REPLY_ARRAY))
  228 + return;
239 229  
240   - for(size_t i = 0; i < reply_obj_->elements; i++) {
241   - redisReply* r = *(reply_obj_->element + i);
  230 + for (size_t i = 0; i < reply_obj_->elements; i++) {
  231 + redisReply *r = *(reply_obj_->element + i);
242 232 reply_val_.emplace_back(r->str, r->len);
243 233 }
244 234 }
245 235  
246   -template<>
247   -void Command<unordered_set<string>>::parseReplyObject() {
  236 +template <> void Command<unordered_set<string>>::parseReplyObject() {
248 237  
249   - if(!isExpectedReply(REDIS_REPLY_ARRAY)) return;
  238 + if (!isExpectedReply(REDIS_REPLY_ARRAY))
  239 + return;
250 240  
251   - for(size_t i = 0; i < reply_obj_->elements; i++) {
252   - redisReply* r = *(reply_obj_->element + i);
  241 + for (size_t i = 0; i < reply_obj_->elements; i++) {
  242 + redisReply *r = *(reply_obj_->element + i);
253 243 reply_val_.emplace(r->str, r->len);
254 244 }
255 245 }
256 246  
257   -template<>
258   -void Command<set<string>>::parseReplyObject() {
  247 +template <> void Command<set<string>>::parseReplyObject() {
259 248  
260   - if(!isExpectedReply(REDIS_REPLY_ARRAY)) return;
  249 + if (!isExpectedReply(REDIS_REPLY_ARRAY))
  250 + return;
261 251  
262   - for(size_t i = 0; i < reply_obj_->elements; i++) {
263   - redisReply* r = *(reply_obj_->element + i);
  252 + for (size_t i = 0; i < reply_obj_->elements; i++) {
  253 + redisReply *r = *(reply_obj_->element + i);
264 254 reply_val_.emplace(r->str, r->len);
265 255 }
266 256 }
... ... @@ -268,9 +258,9 @@ void Command&lt;set&lt;string&gt;&gt;::parseReplyObject() {
268 258 // Explicit template instantiation for available types, so that the generated
269 259 // library contains them and we can keep the method definitions out of the
270 260 // header file.
271   -template class Command<redisReply*>;
  261 +template class Command<redisReply *>;
272 262 template class Command<string>;
273   -template class Command<char*>;
  263 +template class Command<char *>;
274 264 template class Command<int>;
275 265 template class Command<long long int>;
276 266 template class Command<nullptr_t>;
... ...
src/subscriber.cpp
... ... @@ -25,9 +25,8 @@ using namespace std;
25 25  
26 26 namespace redox {
27 27  
28   -Subscriber::Subscriber(
29   - std::ostream& log_stream, log::Level log_level
30   -) : rdx_(log_stream, log_level), logger_(rdx_.logger_) {}
  28 +Subscriber::Subscriber(ostream &log_stream, log::Level log_level)
  29 + : rdx_(log_stream, log_level), logger_(rdx_.logger_) {}
31 30  
32 31 Subscriber::~Subscriber() {}
33 32  
... ... @@ -36,9 +35,7 @@ void Subscriber::disconnect() {
36 35 wait();
37 36 }
38 37  
39   -void Subscriber::wait() {
40   - rdx_.wait();
41   -}
  38 +void Subscriber::wait() { rdx_.wait(); }
42 39  
43 40 // This is a fairly awkward way of shutting down, where
44 41 // we pause to wait for subscriptions to happen, and then
... ... @@ -46,114 +43,127 @@ void Subscriber::wait() {
46 43 // The reason is because hiredis goes into
47 44 // a segfault in freeReplyObject() under redisAsyncDisconnect()
48 45 // if we don't do this first.
49   -// TODO look at hiredis, ask them what causes the error
  46 +// TODO(hayk): look at hiredis, ask them what causes the error
50 47 void Subscriber::stop() {
51 48  
52 49 this_thread::sleep_for(chrono::milliseconds(1000));
53 50  
54   - for(const string& topic : subscribedTopics())
  51 + for (const string &topic : subscribedTopics())
55 52 unsubscribe(topic);
56 53  
57   - for(const string& topic : psubscribedTopics())
  54 + for (const string &topic : psubscribedTopics())
58 55 punsubscribe(topic);
59 56  
60 57 unique_lock<mutex> ul(cv_unsub_guard_);
61 58 cv_unsub_.wait(ul, [this] {
62   - std::lock_guard<std::mutex> lg(subscribed_topics_guard_);
  59 + lock_guard<mutex> lg(subscribed_topics_guard_);
63 60 return (subscribed_topics_.size() == 0);
64 61 });
65 62  
66 63 unique_lock<mutex> ul2(cv_punsub_guard_);
67 64 cv_punsub_.wait(ul, [this] {
68   - std::lock_guard<std::mutex> lg(subscribed_topics_guard_);
  65 + lock_guard<mutex> lg(subscribed_topics_guard_);
69 66 return (psubscribed_topics_.size() == 0);
70 67 });
71 68  
72   - for(Command<redisReply*>* c : commands_)
  69 + for (Command<redisReply *> *c : commands_)
73 70 c->free();
74 71  
75 72 rdx_.stop();
76 73 }
77 74  
78 75 // For debugging only
79   -void debugReply(Command<redisReply*> c) {
  76 +void debugReply(Command<redisReply *> c) {
80 77  
81   - redisReply* reply = c.reply();
  78 + redisReply *reply = c.reply();
82 79  
83 80 cout << "------" << endl;
84 81 cout << c.cmd() << " " << (reply->type == REDIS_REPLY_ARRAY) << " " << (reply->elements) << endl;
85   - for(size_t i = 0; i < reply->elements; i++) {
86   - redisReply* r = reply->element[i];
  82 + for (size_t i = 0; i < reply->elements; i++) {
  83 + redisReply *r = reply->element[i];
87 84 cout << "element " << i << ", reply type = " << r->type << " ";
88   - if(r->type == REDIS_REPLY_STRING) cout << r->str << endl;
89   - else if(r->type == REDIS_REPLY_INTEGER) cout << r->integer << endl;
90   - else cout << "some other type" << endl;
  85 + if (r->type == REDIS_REPLY_STRING)
  86 + cout << r->str << endl;
  87 + else if (r->type == REDIS_REPLY_INTEGER)
  88 + cout << r->integer << endl;
  89 + else
  90 + cout << "some other type" << endl;
91 91 }
92 92 cout << "------" << endl;
93 93 }
94 94  
95 95 void Subscriber::subscribeBase(const string cmd_name, const string topic,
96   - function<void(const string&, const string&)> msg_callback,
97   - function<void(const string&)> sub_callback,
98   - function<void(const string&)> unsub_callback,
99   - function<void(const string&, int)> err_callback
100   -) {
  96 + function<void(const string &, const string &)> msg_callback,
  97 + function<void(const string &)> sub_callback,
  98 + function<void(const string &)> unsub_callback,
  99 + function<void(const string &, int)> err_callback) {
101 100  
102   - Command<redisReply*>& sub_cmd = rdx_.commandLoop<redisReply*>({cmd_name, topic},
103   - [this, topic, msg_callback, err_callback, sub_callback, unsub_callback](Command<redisReply*>& c) {
  101 + Command<redisReply *> &sub_cmd = rdx_.commandLoop<redisReply *>(
  102 + {cmd_name, topic},
  103 + [this, topic, msg_callback, err_callback, sub_callback, unsub_callback](
  104 + Command<redisReply *> &c) {
104 105  
105 106 if (!c.ok()) {
106 107 num_pending_subs_--;
107   - if (err_callback) err_callback(topic, c.status());
  108 + if (err_callback)
  109 + err_callback(topic, c.status());
108 110 return;
109 111 }
110 112  
111   - redisReply* reply = c.reply();
  113 + redisReply *reply = c.reply();
112 114  
113 115 // If the last entry is an integer, then it is a [p]sub/[p]unsub command
114 116 if ((reply->type == REDIS_REPLY_ARRAY) &&
115 117 (reply->element[reply->elements - 1]->type == REDIS_REPLY_INTEGER)) {
116 118  
117   - std::lock_guard<std::mutex> lg(subscribed_topics_guard_);
118   - std::lock_guard<std::mutex> lg2(psubscribed_topics_guard_);
  119 + lock_guard<mutex> lg(subscribed_topics_guard_);
  120 + lock_guard<mutex> lg2(psubscribed_topics_guard_);
119 121  
120 122 if (!strncmp(reply->element[0]->str, "sub", 3)) {
121 123 subscribed_topics_.insert(topic);
122 124 num_pending_subs_--;
123   - if (sub_callback) sub_callback(topic);
  125 + if (sub_callback)
  126 + sub_callback(topic);
124 127 } else if (!strncmp(reply->element[0]->str, "psub", 4)) {
125 128 psubscribed_topics_.insert(topic);
126 129 num_pending_subs_--;
127   - if (sub_callback) sub_callback(topic);
  130 + if (sub_callback)
  131 + sub_callback(topic);
128 132 } else if (!strncmp(reply->element[0]->str, "uns", 3)) {
129 133 subscribed_topics_.erase(topic);
130   - if (unsub_callback) unsub_callback(topic);
  134 + if (unsub_callback)
  135 + unsub_callback(topic);
131 136 cv_unsub_.notify_all();
132 137 } else if (!strncmp(reply->element[0]->str, "puns", 4)) {
133 138 psubscribed_topics_.erase(topic);
134   - if (unsub_callback) unsub_callback(topic);
  139 + if (unsub_callback)
  140 + unsub_callback(topic);
135 141 cv_punsub_.notify_all();
136 142 }
137 143  
138   - else logger_.error() << "Unknown pubsub message: " << reply->element[0]->str;
  144 + else
  145 + logger_.error() << "Unknown pubsub message: " << reply->element[0]->str;
139 146 }
140 147  
141   - // Message for subscribe
  148 + // Message for subscribe
142 149 else if ((reply->type == REDIS_REPLY_ARRAY) && (reply->elements == 3)) {
143   - char* msg = reply->element[2]->str;
144   - if (msg && msg_callback) msg_callback(topic, reply->element[2]->str);
  150 + char *msg = reply->element[2]->str;
  151 + if (msg && msg_callback)
  152 + msg_callback(topic, reply->element[2]->str);
145 153 }
146 154  
147   - // Message for psubscribe
  155 + // Message for psubscribe
148 156 else if ((reply->type == REDIS_REPLY_ARRAY) && (reply->elements == 4)) {
149   - char* msg = reply->element[2]->str;
150   - if (msg && msg_callback) msg_callback(reply->element[2]->str, reply->element[3]->str);
  157 + char *msg = reply->element[2]->str;
  158 + if (msg && msg_callback)
  159 + msg_callback(reply->element[2]->str, reply->element[3]->str);
151 160 }
152 161  
153   - else logger_.error() << "Unknown pubsub message of type " << reply->type;
  162 + else
  163 + logger_.error() << "Unknown pubsub message of type " << reply->type;
154 164 },
155 165 1e10 // To keep the command around for a few hundred years
156   - );
  166 + );
157 167  
158 168 // Add it to the command list
159 169 commands_.insert(&sub_cmd);
... ... @@ -161,13 +171,12 @@ void Subscriber::subscribeBase(const string cmd_name, const string topic,
161 171 }
162 172  
163 173 void Subscriber::subscribe(const string topic,
164   - function<void(const string&, const string&)> msg_callback,
165   - function<void(const string&)> sub_callback,
166   - function<void(const string&)> unsub_callback,
167   - function<void(const string&, int)> err_callback
168   -) {
169   - std::lock_guard<std::mutex> lg(subscribed_topics_guard_);
170   - if(subscribed_topics_.find(topic) != subscribed_topics_.end()) {
  174 + function<void(const string &, const string &)> msg_callback,
  175 + function<void(const string &)> sub_callback,
  176 + function<void(const string &)> unsub_callback,
  177 + function<void(const string &, int)> err_callback) {
  178 + lock_guard<mutex> lg(subscribed_topics_guard_);
  179 + if (subscribed_topics_.find(topic) != subscribed_topics_.end()) {
171 180 logger_.warning() << "Already subscribed to " << topic << "!";
172 181 return;
173 182 }
... ... @@ -175,13 +184,12 @@ void Subscriber::subscribe(const string topic,
175 184 }
176 185  
177 186 void Subscriber::psubscribe(const string topic,
178   - function<void(const string&, const string&)> msg_callback,
179   - function<void(const string&)> sub_callback,
180   - function<void(const string&)> unsub_callback,
181   - function<void(const string&, int)> err_callback
182   -) {
183   - std::lock_guard<std::mutex> lg(psubscribed_topics_guard_);
184   - if(psubscribed_topics_.find(topic) != psubscribed_topics_.end()) {
  187 + function<void(const string &, const string &)> msg_callback,
  188 + function<void(const string &)> sub_callback,
  189 + function<void(const string &)> unsub_callback,
  190 + function<void(const string &, int)> err_callback) {
  191 + lock_guard<mutex> lg(psubscribed_topics_guard_);
  192 + if (psubscribed_topics_.find(topic) != psubscribed_topics_.end()) {
185 193 logger_.warning() << "Already psubscribed to " << topic << "!";
186 194 return;
187 195 }
... ... @@ -189,23 +197,19 @@ void Subscriber::psubscribe(const string topic,
189 197 }
190 198  
191 199 void Subscriber::unsubscribeBase(const string cmd_name, const string topic,
192   - function<void(const string&, int)> err_callback
193   -) {
194   - rdx_.command<redisReply*>({cmd_name, topic},
195   - [topic, err_callback](Command<redisReply*>& c) {
196   - if(!c.ok()) {
197   - if (err_callback) err_callback(topic, c.status());
198   - return;
199   - }
200   - }
201   - );
  200 + function<void(const string &, int)> err_callback) {
  201 + rdx_.command<redisReply *>({cmd_name, topic}, [topic, err_callback](Command<redisReply *> &c) {
  202 + if (!c.ok()) {
  203 + if (err_callback)
  204 + err_callback(topic, c.status());
  205 + return;
  206 + }
  207 + });
202 208 }
203 209  
204   -void Subscriber::unsubscribe(const string topic,
205   - function<void(const string&, int)> err_callback
206   -) {
207   - std::lock_guard<std::mutex> lg(subscribed_topics_guard_);
208   - if(subscribed_topics_.find(topic) == subscribed_topics_.end()) {
  210 +void Subscriber::unsubscribe(const string topic, function<void(const string &, int)> err_callback) {
  211 + lock_guard<mutex> lg(subscribed_topics_guard_);
  212 + if (subscribed_topics_.find(topic) == subscribed_topics_.end()) {
209 213 logger_.warning() << "Cannot unsubscribe from " << topic << ", not subscribed!";
210 214 return;
211 215 }
... ... @@ -213,10 +217,9 @@ void Subscriber::unsubscribe(const string topic,
213 217 }
214 218  
215 219 void Subscriber::punsubscribe(const string topic,
216   - function<void(const string&, int)> err_callback
217   -) {
218   - std::lock_guard<std::mutex> lg(psubscribed_topics_guard_);
219   - if(psubscribed_topics_.find(topic) == psubscribed_topics_.end()) {
  220 + function<void(const string &, int)> err_callback) {
  221 + lock_guard<mutex> lg(psubscribed_topics_guard_);
  222 + if (psubscribed_topics_.find(topic) == psubscribed_topics_.end()) {
220 223 logger_.warning() << "Cannot punsubscribe from " << topic << ", not psubscribed!";
221 224 return;
222 225 }
... ...
test/test.cpp
... ... @@ -35,7 +35,6 @@ using redox::Command;
35 35 class RedoxTest : public ::testing::Test {
36 36  
37 37 protected:
38   -
39 38 Redox rdx;
40 39  
41 40 RedoxTest() {}
... ... @@ -57,19 +56,18 @@ protected:
57 56 mutex cmd_waiter_lock;
58 57  
59 58 // To make the callback code nicer
60   - template<class ReplyT>
61   - using Callback = std::function<void(Command<ReplyT>&)>;
  59 + template <class ReplyT> using Callback = std::function<void(Command<ReplyT> &)>;
62 60  
63 61 /**
64 62 * Helper function that returns a command callback to print out the
65 63 * command/reply and to test the reply against the provided value.
66 64 */
67   - template<class ReplyT>
68   - Callback<ReplyT> check(const ReplyT& value) {
  65 + template <class ReplyT> Callback<ReplyT> check(const ReplyT &value) {
69 66 cmd_count++;
70   - return [this, value](Command<ReplyT>& c) {
  67 + return [this, value](Command<ReplyT> &c) {
71 68 EXPECT_TRUE(c.ok());
72   - if(c.ok()) EXPECT_EQ(value, c.reply());
  69 + if (c.ok())
  70 + EXPECT_EQ(value, c.reply());
73 71 cmd_count--;
74 72 cmd_waiter.notify_all();
75 73 };
... ... @@ -78,10 +76,10 @@ protected:
78 76 /**
79 77 * Wrapper for the callback that also prints out the command.
80 78 */
81   - template<class ReplyT>
82   - Callback<ReplyT> print(Callback<ReplyT> callback) {
83   - return [callback](Command<ReplyT>& c) {
84   - if(c.ok()) cout << "[ASYNC] " << c.cmd() << ": " << c.reply() << endl;
  79 + template <class ReplyT> Callback<ReplyT> print(Callback<ReplyT> callback) {
  80 + return [callback](Command<ReplyT> &c) {
  81 + if (c.ok())
  82 + cout << "[ASYNC] " << c.cmd() << ": " << c.reply() << endl;
85 83 callback(c);
86 84 };
87 85 }
... ... @@ -89,21 +87,19 @@ protected:
89 87 /**
90 88 * Combination of print and check for simplicity.
91 89 */
92   - template<class ReplyT>
93   - Callback<ReplyT> print_and_check(const ReplyT& value) {
  90 + template <class ReplyT> Callback<ReplyT> print_and_check(const ReplyT &value) {
94 91 return print<ReplyT>(check<ReplyT>(value));
95 92 }
96 93  
97 94 /**
98 95 * Check the error
99 96 */
100   - template<class ReplyT>
101   - Callback<ReplyT> print_and_check_error(const ReplyT& value) {
  97 + template <class ReplyT> Callback<ReplyT> print_and_check_error(const ReplyT &value) {
102 98 cmd_count++;
103   - return [this, value](Command<ReplyT>& c) {
  99 + return [this, value](Command<ReplyT> &c) {
104 100 EXPECT_FALSE(c.ok());
105 101 EXPECT_FALSE(c.lastError().empty());
106   -// EXPECT_EQ(value, c.reply());
  102 + // EXPECT_EQ(value, c.reply());
107 103 cout << c.cmd() << ": " << c.lastError() << endl;
108 104 cmd_count--;
109 105 cmd_waiter.notify_all();
... ... @@ -120,15 +116,13 @@ protected:
120 116 rdx.disconnect();
121 117 }
122 118  
123   - template<class ReplyT>
124   - void check_sync(Command<ReplyT>& c, const ReplyT& value) {
  119 + template <class ReplyT> void check_sync(Command<ReplyT> &c, const ReplyT &value) {
125 120 ASSERT_TRUE(c.ok());
126 121 EXPECT_EQ(c.reply(), value);
127 122 c.free();
128 123 }
129 124  
130   - template<class ReplyT>
131   - void print_and_check_sync(Command<ReplyT>& c, const ReplyT& value) {
  125 + template <class ReplyT> void print_and_check_sync(Command<ReplyT> &c, const ReplyT &value) {
132 126 ASSERT_TRUE(c.ok());
133 127 EXPECT_EQ(c.reply(), value);
134 128 cout << "[SYNC] " << c.cmd() << ": " << c.reply() << endl;
... ... @@ -138,12 +132,11 @@ protected:
138 132 /**
139 133 * Check the error
140 134 */
141   - template<class ReplyT>
142   - void print_and_check_error_sync(Command<ReplyT>& c, const ReplyT& value) {
143   - EXPECT_FALSE(c.ok());
144   - EXPECT_FALSE(c.lastError().empty());
145   -// EXPECT_EQ(value, c.reply());
146   - cout << c.cmd() << ": " << c.lastError() << endl;
  135 + template <class ReplyT> void print_and_check_error_sync(Command<ReplyT> &c, const ReplyT &value) {
  136 + EXPECT_FALSE(c.ok());
  137 + EXPECT_FALSE(c.lastError().empty());
  138 + // EXPECT_EQ(value, c.reply());
  139 + cout << c.cmd() << ": " << c.lastError() << endl;
147 140 }
148 141 };
149 142  
... ... @@ -151,18 +144,14 @@ protected:
151 144 // Core unit tests - asynchronous
152 145 // -------------------------------------------
153 146  
154   -TEST_F(RedoxTest, TestConnection) {
155   - EXPECT_TRUE(rdx.connect("localhost", 6379));
156   -}
  147 +TEST_F(RedoxTest, TestConnection) { EXPECT_TRUE(rdx.connect("localhost", 6379)); }
157 148  
158   -TEST_F(RedoxTest, TestConnectionFailure) {
159   - EXPECT_FALSE(rdx.connect("localhost", 6380));
160   -}
  149 +TEST_F(RedoxTest, TestConnectionFailure) { EXPECT_FALSE(rdx.connect("localhost", 6380)); }
161 150  
162 151 TEST_F(RedoxTest, GetSet) {
163 152 connect();
164 153 rdx.command<string>({"SET", "redox_test:a", "apple"}, print_and_check<string>("OK"));
165   - rdx.command<string>({"GET", "redox_test:a"}, print_and_check<string>("apple"));
  154 + rdx.command<string>({"GET", "redox_test:a"}, print_and_check<string>("apple"));
166 155 wait_for_replies();
167 156 }
168 157  
... ... @@ -177,8 +166,8 @@ TEST_F(RedoxTest, Delete) {
177 166 TEST_F(RedoxTest, Incr) {
178 167 connect();
179 168 int count = 100;
180   - for(int i = 0; i < count; i++) {
181   - rdx.command<int>({"INCR", "redox_test:a"}, check(i+1));
  169 + for (int i = 0; i < count; i++) {
  170 + rdx.command<int>({"INCR", "redox_test:a"}, check(i + 1));
182 171 }
183 172 rdx.command<string>({"GET", "redox_test:a"}, print_and_check(to_string(count)));
184 173 wait_for_replies();
... ... @@ -197,12 +186,8 @@ TEST_F(RedoxTest, Loop) {
197 186 int count = 0;
198 187 int target_count = 20;
199 188 double dt = 0.005;
200   - Command<int>& cmd = rdx.commandLoop<int>({"INCR", "redox_test:a"},
201   - [this, &count](Command<int>& c) {
202   - check(++count)(c);
203   - },
204   - dt
205   - );
  189 + Command<int> &cmd = rdx.commandLoop<int>(
  190 + {"INCR", "redox_test:a"}, [this, &count](Command<int> &c) { check(++count)(c); }, dt);
206 191  
207 192 double wait_time = dt * (target_count - 0.5);
208 193 this_thread::sleep_for(std::chrono::duration<double>(wait_time));
... ... @@ -215,7 +200,7 @@ TEST_F(RedoxTest, Loop) {
215 200 TEST_F(RedoxTest, GetSetError) {
216 201 connect();
217 202 rdx.command<string>({"SET", "redox_test:a", "apple"}, print_and_check<string>("OK"));
218   - rdx.command<int>({"GET", "redox_test:a"}, print_and_check_error<int>(3));
  203 + rdx.command<int>({"GET", "redox_test:a"}, print_and_check_error<int>(3));
219 204 wait_for_replies();
220 205 }
221 206  
... ... @@ -241,8 +226,8 @@ TEST_F(RedoxTest, DeleteSync) {
241 226 TEST_F(RedoxTest, IncrSync) {
242 227 connect();
243 228 int count = 100;
244   - for(int i = 0; i < count; i++) {
245   - check_sync(rdx.commandSync<int>({"INCR", "redox_test:a"}), i+1);
  229 + for (int i = 0; i < count; i++) {
  230 + check_sync(rdx.commandSync<int>({"INCR", "redox_test:a"}), i + 1);
246 231 }
247 232 print_and_check_sync(rdx.commandSync<string>({"GET", "redox_test:a"}), to_string(count));
248 233 rdx.disconnect();
... ... @@ -259,7 +244,7 @@ TEST_F(RedoxTest, GetSetSyncError) {
259 244 // End tests
260 245 // -------------------------------------------
261 246  
262   -} // namespace
  247 +} // namespace
263 248  
264 249 int main(int argc, char **argv) {
265 250 ::testing::InitGoogleTest(&argc, argv);
... ...