Skip to content

Commit de53599

Browse files
authored
astutils.cpp: moved memoize() helper to utils.h (danmar#7257)
1 parent 54654b1 commit de53599

File tree

3 files changed

+33
-16
lines changed

3 files changed

+33
-16
lines changed

lib/astutils.cpp

Lines changed: 1 addition & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2875,21 +2875,6 @@ const Token* findEscapeStatement(const Scope* scope, const Library* library)
28752875
return nullptr;
28762876
}
28772877

2878-
// Thread-unsafe memoization
2879-
template<class F, class R=decltype(std::declval<F>()())>
2880-
static std::function<R()> memoize(F f)
2881-
{
2882-
bool init = false;
2883-
R result{};
2884-
return [=]() mutable -> R {
2885-
if (init)
2886-
return result;
2887-
result = f();
2888-
init = true;
2889-
return result;
2890-
};
2891-
}
2892-
28932878
template<class F,
28942879
REQUIRES("F must be a function that returns a Token class",
28952880
std::is_convertible<decltype(std::declval<F>()()), const Token*> )>
@@ -2954,7 +2939,7 @@ Token* findVariableChanged(Token *start, const Token *end, int indirect, const n
29542939
return nullptr;
29552940
if (depth < 0)
29562941
return start;
2957-
auto getExprTok = memoize([&] {
2942+
auto getExprTok = utils::memoize([&] {
29582943
return findExpression(start, exprid);
29592944
});
29602945
for (Token *tok = start; tok != end; tok = tok->next()) {

lib/utils.h

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -411,6 +411,21 @@ namespace utils {
411411
// NOLINTNEXTLINE(bugprone-return-const-ref-from-parameter) - potential false positive
412412
return t;
413413
}
414+
415+
// Thread-unsafe memoization
416+
template<class F, class R=decltype(std::declval<F>()())>
417+
static inline std::function<R()> memoize(F f)
418+
{
419+
bool init = false;
420+
R result{};
421+
return [=]() mutable -> R {
422+
if (init)
423+
return result;
424+
result = f();
425+
init = true;
426+
return result;
427+
};
428+
}
414429
}
415430

416431
#endif

test/testutils.cpp

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ class TestUtils : public TestFixture {
4343
TEST_CASE(replaceEscapeSequences);
4444
TEST_CASE(splitString);
4545
TEST_CASE(as_const);
46+
TEST_CASE(memoize);
4647
}
4748

4849
void isValidGlobPattern() const {
@@ -518,6 +519,22 @@ class TestUtils : public TestFixture {
518519
ASSERT(c.written);
519520
}
520521
}
522+
523+
void memoize() const {
524+
int count = 0;
525+
auto f = [&count]() {
526+
++count;
527+
return count;
528+
};
529+
const auto callF = utils::memoize([&]() {
530+
return f();
531+
});
532+
ASSERT_EQUALS(0, count);
533+
ASSERT_EQUALS(1, callF());
534+
ASSERT_EQUALS(1, count);
535+
ASSERT_EQUALS(1, callF());
536+
ASSERT_EQUALS(1, count);
537+
}
521538
};
522539

523540
REGISTER_TEST(TestUtils)

0 commit comments

Comments
 (0)