-- Copyright (c) 2024 Huawei Technologies Co., Ltd.
-- openUBMC is licensed under Mulan PSL v2.
-- You can use this software according to the terms and conditions of the Mulan PSL v2.
-- You may obtain a copy of Mulan PSL v2 at:
--         http://license.coscl.org.cn/MulanPSL2
-- THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
-- EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
-- MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
-- See the Mulan PSL v2 for more details.

local db_util = {}

local function get_valid_index(index)
    if index then
        return index
    end

    return 0
end

-- 功能:从数组下标from_index开始存储,解析数据库的数据:['/x/x/x/x/x']->[数组]
-- 默认:从0开始存储,非string类型
function db_util.decode_db_info(db_info, store_index, is_string)
    if not db_info then
        return nil
    end

    local data = {}
    local format = '/(%w+)'
    local index = get_valid_index(store_index)
    for word in string.gmatch(db_info, format) do
        if is_string then
            data[index] = word
        else
            data[index] = tonumber(word)
        end
        index = index + 1
    end

    return data
end

-- 功能:从数组下标from_index开始编码,编码数据库的数据:[数组]->['/x/x/x/x/x']
-- 默认:从0开始解析
function db_util.encode_db_info(arr_data, parse_index)
    local text = {}
    local len = #arr_data
    local index = 1
    local from_index = get_valid_index(parse_index)
    for i = from_index, len, 1 do
        local data = arr_data[i]
        if not data then
            return ''
        end

        local s = '/' .. tostring(data)
        -- table是从1开始
        text[index] = s
        index = index + 1
    end

    return table.concat(text)
end

function db_util.construc_init_data(data_len)
    local text = {}
    for i = 1, data_len, 1 do
        local s = '/0'
        -- table是从1开始
        text[i] = s
    end

    return table.concat(text)
end

return db_util