---
--- Date         : 2020-07-10 18:01:23
--- Author       : HUAFEI2, LIAOGAOCAN, LICHAO7
--- LastEditors  : LICHAO7
--- LastEditTime : 2020-07-14 21:51:47
--- Description  : lua string patch function
---

---
--- Remove string space of string start and end.
---
--- @param str string
--- @return string
---
string.trim = function(str)
    return (string.gsub(str, "^%s*(.-)%s*$", "%1"));
end

---
--- Split string with sep
--- Be careful!!! if `sep` is never found in the string,
--- a `table` of length 1 is returned, the only element
--- being a string filled with `\0` and `size`=1.
---
--- @param str string
--- @param sep string
--- @return table
---
string.split = function(str, sep)
    local rt = {};
    if type(str) ~= "string" or type(sep) ~= "string" then
        return rt;
    end
    string.gsub(str, '[^' .. sep .. ']+', function(w)
        table.insert(rt, w)
    end);
    return rt;
end

---
--- Replace searchValue in source with replaceValue.
---
--- @param source string
--- @param searchValue string
--- @param replaceValue string
--- @return string
---
string.replace = function(source, searchValue, replaceValue)
    searchValue = string.gsub(searchValue, "[%%%(%)%.%+%-%*%?%[%^%$]", "%%%1");
    local result = source;
    if type(replaceValue) == "string" then
        replaceValue = string.gsub(replaceValue, "[%%%(%)%.%+%-%*%?%[%^%$]", "%%%1");
        result = string.gsub(source, searchValue, replaceValue, 1);
    else
        result = string.gsub(source, searchValue, function(match)
            return replaceValue(_G, match);
        end, 1);
    end
    return result;
end
