diff --git a/passphrase_cache.cc b/passphrase_cache.cc index fec2d42..6a60e7a 100644 --- a/passphrase_cache.cc +++ b/passphrase_cache.cc @@ -1,3 +1,4 @@ +#include #include "passphrase_cache.hh" namespace pEp { @@ -47,22 +48,17 @@ namespace pEp { std::string PassphraseCache::latest_passphrase() { std::lock_guard lock(_mtx); - cleanup(); - _which = _cache.end(); - return ""; - } + + if (_cache.empty()) + throw std::underflow_error("empty passphrase cache"); - std::string PassphraseCache::next_passphrase() - { - std::lock_guard lock(_mtx); - - if (_cache.empty() || _which == _cache.begin()) { - return ""; - } - else { - --_which; - return _which->passphrase; + if (_which == _cache.begin()) { + _which = _cache.end(); + throw std::underflow_error("out of passphrases"); } + + --_which; + return _which->passphrase; } }; diff --git a/passphrase_cache.hh b/passphrase_cache.hh index 70761aa..c8b4ddd 100644 --- a/passphrase_cache.hh +++ b/passphrase_cache.hh @@ -33,10 +33,11 @@ namespace pEp { public: PassphraseCache(int max_size=20, duration timeout = std::chrono::minutes(10)) : _max_size(max_size), - _timeout(timeout) { } + _timeout(timeout), _which(_cache.end()) { } ~PassphraseCache() { } PassphraseCache(const PassphraseCache& second) : _cache(second._cache), - _max_size(second._max_size), _timeout(second._timeout) { } + _max_size(second._max_size), _timeout(second._timeout), + _which(_cache.end()) { } PassphraseCache operator=(const PassphraseCache& second) { return second; } // adding a passphrase to the cache, which will timeout @@ -52,14 +53,11 @@ namespace pEp { bool for_each_passphrase(const passphrase_callee& callee); // get all passphrases in cache from latest to oldest - // always returns "" + // this function is throwing std::underflow_error when no passphrases + // are left std::string latest_passphrase(); - // get next passphrase; returns "" when no passphrases are left - - std::string next_passphrase(); - // convenience functions // i.e. // status = cache.api(::encrypt_message, session, src, extra, dst, enc_format, flags) diff --git a/test/test_passphrase_cache.cc b/test/test_passphrase_cache.cc index 673d063..3d01ac3 100644 --- a/test/test_passphrase_cache.cc +++ b/test/test_passphrase_cache.cc @@ -1,4 +1,5 @@ #include +#include #include #include @@ -52,11 +53,12 @@ int main() std::cout << "expected: two passphrases in order\n"; pEp::PassphraseCache _cache = cache; - _cache.latest_passphrase(); - for (std::string passphrase = _cache.next_passphrase(); passphrase != "" ; - passphrase = _cache.next_passphrase()) { - std::cout << passphrase << "\n"; + try { + while (1) { + std::cout << "'" << _cache.latest_passphrase() << "'\n"; + } } + catch (std::underflow_error&) { } sleep(2);