Files
dl_old/dl/io/dl_file_csv.h
T
2023-08-27 19:20:33 +08:00

435 lines
9.6 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* @file dl_file_csv.h
* @brief csv文件操作相关
*
*
* @version 1.0
* @author lveyou
* @date 22-09-10
*
* @note
*/
#pragma once
#include <string>
#include "dl_file.h"
#include "memory/dl_stream_output.h"
#include "dl_type.h"
#include "base/dl_range_find.h"
#include "base/dl_vector2.h"
#include "math/dl_math.h"
#include "memory/dl_stream_input.h"
namespace dl::FileCsv
{
constexpr uint32_t CSV_FILE_TYPE = 316;
/**
* @brief 读取一个CSV文件,拆解为每行(换行使用\n替代,所有/变为\)
* @param[in] path_name 路径名称
* @retval 如果失败,会输出日志
*
* @note 出于性能考虑不判断是否为utf8编码,而是使用其他函数提前转换
*/
bool Read(std::string_view path_name, Vector2<std::string>& ret)
{
assert(!ret.IsEmpty());
std::ifstream ifs = File::Get(path_name, false);
if (!ifs.is_open())
{
log_err("csv文件加载失败:{}", path_name);
return false;
}
// 状态
enum class Flag
{
NORMAL, // 正常
LEFT, // 读取到了前引号
TWICE, // 再次读到引号
}flag;
flag = Flag::NORMAL;
// 所有
Vector2<std::string> all;
// 当前行
std::vector<std::string> line;
// 当前段
std::string temp;
while (!ifs.eof())
{
char ch = ifs.get();
switch (flag)
{
case Flag::NORMAL:
if (ch == '\"')// 进入引号模式
flag = Flag::LEFT;
else if (ch == ',')// 写入段
{
line.push_back(temp);
temp.clear();
}
else if (ch == '\n')// 写入行,还要写入当前段
{
line.push_back(temp);
temp.clear();
all.PushBack(line);
line.clear();
}
else
temp.push_back(ch);
break;
case Flag::LEFT:
if (ch == '\"')// 进入两次引号模式
flag = Flag::TWICE;
else if (ch == '\n')// 换行符写入
temp.push_back(ch);
else
temp.push_back(ch);
break;
case Flag::TWICE:
// 这里 必须是引号转义,或是结束(逗号结束,或段结束),其他状态则为错误
if (ch == '\"')//写入一个引号
{
temp.push_back(ch);
flag = Flag::LEFT;
}
else if (ch == ',')// 写入段
{
line.push_back(temp);
temp.clear();
flag = Flag::NORMAL;
}
else if (ch == '\n')// 写入行与段
{
line.push_back(temp);
temp.clear();
all.PushBack(line);
line.clear();
flag = Flag::NORMAL;
}
else
{
log_err0("引号转义出现错误的状态!");
return false;
}
break;
default:
log_err0("错误的状态!");
return false;
}
}
ret = std::move(all);
return true;
}
//
///**
//* @brief 序列化 逗号分隔文件
//*/
//void Serialize(std::string_view path_name, std::string_view out)
//{
// Vector2<std::string> mul_str;
// if (!Read(path_name, mul_str))
// return;
//
// struct TypeFlag
// {
// enum
// {
// Z8,
// Z16,
// Z32,
// Z64,
// N8,
// N16,
// N32,
// N64,
// FLOAT,
// DOUBLE,
// STRING,
// NONE,//占位(=或未知类型)
// ALIGN,//字节对齐填充
// }_type;
// size_t _size;//用于字符串记录长度,包含结束符
// };
//
// //单个元素缓冲区
// std::byte* p = nullptr;
// std::size_t line_size = 0;
//
// //输出流
// StreamOutput s;
//
// //类型标签
// std::vector<TypeFlag> vec_flag;
//
// //寻找 = 的位置
// Index2 pos = Find::FirstIndex(mul_str, "=");
//
// if (pos[1] == -1)
// {
// log_err("=标签查找失败:{}", path_name);
// return;
// }
//
// //字段行
// {
// std::string* vec_str = mul_str[pos[1]];
//
// //最大字段长度
// std::size_t max_size = 1;
// //统计数据大小
// for (std::size_t i = pos[0]; i < mul_str.GetWidth(); ++i)
// {
// if (vec_str[i] == "uint8_t")
// {
// vec_flag.push_back({ TypeFlag::N8, 0 });
// line_size += sizeof(uint8_t);
// }
// else if (vec_str[i] == "uint16_t")
// {
// vec_flag.push_back({ TypeFlag::N16, 0 });
// line_size += sizeof(uint16_t);
// }
// else if (vec_str[i] == "uint32_t")
// {
// vec_flag.push_back({ TypeFlag::N32, 0 });
// line_size += sizeof(uint32_t);
// }
// else if (vec_str[i] == "int32_t")
// {
// vec_flag.push_back({ TypeFlag::Z32, 0 });
// line_size += sizeof(int32_t);
// }
// else if (vec_str[i] == "float")
// {
// if (sizeof(float) > max_size)
// max_size = sizeof(float);
//
// std::size_t start = line_size ? Math::Align(line_size, alignof(float)) : 0;
// if (start != line_size) vec_flag.push_back({ TypeFlag::ALIGN, start - line_size });
//
// vec_flag.push_back({ TypeFlag::FLOAT, 0 });
// line_size += sizeof(float);
// }
// else if (vec_str[i] == "double")
// {
// if (sizeof(double) > max_size)
// max_size = sizeof(double);
//
// std::size_t start = line_size ? Math::Align(line_size, alignof(double)) : 0;
// if (start != line_size) vec_flag.push_back({ TypeFlag::ALIGN, start - line_size });
//
// vec_flag.push_back({ TypeFlag::DOUBLE, 0 });
// line_size += sizeof(double);
// }
// else
// {
// size_t pos = vec_str[i].find("str");
// if (pos != std::string::npos)
// {
// if (sizeof(char) > max_size)
// max_size = sizeof(char);
//
// size_t start = line_size ? Math::Align(line_size, alignof(char)) : 0;
// if (start != line_size) vec_flag.push_back({ TypeFlag::ALIGN, start - line_size });
//
// //
// size_t str_length = std::stoi(std::string(vec_str[i].begin() + 3, vec_str[i].end()));
// if (str_length == 0)
// {
// log_err("字符串必须指定长度,例如str8:{}", path_name);
// str_length = 16;//手动设置大小
// }
// vec_flag.push_back({ TypeFlag::STRING, str_length });
// line_size += sizeof(char) * str_length;
// }
// else
// {
// vec_flag.push_back({ TypeFlag::NONE, 0 });
// line_size += 0;
// if (!vec_str[i].empty() && vec_str[i] != "=")
// log_warn("未知类型标签:{},{}", path_name, vec_str[i]);
// }
// }
// }
//
// if (line_size == 0)
// {
// log_err("数据大小为0:{}", path_name );
// return;
// }
//
// //最大元素对齐
// std::size_t start = line_size ? Math::Align(line_size, max_size) : 0;
// line_size = start;
//
// p = (std::byte*)malloc(line_size);
//
//
// //写入类型
// uint32_t id = CSV_FILE_TYPE;
// s.Write(&id);
//
// //写入单行大小
// s.Write64(&line_size);
// }
//
// //统计除了用于对齐的元素个数
// ptrdiff_t w = pos[0] + count_if(vec_flag.begin(), vec_flag.end(), [](const TypeFlag& flag)
// {
// return flag._type != TypeFlag::ALIGN;
// });
//
// //数据行
// for (size_t h = pos[1] + 1; h < mul_str.GetHeight(); ++h)
// {
// std::string* vec_str = mul_str[h];
//
// if (vec_str[pos[0]] != "+")
// {
// continue;
// }
//
// if (p == nullptr
// || vec_flag.empty()
// || line_size == 0)
// {
// log_err("类型标签未成功读取:{}", path_name);
// return;
// }
//
// if (vec_str.size() != w)
// {
// std::string str_all;
// for (auto& iter : vec_str)
// {
// str_all += iter;
// str_all += ",";
// }
// log_err("此行元素个数不匹配:{},{}", path_name, str_all);
// continue;
// }
//
// size_t offset = 0;
// size_t j = pos[0];//元素下标
// for (size_t i = 0; i < vec_flag.size(); ++i)
// {
// if (vec_flag[i]._type == TypeFlag::ALIGN)
// {
// offset += vec_flag[i]._size;
// continue;
// }
//
//#define DEF_SERIALIZE_CSV_LINE(flag, type, func)\
//if (vec_flag[i]._type == TypeFlag::flag)\
//{\
//type v = 0;\
//if (!vec_str[j].empty())\
//{\
// if(Sub::IsBegin(vec_str[j], std::string("0x")))\
// v = func(vec_str[j], nullptr, 16);\
// else\
// v = func(vec_str[j]);\
//}\
//*(type*)(p + offset) = v;\
//offset += sizeof(type);\
//++j;\
//continue;\
//}
//
//#define DEF_SERIALIZE_CSV_LINE_F(flag, type, func)\
//if (vec_flag[i]._type == TypeFlag::flag)\
//{\
//*(type*)(p + offset) = (type)(vec_str[j].empty() ? 0 : func(vec_str[j]));\
//offset += sizeof(type);\
//++j;\
//continue;\
//}
// DEF_SERIALIZE_CSV_LINE(Z8, int8_t, stoi);
// DEF_SERIALIZE_CSV_LINE(Z16, int16_t, stoi);
// DEF_SERIALIZE_CSV_LINE(Z32, int32_t, stoi);
// DEF_SERIALIZE_CSV_LINE(Z64, int64_t, stoll);
// DEF_SERIALIZE_CSV_LINE(N8, uint8_t, stoi);
// DEF_SERIALIZE_CSV_LINE(N16, uint16_t, stoi);
// DEF_SERIALIZE_CSV_LINE(N32, uint32_t, stoul);
// DEF_SERIALIZE_CSV_LINE(N64, uint64_t, stoull);
// DEF_SERIALIZE_CSV_LINE_F(FLOAT, float, stof);
// DEF_SERIALIZE_CSV_LINE_F(DOUBLE, double, stod);
//
// if (vec_flag[i]._type == TypeFlag::STRING)
// {//string
// if (vec_str[j].empty())
// *(char*)(p + offset) = 0;
// else//strcpy_s并没有考虑源过大
// CodeCvt::Utf8::Copy((char*)(p + offset), vec_flag[i]._size, vec_str[j]);
//
// //strcpy_s((char*)(p + offset), vec_flag[i]._size, vec_str[j].c_str());
// offset += sizeof(char) * vec_flag[i]._size;
// }
//
// ++j;
//
// }
//
// if (line_size != offset)
// {
// log_err("单行写入大小不匹配:{}", path_name );
// }
//
// s.Write(p, line_size);
// }
// free(p);
// s.Save(out);
//}
/**
* @brief 反序列化 序列化的Csv文件到 对象
*/
template<typename T, typename F>
void Deserialize(std::string_view path_name, F fn)
{
StreamInput s;
s.LoadFromFile(path_name);
//id
uint32_t id = 0;
s.Read(&id);
if (id != CSV_FILE_TYPE)
{
log_err("CSV二进制文件错误:{}", path_name);
return;
}
//大小检查
std::size_t size = 0;
s.Read64(&size);
if (size != sizeof(T))
{
log_err("CSV二进制文件不匹配POD类型大小{},{}:{}", size, sizeof(T), path_name);
return;
}
while (!s.IsEnd())
{
T t;
s.Read(&t);
fn(t);
}
}
template<typename T>
void Deserialize(std::string_view path_name, std::vector<T>& container)
{
Deserialize<T>(path_name, [&](T& line)
{
container.push_back(line);
});
}
}