From 13380aa85d12c1d9d29f557506ec7b6fcd6035e6 Mon Sep 17 00:00:00 2001 From: Mathew Sutcliffe Date: Tue, 25 Oct 2016 22:40:22 +0100 Subject: [PATCH] refs #784 Added CMemoTable, a data structure for performing memoization. --- src/blackmisc/memotable.h | 51 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 src/blackmisc/memotable.h diff --git a/src/blackmisc/memotable.h b/src/blackmisc/memotable.h new file mode 100644 index 000000000..d976cc919 --- /dev/null +++ b/src/blackmisc/memotable.h @@ -0,0 +1,51 @@ +/* Copyright (C) 2016 + * swift project Community / Contributors + * + * This file is part of swift project. It is subject to the license terms in the LICENSE file found in the top-level + * directory of this distribution and at http://www.swift-project.org/license.html. No part of swift project, + * including this file, may be copied, modified, propagated, or distributed except according to the terms + * contained in the LICENSE file. + */ + +//! \file + +#ifndef BLACKMISC_MEMOTABLE_H +#define BLACKMISC_MEMOTABLE_H + +#include "blackmisc/dictionary.h" +#include "blackmisc/sequence.h" + +namespace BlackMisc +{ + /*! + * A data memoization pattern useful for compressing JSON representations of containers. + */ + template + class CMemoTable + { + public: + //! Return the index of a value, inserting it if it is not already in the table. + int getIndex(const T &value) + { + int &index = m_dict[value]; + if (! index) + { + m_list.push_back(value); + index = m_list.size(); + } + return index - 1; + } + + //! Return the values in the table as a flat list. + const CSequence &getTable() const + { + return m_list; + } + + private: + CSequence m_list; + CDictionary m_dict; + }; +} + +#endif