64 lines
2.1 KiB
C++

/**
This file is a part of rexy's matrix client
Copyright (C) 2019-2020 rexy712
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef RAII_UTIL_HPP
#define RAII_UTIL_HPP
#include <rexy/string.hpp>
namespace raii{
namespace detail{
size_t _calc_escaped_len(const char* str);
char _escape_to_letter(char escape);
size_t _sanitize_json_copy(char* dest, const char* in);
template<class Tup, size_t I = 0>
void _js_assign(char* dest, Tup&& t, size_t offset){
size_t written = _sanitize_json_copy(dest+offset, std::get<I>(t));
if constexpr(I+2 < std::tuple_size<std::remove_reference_t<Tup>>::value){
_js_assign<Tup,I+2>(dest, std::forward<Tup>(t), offset+written);
}
}
template<class T, size_t I = 0>
size_t _calc_escaped_len_all(T&& t){
size_t len = _calc_escaped_len(std::get<I>(t));
if constexpr(I+2 < std::tuple_size<std::remove_reference_t<T>>::value){
len += _calc_escaped_len_all<T,I+2>(std::forward<T>(t));
}
return len;
}
}
template<class T, typename std::enable_if<rexy::detail::is_string<T>::value && !rexy::detail::is_concrete_string<T>::value,void>::type* = nullptr>
rexy::string json_escape(T&& t){
auto tup = t.get();
size_t len = detail::_calc_escaped_len_all(tup);
char* tmp = reinterpret_cast<char*>(rexy::string::allocator_type::allocate(len+1));
detail::_js_assign(tmp, tup, 0);
tmp[len] = 0;
return rexy::string(tmp, len);
}
rexy::string json_escape(const rexy::string_base& str);
size_t intlen(int i);
rexy::string itostr(int i);
}
#endif