simple_math.h 1.3 KB
Newer Older
1
// Copyright (C) 2018-2020 Intel Corporation
openvino-pushbot's avatar
openvino-pushbot committed
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
// SPDX-License-Identifier: Apache-2.0
//

#pragma once
#include <set>
#include <map>
#include <vector>
#include <functional>
#include <string>
#include <utility>

/*
*   Simple integer arithmetics to be used for the work sizes calculation
*   Supported ops: +,-,*,/,%,(,)
*   * no unary -,+
*   Variables defined as single chars and should not include one of the ops, whitespaces or 0-9
*/


class SimpleMathExpression {
public:
    SimpleMathExpression() :m_parsed(false) {}
    void SetVariables(const std::map<char, int>& vars);
    bool SetExpression(const std::string& expression);
    bool IsParsed()const { return m_parsed; }
    int Evaluate()const;  // undefined behavior if not parsed properly

private:
    std::map<char, int> m_variables;
    std::string m_expression;
    bool m_parsed;
    bool Parse();

    struct Token {
        enum TokenType {
            Value,
            Operator,
        } type;
        int value;
        char op;
        explicit Token(TokenType t = Value, int v = 0, char o = 0) :type(t), value(v), op(o) {}
    };
    std::vector<Token> m_parsedTokens;

    static const std::set<char> whitespaces;
    using Operator = std::pair<int, std::function<int(int, int)>>;  // priority, function
    static const std::map<char, Operator> operators;
};