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,14 +54,13 @@ static const std::string REDIS_DEFAULT_PATH = "/var/run/redis/redis.sock";
54 class Redox { 54 class Redox {
55 55
56 public: 56 public:
57 -  
58 // Connection states 57 // Connection states
59 static const int NOT_YET_CONNECTED = 0; // Starting state 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 // Core public API 66 // Core public API
@@ -70,10 +69,7 @@ public: @@ -70,10 +69,7 @@ public:
70 /** 69 /**
71 * Constructor. Optionally specify a log stream and a log level. 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 * Disconnects from the Redis server, shuts down the event loop, and cleans up. 75 * Disconnects from the Redis server, shuts down the event loop, and cleans up.
@@ -89,7 +85,7 @@ public: @@ -89,7 +85,7 @@ public:
89 * is off. 85 * is off.
90 * 86 *
91 * Implementation note: When enabled, the event thread calls libev's ev_run in a 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 void noWait(bool state); 90 void noWait(bool state);
95 91
@@ -97,18 +93,15 @@ public: @@ -97,18 +93,15 @@ public:
97 * Connects to Redis over TCP and starts an event loop in a separate thread. Returns 93 * Connects to Redis over TCP and starts an event loop in a separate thread. Returns
98 * true once everything is ready, or false on failure. 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 * Connects to Redis over a unix socket and starts an event loop in a separate 100 * Connects to Redis over a unix socket and starts an event loop in a separate
107 * thread. Returns true once everything is ready, or false on failure. 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 * Disconnect from Redis, shut down the event loop, then return. A simple 107 * Disconnect from Redis, shut down the event loop, then return. A simple
@@ -134,16 +127,14 @@ public: @@ -134,16 +127,14 @@ public:
134 * memory for it is automatically freed when the callback returns. 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 * Asynchronously runs a command and ignores any errors or replies. 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 * Synchronously runs a command, returning the Command object only once 140 * Synchronously runs a command, returning the Command object only once
@@ -151,14 +142,13 @@ public: @@ -151,14 +142,13 @@ public:
151 * calling .free() on the returned Command object. 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 * Synchronously runs a command, returning only once a reply is received 148 * Synchronously runs a command, returning only once a reply is received
159 * or there's an error. Returns true on successful reply, false on error. 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 * Creates an asynchronous command that is run every [repeat] seconds, 154 * Creates an asynchronous command that is run every [repeat] seconds,
@@ -167,13 +157,10 @@ public: @@ -167,13 +157,10 @@ public:
167 * on the returned Command object. 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 * Creates an asynchronous command that is run once after a given 166 * Creates an asynchronous command that is run once after a given
@@ -182,12 +169,9 @@ public: @@ -182,12 +169,9 @@ public:
182 * after the callback returns. 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 // Utility methods 177 // Utility methods
@@ -197,13 +181,13 @@ public: @@ -197,13 +181,13 @@ public:
197 * Given a vector of strings, returns a string of the concatenated elements, separated 181 * Given a vector of strings, returns a string of the concatenated elements, separated
198 * by the delimiter. Useful for printing out a command string from a vector. 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 * Given a command string, returns a vector of strings by splitting the input by 187 * Given a command string, returns a vector of strings by splitting the input by
204 * the delimiter. Useful for turning a string input into a command. 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 // Command wrapper methods for convenience only 193 // Command wrapper methods for convenience only
@@ -213,32 +197,32 @@ public: @@ -213,32 +197,32 @@ public:
213 * Redis GET command wrapper - return the value for the given key, or throw 197 * Redis GET command wrapper - return the value for the given key, or throw
214 * an exception if there is an error. Blocking call. 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 * Redis SET command wrapper - set the value for the given key. Return 203 * Redis SET command wrapper - set the value for the given key. Return
220 * true if succeeded, false if error. Blocking call. 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 * Redis DEL command wrapper - delete the given key. Return true if succeeded, 209 * Redis DEL command wrapper - delete the given key. Return true if succeeded,
226 * false if error. Blocking call. 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 * Redis PUBLISH command wrapper - publish the given message to all subscribers. 215 * Redis PUBLISH command wrapper - publish the given message to all subscribers.
232 * Non-blocking call. 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 // Public members 221 // Public members
238 // ------------------------------------------------ 222 // ------------------------------------------------
239 223
240 // Hiredis context, left public to allow low-level access 224 // Hiredis context, left public to allow low-level access
241 - redisAsyncContext * ctx_; 225 + redisAsyncContext *ctx_;
242 226
243 // TODO make these private 227 // TODO make these private
244 // Redox server over TCP 228 // Redox server over TCP
@@ -252,7 +236,6 @@ public: @@ -252,7 +236,6 @@ public:
252 log::Logger logger_; 236 log::Logger logger_;
253 237
254 private: 238 private:
255 -  
256 // ------------------------------------------------ 239 // ------------------------------------------------
257 // Private methods 240 // Private methods
258 // ------------------------------------------------ 241 // ------------------------------------------------
@@ -262,14 +245,10 @@ private: @@ -262,14 +245,10 @@ private:
262 245
263 // One stop shop for creating commands. The base of all public 246 // One stop shop for creating commands. The base of all public
264 // methods that run commands. 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 // Setup code for the constructors 253 // Setup code for the constructors
275 // Return true on success, false on failure 254 // Return true on success, false on failure
@@ -277,54 +256,48 @@ private: @@ -277,54 +256,48 @@ private:
277 bool initHiredis(); 256 bool initHiredis();
278 257
279 // Callbacks invoked on server connection/disconnection 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 // Main event loop, run in a separate thread 262 // Main event loop, run in a separate thread
284 void runEventLoop(); 263 void runEventLoop();
285 264
286 // Return the command map corresponding to the templated reply type 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 // Return the given Command from the relevant command map, or nullptr if not there 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 // Send all commands in the command queue to the server 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 // Process the command with the given ID. Return true if the command had the 274 // Process the command with the given ID. Return true if the command had the
298 // templated type, and false if it was not in the command map of that type. 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 // Callback given to libev for a Command's timer watcher, to be processed in 278 // Callback given to libev for a Command's timer watcher, to be processed in
303 // a deferred or looping state 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 // Submit an asynchronous command to the Redox server. Return 283 // Submit an asynchronous command to the Redox server. Return
308 // true if succeeded, false otherwise. 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 // Callback given to hiredis to invoke when a reply is received 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 // Free all commands in the commands_to_free_ queue 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 // Free the command with the given ID. Return true if the command had the templated 294 // Free the command with the given ID. Return true if the command had the templated
320 // type, and false if it was not in the command map of that type. 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 // Invoked by Command objects when they are completed. Removes them 298 // Invoked by Command objects when they are completed. Removes them
325 // from the command map. 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 std::lock_guard<std::mutex> lg1(command_map_guard_); 301 std::lock_guard<std::mutex> lg1(command_map_guard_);
329 getCommandMap<ReplyT>().erase(id); 302 getCommandMap<ReplyT>().erase(id);
330 commands_deleted_ += 1; 303 commands_deleted_ += 1;
@@ -334,8 +307,7 @@ private: @@ -334,8 +307,7 @@ private:
334 long freeAllCommands(); 307 long freeAllCommands();
335 308
336 // Helper function for freeAllCommands to access a specific command map 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 // Private members 313 // Private members
@@ -350,15 +322,15 @@ private: @@ -350,15 +322,15 @@ private:
350 std::function<void(int)> user_connection_callback_; 322 std::function<void(int)> user_connection_callback_;
351 323
352 // Dynamically allocated libev event loop 324 // Dynamically allocated libev event loop
353 - struct ev_loop* evloop_; 325 + struct ev_loop *evloop_;
354 326
355 // No-wait mode for high-performance 327 // No-wait mode for high-performance
356 std::atomic_bool nowait_ = {false}; 328 std::atomic_bool nowait_ = {false};
357 329
358 // Asynchronous watchers 330 // Asynchronous watchers
359 ev_async watcher_command_; // For processing commands 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 // Track of Command objects allocated. Also provides unique Command IDs. 335 // Track of Command objects allocated. Also provides unique Command IDs.
364 std::atomic_long commands_created_ = {0}; 336 std::atomic_long commands_created_ = {0};
@@ -374,7 +346,7 @@ private: @@ -374,7 +346,7 @@ private:
374 346
375 // Variable and CV to know when the event loop stops running 347 // Variable and CV to know when the event loop stops running
376 std::atomic_bool to_exit_ = {false}; // Signal to exit 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 std::mutex exit_waiter_lock_; 350 std::mutex exit_waiter_lock_;
379 std::condition_variable exit_waiter_; 351 std::condition_variable exit_waiter_;
380 352
@@ -385,15 +357,16 @@ private: @@ -385,15 +357,16 @@ private:
385 // template<class ReplyT> 357 // template<class ReplyT>
386 // std::unordered_map<long, Command<ReplyT>*> commands_; 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 std::mutex command_map_guard_; // Guards access to all of the above 370 std::mutex command_map_guard_; // Guards access to all of the above
398 371
399 // Command IDs pending to be sent to the server 372 // Command IDs pending to be sent to the server
@@ -406,36 +379,28 @@ private: @@ -406,36 +379,28 @@ private:
406 379
407 // Commands use this method to deregister themselves from Redox, 380 // Commands use this method to deregister themselves from Redox,
408 // give it access to private members 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 // Access to call disconnectedCallback 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 // Implementation of templated methods 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 throw std::runtime_error("[ERROR] Need to connect Redox before running commands!"); 398 throw std::runtime_error("[ERROR] Need to connect Redox before running commands!");
432 } 399 }
433 400
434 commands_created_ += 1; 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 std::lock_guard<std::mutex> lg(queue_guard_); 405 std::lock_guard<std::mutex> lg(queue_guard_);
441 std::lock_guard<std::mutex> lg2(command_map_guard_); 406 std::lock_guard<std::mutex> lg2(command_map_guard_);
@@ -449,36 +414,27 @@ Command&lt;ReplyT&gt;&amp; Redox::createCommand( @@ -449,36 +414,27 @@ Command&lt;ReplyT&gt;&amp; Redox::createCommand(
449 return *c; 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 createCommand(cmd, callback); 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 return createCommand(cmd, callback, repeat, after, false); 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 createCommand(cmd, callback, 0, after, true); 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 c.wait(); 438 c.wait();
483 return c; 439 return c;
484 } 440 }
include/redox/command.hpp
@@ -42,19 +42,17 @@ class Redox; @@ -42,19 +42,17 @@ class Redox;
42 * represent a deferred or looping command, in which case the success or 42 * represent a deferred or looping command, in which case the success or
43 * error callbacks are invoked more than once. 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 public: 47 public:
49 -  
50 // Reply codes 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 static const int ERROR_REPLY = 2; // Got an error reply 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 * Returns the reply status of this command. 58 * Returns the reply status of this command.
@@ -94,7 +92,7 @@ public: @@ -94,7 +92,7 @@ public:
94 std::string cmd() const; 92 std::string cmd() const;
95 93
96 // Allow public access to constructed data 94 // Allow public access to constructed data
97 - Redox* const rdx_; 95 + Redox *const rdx_;
98 const long id_; 96 const long id_;
99 const std::vector<std::string> cmd_; 97 const std::vector<std::string> cmd_;
100 const double repeat_; 98 const double repeat_;
@@ -102,26 +100,22 @@ public: @@ -102,26 +100,22 @@ public:
102 const bool free_memory_; 100 const bool free_memory_;
103 101
104 private: 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 // Handles a new reply from the server 107 // Handles a new reply from the server
117 - void processReply(redisReply* r); 108 + void processReply(redisReply *r);
118 109
119 // Invoke a user callback from the reply object. This method is specialized 110 // Invoke a user callback from the reply object. This method is specialized
120 // for each ReplyT of Command. 111 // for each ReplyT of Command.
121 void parseReplyObject(); 112 void parseReplyObject();
122 113
123 // Directly invoke the user callback if it exists 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 bool checkErrorReply(); 120 bool checkErrorReply();
127 bool checkNilReply(); 121 bool checkNilReply();
@@ -132,10 +126,10 @@ private: @@ -132,10 +126,10 @@ private:
132 void freeReply(); 126 void freeReply();
133 127
134 // The last server reply 128 // The last server reply
135 - redisReply* reply_obj_ = nullptr; 129 + redisReply *reply_obj_ = nullptr;
136 130
137 // User callback 131 // User callback
138 - const std::function<void(Command<ReplyT>&)> callback_; 132 + const std::function<void(Command<ReplyT> &)> callback_;
139 133
140 // Place to store the reply value and status. 134 // Place to store the reply value and status.
141 ReplyT reply_val_; 135 ReplyT reply_val_;
@@ -161,13 +155,13 @@ private: @@ -161,13 +155,13 @@ private:
161 std::atomic_bool waiting_done_ = {false}; 155 std::atomic_bool waiting_done_ = {false};
162 156
163 // Passed on from Redox class 157 // Passed on from Redox class
164 - log::Logger& logger_; 158 + log::Logger &logger_;
165 159
166 // Explicitly delete copy constructor and assignment operator, 160 // Explicitly delete copy constructor and assignment operator,
167 // Command objects should never be copied because they hold 161 // Command objects should never be copied because they hold
168 // state with a network resource. 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 friend class Redox; 166 friend class Redox;
173 }; 167 };
include/redox/subscriber.hpp
@@ -27,14 +27,10 @@ namespace redox { @@ -27,14 +27,10 @@ namespace redox {
27 class Subscriber { 27 class Subscriber {
28 28
29 public: 29 public:
30 -  
31 /** 30 /**
32 * Constructor. Same as Redox. 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 * Cleans up. 36 * Cleans up.
@@ -49,19 +45,16 @@ public: @@ -49,19 +45,16 @@ public:
49 /** 45 /**
50 * Same as .connect() on a Redox instance. 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 return rdx_.connect(host, port, connection_callback); 50 return rdx_.connect(host, port, connection_callback);
57 } 51 }
58 52
59 /** 53 /**
60 * Same as .connectUnix() on a Redox instance. 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 return rdx_.connectUnix(path, connection_callback); 58 return rdx_.connectUnix(path, connection_callback);
66 } 59 }
67 60
@@ -88,11 +81,10 @@ public: @@ -88,11 +81,10 @@ public:
88 * err_callback: invoked on some error state 81 * err_callback: invoked on some error state
89 */ 82 */
90 void subscribe(const std::string topic, 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 * Subscribe to a topic with a pattern. 90 * Subscribe to a topic with a pattern.
@@ -102,11 +94,10 @@ public: @@ -102,11 +94,10 @@ public:
102 * err_callback: invoked on some error state 94 * err_callback: invoked on some error state
103 */ 95 */
104 void psubscribe(const std::string topic, 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 * Unsubscribe from a topic. 103 * Unsubscribe from a topic.
@@ -114,8 +105,7 @@ public: @@ -114,8 +105,7 @@ public:
114 * err_callback: invoked on some error state 105 * err_callback: invoked on some error state
115 */ 106 */
116 void unsubscribe(const std::string topic, 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 * Unsubscribe from a topic with a pattern. 111 * Unsubscribe from a topic with a pattern.
@@ -123,8 +113,7 @@ public: @@ -123,8 +113,7 @@ public:
123 * err_callback: invoked on some error state 113 * err_callback: invoked on some error state
124 */ 114 */
125 void punsubscribe(const std::string topic, 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 * Return the topics that are subscribed() to. 119 * Return the topics that are subscribed() to.
@@ -143,19 +132,16 @@ public: @@ -143,19 +132,16 @@ public:
143 } 132 }
144 133
145 private: 134 private:
146 -  
147 // Base for subscribe and psubscribe 135 // Base for subscribe and psubscribe
148 void subscribeBase(const std::string cmd_name, const std::string topic, 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 // Base for unsubscribe and punsubscribe 142 // Base for unsubscribe and punsubscribe
156 void unsubscribeBase(const std::string cmd_name, const std::string topic, 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 // Underlying Redis client 146 // Underlying Redis client
161 Redox rdx_; 147 Redox rdx_;
@@ -170,10 +156,10 @@ private: @@ -170,10 +156,10 @@ private:
170 std::mutex psubscribed_topics_guard_; 156 std::mutex psubscribed_topics_guard_;
171 157
172 // Set of persisting commands, so that we can cancel them 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 // Reference to rdx_.logger_ for convenience 161 // Reference to rdx_.logger_ for convenience
176 - log::Logger& logger_; 162 + log::Logger &logger_;
177 163
178 // CVs to wait for unsubscriptions 164 // CVs to wait for unsubscriptions
179 std::condition_variable cv_unsub_; 165 std::condition_variable cv_unsub_;
src/client.cpp
@@ -26,63 +26,56 @@ using namespace std; @@ -26,63 +26,56 @@ using namespace std;
26 26
27 namespace redox { 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 host_ = host; 35 host_ = host;
40 port_ = port; 36 port_ = port;
41 user_connection_callback_ = connection_callback; 37 user_connection_callback_ = connection_callback;
42 38
43 - if(!initEv()) return false; 39 + if (!initEv())
  40 + return false;
44 41
45 // Connect over TCP 42 // Connect over TCP
46 ctx_ = redisAsyncConnect(host.c_str(), port); 43 ctx_ = redisAsyncConnect(host.c_str(), port);
47 44
48 - if(!initHiredis()) return false; 45 + if (!initHiredis())
  46 + return false;
49 47
50 event_loop_thread_ = thread([this] { runEventLoop(); }); 48 event_loop_thread_ = thread([this] { runEventLoop(); });
51 49
52 // Block until connected and running the event loop, or until 50 // Block until connected and running the event loop, or until
53 // a connection error happens and the event loop exits 51 // a connection error happens and the event loop exits
54 unique_lock<mutex> ul(running_waiter_lock_); 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 // Return if succeeded 55 // Return if succeeded
60 return connect_state_ == CONNECTED; 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 path_ = path; 61 path_ = path;
69 user_connection_callback_ = connection_callback; 62 user_connection_callback_ = connection_callback;
70 63
71 - if(!initEv()) return false; 64 + if (!initEv())
  65 + return false;
72 66
73 // Connect over unix sockets 67 // Connect over unix sockets
74 ctx_ = redisAsyncConnectUnix(path.c_str()); 68 ctx_ = redisAsyncConnectUnix(path.c_str());
75 69
76 - if(!initHiredis()) return false; 70 + if (!initHiredis())
  71 + return false;
77 72
78 event_loop_thread_ = thread([this] { runEventLoop(); }); 73 event_loop_thread_ = thread([this] { runEventLoop(); });
79 74
80 // Block until connected and running the event loop, or until 75 // Block until connected and running the event loop, or until
81 // a connection error happens and the event loop exits 76 // a connection error happens and the event loop exits
82 unique_lock<mutex> ul(running_waiter_lock_); 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 // Return if succeeded 80 // Return if succeeded
88 return connect_state_ == CONNECTED; 81 return connect_state_ == CONNECTED;
@@ -107,16 +100,20 @@ void Redox::wait() { @@ -107,16 +100,20 @@ void Redox::wait() {
107 Redox::~Redox() { 100 Redox::~Redox() {
108 101
109 // Bring down the event loop 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 if (status != REDIS_OK) { 118 if (status != REDIS_OK) {
122 rdx->logger_.fatal() << "Could not connect to Redis: " << ctx->errstr; 119 rdx->logger_.fatal() << "Could not connect to Redis: " << ctx->errstr;
@@ -131,12 +128,13 @@ void Redox::connectedCallback(const redisAsyncContext* ctx, int status) { @@ -131,12 +128,13 @@ void Redox::connectedCallback(const redisAsyncContext* ctx, int status) {
131 } 128 }
132 129
133 rdx->connect_waiter_.notify_all(); 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 if (status != REDIS_OK) { 139 if (status != REDIS_OK) {
142 rdx->logger_.error() << "Disconnected from Redis on error: " << ctx->errstr; 140 rdx->logger_.error() << "Disconnected from Redis on error: " << ctx->errstr;
@@ -148,25 +146,26 @@ void Redox::disconnectedCallback(const redisAsyncContext* ctx, int status) { @@ -148,25 +146,26 @@ void Redox::disconnectedCallback(const redisAsyncContext* ctx, int status) {
148 146
149 rdx->stop(); 147 rdx->stop();
150 rdx->connect_waiter_.notify_all(); 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 bool Redox::initEv() { 153 bool Redox::initEv() {
155 signal(SIGPIPE, SIG_IGN); 154 signal(SIGPIPE, SIG_IGN);
156 evloop_ = ev_loop_new(EVFLAG_AUTO); 155 evloop_ = ev_loop_new(EVFLAG_AUTO);
157 - if(evloop_ == nullptr) { 156 + if (evloop_ == nullptr) {
158 logger_.fatal() << "Could not create a libev event loop."; 157 logger_.fatal() << "Could not create a libev event loop.";
159 connect_state_ = INIT_ERROR; 158 connect_state_ = INIT_ERROR;
160 connect_waiter_.notify_all(); 159 connect_waiter_.notify_all();
161 return false; 160 return false;
162 } 161 }
163 - ev_set_userdata(evloop_, (void*)this); // Back-reference 162 + ev_set_userdata(evloop_, (void *)this); // Back-reference
164 return true; 163 return true;
165 } 164 }
166 165
167 bool Redox::initHiredis() { 166 bool Redox::initHiredis() {
168 167
169 - ctx_->data = (void*)this; // Back-reference 168 + ctx_->data = (void *)this; // Back-reference
170 169
171 if (ctx_->err) { 170 if (ctx_->err) {
172 logger_.fatal() << "Could not create a hiredis context: " << ctx_->errstr; 171 logger_.fatal() << "Could not create a hiredis context: " << ctx_->errstr;
@@ -176,7 +175,7 @@ bool Redox::initHiredis() { @@ -176,7 +175,7 @@ bool Redox::initHiredis() {
176 } 175 }
177 176
178 // Attach event loop to hiredis 177 // Attach event loop to hiredis
179 - if(redisLibevAttach(evloop_, ctx_) != REDIS_OK) { 178 + if (redisLibevAttach(evloop_, ctx_) != REDIS_OK) {
180 logger_.fatal() << "Could not attach libev event loop to hiredis."; 179 logger_.fatal() << "Could not attach libev event loop to hiredis.";
181 connect_state_ = INIT_ERROR; 180 connect_state_ = INIT_ERROR;
182 connect_waiter_.notify_all(); 181 connect_waiter_.notify_all();
@@ -184,14 +183,14 @@ bool Redox::initHiredis() { @@ -184,14 +183,14 @@ bool Redox::initHiredis() {
184 } 183 }
185 184
186 // Set the callbacks to be invoked on server connection/disconnection 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 logger_.fatal() << "Could not attach connect callback to hiredis."; 187 logger_.fatal() << "Could not attach connect callback to hiredis.";
189 connect_state_ = INIT_ERROR; 188 connect_state_ = INIT_ERROR;
190 connect_waiter_.notify_all(); 189 connect_waiter_.notify_all();
191 return false; 190 return false;
192 } 191 }
193 192
194 - if(redisAsyncSetDisconnectCallback(ctx_, Redox::disconnectedCallback) != REDIS_OK) { 193 + if (redisAsyncSetDisconnectCallback(ctx_, Redox::disconnectedCallback) != REDIS_OK) {
195 logger_.fatal() << "Could not attach disconnect callback to hiredis."; 194 logger_.fatal() << "Could not attach disconnect callback to hiredis.";
196 connect_state_ = INIT_ERROR; 195 connect_state_ = INIT_ERROR;
197 connect_waiter_.notify_all(); 196 connect_waiter_.notify_all();
@@ -202,12 +201,14 @@ bool Redox::initHiredis() { @@ -202,12 +201,14 @@ bool Redox::initHiredis() {
202 } 201 }
203 202
204 void Redox::noWait(bool state) { 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 nowait_ = state; 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 ev_break(loop, EVBREAK_ALL); 212 ev_break(loop, EVBREAK_ALL);
212 } 213 }
213 214
@@ -222,7 +223,7 @@ void Redox::runEventLoop() { @@ -222,7 +223,7 @@ void Redox::runEventLoop() {
222 connect_waiter_.wait(ul, [this] { return connect_state_ != NOT_YET_CONNECTED; }); 223 connect_waiter_.wait(ul, [this] { return connect_state_ != NOT_YET_CONNECTED; });
223 224
224 // Handle connection error 225 // Handle connection error
225 - if(connect_state_ != CONNECTED) { 226 + if (connect_state_ != CONNECTED) {
226 logger_.warning() << "Did not connect, event loop exiting."; 227 logger_.warning() << "Did not connect, event loop exiting.";
227 exited_ = true; 228 exited_ = true;
228 running_ = false; 229 running_ = false;
@@ -250,7 +251,7 @@ void Redox::runEventLoop() { @@ -250,7 +251,7 @@ void Redox::runEventLoop() {
250 // Run the event loop, using NOWAIT if enabled for maximum 251 // Run the event loop, using NOWAIT if enabled for maximum
251 // throughput by avoiding any sleeping 252 // throughput by avoiding any sleeping
252 while (!to_exit_) { 253 while (!to_exit_) {
253 - if(nowait_) { 254 + if (nowait_) {
254 ev_run(evloop_, EVRUN_NOWAIT); 255 ev_run(evloop_, EVRUN_NOWAIT);
255 } else { 256 } else {
256 ev_run(evloop_); 257 ev_run(evloop_);
@@ -266,14 +267,15 @@ void Redox::runEventLoop() { @@ -266,14 +267,15 @@ void Redox::runEventLoop() {
266 this_thread::sleep_for(chrono::milliseconds(10)); 267 this_thread::sleep_for(chrono::milliseconds(10));
267 ev_run(evloop_, EVRUN_NOWAIT); 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 // Run once more to disconnect 273 // Run once more to disconnect
272 ev_run(evloop_, EVRUN_NOWAIT); 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 exited_ = true; 281 exited_ = true;
@@ -285,27 +287,26 @@ void Redox::runEventLoop() { @@ -285,27 +287,26 @@ void Redox::runEventLoop() {
285 logger_.info() << "Event thread exited."; 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 lock_guard<mutex> lg(command_map_guard_); 292 lock_guard<mutex> lg(command_map_guard_);
292 293
293 - auto& command_map = getCommandMap<ReplyT>(); 294 + auto &command_map = getCommandMap<ReplyT>();
294 auto it = command_map.find(id); 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 return it->second; 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 long id = (long)privdata; 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 freeReplyObject(reply_obj); 310 freeReplyObject(reply_obj);
310 return; 311 return;
311 } 312 }
@@ -313,26 +314,23 @@ void Redox::commandCallback(redisAsyncContext* ctx, void* r, void* privdata) { @@ -313,26 +314,23 @@ void Redox::commandCallback(redisAsyncContext* ctx, void* r, void* privdata) {
313 c->processReply(reply_obj); 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 c->pending_++; 320 c->pending_++;
321 321
322 // Construct a char** from the vector 322 // Construct a char** from the vector
323 - vector<const char*> argv; 323 + vector<const char *> argv;
324 transform(c->cmd_.begin(), c->cmd_.end(), back_inserter(argv), 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 // Construct a size_t* of string lengths from the vector 327 // Construct a size_t* of string lengths from the vector
329 vector<size_t> argvlen; 328 vector<size_t> argvlen;
330 transform(c->cmd_.begin(), c->cmd_.end(), back_inserter(argvlen), 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 rdx->logger_.error() << "Could not send \"" << c->cmd() << "\": " << rdx->ctx_->errstr; 334 rdx->logger_.error() << "Could not send \"" << c->cmd() << "\": " << rdx->ctx_->errstr;
337 c->reply_status_ = Command<ReplyT>::SEND_ERROR; 335 c->reply_status_ = Command<ReplyT>::SEND_ERROR;
338 c->invoke(); 336 c->invoke();
@@ -342,34 +340,34 @@ bool Redox::submitToServer(Command&lt;ReplyT&gt;* c) { @@ -342,34 +340,34 @@ bool Redox::submitToServer(Command&lt;ReplyT&gt;* c) {
342 return true; 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 long id = (long)timer->data; 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 rdx->logger_.error() << "Couldn't find Command " << id 351 rdx->logger_.error() << "Couldn't find Command " << id
354 - << " in command_map (submitCommandCallback)."; 352 + << " in command_map (submitCommandCallback).";
355 return; 353 return;
356 } 354 }
357 355
358 submitToServer<ReplyT>(c); 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 submitToServer<ReplyT>(c); 366 submitToServer<ReplyT>(c);
369 367
370 } else { 368 } else {
371 369
372 - c->timer_.data = (void*)c->id_; 370 + c->timer_.data = (void *)c->id_;
373 ev_timer_init(&c->timer_, submitCommandCallback<ReplyT>, c->after_, c->repeat_); 371 ev_timer_init(&c->timer_, submitCommandCallback<ReplyT>, c->after_, c->repeat_);
374 ev_timer_start(evloop_, &c->timer_); 372 ev_timer_start(evloop_, &c->timer_);
375 373
@@ -379,62 +377,64 @@ bool Redox::processQueuedCommand(long id) { @@ -379,62 +377,64 @@ bool Redox::processQueuedCommand(long id) {
379 return true; 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 lock_guard<mutex> lg(rdx->queue_guard_); 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 long id = rdx->command_queue_.front(); 388 long id = rdx->command_queue_.front();
391 rdx->command_queue_.pop(); 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 lock_guard<mutex> lg(rdx->free_queue_guard_); 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 long id = rdx->commands_to_free_.front(); 412 long id = rdx->commands_to_free_.front();
414 rdx->commands_to_free_.pop(); 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 c->freeReply(); 434 c->freeReply();
435 435
436 // Stop the libev timer if this is a repeating command 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 lock_guard<mutex> lg(c->timer_guard_); 438 lock_guard<mutex> lg(c->timer_guard_);
439 ev_timer_stop(c->rdx_->evloop_, &c->timer_); 439 ev_timer_stop(c->rdx_->evloop_, &c->timer_);
440 } 440 }
@@ -447,33 +447,28 @@ bool Redox::freeQueuedCommand(long id) { @@ -447,33 +447,28 @@ bool Redox::freeQueuedCommand(long id) {
447 } 447 }
448 448
449 long Redox::freeAllCommands() { 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 lock_guard<mutex> lg(free_queue_guard_); 459 lock_guard<mutex> lg(free_queue_guard_);
465 lock_guard<mutex> lg2(queue_guard_); 460 lock_guard<mutex> lg2(queue_guard_);
466 461
467 - auto& command_map = getCommandMap<ReplyT>(); 462 + auto &command_map = getCommandMap<ReplyT>();
468 long len = command_map.size(); 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 c->freeReply(); 468 c->freeReply();
474 469
475 // Stop the libev timer if this is a repeating command 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 lock_guard<mutex> lg3(c->timer_guard_); 472 lock_guard<mutex> lg3(c->timer_guard_);
478 ev_timer_stop(c->rdx_->evloop_, &c->timer_); 473 ev_timer_stop(c->rdx_->evloop_, &c->timer_);
479 } 474 }
@@ -491,89 +486,95 @@ long Redox::freeAllCommandsOfType() { @@ -491,89 +486,95 @@ long Redox::freeAllCommandsOfType() {
491 // get_command_map specializations 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 // Helpers 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 string str; 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 str += vec[i] + delimiter; 534 str += vec[i] + delimiter;
529 - str += vec[vec.size()-1]; 535 + str += vec[vec.size() - 1];
530 return str; 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 vector<string> vec; 540 vector<string> vec;
535 size_t last = 0; 541 size_t last = 0;
536 size_t next = 0; 542 size_t next = 0;
537 while ((next = s.find(delimiter, last)) != string::npos) { 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 last = next + 1; 545 last = next + 1;
540 } 546 }
541 vec.push_back(s.substr(last)); 547 vec.push_back(s.substr(last));
542 return vec; 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 bool succeeded = c.ok(); 555 bool succeeded = c.ok();
552 c.free(); 556 c.free();
553 return succeeded; 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 string reply = c.reply(); 567 string reply = c.reply();
563 c.free(); 568 c.free();
564 return reply; 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 } // End namespace redis 580 } // End namespace redis
src/command.cpp
@@ -29,32 +29,27 @@ using namespace std; @@ -29,32 +29,27 @@ using namespace std;
29 29
30 namespace redox { 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 timer_guard_.lock(); 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 waiter_.wait(lk, [this]() { return waiting_done_.load(); }); 43 waiter_.wait(lk, [this]() { return waiting_done_.load(); });
48 waiting_done_ = {false}; 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 last_error_.clear(); 49 last_error_.clear();
55 reply_obj_ = r; 50 reply_obj_ = r;
56 51
57 - if(reply_obj_ == nullptr) { 52 + if (reply_obj_ == nullptr) {
58 reply_status_ = ERROR_REPLY; 53 reply_status_ = ERROR_REPLY;
59 last_error_ = "Received null redisReply* from hiredis."; 54 last_error_ = "Received null redisReply* from hiredis.";
60 logger_.error() << last_error_; 55 logger_.error() << last_error_;
@@ -73,34 +68,35 @@ void Command&lt;ReplyT&gt;::processReply(redisReply* r) { @@ -73,34 +68,35 @@ void Command&lt;ReplyT&gt;::processReply(redisReply* r) {
73 waiter_.notify_all(); 68 waiter_.notify_all();
74 69
75 // Always free the reply object for repeating commands 70 // Always free the reply object for repeating commands
76 - if(repeat_ > 0) { 71 + if (repeat_ > 0) {
77 freeReply(); 72 freeReply();
78 73
79 } else { 74 } else {
80 75
81 // User calls .free() 76 // User calls .free()
82 - if (!free_memory_) return; 77 + if (!free_memory_)
  78 + return;
83 79
84 // Free non-repeating commands automatically 80 // Free non-repeating commands automatically
85 // once we receive expected replies 81 // once we receive expected replies
86 - if(pending_ == 0) free(); 82 + if (pending_ == 0)
  83 + free();
87 } 84 }
88 } 85 }
89 86
90 // This is the only method in Command that has 87 // This is the only method in Command that has
91 // access to private members of Redox 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 lock_guard<mutex> lg(rdx_->free_queue_guard_); 91 lock_guard<mutex> lg(rdx_->free_queue_guard_);
96 rdx_->commands_to_free_.push(id_); 92 rdx_->commands_to_free_.push(id_);
97 ev_async_send(rdx_->evloop_, &rdx_->watcher_free_); 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 freeReplyObject(reply_obj_); 101 freeReplyObject(reply_obj_);
106 reply_obj_ = nullptr; 102 reply_obj_ = nullptr;
@@ -111,60 +107,55 @@ void Command&lt;ReplyT&gt;::freeReply() { @@ -111,60 +107,55 @@ void Command&lt;ReplyT&gt;::freeReply() {
111 * to make sure we don't return a reply while it is being 107 * to make sure we don't return a reply while it is being
112 * modified. 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 if (!ok()) { 112 if (!ok()) {
118 logger_.warning() << cmd() << ": Accessing reply value while status != OK."; 113 logger_.warning() << cmd() << ": Accessing reply value while status != OK.";
119 } 114 }
120 return reply_val_; 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 reply_status_ = OK_REPLY; 123 reply_status_ = OK_REPLY;
133 return true; 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 last_error_ = errorMessage.str(); 133 last_error_ = errorMessage.str();
142 logger_.error() << cmd() << ": " << last_error_; 134 logger_.error() << cmd() << ": " << last_error_;
143 reply_status_ = WRONG_TYPE; 135 reply_status_ = WRONG_TYPE;
144 return false; 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 reply_status_ = OK_REPLY; 142 reply_status_ = OK_REPLY;
152 return true; 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 last_error_ = errorMessage.str(); 152 last_error_ = errorMessage.str();
161 logger_.error() << cmd() << ": " << last_error_; 153 logger_.error() << cmd() << ": " << last_error_;
162 reply_status_ = WRONG_TYPE; 154 reply_status_ = WRONG_TYPE;
163 return false; 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 if (reply_obj_->type == REDIS_REPLY_ERROR) { 160 if (reply_obj_->type == REDIS_REPLY_ERROR) {
170 if (reply_obj_->str != 0) { 161 if (reply_obj_->str != 0) {
@@ -178,8 +169,7 @@ bool Command&lt;ReplyT&gt;::checkErrorReply() { @@ -178,8 +169,7 @@ bool Command&lt;ReplyT&gt;::checkErrorReply() {
178 return false; 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 if (reply_obj_->type == REDIS_REPLY_NIL) { 174 if (reply_obj_->type == REDIS_REPLY_NIL) {
185 logger_.warning() << cmd() << ": Nil reply."; 175 logger_.warning() << cmd() << ": Nil reply.";
@@ -193,74 +183,74 @@ bool Command&lt;ReplyT&gt;::checkNilReply() { @@ -193,74 +183,74 @@ bool Command&lt;ReplyT&gt;::checkNilReply() {
193 // Specializations of parseReplyObject for all expected return types 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 reply_val_ = reply_obj_; 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 reply_val_ = {reply_obj_->str, static_cast<size_t>(reply_obj_->len)}; 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 reply_val_ = reply_obj_->str; 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 reply_val_ = reply_obj_->integer; 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 reply_val_ = nullptr; 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 reply_val_.emplace_back(r->str, r->len); 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 reply_val_.emplace(r->str, r->len); 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 reply_val_.emplace(r->str, r->len); 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,9 +258,9 @@ void Command&lt;set&lt;string&gt;&gt;::parseReplyObject() {
268 // Explicit template instantiation for available types, so that the generated 258 // Explicit template instantiation for available types, so that the generated
269 // library contains them and we can keep the method definitions out of the 259 // library contains them and we can keep the method definitions out of the
270 // header file. 260 // header file.
271 -template class Command<redisReply*>; 261 +template class Command<redisReply *>;
272 template class Command<string>; 262 template class Command<string>;
273 -template class Command<char*>; 263 +template class Command<char *>;
274 template class Command<int>; 264 template class Command<int>;
275 template class Command<long long int>; 265 template class Command<long long int>;
276 template class Command<nullptr_t>; 266 template class Command<nullptr_t>;
src/subscriber.cpp
@@ -25,9 +25,8 @@ using namespace std; @@ -25,9 +25,8 @@ using namespace std;
25 25
26 namespace redox { 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 Subscriber::~Subscriber() {} 31 Subscriber::~Subscriber() {}
33 32
@@ -36,9 +35,7 @@ void Subscriber::disconnect() { @@ -36,9 +35,7 @@ void Subscriber::disconnect() {
36 wait(); 35 wait();
37 } 36 }
38 37
39 -void Subscriber::wait() {  
40 - rdx_.wait();  
41 -} 38 +void Subscriber::wait() { rdx_.wait(); }
42 39
43 // This is a fairly awkward way of shutting down, where 40 // This is a fairly awkward way of shutting down, where
44 // we pause to wait for subscriptions to happen, and then 41 // we pause to wait for subscriptions to happen, and then
@@ -46,114 +43,127 @@ void Subscriber::wait() { @@ -46,114 +43,127 @@ void Subscriber::wait() {
46 // The reason is because hiredis goes into 43 // The reason is because hiredis goes into
47 // a segfault in freeReplyObject() under redisAsyncDisconnect() 44 // a segfault in freeReplyObject() under redisAsyncDisconnect()
48 // if we don't do this first. 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 void Subscriber::stop() { 47 void Subscriber::stop() {
51 48
52 this_thread::sleep_for(chrono::milliseconds(1000)); 49 this_thread::sleep_for(chrono::milliseconds(1000));
53 50
54 - for(const string& topic : subscribedTopics()) 51 + for (const string &topic : subscribedTopics())
55 unsubscribe(topic); 52 unsubscribe(topic);
56 53
57 - for(const string& topic : psubscribedTopics()) 54 + for (const string &topic : psubscribedTopics())
58 punsubscribe(topic); 55 punsubscribe(topic);
59 56
60 unique_lock<mutex> ul(cv_unsub_guard_); 57 unique_lock<mutex> ul(cv_unsub_guard_);
61 cv_unsub_.wait(ul, [this] { 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 return (subscribed_topics_.size() == 0); 60 return (subscribed_topics_.size() == 0);
64 }); 61 });
65 62
66 unique_lock<mutex> ul2(cv_punsub_guard_); 63 unique_lock<mutex> ul2(cv_punsub_guard_);
67 cv_punsub_.wait(ul, [this] { 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 return (psubscribed_topics_.size() == 0); 66 return (psubscribed_topics_.size() == 0);
70 }); 67 });
71 68
72 - for(Command<redisReply*>* c : commands_) 69 + for (Command<redisReply *> *c : commands_)
73 c->free(); 70 c->free();
74 71
75 rdx_.stop(); 72 rdx_.stop();
76 } 73 }
77 74
78 // For debugging only 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 cout << "------" << endl; 80 cout << "------" << endl;
84 cout << c.cmd() << " " << (reply->type == REDIS_REPLY_ARRAY) << " " << (reply->elements) << endl; 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 cout << "element " << i << ", reply type = " << r->type << " "; 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 cout << "------" << endl; 92 cout << "------" << endl;
93 } 93 }
94 94
95 void Subscriber::subscribeBase(const string cmd_name, const string topic, 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 if (!c.ok()) { 106 if (!c.ok()) {
106 num_pending_subs_--; 107 num_pending_subs_--;
107 - if (err_callback) err_callback(topic, c.status()); 108 + if (err_callback)
  109 + err_callback(topic, c.status());
108 return; 110 return;
109 } 111 }
110 112
111 - redisReply* reply = c.reply(); 113 + redisReply *reply = c.reply();
112 114
113 // If the last entry is an integer, then it is a [p]sub/[p]unsub command 115 // If the last entry is an integer, then it is a [p]sub/[p]unsub command
114 if ((reply->type == REDIS_REPLY_ARRAY) && 116 if ((reply->type == REDIS_REPLY_ARRAY) &&
115 (reply->element[reply->elements - 1]->type == REDIS_REPLY_INTEGER)) { 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 if (!strncmp(reply->element[0]->str, "sub", 3)) { 122 if (!strncmp(reply->element[0]->str, "sub", 3)) {
121 subscribed_topics_.insert(topic); 123 subscribed_topics_.insert(topic);
122 num_pending_subs_--; 124 num_pending_subs_--;
123 - if (sub_callback) sub_callback(topic); 125 + if (sub_callback)
  126 + sub_callback(topic);
124 } else if (!strncmp(reply->element[0]->str, "psub", 4)) { 127 } else if (!strncmp(reply->element[0]->str, "psub", 4)) {
125 psubscribed_topics_.insert(topic); 128 psubscribed_topics_.insert(topic);
126 num_pending_subs_--; 129 num_pending_subs_--;
127 - if (sub_callback) sub_callback(topic); 130 + if (sub_callback)
  131 + sub_callback(topic);
128 } else if (!strncmp(reply->element[0]->str, "uns", 3)) { 132 } else if (!strncmp(reply->element[0]->str, "uns", 3)) {
129 subscribed_topics_.erase(topic); 133 subscribed_topics_.erase(topic);
130 - if (unsub_callback) unsub_callback(topic); 134 + if (unsub_callback)
  135 + unsub_callback(topic);
131 cv_unsub_.notify_all(); 136 cv_unsub_.notify_all();
132 } else if (!strncmp(reply->element[0]->str, "puns", 4)) { 137 } else if (!strncmp(reply->element[0]->str, "puns", 4)) {
133 psubscribed_topics_.erase(topic); 138 psubscribed_topics_.erase(topic);
134 - if (unsub_callback) unsub_callback(topic); 139 + if (unsub_callback)
  140 + unsub_callback(topic);
135 cv_punsub_.notify_all(); 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 else if ((reply->type == REDIS_REPLY_ARRAY) && (reply->elements == 3)) { 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 else if ((reply->type == REDIS_REPLY_ARRAY) && (reply->elements == 4)) { 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 1e10 // To keep the command around for a few hundred years 165 1e10 // To keep the command around for a few hundred years
156 - ); 166 + );
157 167
158 // Add it to the command list 168 // Add it to the command list
159 commands_.insert(&sub_cmd); 169 commands_.insert(&sub_cmd);
@@ -161,13 +171,12 @@ void Subscriber::subscribeBase(const string cmd_name, const string topic, @@ -161,13 +171,12 @@ void Subscriber::subscribeBase(const string cmd_name, const string topic,
161 } 171 }
162 172
163 void Subscriber::subscribe(const string topic, 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 logger_.warning() << "Already subscribed to " << topic << "!"; 180 logger_.warning() << "Already subscribed to " << topic << "!";
172 return; 181 return;
173 } 182 }
@@ -175,13 +184,12 @@ void Subscriber::subscribe(const string topic, @@ -175,13 +184,12 @@ void Subscriber::subscribe(const string topic,
175 } 184 }
176 185
177 void Subscriber::psubscribe(const string topic, 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 logger_.warning() << "Already psubscribed to " << topic << "!"; 193 logger_.warning() << "Already psubscribed to " << topic << "!";
186 return; 194 return;
187 } 195 }
@@ -189,23 +197,19 @@ void Subscriber::psubscribe(const string topic, @@ -189,23 +197,19 @@ void Subscriber::psubscribe(const string topic,
189 } 197 }
190 198
191 void Subscriber::unsubscribeBase(const string cmd_name, const string topic, 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 logger_.warning() << "Cannot unsubscribe from " << topic << ", not subscribed!"; 213 logger_.warning() << "Cannot unsubscribe from " << topic << ", not subscribed!";
210 return; 214 return;
211 } 215 }
@@ -213,10 +217,9 @@ void Subscriber::unsubscribe(const string topic, @@ -213,10 +217,9 @@ void Subscriber::unsubscribe(const string topic,
213 } 217 }
214 218
215 void Subscriber::punsubscribe(const string topic, 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 logger_.warning() << "Cannot punsubscribe from " << topic << ", not psubscribed!"; 223 logger_.warning() << "Cannot punsubscribe from " << topic << ", not psubscribed!";
221 return; 224 return;
222 } 225 }
test/test.cpp
@@ -35,7 +35,6 @@ using redox::Command; @@ -35,7 +35,6 @@ using redox::Command;
35 class RedoxTest : public ::testing::Test { 35 class RedoxTest : public ::testing::Test {
36 36
37 protected: 37 protected:
38 -  
39 Redox rdx; 38 Redox rdx;
40 39
41 RedoxTest() {} 40 RedoxTest() {}
@@ -57,19 +56,18 @@ protected: @@ -57,19 +56,18 @@ protected:
57 mutex cmd_waiter_lock; 56 mutex cmd_waiter_lock;
58 57
59 // To make the callback code nicer 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 * Helper function that returns a command callback to print out the 62 * Helper function that returns a command callback to print out the
65 * command/reply and to test the reply against the provided value. 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 cmd_count++; 66 cmd_count++;
70 - return [this, value](Command<ReplyT>& c) { 67 + return [this, value](Command<ReplyT> &c) {
71 EXPECT_TRUE(c.ok()); 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 cmd_count--; 71 cmd_count--;
74 cmd_waiter.notify_all(); 72 cmd_waiter.notify_all();
75 }; 73 };
@@ -78,10 +76,10 @@ protected: @@ -78,10 +76,10 @@ protected:
78 /** 76 /**
79 * Wrapper for the callback that also prints out the command. 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 callback(c); 83 callback(c);
86 }; 84 };
87 } 85 }
@@ -89,21 +87,19 @@ protected: @@ -89,21 +87,19 @@ protected:
89 /** 87 /**
90 * Combination of print and check for simplicity. 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 return print<ReplyT>(check<ReplyT>(value)); 91 return print<ReplyT>(check<ReplyT>(value));
95 } 92 }
96 93
97 /** 94 /**
98 * Check the error 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 cmd_count++; 98 cmd_count++;
103 - return [this, value](Command<ReplyT>& c) { 99 + return [this, value](Command<ReplyT> &c) {
104 EXPECT_FALSE(c.ok()); 100 EXPECT_FALSE(c.ok());
105 EXPECT_FALSE(c.lastError().empty()); 101 EXPECT_FALSE(c.lastError().empty());
106 -// EXPECT_EQ(value, c.reply()); 102 + // EXPECT_EQ(value, c.reply());
107 cout << c.cmd() << ": " << c.lastError() << endl; 103 cout << c.cmd() << ": " << c.lastError() << endl;
108 cmd_count--; 104 cmd_count--;
109 cmd_waiter.notify_all(); 105 cmd_waiter.notify_all();
@@ -120,15 +116,13 @@ protected: @@ -120,15 +116,13 @@ protected:
120 rdx.disconnect(); 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 ASSERT_TRUE(c.ok()); 120 ASSERT_TRUE(c.ok());
126 EXPECT_EQ(c.reply(), value); 121 EXPECT_EQ(c.reply(), value);
127 c.free(); 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 ASSERT_TRUE(c.ok()); 126 ASSERT_TRUE(c.ok());
133 EXPECT_EQ(c.reply(), value); 127 EXPECT_EQ(c.reply(), value);
134 cout << "[SYNC] " << c.cmd() << ": " << c.reply() << endl; 128 cout << "[SYNC] " << c.cmd() << ": " << c.reply() << endl;
@@ -138,12 +132,11 @@ protected: @@ -138,12 +132,11 @@ protected:
138 /** 132 /**
139 * Check the error 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,18 +144,14 @@ protected:
151 // Core unit tests - asynchronous 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 TEST_F(RedoxTest, GetSet) { 151 TEST_F(RedoxTest, GetSet) {
163 connect(); 152 connect();
164 rdx.command<string>({"SET", "redox_test:a", "apple"}, print_and_check<string>("OK")); 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 wait_for_replies(); 155 wait_for_replies();
167 } 156 }
168 157
@@ -177,8 +166,8 @@ TEST_F(RedoxTest, Delete) { @@ -177,8 +166,8 @@ TEST_F(RedoxTest, Delete) {
177 TEST_F(RedoxTest, Incr) { 166 TEST_F(RedoxTest, Incr) {
178 connect(); 167 connect();
179 int count = 100; 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 rdx.command<string>({"GET", "redox_test:a"}, print_and_check(to_string(count))); 172 rdx.command<string>({"GET", "redox_test:a"}, print_and_check(to_string(count)));
184 wait_for_replies(); 173 wait_for_replies();
@@ -197,12 +186,8 @@ TEST_F(RedoxTest, Loop) { @@ -197,12 +186,8 @@ TEST_F(RedoxTest, Loop) {
197 int count = 0; 186 int count = 0;
198 int target_count = 20; 187 int target_count = 20;
199 double dt = 0.005; 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 double wait_time = dt * (target_count - 0.5); 192 double wait_time = dt * (target_count - 0.5);
208 this_thread::sleep_for(std::chrono::duration<double>(wait_time)); 193 this_thread::sleep_for(std::chrono::duration<double>(wait_time));
@@ -215,7 +200,7 @@ TEST_F(RedoxTest, Loop) { @@ -215,7 +200,7 @@ TEST_F(RedoxTest, Loop) {
215 TEST_F(RedoxTest, GetSetError) { 200 TEST_F(RedoxTest, GetSetError) {
216 connect(); 201 connect();
217 rdx.command<string>({"SET", "redox_test:a", "apple"}, print_and_check<string>("OK")); 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 wait_for_replies(); 204 wait_for_replies();
220 } 205 }
221 206
@@ -241,8 +226,8 @@ TEST_F(RedoxTest, DeleteSync) { @@ -241,8 +226,8 @@ TEST_F(RedoxTest, DeleteSync) {
241 TEST_F(RedoxTest, IncrSync) { 226 TEST_F(RedoxTest, IncrSync) {
242 connect(); 227 connect();
243 int count = 100; 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 print_and_check_sync(rdx.commandSync<string>({"GET", "redox_test:a"}), to_string(count)); 232 print_and_check_sync(rdx.commandSync<string>({"GET", "redox_test:a"}), to_string(count));
248 rdx.disconnect(); 233 rdx.disconnect();
@@ -259,7 +244,7 @@ TEST_F(RedoxTest, GetSetSyncError) { @@ -259,7 +244,7 @@ TEST_F(RedoxTest, GetSetSyncError) {
259 // End tests 244 // End tests
260 // ------------------------------------------- 245 // -------------------------------------------
261 246
262 -} // namespace 247 +} // namespace
263 248
264 int main(int argc, char **argv) { 249 int main(int argc, char **argv) {
265 ::testing::InitGoogleTest(&argc, argv); 250 ::testing::InitGoogleTest(&argc, argv);