移除YLIB内置

This commit is contained in:
xx
2024-05-28 17:21:30 +08:00
parent b5e3ac9f9f
commit d203466193
96 changed files with 0 additions and 6815 deletions

View File

@@ -1,93 +0,0 @@
#pragma once
#include <string>
#include <vector>
#include "base/define.h"
namespace ylib
{
class mem_pool
{
public:
mem_pool(size_t initial_length = 1024);
~mem_pool();
void append(const uchar* data,size_t length);
void clear();
size_t length() const;
uchar* data() const;
void resize(size_t length);
void set(const uchar* data,size_t length);
bool empty() const;
private:
void renew(size_t length);
public:
// 内存数据指针
uchar* m_data = nullptr;
// 内存长度
size_t m_length = 0;
// 使用长度
size_t m_use_length = 0;
};
/**
* @brief BUFF字节流
*/
class buffer
{
public:
buffer(size_t initial_length = 1024);
buffer(char data, size_t len);
buffer(const char* data,size_t len);
buffer(const ylib::buffer& data);
buffer(const std::string& data);
buffer(std::initializer_list<uchar> char_list);
~buffer();
void set(const char* data, size_t length);
void set(const ylib::buffer& data);
void append(const std::string& data);
void append(const char* data, size_t length);
void append(const ylib::buffer& data);
void append(std::initializer_list<uchar> char_list);
template<typename T>
void append(const T& value) {
append((const char*)&value, sizeof(T));
}
void clear();
void resize(size_t length);
size_t find(const char* data, size_t len, size_t start_pos = 0) const;
size_t find(const ylib::buffer& data, size_t start_pos = 0) const;
std::vector<size_t> find_list(const ylib::buffer& value, size_t start = 0) const;
std::vector<ylib::buffer> split(const ylib::buffer& value, size_t start = 0) const;
std::string to_string() const;
bool empty() const;
ylib::buffer left(size_t len) const;
ylib::buffer right(size_t len) const;
ylib::buffer sub(size_t start,size_t len) const;
ylib::buffer sub(size_t start) const;
//ylib::buffer sub(size_t start,size_t len);
operator std::string() const;
ylib::buffer operator+(const ylib::buffer& other) const;
ylib::buffer& operator=(const std::string& data);
ylib::buffer& operator=(const ylib::buffer& data);
unsigned char& operator[](size_t index) const;
const char* data() const;
const size_t length() const;
const size_t size() const { return length(); };
ylib::buffer trim_end(char value);
ylib::buffer trim_begin(char value);
ylib::buffer trim(char value);
std::string to_hex();
size_t& cursor(){ return m_cursor; }
private:
ylib::mem_pool m_data;
size_t m_cursor = 0;
};
}

View File

@@ -1,36 +0,0 @@
#pragma once
#include <string>
#include "define.h"
#include "base/buffer.h"
namespace ylib
{
int32 stoi(const std::string& value);
int32 stoi(char value);
uint64 stoull(const std::string& value);
int64 stoll(const std::string& value);
double stod(const std::string& value);
float stof(const std::string& value);
//保留小数点
std::string to_fixed(double num, uint32 x);
namespace bytes{
/*流转*/
void to_int(int32& dest, const char* src, bool reverse = false);
void to_uint(uint32& dest, const char* src, bool reverse = false);
void to_short(short& dest, const char* src, bool reverse = false);
void to_ushort(ushort& dest, const char* src, bool reverse = false);
void to_char(char* dest, short src, bool reverse = false);
void to_char(char* dest, int32 src, bool reverse = false);
void to_char(char* dest, int64 src, bool reverse = false);
ylib::buffer to_buffer(short src, bool reverse = false);
ylib::buffer to_buffer(int32 src, bool reverse = false);
ylib::buffer to_buffer(int64 src, bool reverse = false);
ylib::buffer to_buffer(uchar src);
// 反转
void reverse(void* dest, size_t length);
void to_uint64(uint64& dest, const char* src, bool reverse = false);
void to_int64(int64& dest, const char* src, bool reverse = false);
}
}

View File

@@ -1,150 +0,0 @@
#pragma once
#include "typedef.h"
#include "exception.h"
#include "error.h"
// 是否DEBUG调试内存申请情况
#define DEBUG_MEM 0
using namespace ylib;
// 斜杆
#ifdef _WIN32
#define SEPRATOR std::string("\\")
#else
#define SEPRATOR std::string("/")
#endif
// 遍历STL
#define for_iter(LOOP_VAR,LOOP_NUM) for(auto LOOP_VAR = LOOP_NUM.begin();LOOP_VAR != LOOP_NUM.end();LOOP_VAR++)
#define for_riter(LOOP_VAR,LOOP_NUM) for(auto LOOP_VAR = LOOP_NUM.rbegin();LOOP_VAR != LOOP_NUM.rend();LOOP_VAR++)
// 抛出异常
//#define THROW_FORMAT(DATA,...) throw std::exception(std::format(DATA,__VA_ARGS__).c_str())
#ifdef YLIB_STATIC
#define YLIB_API
#else
#define NEWOBJ_EXPORT_API __declspec(dllexport)
#ifdef EXPORT_DLL
#define C_DLL_HEADER extern "C" __declspec(dllexport)
#else
#define C_DLL_HEADER extern "C" __declspec(dllimport)
#endif
#define C_CALL __stdcall
#endif
#define ylib_max(a,b) (((a) > (b)) ? (a) : (b))
#define ylib_min(a,b) (((a) < (b)) ? (a) : (b))
/**
* @brief 定义命名空间 ylib
*/
namespace ylib {
/**
* @brief 定义一个矩形结构体
*
* 包含四个成员变量left, top, right, bottom用于表示矩形的位置和大小。
* 构造函数初始化了这四个变量的值为0。
*/
struct Rect{
Rect() { left = 0; top = 0; right = 0; bottom = 0; } // 默认构造函数初始化矩形的位置和大小为0
int left; // 矩形的左边界
int top; // 矩形的上边界
int right; // 矩形的右边界
int bottom; // 矩形的下边界
};
struct Geometry {
Geometry(){
width = 0;
height = 0;
x = 0;
y = 0;
}
int width;
int height;
int x;
int y;
};
/**
* @brief 定义一个键值对结构体模板
*
* 模板结构体,接受两个类型参数 K 和 V。
* 包含两个成员变量name 和 value分别用于存储键和值。
*/
template<typename K,typename V>
struct KeyValue{
K name; // 键
V value; // 值
};
/**
* @brief 定义一个带宽信息结构体
*/
struct BandInfo
{
BandInfo() { // 默认构造函数初始化带宽信息的所有成员变量为0
}
uint64 up_all = 0; // 上行总带宽
uint64 down_all = 0; // 下行总带宽
uint64 up_sec_byte = 0; // 上行第二字节带宽
uint64 down_sec_byte = 0; // 下行第二字节带宽
};
// 地址信息
struct AddressPort {
std::string address; // 存储地址的字符串成员
ushort port = 0; // 存储端口的整数成员
//inline std::string to_string() { return address + std::to_string(port); }
};
// 控制台文本颜色
enum ConsoleTextColor {
BLUE = 0x0001,
GREEN = 0x0002,
RED = 0x0004,
YELLOW = 0x0008,
DEFAULT = RED | GREEN | BLUE,
};
// 文件类型
enum FileType {
IS_FILE,
IS_DIRECTORY
};
// 磁盘容量
struct DiskCapacity
{
// 用户可用剩余容量(一般用这个)
uint64 freeBytesUser = 0;
// 可用剩余容量
uint64 freeBytes = 0;
// 用户可用剩余容量
uint64 totalBytes = 0;
};
// 网络接收类型
enum receive_model
{
// 默认模型
PUSH_DEFAULT,
// 封装PACK
PACK,
// 自定义读取流
PULL,
};
// 全路径
class FullPath
{
public:
std::string name;
std::string path;
public:
std::string to_string() { return path + SEPRATOR + name; }
};
} // end of namespace ylib

View File

@@ -1,52 +0,0 @@
#pragma once
#include <map>
#include <string>
#include <mutex>
#include "base/define.h"
#include "base/log4.h"
namespace ylib
{
class environment
{
public:
template<typename T>
T* to(const std::string& name)
{
std::unique_lock<std::mutex> auto_lock(m_mutex);
return (T*)m_map[name];
}
template<typename T>
void set(const std::string name,T* value)
{
std::unique_lock<std::mutex> auto_lock(m_mutex);
m_map[name] = value;
}
void del(const std::string& name)
{
std::unique_lock<std::mutex> auto_lock(m_mutex);
auto iter = m_map.find(name);
if (iter != m_map.end())
m_map.erase(iter);
}
private:
std::mutex m_mutex;
std::map<std::string,void*> m_map;
};
namespace network
{
namespace http
{
class center;
}
}
namespace mysql_plus
{
class pool;
}
}
namespace ylib
{
extern ylib::environment *env;
extern ylib::log4 *log;
}

View File

@@ -1,23 +0,0 @@
#pragma once
#include <string>
#include <iostream>
/**
* 基础错误类
*/
namespace ylib
{
class error_base
{
public:
const std::string& last_error();
public:
std::string m_lastErrorDesc;
};
namespace error{
void print(const std::string& value);
}
}

View File

@@ -1,28 +0,0 @@
#pragma once
#include <string>
#include <exception>
#include "base/define.h"
/**
* @brief 异常处理类
*/
namespace ylib
{
class exception:public std::exception
{
public:
exception(const std::string &msg);
~exception();
virtual char const* what() const
#ifdef __linux__
noexcept
#endif
override{return m_msg.c_str();}
private:
std::string m_msg;
};
}

View File

@@ -1,26 +0,0 @@
#pragma once
#include "define.h"
namespace ylib
{
/*
* @classLog4cplus 日志封装类
* @desc
* 1、程序默认开启如需更改请修改 public/environment.cpp 中的全局变量实现(注释new即可)
* 2、默认配置文件放置程序目录 res/log.properties, 示例文件参考res/log.properties
*/
class log4
{
public:
log4(const std::string& config_filepath);
~log4();
ylib::log4& info(const std::string& value,const std::string& name = "ALL");
ylib::log4& error(const std::string& value,const std::string& name = "ALL");
ylib::log4& fatal(const std::string& value,const std::string& name = "ALL");
ylib::log4& warn(const std::string& value,const std::string& name = "ALL");
ylib::log4& debug(const std::string& value,const std::string& name = "ALL");
private:
void* m_appender;
void* m_appender_console;
};
}

View File

@@ -1,33 +0,0 @@
#pragma once
#include <string>
#include <iostream>
/**
* 基础错误类
*/
namespace ylib
{
// 单例基类模板
template <typename T>
class singleton {
public:
// 获取单例对象的静态方法
static T* getInstance() {
static T instance; // C++11以后局部静态变量的初始化是线程安全的
return &instance;
}
protected:
// 默认构造函数
singleton() = default;
// 禁止拷贝构造函数和拷贝赋值操作
singleton(const singleton&) = delete;
singleton& operator=(const singleton&) = delete;
// 允许析构
virtual ~singleton() = default;
};
}

View File

@@ -1,14 +0,0 @@
#pragma once
/***************************************************[类型]***************************************************/
typedef int int32;
typedef unsigned int uint32;
typedef long long int64;
typedef unsigned long long uint64;
typedef unsigned long ulong;
typedef unsigned short ushort;
typedef int64 llong;
typedef uint64 ullong;
typedef unsigned char uchar;
typedef int64 timestamp;

View File

@@ -1,127 +0,0 @@
#pragma once
#ifdef _WIN32
#include <vector>
#include <string>
#include <list>
#ifndef _WIN32
#include <stddef.h>
#endif
#include "base/define.h"
#include "base/error.h"
#include "util/json.h"
#include "util/pool.hpp"
namespace ylib::mssql
{
class pool;
class result;
class conn;
class prepare_statement;
struct mssql_conn_info
{
mssql_conn_info() {
}
std::string odbcname;
std::string username;
std::string password;
};
class result :public ylib::error_base
{
public:
result();
~result();
// 列数量
uint32 field_count();
// 行数量
size_t row_count();
// 取文本值
std::string get(uint32 field);
// 下一行
bool next();
int32 get_int32(uint32 index);
int32 get_int32(const std::string& name);
uint32 get_uint32(uint32 index);
uint32 get_uint32(const std::string& name);
int64 get_int64(uint32 index);
int64 get_int64(const std::string& name);
uint64 get_uint64(uint32 index);
uint64 get_uint64(const std::string& name);
std::string get_string(uint32 index);
std::string get_string(const std::string& name);
bool get_boolean(uint32 index);
bool get_boolean(const std::string& name);
double get_double(uint32 index);
double get_double(const std::string& name);
friend class ylib::mssql::prepare_statement;
private:
void* m_handle = nullptr;
uint32 m_field_count = 0;
uint32 m_row_count = 0;
std::map<std::string, short> m_field_name_index;
};
class prepare_statement :public ylib::error_base {
public:
prepare_statement();
~prepare_statement();
void set_boolean(uint32 index, bool value);
void set_datetime(uint32 index, const std::string& value);
void set_double(uint32 index, double value);
void set_int32(uint32 index, int32 value);
void set_uint32(uint32 index, uint32 value);
void set_int64(uint32 index, int64 value);
void set_uint64(uint32 index, uint64 value);
void set_null(uint32 index);
void set_string(uint32 index, const std::string& value);
void clear();
uint64 update();
ylib::mssql::result* query();
friend class ylib::mssql::conn;
private:
ylib::mssql::result* m_result = nullptr;
void* m_handle = nullptr;
};
class conn :public ylib::example<ylib::mssql::mssql_conn_info>, public ylib::error_base
{
public:
conn();
~conn();
virtual EXAMPLE_START_RESULT start(const ylib::mssql::mssql_conn_info& info) override;
virtual void close() override;
virtual void recover() override;
virtual void task_out() override;
void clear();
ylib::mssql::prepare_statement* setsql(const std::string& sql);
void begin();
void commit();
void rollback();
friend class ylib::mssql::pool;
private:
void* m_handle = nullptr;
ylib::mssql::mssql_conn_info m_info;
class prepare_statement* m_ppst = nullptr;
int m_sw = 0;
};
class pool : public ylib::pool<ylib::mssql::conn, ylib::mssql::mssql_conn_info>
{
public:
pool();
~pool();
};
}
#endif

View File

@@ -1,163 +0,0 @@
#pragma once
#include <vector>
#include <string>
#include <list>
#ifndef _WIN32
#include <stddef.h>
#endif
#include "base/define.h"
#include "base/error.h"
#include "util/json.h"
#include "util/pool.hpp"
namespace ylib::mysql
{
class pool;
class result;
class conn;
class prepare_statement;
struct field {
uint32 index = 0;
std::string name;
std::string type_name;
};
struct mysql_conn_info
{
mysql_conn_info() {
port = 0;
}
std::string ipaddress;
std::string username;
std::string password;
std::string database;
std::string charset;
uint32 port;
};
class result :public ylib::error_base
{
public:
result(void* handle);
~result();
// 列名
std::string field_name(uint32 index);
// 列类型
std::string field_type(uint32 index);
std::string field_type(const std::string& name);
// 列数量
uint32 field_count();
// 行数量
size_t row_count();
// 下一行
bool next();
int32 get_int32(uint32 index);
int32 get_int32(const std::string& name);
uint32 get_uint32(uint32 index);
uint32 get_uint32(const std::string& name);
int64 get_int64(uint32 index);
int64 get_int64(const std::string& name);
uint64 get_uint64(uint32 index);
uint64 get_uint64(const std::string& name);
std::string get_string(uint32 index);
std::string get_string(const std::string& name);
bool get_boolean(uint32 index);
bool get_boolean(const std::string& name);
double get_double(uint32 index);
double get_double(const std::string& name);
ylib::json to_json();
private:
void* m_handle = nullptr;
uint32 m_field_count = 0;
uint32 m_row_count = 0;
std::vector<ylib::mysql::field> m_fields;
};
class prepare_statement :public ylib::error_base {
public:
prepare_statement();
~prepare_statement();
void set_bigint(uint32 index, const std::string& value);
void set_boolean(uint32 index, bool value);
void set_datetime(uint32 index, const std::string& value);
void set_double(uint32 index, double value);
void set_int32(uint32 index, int32 value);
void set_uint32(uint32 index, uint32 value);
void set_int64(uint32 index, int64 value);
void set_uint64(uint32 index, uint64 value);
void set_null(uint32 index);
void set_string(uint32 index, const std::string& value);
void set_blob(uint32 index, const ylib::buffer& value);
void clear();
uint64 update();
ylib::mysql::result* query();
friend class ylib::mysql::conn;
private:
ylib::mysql::result* m_result = nullptr;
void* m_handle = nullptr;
};
class conn :public ylib::example<ylib::mysql::mysql_conn_info>, public ylib::error_base
{
public:
conn();
~conn();
virtual EXAMPLE_START_RESULT start(const ylib::mysql::mysql_conn_info& info) override;
virtual void close() override;
virtual void recover() override;
virtual void task_out() override;
void clear();
ylib::mysql::prepare_statement* setsql(const std::string& sql);
uint64 insert_id();
void begin(bool autocommit = false);
void commit();
void rollback();
void setDatabase(const std::string& name);
friend class ylib::mysql::pool;
private:
void* m_handle = nullptr;
ylib::mysql::mysql_conn_info m_info;
class prepare_statement* m_ppst = nullptr;
// 事务状态 0=未开启 1=已开启 2=执行完毕
int m_sw = 0;
};
class pool : public ylib::pool<ylib::mysql::conn, ylib::mysql::mysql_conn_info>
{
public:
pool()
{
}
~pool()
{
}
};
/// <summary>
/// 协程调用
/// 执行期间会让出协程,并等待再次调度
/// </summary>
/// <param name="ppst"></param>
/// <returns></returns>
std::tuple<bool, std::string> co_query(ylib::mysql::prepare_statement* ppst);
}

View File

@@ -1,264 +0,0 @@
#pragma once
#include "base/error.h"
#include "mysql.h"
#include <any>
namespace ylib
{
struct where {
std::string name;
std::string expression;
std::any value;
// 0=普通 1=Like 2=自定义
int type = 0;
};
struct limit {
int64 start = -1;
int64 count = -1;
};
enum sort {
ASC,
DESC
};
struct order_by {
std::string field;
ylib::sort sort;
};
struct keyvalue {
std::string name;
std::any value;
int extra = 0;
};
/// <summary>
/// MYSQL SELECT 查询器
/// </summary>
class select :public ylib::error_base {
public:
select(mysql::conn* conn);
~select();
/// <summary>
/// 表名
/// </summary>
/// <param name="field"></param>
/// <returns></returns>
select& table(const std::string& table_name);
/// <summary>
/// 查询字段
/// </summary>
/// <param name="field"></param>
/// <param name="sort"></param>
/// <returns></returns>
select& field(const std::vector<std::string>& field);
/// <summary>
/// 条件[A=B]
/// </summary>
select& where(const std::string& name, const std::string& expression, const std::any& value);
/// <summary>
/// 条件[模糊查询]
/// </summary>
select& where_like(const std::string& name, const std::string& value);
/// <summary>
/// 条件[自定义]
/// </summary>
select& where(const std::string& expression);
/// <summary>
/// LIMIT[页]
/// </summary>
select& page(uint32 page, uint32 count);
/// <summary>
/// LIMIT
/// </summary>
select& limit(uint32 start, uint32 count);
/// <summary>
/// 排序
/// </summary>
select& orderby(const std::string& field, sort sort = DESC);
/// <summary>
/// 查询数量
/// </summary>
/// <returns></returns>
uint64 count();
/// <summary>
/// 查询
/// </summary>
ylib::mysql::result* query();
#if 0
/// <summary>
/// 查询转换为layui需求模板
/// </summary>
/// <returns></returns>
ylib::json query_layui();
#endif
private:
/// <summary>
/// 生成SQL片段
/// </summary>
/// <param name="field_name"></param>
/// <param name="where"></param>
/// <param name="orderby"></param>
/// <param name="limit"></param>
void make_sql(std::string& field_name, std::string& where, std::string& orderby, std::string& limit, std::vector<std::any>& insert_values);
private:
mysql::conn* m_conn = nullptr;
std::vector<ylib::where> m_wheres;
std::string m_table_name;
std::vector<std::string> m_fields;
ylib::limit m_limit;
order_by m_orderby;
};
/// <summary>
/// MYSQL UPDATE
/// </summary>
class update :public ylib::error_base {
struct set {
std::string name;
std::any value;
std::string expression;
// 0=普通 1=表达式
int type = 0;
};
public:
update(mysql::conn* conn);
~update();
/// <summary>
/// 表名
/// </summary>
/// <param name="field"></param>
/// <returns></returns>
update& table(const std::string& table_name);
/// <summary>
/// 更新
/// </summary>
update& set(const std::string& name, const std::any& value);
update& set(const std::string& expression);
/// <summary>
/// 条件[A=B]
/// </summary>
update& where(const std::string& name, const std::string& expression, const std::any& value);
/// <summary>
/// 条件[模糊查询]
/// </summary>
update& where_like(const std::string& name, const std::string& value);
/// <summary>
/// 条件[自定义]
/// </summary>
update& where(const std::string& expression);
/// <summary>
/// LIMIT[页]
/// </summary>
update& page(uint32 page, uint32 count);
/// <summary>
/// LIMIT
/// </summary>
update& limit(uint32 start, uint32 count);
/// <summary>
/// 排序
/// </summary>
update& orderby(const std::string& field, sort sort = DESC);
/// <summary>
/// 查询
/// </summary>
uint64 exec();
private:
/// <summary>
/// 生成SQL片段
/// </summary>
/// <param name="set"></param>
/// <param name="where"></param>
/// <param name="orderby"></param>
/// <param name="limit"></param>
void make_sql(std::string& set, std::string& where, std::string& orderby, std::string& limit, std::vector<std::any>& insert_values);
private:
mysql::conn* m_conn = nullptr;
std::vector<ylib::where> m_wheres;
std::string m_table_name;
std::vector<struct ylib::update::set> m_sets;
ylib::limit m_limit;
order_by m_orderby;
};
/// <summary>
/// MYSQL INSERT
/// </summary>
class insert :public ylib::error_base {
public:
insert(mysql::conn* conn);
~insert();
/// <summary>
/// 表名
/// </summary>
/// <param name="field"></param>
/// <returns></returns>
insert& table(const std::string& table_name);
/// <summary>
/// 更新
/// </summary>
insert& set(const std::string& name, const std::any& value);
insert& set_not_pret(const std::string& name, const std::string& value);
/// <summary>
/// 查询
/// </summary>
uint64 exec();
private:
mysql::conn* m_conn = nullptr;
std::string m_table_name;
std::vector<keyvalue> m_sets;
};
/// <summary>
/// MYSQL DELETE
/// </summary>
class delete_ :public ylib::error_base {
public:
delete_(mysql::conn* conn);
~delete_();
/// <summary>
/// 表名
/// </summary>
/// <param name="field"></param>
/// <returns></returns>
delete_& table(const std::string& table_name);
/// <summary>
/// 条件[A=B]
/// </summary>
delete_& where(const std::string& name, const std::string& expression, const std::any& value);
/// <summary>
/// 条件[模糊查询]
/// </summary>
delete_& where_like(const std::string& name, const std::string& value);
/// <summary>
/// 条件[自定义]
/// </summary>
delete_& where(const std::string& expression);
/// <summary>
/// LIMIT[页]
/// </summary>
delete_& page(uint32 page, uint32 count);
/// <summary>
/// LIMIT
/// </summary>
delete_& limit(uint32 start, uint32 count);
/// <summary>
/// 排序
/// </summary>
delete_& orderby(const std::string& field, sort sort = DESC);
/// <summary>
/// 查询
/// </summary>
uint64 exec();
private:
/// <summary>
/// 生成SQL片段
/// </summary>
/// <param name="where"></param>
/// <param name="orderby"></param>
/// <param name="limit"></param>
void make_sql(std::string& where, std::string& orderby, std::string& limit, std::vector<std::any>& insert_values);
private:
mysql::conn* m_conn = nullptr;
std::vector<ylib::where> m_wheres;
std::string m_table_name;
ylib::limit m_limit;
order_by m_orderby;
};
}

View File

@@ -1,58 +0,0 @@
#pragma once
#include "base/define.h"
#include "base/error.h"
#include "base/buffer.h"
#include "util/json.h"
// HTTP
#define USE_NET_HTTP 1
// TCP
#define USE_NET_TCP 1
// UDP
#define USE_NET_UDP_NODE 1
// FTP
#define USE_NET_FTP 1
#if (USE_NET_TCP)
#define USE_NET_TCP_CLIENT 1
#define USE_NET_TCP_SERVER 1
#define USE_NET_TCP_AGENT 1
#define USE_NET_TCP_FORWARD 1
#else
#define USE_NET_TCP_CLIENT 0
#define USE_NET_TCP_SERVER 0
#define USE_NET_TCP_AGENT 0
#endif
#if (USE_NET_HTTP)
#define USE_NET_HTTP_WEBSITE 1
#define USE_NET_HTTP_CLIENT 1
#define USE_NET_HTTP_UTIL 1
#define USE_NET_HTTP_AGENT 0
#else
#define USE_NET_HTTP_WEBSITE 0
#define USE_NET_HTTP_CLIENT 0
#define USE_NET_HTTP_UTIL 0
#define USE_NET_HTTP_AGENT 0
#endif
/*请勿修改*/
#if (USE_NET_TCP_SERVER==0 || USE_NET_TCP_AGENT==0)
#ifdef USE_NET_TCP_FORWARD
#undef USE_NET_TCP_FORWARD
#endif
#define USE_NET_TCP_FORWARD 0
#else
#ifndef USE_NET_TCP_FORWARD
#undef USE_NET_TCP_FORWARD
#define USE_NET_TCP_FORWARD 1
#endif
#endif

View File

@@ -1,61 +0,0 @@
#pragma once
#include "define.h"
#include "util/file.h"
#include "util/thread.h"
#include "base/error.h"
#if USE_NET_FTP
namespace ylib
{
namespace network
{
namespace ftp
{
class client;
typedef void(*CALLBACK_FTPCLIENT_DOWNLOADING)(class ylib::network::ftp::client* client, uint32 all_size, uint32 down_size, uint64 param);
typedef void(*CALLBACK_FTPCLIENT_DOWNLOADED)(class ylib::network::ftp::client* client, bool result, uint64 param);
struct DownInfo
{
~DownInfo()
{
if (file != nullptr)
{
file->close();
delete file;
}
}
ylib::file_io* file = nullptr;
uint32 size = 0;
void* fileptr = nullptr;
std::string local_path;
std::string remote_path;
uint64 param = 0;
CALLBACK_FTPCLIENT_DOWNLOADING downloading = nullptr;
CALLBACK_FTPCLIENT_DOWNLOADED downloaded = nullptr;
bool ok = false;
};
class client :public ylib::error_base, private ylib::ithread
{
public:
client();
~client();
bool connect(const std::string& ipaddress, const std::string& username, const std::string& password, ushort port);
void close();
bool upload(const std::string& local_filepath, const std::string& remote_filepath);
bool download(const std::string& local_filepath, const std::string& remote_filepath, size_t param, CALLBACK_FTPCLIENT_DOWNLOADING downloading, CALLBACK_FTPCLIENT_DOWNLOADED downloaded);
void wait();
bool download(const std::string& local_filepath, const std::string& remote_filepath);
bool create_dir(const std::string& remote_path);
bool delete_dir(const std::string& remote_path);
bool delete_file(const std::string& remote_path);
private:
void* m_ptr = nullptr;
DownInfo* m_download = nullptr;
CALLBACK_FTPCLIENT_DOWNLOADING m_cb_downloading = nullptr;
CALLBACK_FTPCLIENT_DOWNLOADED m_cb_downloaded = nullptr;
virtual bool run() override;
};
}
}
};
#endif

View File

@@ -1,36 +0,0 @@
#pragma once
#include "http_define.h"
#include "util/cache.h"
#if USE_NET_HTTP_WEBSITE
class http_agent_listener;
class http_agent_extra;
namespace ylib
{
namespace network
{
namespace http
{
class reqpack;
class server;
class agent :public ylib::error_base
{
public:
agent();
~agent();
bool start();
void stop();
void disconnect(bool ssl, uint64 connid);
bool request(int32 wait_msec, reqpack* rp, network::http::proxy* proxy);
private:
void* get();
private:
void* m_agent_ssl;
void* m_agent;
http_agent_listener* m_listener;
bool m_ssl;
};
}
}
}
#endif

View File

@@ -1,33 +0,0 @@
#pragma once
#include "http_define.h"
#include "http_reqpack.h"
#include "http_interface.h"
#include "util/map.hpp"
namespace ylib
{
namespace network
{
namespace http
{
class cache :public network::http::interface_, public ylib::error_base
{
public:
cache();
~cache();
bool start(const server_cache_config& config);
void stop();
bool have_send(network::http::reqpack* rp);
bool enable();
std::string make_key(const std::string& filepath);
bool find_ext(const std::string& filepath);
std::string make_cache_filepath(const std::string& filepath);
private:
server_cache_config m_config;
ylib::map<std::string, std::string> m_keys;
};
}
}
}

View File

@@ -1,64 +0,0 @@
#pragma once
#include "http_define.h"
#include "http_reqpack.h"
#include "http_interface.h"
#include "http_client_plus.h"
#include "util/thread.h"
namespace ylib
{
namespace network
{
namespace http
{
class cnode :public ylib::error_base
{
public:
cnode(const cdn_config::node_config& config);
~cnode();
const cdn_config::node_config& config() { return m_config; }
int score();
bool update();
private:
network::http::client_plus m_client;
private:
cdn_config::node_config m_config;
// 管理地址
std::string m_mang_url;
// 回复耗时
timestamp m_reply_wait_msec;
// 当前带宽上传
uint64 m_send_bytes_sec;
// 当前带宽下载
uint64 m_recv_bytes_sec;
// 更新时间
timestamp m_update_sec;
// 通信状态
bool m_net_status;
// 通信状态错误描述
std::string m_net_errormsg;
// 最大带宽
uint64 m_max_band;
};
class cdn :public network::http::interface_, public ylib::error_base, private ylib::ithread
{
public:
cdn();
~cdn();
bool start(const cdn_config& config);
std::string host();
virtual bool run() override;
const cdn_config& config() { return m_config; }
private:
cdn_config m_config;
std::vector<network::http::cnode*> m_nodes;
std::string m_cdn_node_key;
uint64 m_cdn_node_max_band;
ylib::BandInfo m_cdn_node_bandinfo;
};
}
}
}

View File

@@ -1,86 +0,0 @@
#pragma once
#include "http_define.h"
#if USE_NET_HTTP_WEBSITE
#include <functional>
#include <vector>
#include "util/map.hpp"
#include "util/json.h"
namespace ylib
{
namespace network
{
namespace http
{
/*绑定域名*/
struct domain_info
{
domain_info() {
https = false;
}
// 是否HTTPS
bool https;
// 域名
std::string domain;
};
class server;
class router;
class website;
/***************************************************************
* Class控制中心
***************************************************************/
class center :public ylib::error_base
{
public:
center();
~center();
/******************************************************************
* function创建
* param
* config 配置项
* return
* 失败可通过 last_error() 返回错误信息。
******************************************************************/
bool create(const start_config& config);
bool start();
/******************************************************************
* function关闭
******************************************************************/
void close();
network::http::server* server(ushort port);
network::http::website* website(const std::string& host);
network::http::website* website_byname(const std::string& name);
const start_config& config() { return m_config; }
private:
//所有监听端口
std::vector<ushort> listen_ports();
//端口是否需要SSL
bool port_have_ssl(ushort port);
private:
// HTTP 服务
std::vector<network::http::server*> m_server;
// 站点
std::vector<network::http::website*> m_website;
// 配置缓存
//ylib::map<std::string, std::string> m_config;
// 启动信息
start_config m_config;
public:
uint64 m_temp[10];
};
}
}
}
#endif

View File

@@ -1,30 +0,0 @@
#pragma once
#include "http_define.h"
#if USE_NET_HTTP_CLIENT
namespace ylib
{
namespace network
{
namespace http
{
class client_plus;
//客户端缓存
class client_cache
{
public:
client_cache();
~client_cache();
void open(const std::string& dirpath);
bool read(network::http::client_plus* client, ylib::buffer& cache);
void set_header(network::http::client_plus* client, const std::string& url);
void close();
void write(network::http::client_plus* client);
bool read(const std::string& url, ylib::buffer& cache);
private:
bool m_open;
std::string m_dirpath;
};
}
}
}
#endif

View File

@@ -1,119 +0,0 @@
#pragma once
#include "http_define.h"
#if USE_NET_HTTP_CLIENT
#include <functional>
#include "http_header.h"
#include "http_client_cache.h"
#include "http_cookie.h"
#include "make_form.h"
class http_client_listener;
namespace ylib
{
namespace network
{
namespace http
{
class client_plus :public ylib::error_base
{
public:
client_plus();
~client_plus();
void close();
void set_timeout(uint32 connect_msec = 3000, uint32 recv_msec = 8000);
bool del(const std::string& url, const std::map<std::string, std::string>& value = std::map<std::string, std::string>());
bool get(const std::string& url, const std::map<std::string, std::string>& value = std::map<std::string, std::string>(), bool wait = true);
bool post(const std::string& url, const std::map<std::string, std::string>& value, bool to_utf8 = false);
bool post(const std::string& url, const ylib::json& value, bool to_utf8 = false);
bool post(const std::string& url, const ylib::buffer& value);
bool post(const std::string& url, const http::make_form& value);
bool head(const std::string& url);
/// <summary>
/// 连接代理服务器
/// </summary>
/// <param name="address"></param>
/// <param name="port"></param>
/// <returns></returns>
void setproxy(const std::string& address,ushort port);
network::http::header_list& headers_request();
network::http::header_list& headers_response();
uint32 status();
ylib::buffer& response();
/*设置缓存*/
void cache(client_cache* cache);
/*请求路径*/
inline const std::string& url() { return m_url; }
/*cookie*/
inline network::http::cookie& cookie() { return m_cookie; }
inline void cookie(const network::http::cookie& ck) { m_cookie = ck; }
/*[回调] 正在下载*/
void on_down_ing(const std::function<bool(void* data, uint32 downsize, uint64 alldownsize, uint64 allsize, network::http::client_plus& client)>& callback);
/*[回调] 下载结束*/
void on_down_end(const std::function<void(network::http::client_plus& client)>& callback);
/*[回调] 下载失败*/
void on_down_failed(const std::function<void(network::http::client_plus& client)>& callback);
// 清理所有Cookie缓存
static void clear_all_cookies();
friend class http_client_listener;
public:
uint64 m_temp[10];
private:
bool parseurl(std::string url);
bool connect();
bool init();
bool request();
bool post(const std::string& url);
void* client();
bool init_proxy();
private:
// HP客户端
void* m_client;
// HP客户端-SSL
void* m_client_ssl;
// HP监听器
http_client_listener* m_listener;
// 是否已初始化
bool m_init;
// 连接IP
std::string m_ipaddress;
// 连接端口
ushort m_port;
// HTTPS
bool m_ssl;
// 请求链接
std::string m_url;
// 请求路径
std::string m_path;
// 请求方式
network::http::method m_method;
// 请求数据
ylib::buffer m_request_body;
// [header] 请求
network::http::header_list m_headers_request;
// 超时时间 连接
timestamp m_timeout_connect_msec;
// 超时时间 接收
timestamp m_timeout_recv_msec;
// 缓存
client_cache* m_cache;
// cookie
network::http::cookie m_cookie;
// 请求等待
bool m_request_wait = true;
#ifndef _WIN32
public:
#endif
// 关闭
bool m_close;
// 代理服务器
ylib::AddressPort m_proxy;
};
}
}
}
#endif

View File

@@ -1,104 +0,0 @@
#pragma once
#include "http_define.h"
#if USE_NET_HTTP_WEBSITE
#include "http_request.h"
#include "http_response.h"
#include "http_reqpack.h"
#include "http_interface.h"
#define _DBL_MIN 2.2250738585072014e-308 // min positive value
#define _DBL_MAX 1.7976931348623158e+308 // max value
#define _INT_MIN (-2147483647 - 1)
#define _INT_MAX 2147483647
#define _UINT_MAX 0xffffffff
#define _LONG_MIN (-2147483647L - 1)
#define _LONG_MAX 2147483647L
#define _ULONG_MAX 0xffffffff
#ifndef _LLONG_MAX
#define _LLONG_MAX 9223372036854775807
#endif
#define _LLONG_MIN (-9223372036854775807 - 1)
#define _ULLONG_MAX 0xffffffffffffffff
#define _INT8_MIN (-127 - 1)
#define _INT16_MIN (-32767 - 1)
#define _INT32_MIN (-2147483647 - 1)
#define _INT64_MIN (-9223372036854775807 - 1)
#define _INT8_MAX 127
#define _INT16_MAX 32767
#define _INT32_MAX 2147483647
#define _INT64_MAX 9223372036854775807
#define _UINT8_MAX 0xff
#define _UINT16_MAX 0xffff
#define _UINT32_MAX 0xffffffff
#define _UINT64_MAX 0xffffffffffffffff
#define _FLT_MIN 1.175494351e-38F // min normalized positive value
#define _FLT_MAX 3.402823466e+38F // max value
using namespace ylib::network::http;
// 成功回复
#define REPLY_SUCC rpjson()["code"] = 200;return RT_OK
// 自定义回复
#define REPLY(CODE,MSG) rpjson()["code"] = CODE;rpjson()["msg"]=MSG;return RT_OK
// 失败回复
#define REPLY_ERROR(MSG) rpjson()["code"] = -1;rpjson()["msg"]=MSG;return RT_OK
/**********************************************************
* ClassHttp控制器接口
*********************************************************/
//#define check_qry_json(NAME) request()->parser()->json()[NAME].is_empty()
#define qry_json_string(NAME) request()->parser()->json()[NAME].to<std::string>(true)
#define qry_json_uint32(NAME) request()->parser()->json()[NAME].to<uint32>(true)
#define qry_json_uint64(NAME) request()->parser()->json()[NAME].to<uint64>(true)
#define qry_json_int32(NAME) request()->parser()->json()[NAME].to<int32>(true)
#define qry_json_double(NAME) request()->parser()->json()[NAME].to<double>(true)
#define qry_json_short(NAME) request()->parser()->json()[NAME].to<short>(true)
#define qry_json_bool(NAME) request()->parser()->json()[NAME].to<bool>(true)
namespace ylib
{
namespace network
{
namespace http
{
class router;
class controller :public network::http::interface_
{
public:
controller();
~controller();
network::http::request* request();
network::http::response* response();
//min和max为<=或>= ,若填-1则不使用该条件
std::string qry_string(const std::string& name,bool exception = true);
int32 qry_int32(const std::string& name, bool exception = true);
uint32 qry_uint32(const std::string& name, bool exception = true);
int64 qry_int64(const std::string& name, bool exception = true);
uint64 qry_uint64(const std::string& name, bool exception = true);
double qry_double(const std::string& name, bool exception = true);
float qry_float(const std::string& name, bool exception = true);
bool qry_empty(const std::string& name, bool exception = true);
bool qry_bool(const std::string& name, bool exception = true);
ylib::buffer qry_buffer(const std::string& name, bool exception);
// 请求参数
bool request_param(const std::string& name, std::string& value);
// 获取回复JSON
inline ylib::json& rpjson() { return response()->sjson["data"]; }
inline ylib::json& rpcode() { return response()->sjson["code"]; }
//inline ylib::json& rp() { return response()->sjson["code"]; }
inline void rp(int code, const std::string& msg = "", const ylib::json& data = ylib::json())
{
response()->sjson["code"] = code;
response()->sjson["msg"] = msg;
response()->sjson["data"] = data;
};
void send(const ylib::json& data);
friend class router;
private:
network::http::reqpack* m_reqpack = nullptr;
};
}
}
}
#endif

View File

@@ -1,27 +0,0 @@
#pragma once
#include "http_define.h"
#if USE_NET_HTTP_UTIL
#include <map>
namespace ylib
{
namespace network
{
namespace http
{
class cookie
{
public:
cookie();
~cookie();
void merge(const cookie& ck);
void merge(const std::string& ck);
std::string to_string();
void clear();
private:
std::map<std::string, std::string> m_param;
};
}
}
}
#endif

View File

@@ -1,338 +0,0 @@
#pragma once
#include <vector>
#include <map>
#include <regex>
#include "define.h"
#include "util/file.h"
#include "base/buffer.h"
#include "base/environment.h"
#define POINT_QUEUE_REQUEST_CLEAR_MAX 1000
#define POINT_QUEUE_REQUEST_CLEAR_SEC 60
#define POINT_QUEUE_RESPONSE_CLEAR_MAX 1000
#define POINT_QUEUE_RESPONSE_CLEAR_SEC 60
#define POINT_QUEUE_ROUTER_CLEAR_MAX 1000
#define POINT_QUEUE_ROUTER_CLEAR_SEC 60
#define POINT_QUEUE_REQPACK_CLEAR_MAX 1000
#define POINT_QUEUE_REQPACK_CLEAR_SEC 60
// http_agent 调试日志打印
#define HTTP_AGENT_DEBUG_PRINT 0
// http_agent 生产日志打印
#define HTTP_AGENT_PRINT 0
// http_server 调试日志打印
#define HTTP_SERVER_DEBUG_PRINT 0
// http_server 生产日志打印
#define HTTP_SERVER_PRINT 0
// http_router 生产日志打印
#define HTTP_ROUTER_PRINT 0
// http_interceptor 生产日志打印
#define HTTP_INTERCEPTOR_PRINT 0
// http lua 引擎
//#define HTTP_LUA_ENGINE 0
namespace ylib
{
namespace network
{
namespace http
{
/// <summary>
/// 服务端缓存
/// </summary>
struct server_cache_config {
// 缓存保存目录
std::string dirpath;
// 开启
bool enable = false;
// 最小过期时间
uint32 timeout_min;
// 支持扩展名
std::vector<std::string> exts;
};
/// <summary>
/// SSL验证类型
/// </summary>
enum ssl_verify_type
{
// 完全忽略验证证书的结果。当握手必须完成的话,就选中这个选项。其实真正有证书的人很少,尤其是在中国,那么如果 SSL 运用于一些免费的服务,比如 EMAIL 的时候SERVER 端最好采用这个模式。
SVT_VERIFY_NONE = 0x00,
// 希望验证对方的证书。这个是最一般的模式。对 CLIENT 来说如果设置了这样的模式验证SERVER的证书出了任何错误SSL 握手都告吹。对 SERVER 来说,如果设置了这样的模式CLIENT 倒不一定要把自己的证书交出去。如果 CLIENT 没有交出证书SERVER 自己决定下一步怎么做。
SVT_VERIFY_PEER = 0x01,
// 这是 SERVER 使用的一种模式,在这种模式下, SERVER 会向 CLIENT 要证书。如果 CLIENT 不给SSL 握手告吹
SVT_VERIFY_FAIL_IF_NO_PEER_CERT = 0x02,
// 这是仅能使用在 SSL SESSION RENEGOTIATION 阶段的一种方式。如果不是用这个模式的话,那么在 RENEGOTIATION 的时候CLIENT 都要把自己的证书送给 SERVER然后做一番分析。这个过程很消耗 CPU 时间的,而这个模式则不需要 CLIENT 在 RENEGOTIATION 的时候重复送自己的证书了。
SVT_VERIFY_CLIENT_ONCE = 0x03
};
/// <summary>
/// 主机域名配置
/// </summary>
struct host_config {
// 域名
std::string domain;
// 端口
ushort port = 0;
// 开启SSL
bool ssl = false;
};
/// <summary>
/// CDN配置
/// </summary>
struct cdn_config {
struct node_config {
std::string host;
std::string key;
std::string mang_domain;
};
bool manager = false;
bool enable = false;
std::vector<node_config> node;
uint64 max_band = 0;
std::string key;
};
/// <summary>
/// SSL配置
/// </summary>
struct ssl_config {
bool enable = false;
// 验证类型
ssl_verify_type type = SVT_VERIFY_PEER;
std::string pem_cert;
std::string pem_key;
std::string pem_ca;
std::string pem_password;
};
/// <summary>
/// 线程池配置
/// </summary>
struct threadpool_config {
// 线程数量
uint32 size = 0;
// 最大队列数量
uint32 queuemax = 0;
};
/// <summary>
/// 路由配置
/// </summary>
struct router_config {
// 线程池
threadpool_config threadpool;
};
/// <summary>
/// 会话配置
/// </summary>
struct session_config {
// 超时时间
uint32 timeout_sec = 0;
// 保存路径
std::string dirpath;
};
/// <summary>
/// 代理配置
/// </summary>
struct proxy_config {
std::string src;
std::string dst;
std::string remote;
std::string host;
std::map<std::string, std::string> header_request;
std::map<std::string, std::string> header_response;
};
/// <summary>
/// 网站配置
/// </summary>
struct website_config {
// 名称
std::string name;
// 域名列表
std::vector<host_config> host;
// 路由
router_config router;
// 会话
session_config session;
// 本地缓存
server_cache_config cache;
// CDN
cdn_config cdn;
// 代理
std::vector<proxy_config> proxy;
// GZIP
bool gzip = false;
};
/// <summary>
/// 启动信息
/// </summary>
struct start_config {
// 网站
std::vector<website_config> website;
// 证书
std::map<std::string, ssl_config> cert;
};
class agent;
class website;
// 临时接收
struct temp_recv
{
temp_recv()
{
agent_connid = 0;
agent_ssl = false;
}
void clear()
{
agent_connid = 0;
agent_ssl = false;
url.clear();
ipaddress_port.clear();
host.clear();
}
// 接收数据
ylib::buffer data;
// 代理ID
uint64 agent_connid;
// 代理SSL
bool agent_ssl;
// URL
std::string url;
// 代理连接IP及端口
std::string ipaddress_port;
// Host
std::string host;
// 缓存路径
ylib::file_io cache_file;
};
// 代理
struct proxy
{
proxy()
{
remote_port = 0;
ssl = false;
}
// 拦截地址正则
std::regex src_express;
// 拦截地址字符串
std::string src_str;
// 目标地址
std::string dst;
// 请求URL
std::string remote_url;
// 请求地址
std::string remote_ipaddress;
// 请求端口
ushort remote_port;
// 主机
std::string host;
// 附加协议头
std::map<std::string, std::string> request_headers;
std::map<std::string, std::string> response_headers;
// SSL
bool ssl;
};
// httpserver代理后连接附加数据
struct httpserver_proxy_extra
{
httpserver_proxy_extra()
{
agent = nullptr;
connid = 0;
index = 45854;
}
void* agent;
uint64 connid;
uint64 index;
};
//struct website_info
//{
// website_info()
// {
// gzip = false;
// download_maxbaud = 0;
// }
// // 根目录
// std::string rootdir;
// // GZIP
// bool gzip;
// // 默认编码方式
// std::string default_codec;
// // 带宽限制
// uint32 download_maxbaud;
//};
/*表单信息*/
struct form_info
{
form_info()
{
start = -1;
length = -1;
}
std::string disposition;
std::string content_type;
std::string name;
std::string filename;
int64 start;
int64 length;
ylib::buffer data;
};
class controller;
//请求类型
enum content_type
{
CT_FORM = 0, //表单: application/x-www-CT_FORM-urlencoded
CT_JSON = 1, //CT_JSON: application/CT_JSON
CT_TEXT = 2, //文本: text/plain
CT_NIL = 3, //无
CT_ALL = 4 //所有
};
/*HTTP请求类型*/
enum method
{
GET = 0,
POST = 1,
PUT = 2,
DEL = 3,
OTHER = 4,
HEAD = 5,
ALL = 100
};
inline std::string method_to_string(enum method m) {
switch (m) {
case GET:
return "GET";
case POST:
return "POST";
case PUT:
return "PUT";
case DEL:
return "DEL";
case OTHER:
return "OTHER";
case ALL:
return "ALL";
default:
return "unknown";
}
return "";
};
/*控制器内返回结果*/
enum response_type
{
RT_OK, //成功或已处理
RT_500, //服务器内部错误
RT_406, //服务器解析客户端数据失败或格式不正确拒绝解析
RT_401 //需要鉴权,无权限
};
//控制器指针
typedef response_type(network::http::controller::* HTTP_CTR_FUNCTION)();
}
}
}

View File

@@ -1,54 +0,0 @@
#pragma once
#include "define.h"
#if USE_NET_HTTP_UTIL
#include <map>
namespace ylib
{
namespace network
{
namespace http
{
class header
{
public:
header();
~header();
void clear();
void name(const std::string& value);
std::string name() const;
std::map<std::string, std::string> param();
void parse(const std::string& body);
void push(const std::string& value);
void push(const std::string& key, const std::string& value);
bool exist(const std::string& key);
std::string to_string() const;
private:
std::string m_name;
std::map<std::string, std::string> m_param;
std::vector<std::string> m_values;
};
class header_list
{
public:
header_list();
~header_list();
bool exist(const std::string& name) const;
ylib::network::http::header get(const std::string& name);
void set(const std::string& name, const ylib::network::http::header& header);
void set(const std::string& name, const std::string& value);
void del(const std::string& name);
std::map<std::string, std::string> to() const;
size_t size();
void clear();
private:
std::map<std::string, header> m_headers;
};
}
}
}
#endif

View File

@@ -1,34 +0,0 @@
#pragma once
#include "define.h"
#if USE_NET_HTTP_WEBSITE
#include "net/http_interface.h"
namespace ylib
{
namespace network
{
namespace http
{
/******************************************************
* class域名器
******************************************************/
class ssl;
class host :public ylib::error_base, public network::http::interface_
{
public:
host();
~host();
void init(const std::string& host, ushort port, network::http::ssl* ssl = nullptr);
inline network::http::ssl* ssl() { return m_ssl; }
inline bool equal(const std::string& host) { return m_host == host; }
inline const std::string& hostname() { return m_return_host; }
private:
std::string m_host;
std::string m_return_host;
ushort m_port;
network::http::ssl* m_ssl;
};
}
}
}
#endif

View File

@@ -1,39 +0,0 @@
#pragma once
#include "define.h"
#if USE_NET_HTTP_WEBSITE
#include <regex>
#include <functional>
#include "net/http_interface.h"
#include "util/array.hpp"
namespace ylib
{
namespace network
{
namespace http
{
class reqpack;
struct interceptor_info {
std::regex express;
std::string express_string;
std::function<bool(network::http::reqpack* rp, const std::string& express)> callback;
};
/******************************************************
* class拦截器
******************************************************/
class interceptor :public ylib::error_base, public network::http::interface_
{
public:
interceptor();
~interceptor();
size_t add(const std::string& regex_express, std::function<bool(network::http::reqpack* rp,const std::string& express)> callback);
bool trigger(const std::string& url, network::http::reqpack* rp);
private:
ylib::nolock_array<interceptor_info*> m_array;
};
}
}
}
#endif

View File

@@ -1,32 +0,0 @@
#pragma once
#include "http_define.h"
#if USE_NET_HTTP_WEBSITE
#include <functional>
#include <map>
using namespace ylib::network::http;
namespace ylib
{
namespace network
{
namespace http
{
/*************************************************************************
* class通用接口
*************************************************************************/
class website;
class center;
class interface_
{
public:
inline void website(network::http::website* website) { m_website = website; }
inline network::http::website* website() { return m_website; }
inline void center(network::http::center* center) { m_center = center; }
inline network::http::center* center() { return m_center; }
private:
network::http::website* m_website;
network::http::center* m_center;
};
}
}
}
#endif

View File

@@ -1,130 +0,0 @@
#pragma once
#include "http_define.h"
#if USE_NET_HTTP_WEBSITE
#include <map>
namespace ylib
{
namespace network
{
namespace http
{
class parser;
/*************************************************************************
* classFORM表单解析器
*************************************************************************/
class form_parser {
public:
form_parser();
~form_parser();
std::vector<std::string> names();
bool get(const std::string& name, form_info& info);
bool write_file(const std::string& name, const std::string& filepath);
friend class parser;
private:
bool parse(ylib::buffer* data);
void parse_count(std::vector<uint32>& starts, std::vector<uint32>& lengths);
void parse_form(uint32 start, uint32 length);
char getchar(size_t index);
private:
ylib::buffer* m_data;
std::map<std::string, form_info> m_infos;
};
/*************************************************************************
* class解析器
*************************************************************************/
class parser
{
public:
/******************************************************************
* function初始化
* param
*
* url 请求地址
* method 请求类型
* data 请求数据
* content_type 类型协议头
******************************************************************/
bool init(const std::string& url, const network::http::method& method, const ylib::buffer& data, const std::string& content_type);
public:
parser();
~parser();
const ylib::json& json();
std::string text();
/******************************************************************
* function取URL参数
* param
* name 名称
* value 数据
******************************************************************/
bool url_param(const std::string& name, std::string& value);
bool url_param_exist(const std::string& name);
/******************************************************************
* function取URL请求参数名列表
******************************************************************/
std::vector<std::string> url_param_names();
/******************************************************************
* function取BODY参数
* param
* name 名称
* value 数据
******************************************************************/
bool body_param(const std::string& name, std::string& value);
bool body_param_exist(const std::string& name);
/******************************************************************
* function取BODY请求参数名列表
******************************************************************/
std::vector<std::string> body_param_names();
/******************************************************************
* function取BODY请求参数名列表
******************************************************************/
form_parser* form();
const std::map<std::string, std::string>& url_param() { return m_url_param; }
const std::map<std::string, std::string>& body_param() { return m_body_param; }
private:
/******************************************************************
* function解析URL
******************************************************************/
void parse_url(const std::string& url, std::map<std::string, std::string>& map);
/******************************************************************
* function解析JSON
******************************************************************/
void parse_json();
/******************************************************************
* function解析FORM表单
******************************************************************/
void parse_form();
/******************************************************************
* function解析URL格式数据
******************************************************************/
bool read_url_param(const std::map<std::string, std::string>& map, const std::string& name, std::string& value);
private:
// URL参数
std::map<std::string, std::string> m_url_param;
// BODY参数
std::map<std::string, std::string> m_body_param;
// JSON参数
ylib::json m_json_param;
// FORM解析器
network::http::form_parser m_form;
// 请求地址
std::string m_url;
// 请求数据
ylib::buffer m_data;
// 请求内容类型
std::string m_content_type;
// 请求类型
network::http::method m_method;
};
}
}
}
#endif

View File

@@ -1,113 +0,0 @@
#pragma once
#include "http_define.h"
#if USE_NET_HTTP_WEBSITE
#include "http_server.h"
#include "util/strutils.h"
#include "util/time.h"
namespace ylib
{
namespace network
{
namespace http
{
class server;
class response;
class request;
class website;
/*************************************************************************
* class请求包
*************************************************************************/
class reqpack
{
public:
reqpack();
~reqpack();
void init(const std::string& url, const std::string& host, const ylib::buffer& data, uint64 connid, network::http::server* server);
void clear();
network::http::request* request();
network::http::response* response();
const std::string& host()
{
/*获取基本请求信息*/
return m_host;
}
network::http::method method();
const std::string& filepath();
void filepath(const std::string& path);
network::http::server* server()
{
return m_server;
}
ylib::buffer& data()
{
return m_data;
}
const std::string& url()
{
return m_url;
}
const std::string& referrer()
{
return m_referrer;
}
const uint64& connid()
{
return m_connid;
}
network::http::website* website() {
return m_website;
}
void website(network::http::website* website) {
m_website = website;
}
timestamp begin_msec() {
return m_begin_msec;
}
std::string exec_msec() {
return std::to_string(time::now_msec() - m_begin_msec);
}
const std::string& remote() {
if (m_remote_ipaddress.empty()) {
ushort port;
m_server->remote(connid(), m_remote_ipaddress, port);
}
return m_remote_ipaddress;
}
ylib::json& extra() { return m_extra; }
private:
// 请求主机
std::string m_host;
// 请求方式
network::http::method m_method;
// 请求路径
std::string m_filepath;
// HPSERVER
network::http::server* m_server;
// 转发来路
std::string m_referrer;
// 请求ID
uint64 m_connid;
// 站点
network::http::website* m_website;
// 接收数据
ylib::buffer m_data;
// URL
std::string m_url;
// 请求发起时间
timestamp m_begin_msec;
// 远程IP
std::string m_remote_ipaddress;
// 附加数据
ylib::json m_extra;
private:
network::http::request* m_request;
network::http::response* m_response;
};
}
}
}
#endif

View File

@@ -1,79 +0,0 @@
#pragma once
#include "http_define.h"
#if USE_NET_HTTP_WEBSITE
#include <string>
#include <vector>
#include "http_session.h"
#include "http_parser.h"
#include "http_interface.h"
namespace ylib
{
namespace network
{
namespace http
{
class reqpack;
class server;
/********************************************************************
* classHttp请求解析类
********************************************************************/
class request :public network::http::interface_
{
public:
request();
~request();
/***************************************************************************
* function取协议头
* param
* name 名称
* value 内容
***************************************************************************/
bool header(const std::string& name, std::string& value);
/***************************************************************************
* function取请求类型
***************************************************************************/
network::http::method method();
/***************************************************************************
* function取请求路径
***************************************************************************/
std::string filepath();
/***************************************************************************
* function取请求主机
***************************************************************************/
std::string host();
/***************************************************************************
* function取Session
***************************************************************************/
network::http::session& session(const std::string& session_id);
/// <summary>
/// 取TOKEN
/// </summary>
/// <returns></returns>
std::string token();
/***************************************************************************
* function取reqpack
***************************************************************************/
network::http::reqpack* reqpack();
/***************************************************************************
* function解析器
***************************************************************************/
network::http::parser* parser();
/***************************************************************************
* functionGet Browserr Remote Ipaddress
***************************************************************************/
std::string remote_ipaddress(bool find_header = false, const std::string& inside_ipaddress = "");
ushort remote_port();
friend class reqpack;
private:
network::http::reqpack* m_reqpack;
network::http::session m_session;
network::http::parser m_parser;
};
}
}
}
#endif

View File

@@ -1,47 +0,0 @@
#pragma once
#include "http_define.h"
#if USE_NET_HTTP_WEBSITE
#include <string>
#include <vector>
#include <list>
#include "http_header.h"
#include "http_interface.h"
namespace ylib
{
namespace network
{
namespace http
{
class server;
class reqpack;
class response :public network::http::interface_
{
public:
response();
~response();
void init(reqpack* rp);
bool send(const char* buf, size_t buf_len, ushort stateNum = 200, const std::string& stateDesc = "OK");
bool send(const ylib::buffer& value, ushort stateNum = 200, const std::string& stateDesc = "OK");
bool send(const std::string& value, ushort stateNum = 200, const std::string& stateDesc = "OK");
bool send(const ylib::json& json, ushort stateNum = 200, const std::string& stateDesc = "OK");
bool send_file(const std::string& filepath, int32 downbaud = -1, ushort stateNum = 200, const std::string& stateDesc = "OK");
std::map<std::string, std::string>* headers();
bool redirect(const std::string& filepath, bool MovedPermanently = false);
bool forward(const std::string& filepath);
public:
ylib::json sjson;
private:
bool filecache(const uint64& last_modify_time);
bool fileoffset(long filesize, long& start, long& len);
private:
std::map<std::string, std::string> m_headers;
bool m_response;
network::http::reqpack* m_reqpack;
};
}
}
}
#endif

View File

@@ -1,182 +0,0 @@
#pragma once
#include "http_define.h"
#if USE_NET_HTTP_WEBSITE
#include "http_interface.h"
#include <functional>
#include <map>
#include <regex>
#include "util/array.hpp"
#include "util/queue.hpp"
#include "util/thread.h"
//#include "sol/sol.hpp"
class IHPThreadPool;
namespace ylib
{
namespace network
{
namespace http
{
class reqpack;
class http_server_lst;
class request;
class response;
class interceptor;
/*************************************
* struct订阅信息
*************************************/
struct subscribe_info {
subscribe_info()
{
method = network::http::ALL;
controller = false;
controller_function = nullptr;
}
// 请求路径
std::regex express;
// 请求类型
network::http::method method;
// 回调函数
std::function<void(network::http::request*, network::http::response*,void *extra)> callback;
// 控制器。为控制器则启动下面两个属性
bool controller;
// 创建控制器类指针
std::function<void* ()> create_controller_callback;
// 控制器函数
HTTP_CTR_FUNCTION controller_function;
#if HTTP_LUA_ENGINE == 1
// LUA
std::string lua_filepath;
// LUA虚拟机初始化回调
std::function<void(sol::state& state)> lua_init_state;
#endif
// 附加数据
void* extra = nullptr;
};
/*************************************************************************
* class路由中专服务
*************************************************************************/
class router :public ylib::error_base, public network::http::interface_, private ylib::ithread
{
public:
/*线程参数信息*/
struct thread_param_info
{
void clear() {}
network::http::router* router;
network::http::reqpack* reqpack;
};
public:
router();
~router();
/******************************************************************
* function启动
* param
* config 配置项
* return
* 失败可通过 last_error() 返回错误信息。
******************************************************************/
bool start(const router_config& config);
/******************************************************************
* function关闭
******************************************************************/
void close();
/******************************************************************
* function拦截器
******************************************************************/
network::http::interceptor* interceptor();
/******************************************************************
* function订阅
* desc浏览器请求会首先触发订阅订阅未找到符合项则触发 other 传入函数。
* param
* path 路径
* method 请求类型
* callback 触发回调
* return
* 同一地址不允许订阅两次
******************************************************************/
void subscribe(
const std::string& path,
network::http::method method,
std::function<void(network::http::request*, network::http::response*, void*)> callback,
void* extra = nullptr
);
#define SUBSCRIBE(ROUTER,CONTROLLER,FUNCTION,PATH,METHOD) ROUTER->subscribe([]()->void*{return new CONTROLLER;},(ylib::network::http::HTTP_CTR_FUNCTION)&CONTROLLER::FUNCTION,PATH,METHOD)
void subscribe(
std::function<void* ()> create_controller_callback,
network::http::HTTP_CTR_FUNCTION function,
std::string path,
network::http::method method
);
#if HTTP_LUA_ENGINE == 1
void subscribe(
const std::string& lua_filepath,
std::string path,
network::http::method method,
std::function<void(sol::state& state)> init_state = nullptr
);
#endif
/******************************************************************
* function其它
* desc未订阅请求触发该回调
* param
* callback 触发回调
******************************************************************/
void other(std::function<void(network::http::request*, network::http::response*)> callback);
/******************************************************************
* function数据接收后回调
******************************************************************/
void on_recved(std::function<void(const ylib::buffer& begin, ylib::buffer* end)> callback);
/******************************************************************
* function数据发送前回调
* desc不支持大文件断点传输方式
******************************************************************/
void on_sendbefore(std::function<void(const ylib::buffer& begin, ylib::buffer* end)> callback);
/******************************************************************
* function线程回调[禁止调用]
* descput提交后投递到线程池线程池开始执行调用该回调。
* param
* param 线程参数
******************************************************************/
void __thread_callback(reqpack* rq);
friend class http_server_lst;
friend class response;
/******************************************************************
* function队列数
******************************************************************/
size_t queue_size();
private:
// 添加任务
void push(reqpack* rp);
// 是否为代理任务
bool is_proxy(reqpack* rp);
// 是否为CDN服务
bool is_cdn(reqpack* rp);
#if HTTP_LUA_ENGINE == 1
// LUA执行
void lua_engine(reqpack *rp,const network::http::subscribe_info& info);
#endif
private:
// 订阅列表
ylib::nolock_array<network::http::subscribe_info*> m_subscribe;
// 线程池
IHPThreadPool* m_threadpool;
// [回调] 未订阅请求
std::function<void(network::http::request*, network::http::response*)> m_callback_other;
// [回调] 接收后
std::function<void(const ylib::buffer& begin, ylib::buffer* end)> m_callback_recved;
// [回调] 发送前
std::function<void(const ylib::buffer& begin, ylib::buffer* end)> m_callback_sendbefore;
// 拦截器
network::http::interceptor* m_interceptor;
private:
ylib::queue<network::http::reqpack*> m_handle_queue;
router_config m_config;
// 通过 ithread 继承
virtual bool run() override;
};
}
}
}
#endif

View File

@@ -1,87 +0,0 @@
#pragma once
#include "http_define.h"
#if USE_NET_HTTP_WEBSITE
#include <string>
#include <vector>
#include <map>
#include <functional>
#include <map>
#include "http_interface.h"
#include "qps.hpp"
namespace ylib
{
namespace network
{
namespace http
{
class http_server_lst;
class host;
/*************************************************************************
* classHTTP服务器
*************************************************************************/
class server :public ylib::error_base, public network::http::interface_
{
public:
server();
~server();
bool create(bool https, ushort port);
/******************************************************************
* Function启动
* Param
* ipaddress 监听地址
* port 监听端口
******************************************************************/
bool start();
/******************************************************************
* Function关闭
******************************************************************/
bool close();
/******************************************************************
* Function取远程信息
* Param
* connid 连接ID
* ipaddress 远程地址
* port 远程端口
******************************************************************/
bool remote(uint64 connid, std::string& ipaddress, ushort& port);
/******************************************************************
* FunctionHP服务指针
******************************************************************/
void* hpserver();
/******************************************************************
* Function每秒请求数
******************************************************************/
network::qps* qps();
inline const ushort port() { return m_port; }
#if USE_NET_HTTP_AGENT == 1
inline network::http::agent* agent() { return m_agent; }
#endif
public:
bool m_init_ssl;
private:
friend class http_server_lst;
private:
// HP HttpServer 指针
void* m_server;
// HP Listener 指针
network::http::http_server_lst* m_listener;
// https
bool m_https;
// 端口
ushort m_port;
// QPS
network::qps m_qps;
#if USE_NET_HTTP_AGENT == 1
// 代理指针
network::http::agent* m_agent;
#endif
};
}
}
}
#endif

View File

@@ -1,54 +0,0 @@
#pragma once
#include "http_define.h"
#if USE_NET_HTTP_WEBSITE
#include "HPSocket/HPSocket.h"
#include <string>
namespace ylib
{
namespace network
{
namespace http
{
class server;
class agent;
class http_server_lst : public IHttpServerListener
{
public:
public:
http_server_lst(server* server);
~http_server_lst();
friend class server;
private:
EnHandleResult OnPrepareListen(ITcpServer* pSender, SOCKET soListen);
EnHandleResult OnAccept(ITcpServer* pSender, CONNID dwConnID, UINT_PTR soClient);
EnHandleResult OnHandShake(ITcpServer* pSender, CONNID dwConnID);
EnHandleResult OnReceive(ITcpServer* pSender, CONNID dwConnID, int iLength);
virtual EnHandleResult OnReceive(ITcpServer* pSender, CONNID dwConnID, const BYTE* pData, int iLength) override;
EnHandleResult OnSend(ITcpServer* pSender, CONNID dwConnID, const BYTE* pData, int iLength);
EnHandleResult OnShutdown(ITcpServer* pSender);
EnHandleResult OnClose(ITcpServer* pSender, CONNID dwConnID, EnSocketOperation enOperation, int iErrorCode);
EnHttpParseResult OnMessageBegin(IHttpServer* pSender, CONNID dwConnID);
EnHttpParseResult OnRequestLine(IHttpServer* pSender, CONNID dwConnID, LPCSTR lpszMethod, LPCSTR lpszUrl);
EnHttpParseResult OnStatusLine(IHttpServer* pSender, CONNID dwConnID, USHORT usStatusCode, LPCSTR lpszDesc);
EnHttpParseResult OnHeader(IHttpServer* pSender, CONNID dwConnID, LPCSTR lpszName, LPCSTR lpszValue);
EnHttpParseResult OnHeadersComplete(IHttpServer* pSender, CONNID dwConnID);
EnHttpParseResult OnChunkHeader(IHttpServer* pSender, CONNID dwConnID, int iLength);
EnHttpParseResult OnChunkComplete(IHttpServer* pSender, CONNID dwConnID);
EnHttpParseResult OnUpgrade(IHttpServer* pSender, CONNID dwConnID, EnHttpUpgradeType enUpgradeType);
EnHttpParseResult OnBody(IHttpServer* pSender, CONNID dwConnID, const BYTE* pData, int iLength);
EnHttpParseResult OnMessageComplete(IHttpServer* pSender, CONNID dwConnID);
EnHttpParseResult OnParseError(IHttpServer* pSender, CONNID dwConnID, int iErrorCode, LPCSTR lpszErrorDesc);
EnHandleResult OnWSMessageHeader(IHttpServer* pSender, CONNID dwConnID, BOOL bFinal, BYTE iReserved, BYTE iOperationCode, const BYTE lpszMask[4], ULONGLONG ullBodyLen);
EnHandleResult OnWSMessageBody(IHttpServer* pSender, CONNID dwConnID, const BYTE* pData, int iLength);
EnHandleResult OnWSMessageComplete(IHttpServer* pSender, CONNID dwConnID);
private:
// HPSERVER 指针
network::http::server* m_server;
};
}
}
}
#endif

View File

@@ -1,68 +0,0 @@
#pragma once
#include "http_define.h"
#if USE_NET_HTTP_WEBSITE
#include <map>
#include <string>
#include <vector>
#include "util/counter.hpp"
namespace ylib
{
namespace network
{
namespace http
{
class website;
class server;
/// <summary>
/// 会话数据
/// </summary>
class session
{
public:
session();
~session();
/// <summary>
/// 初始化
/// </summary>
/// <param name="id"></param>
void init(network::http::website* website,const std::string& id);
/// <summary>
/// 唯一ID
/// </summary>
/// <returns></returns>
std::string id();
/// <summary>
/// 更新(防止过期)
/// </summary>
void update();
/// <summary>
/// 置数据
/// </summary>
/// <param name="name"></param>
/// <param name="value"></param>
void set(const std::string& name,const std::string& value);
/// <summary>
/// 读数据
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
std::string get(const std::string& name);
/// <summary>
/// 校验是否过期
/// </summary>
/// <returns></returns>
bool check();
private:
// 唯一ID
std::string m_id;
// 网站
network::http::website* m_website = nullptr;
};
}
}
}
#endif

View File

@@ -1,47 +0,0 @@
#pragma once
#include "http_define.h"
#if USE_NET_HTTP_WEBSITE
#include <functional>
#include "http_interface.h"
#include <map>
namespace ylib
{
namespace network
{
namespace http
{
class server;
/******************************************************
* class域名器
******************************************************/
class ssl :public ylib::error_base, public network::http::interface_
{
public:
/**********************************************************************************************
* function构造函数
* param
* server HTTP服务
* config 配置
**********************************************************************************************/
ssl(network::http::server* server,ssl_config config);
~ssl();
/**********************************************************************************************
* function注册证书
**********************************************************************************************/
bool regist();
/**********************************************************************************************
* function绑定
**********************************************************************************************/
bool bind(const std::string& host);
private:
ssl_config m_config;
std::string m_pem_cert_data;
std::string m_pem_key_data;
std::string m_pem_ca_data;
network::http::server* m_server;
int32 m_index;
};
}
}
}
#endif

View File

@@ -1,72 +0,0 @@
#pragma once
#include "http_define.h"
#if USE_NET_HTTP_UTIL
#include <functional>
#include <map>
#include <regex>
#include "http_interface.h"
#include "util/array.hpp"
#include "util/localstorage.h"
namespace ylib
{
namespace network
{
namespace http
{
class server;
class router;
class host;
class agent;
class cache;
class cdn;
class website :public ylib::error_base, public network::http::interface_
{
public:
public:
website();
~website();
/******************************************************************
* function启动
* param
* config 配置项
* return
* 失败可通过 last_error() 返回错误信息。
******************************************************************/
bool start(const website_config& config);
/******************************************************************
* function关闭
******************************************************************/
void close();
network::http::router* router();
inline network::http::cache* cache() { return m_cache; }
inline network::http::cdn* cdn() { return m_cdn; }
ylib::local_storage* session() { return m_session_local_storage; }
const website_config& config() { return m_config; }
bool host(const std::string& host);
ylib::nolock_array<network::http::proxy*>* proxy();
private:
// 文件缓存
network::http::cache* m_cache;
// SESSION缓存
ylib::local_storage* m_session_local_storage;
// router路由 服务
network::http::router* m_router;
// CDN服务
network::http::cdn* m_cdn;
// HOST
std::vector<network::http::host*> m_hosts;
// HTTPS
bool m_https;
// 反向代理
ylib::nolock_array<network::http::proxy*> m_proxy;
// 配置
website_config m_config;
};
}
}
}
#endif

View File

@@ -1,27 +0,0 @@
#pragma once
#include "http_define.h"
#if USE_NET_HTTP_UTIL
#include "util/vector.hpp"
namespace ylib
{
namespace network
{
namespace http
{
class make_form
{
public:
make_form();
~make_form();
bool add(const std::string& name, const std::string& value);
bool add(const std::string& name, const std::string& filename, const std::string& content_type, const ylib::buffer& data);
bool make(ylib::buffer& data, std::string& boundary) const;
private:
ylib::vector<form_info*> m_list;
ylib::buffer m_data;
};
}
}
}
#endif

View File

@@ -1,62 +0,0 @@
#pragma once
#include <mutex>
#include "base/define.h"
#include "util/system.h"
namespace ylib
{
namespace network
{
class qps
{
public:
qps()
{
m_record = false;
}
void request(const uint64& size, bool no_count = false)
{
if (m_record == false)
return;
std::unique_lock<std::mutex> guard(m_mutex);
if (no_count == false)
request_sec_count++;
request_sec_size += size;
}
void response(const uint64& size, bool no_count = false)
{
if (m_record == false)
return;
std::unique_lock<std::mutex> guard(m_mutex);
if (no_count == false)
response_sec_count++;
response_sec_size += size;
}
void record(uint32 wait_msec = 1000)
{
request_sec_count = 0;
request_sec_size = 0;
response_sec_count = 0;
response_sec_size = 0;
m_record = true;
system::sleep_msec(wait_msec);
m_record = false;
}
public:
// 每秒请求数
uint64 request_sec_count;
// 每秒请求大小
uint64 request_sec_size;
// 每秒回复数
uint64 response_sec_count;
// 每秒回复大小
uint64 response_sec_size;
private:
std::mutex m_mutex;
// record
bool m_record;
};
}
}

View File

@@ -1,33 +0,0 @@
#pragma once
#include <string>
#include "base/define.h"
#include "base/buffer.h"
#include "base/error.h"
#include "util/map.hpp"
namespace ylib
{
namespace network
{
namespace tcp
{
class agent;
class server;
class tcp2tcp :public ylib::error_base
{
public:
tcp2tcp();
~tcp2tcp();
bool start(const std::string& listen_address, ushort listen_port, bool agent_async_connect = false/*是否异步*/, ylib::receive_model agent_model = PUSH_DEFAULT, ylib::receive_model server_model = PUSH_DEFAULT);
void stop();
network::tcp::server* server() { return m_server; }
network::tcp::agent* agent() { return m_agent; }
private:
// TCP服务
network::tcp::server* m_server = nullptr;
// TCP代理
network::tcp::agent* m_agent = nullptr;
};
}
}
}

View File

@@ -1,65 +0,0 @@
#pragma once
#include <string>
#include "base/define.h"
#include "base/buffer.h"
#include "base/error.h"
#include "util/map.hpp"
#include "net/http_define.h"
class ITcpAgent;
namespace ylib
{
namespace network
{
namespace tcp
{
class agent_lst;
class agent :public ylib::error_base
{
public:
agent();
~agent();
// 启动,是否采用异步
bool start(bool async = false, ylib::receive_model model = ylib::PUSH_DEFAULT);
void stop();
bool connect(const std::string& address, const ushort& port, uint64& connid, void* extra = nullptr);
bool disConnect(uint64 connid);
bool isConnect(uint64 connid);
bool send(uint64 connid, const char* data, uint32 len);
bool send(uint64 connid, const ylib::buffer& data);
void* extra_ptr(uint64 connid);
bool extra_ptr(uint64 connid, void* extra);
template<typename T>
T* extra(uint64 connid)
{
return (T*)extra_ptr(connid);
}
ITcpAgent* getHP() {
return m_agent;
}
void on_handshake(std::function<void(ylib::network::tcp::agent*, uint64)> callback) { m_on_handshake_callback = callback; }
void on_send(std::function<void(ylib::network::tcp::agent*, uint64, const char*, int)> callback) { m_on_send_callback = callback; }
void on_receive(std::function<void(ylib::network::tcp::agent*, uint64, const char*, int)> callback) { m_on_receive_callback = callback; }
void on_receive(std::function<void(ylib::network::tcp::agent*, uint64, int)> callback) { m_on_receive_notdata_callback = callback; }
void on_close(std::function<void(ylib::network::tcp::agent*, uint64)> callback) { m_on_close_callback = callback; }
void on_shutdown(std::function<void(ylib::network::tcp::agent*)> callback) { m_on_shutdown_callback = callback; }
void on_prepareconnect(std::function<void(ylib::network::tcp::agent*, uint64)> callback) { m_on_prepareconnect_callback = callback; }
void on_connect(std::function<void(ylib::network::tcp::agent*, uint64)> callback) { m_on_connect_callback = callback; }
friend class agent_lst;
public:
std::function<void(ylib::network::tcp::agent*, uint64, const char*, int)> m_on_receive_callback;
private:
std::function<void(ylib::network::tcp::agent*, uint64)> m_on_handshake_callback;
std::function<void(ylib::network::tcp::agent*, uint64, const char*, int)> m_on_send_callback;
std::function<void(ylib::network::tcp::agent*, uint64, int)> m_on_receive_notdata_callback;
std::function<void(ylib::network::tcp::agent*, uint64)> m_on_close_callback;
std::function<void(ylib::network::tcp::agent*)> m_on_shutdown_callback;
std::function<void(ylib::network::tcp::agent*, uint64)> m_on_prepareconnect_callback;
std::function<void(ylib::network::tcp::agent*, uint64)> m_on_connect_callback;
ITcpAgent* m_agent = nullptr;
network::tcp::agent_lst* m_listener = nullptr;
ylib::receive_model m_model = ylib::PUSH_DEFAULT;
};
}
}
}

View File

@@ -1,32 +0,0 @@
#pragma once
#include "define.h"
#ifdef USE_NET_TCP_AGENT
#include <string.h>
#include "HPSocket/HPSocket.h"
namespace ylib
{
namespace network
{
namespace tcp
{
class agent;
class agent_lst :public ITcpAgentListener
{
public:
agent_lst(ylib::network::tcp::agent* agent);
~agent_lst();
EnHandleResult OnHandShake(ITcpAgent* pSender, CONNID dwConnID) override;
EnHandleResult OnSend(ITcpAgent* pSender, CONNID dwConnID, const BYTE* pData, int iLength) override;
EnHandleResult OnReceive(ITcpAgent* pSender, CONNID dwConnID, const BYTE* pData, int iLength) override;
EnHandleResult OnReceive(ITcpAgent* pSender, CONNID dwConnID, int iLength) override;
EnHandleResult OnClose(ITcpAgent* pSender, CONNID dwConnID, EnSocketOperation enOperation, int iErrorCode) override;
EnHandleResult OnShutdown(ITcpAgent* pSender) override;
EnHandleResult OnPrepareConnect(ITcpAgent* pSender, CONNID dwConnID, SOCKET socket) override;
EnHandleResult OnConnect(ITcpAgent* pSender, CONNID dwConnID) override;
private:
ylib::network::tcp::agent* m_agent = nullptr;
};
}
}
}
#endif

View File

@@ -1,54 +0,0 @@
#pragma once
#include "define.h"
#ifdef USE_NET_TCP_CLIENT
#include <string>
#include <functional>
#include "base/buffer.h"
#include "base/error.h"
class ITcpClient;
namespace ylib
{
namespace network
{
namespace tcp
{
class client_lst;
class client :public ylib::error_base
{
public:
client(ylib::receive_model model = ylib::PUSH_DEFAULT);
~client();
// 通过 IClient 继承
bool start();
bool start(const ylib::AddressPort& remote_ap);
bool disconn();
bool close(uint32 wait_msec = 0);
bool connect(const ylib::AddressPort& remote_ap, int32 wait_msec = -1);
bool send(const char* buff, uint32 len);
inline const ITcpClient* getHP() { return m_client; }
friend class client_lst;
public:
void on_recv(std::function<void(ylib::network::tcp::client*, const char*, uint32)> callback) { m_callback_onrecv = callback; }
void on_accept(std::function<void(ylib::network::tcp::client*)> callback) { m_callback_onaccept = callback; }
void on_close(std::function<void(ylib::network::tcp::client*)> callback) { m_callback_onclose = callback; }
void on_filter(std::function<void(ylib::network::tcp::client*, uint32)> callback) { m_callback_onfilter = callback; }
private:
std::function<void(ylib::network::tcp::client*)> m_callback_onaccept;
std::function<void(ylib::network::tcp::client*)> m_callback_onclose;
std::function<void(ylib::network::tcp::client*, const char*, uint32)> m_callback_onrecv;
std::function<void(ylib::network::tcp::client*, uint32)> m_callback_onfilter;
ylib::AddressPort m_remote_ap;
// 是否PULL模型
bool m_ispull = false;
ITcpClient* m_client = nullptr;
client_lst* m_client_listener = nullptr;
ylib::receive_model m_model = ylib::PUSH_DEFAULT;
};
}
}
}
#endif

View File

@@ -1,36 +0,0 @@
#pragma once
#include "define.h"
#ifdef USE_NET_TCP_CLIENT
#include <string.h>
#include "HPSocket/HPSocket.h"
namespace ylib
{
namespace network
{
namespace tcp
{
/*接收数据的线程池调用线程,用于再调用用户提供的指针,主要是考虑到 m_sportMode 模式才会使用到该函数*/
void __HP_CALL callback_thread_recv_tcpclient(PVOID param);
class client;
class client_lst :public CTcpClientListener
{
public:
client_lst(client* client);
~client_lst();
friend class client;
private:
virtual EnHandleResult OnPrepareConnect(ITcpClient* pSender, CONNID dwConnID, SOCKET socket) override;
virtual EnHandleResult OnConnect(ITcpClient* pSender, CONNID dwConnID) override;
virtual EnHandleResult OnHandShake(ITcpClient* pSender, CONNID dwConnID) override;
virtual EnHandleResult OnReceive(ITcpClient* pSender, CONNID dwConnID, const BYTE* pData, int iLength) override;
virtual EnHandleResult OnSend(ITcpClient* pSender, CONNID dwConnID, const BYTE* pData, int iLength) override;
virtual EnHandleResult OnClose(ITcpClient* pSender, CONNID dwConnID, EnSocketOperation enOperation, int iErrorCode) override;
virtual EnHandleResult OnReceive(ITcpClient* pSender, CONNID dwConnID, int iLength) override;
private:
int m_state;
ylib::network::tcp::client* m_client;
};
}
}
}
#endif

View File

@@ -1,35 +0,0 @@
#pragma once
#include "net/tcp2tcp.h"
#include "util/map.hpp"
namespace ylib
{
namespace network
{
namespace tcp
{
class forward
{
public:
struct Packages : public std::vector<ylib::buffer>
{
};
public:
forward();
~forward();
bool start(const std::string& listen_address, ushort listen_port);
void stop();
void setAP(const ylib::AddressPort& remote) { m_remote = remote; }
void setMaxConntionCount(uint32 max) { m_max_connection_count = max; }
uint64 connectionCount();
void disIpAddress(const std::string& ipaddress);
private:
ylib::AddressPort m_remote;
network::tcp::tcp2tcp m_t2t;
uint32 m_max_connection_count = 0;
// 待发送
ylib::map<uint64, Packages*> m_wait_send_data;
};
}
}
}

View File

@@ -1,81 +0,0 @@
#pragma once
#include <functional>
#include "net/define.h"
#include "base/error.h"
#ifdef USE_NET_TCP_SERVER
class ITcpServer;
namespace ylib
{
namespace network
{
namespace tcp
{
class server_lst;
/****************************************************************
* Class: TCP服务器
* Desc使用HPSocket开源库。
****************************************************************/
class server :public ylib::error_base
{
public:
server();
~server();
// 通过 IServer 继承
bool start(const ylib::AddressPort& bind_ap, ylib::receive_model model = ylib::PUSH_DEFAULT);
void close();
bool send(uint64 connid, const char* data, uint32 len);
bool send(uint64 connid, const ylib::buffer& data);
bool started();
bool disConnect(uint64 connid);
bool isConnect(uint64 connid);
template<typename T>
T* extra(uint64 connid)
{
return (T*)extra_ptr(connid);
}
void* extra_ptr(uint64 connid);
bool extra_ptr(uint64 connid, void* extra);
inline ITcpServer* getHP() { return m_server; }
/****************************************************************
* Fun[事件]连接
****************************************************************/
void on_accept(std::function<void(ylib::network::tcp::server* server, uint64 connid)> callback) { m_callback_accept = callback; }
/****************************************************************
* Fun[事件]关闭
****************************************************************/
void on_close(std::function<void(ylib::network::tcp::server* server, uint64 connid)> callback) { m_callback_close = callback; }
/****************************************************************
* Fun[事件]接收
****************************************************************/
void on_recv(std::function<void(ylib::network::tcp::server* server, uint64 connid, const char* data, uint32 len)> callback) { m_callback_recv = callback; }
/****************************************************************
* Fun[事件]握手
****************************************************************/
void on_handshake(std::function<void(ylib::network::tcp::server* server, uint64 connid)> callback) { m_callback_handshake = callback; }
/****************************************************************
* Fun[事件]已发送
****************************************************************/
void on_send(std::function<void(ylib::network::tcp::server* server, uint64 connid, const char* data, uint32 len)> callback) { m_callback_send = callback; }
/****************************************************************
* Fun[事件]过滤接收
****************************************************************/
void on_recv(std::function<void(ylib::network::tcp::server* server, uint64 connid, uint32 len)> callback) { m_callback_filter = callback; }
friend class server_lst;
public:
std::function<void(ylib::network::tcp::server*, uint64, const char*, uint32)> m_callback_recv;
private:
std::function<void(ylib::network::tcp::server*, uint64)> m_callback_accept;
std::function<void(ylib::network::tcp::server*, uint64)> m_callback_close;
std::function<void(ylib::network::tcp::server*, uint64, const char*, uint32)> m_callback_send;
std::function<void(ylib::network::tcp::server*, uint64)> m_callback_handshake;
std::function<void(ylib::network::tcp::server*, uint64, uint32)> m_callback_filter;
ylib::receive_model m_model = ylib::PUSH_DEFAULT;
ITcpServer* m_server = nullptr;
ylib::network::tcp::server_lst* m_server_listener = nullptr;
};
}
}
}
#endif

View File

@@ -1,31 +0,0 @@
#pragma once
#include "net/define.h"
#ifdef USE_NET_TCP_SERVER
#include "HPSocket/HPSocket.h"
namespace ylib
{
namespace network
{
namespace tcp
{
class server;
class server_lst :public CTcpServerListener
{
public:
server_lst(ylib::network::tcp::server* server);
~server_lst();
virtual EnHandleResult OnPrepareListen(ITcpServer* pSender, SOCKET soListen);
virtual EnHandleResult OnSend(ITcpServer* pSender, CONNID dwConnID, const BYTE* pData, int iLength);
virtual EnHandleResult OnReceive(ITcpServer* pSender, CONNID dwConnID, const BYTE* pData, int iLength);
virtual EnHandleResult OnClose(ITcpServer* pSender, CONNID dwConnID, EnSocketOperation enOperation, int iErrorCode);
virtual EnHandleResult OnAccept(ITcpServer* pSender, CONNID dwConnID, UINT_PTR soClient);
virtual EnHandleResult OnShutdown(ITcpServer* pSender);
virtual EnHandleResult OnHandShake(ITcpServer* pSender, CONNID dwConnID);
virtual EnHandleResult OnReceive(ITcpServer* pSender, CONNID dwConnID, int iLength);
public:
ylib::network::tcp::server* m_server;
};
}
}
}
#endif

View File

@@ -1,40 +0,0 @@
#pragma once
#include <string>
#include "base/define.h"
#include "base/buffer.h"
#include "util/map.hpp"
namespace ylib::network::tcp { class server; }
class UdpClientListener;
namespace ylib
{
namespace network
{
class ttu_client
{
public:
struct Packages : public std::vector<ylib::buffer>
{
};
public:
ttu_client();
~ttu_client();
bool start(const ylib::AddressPort& listen);
void close();
// 设置远程地址
void setRemoteAP(const ylib::AddressPort& remote_ap) { m_remote_ap = remote_ap; }
void setMacConnectionCount(int count = -1) { m_max_connection_count = count; }
size_t getConnectionCount();
friend class UdpClientListener;
public:
ylib::AddressPort m_remote_ap;
ylib::network::tcp::server* m_server = nullptr;
// 待发送
ylib::map<uint64, Packages*> m_wait_send_data;
// 最大连接数
int m_max_connection_count = -1;
};
}
}

View File

@@ -1,35 +0,0 @@
#pragma once
#include "net/define.h"
#if USE_NET_UDP_NODE
#include <functional>
#include "base/error.h"
class IUdpNode;
namespace ylib
{
namespace network
{
namespace udp
{
class node_lst;
class node :public ylib::error_base
{
public:
node();
~node();
// 通过 IServer 继承
bool start(const ylib::AddressPort& bind_ap);
bool close();
bool send(const std::string& remote_ipaddress, ushort remote_port, const char* pData, uint32 len);
void on_recv(std::function<void(ylib::network::udp::node* node, const ylib::AddressPort& remote_ap, const char* data, uint32 len)> callback) { m_callback_recv = callback; }
const ylib::AddressPort& local() { return m_local_ap; }
friend class node_lst;
private:
std::function<void(ylib::network::udp::node*, const ylib::AddressPort&, const char*, uint32)> m_callback_recv;
ylib::AddressPort m_local_ap;
IUdpNode* m_node = nullptr;
ylib::network::udp::node_lst* m_node_listener = nullptr;
};
}
}
}
#endif

View File

@@ -1,30 +0,0 @@
#pragma once
#include "net/define.h"
#if USE_NET_UDP_NODE
#include "HPSocket/HPSocket.h"
#include <string>
namespace ylib
{
namespace network
{
namespace udp
{
class node;
class node_lst :public CUdpNodeListener
{
public:
node_lst(ylib::network::udp::node* node);
~node_lst();
private:
virtual EnHandleResult OnPrepareListen(IUdpNode* pSender, SOCKET soListen);
virtual EnHandleResult OnSend(IUdpNode* pSender, LPCTSTR lpszRemoteAddress, USHORT usRemotePort, const BYTE* pData, int iLength);
virtual EnHandleResult OnReceive(IUdpNode* pSender, LPCTSTR lpszRemoteAddress, USHORT usRemotePort, const BYTE* pData, int iLength);
virtual EnHandleResult OnError(IUdpNode* pSender, EnSocketOperation enOperation, int iErrorCode, LPCTSTR lpszRemoteAddress, USHORT usRemotePort, const BYTE* pBuffer, int iLength);
virtual EnHandleResult OnShutdown(IUdpNode* pSender);
private:
ylib::network::udp::node* m_node = nullptr;
};
}
}
}
#endif

View File

@@ -1,58 +0,0 @@
#pragma once
#include "http_define.h"
#if USE_NET_HTTP_UTIL
#include <string>
#include <list>
namespace ylib
{
namespace network
{
//取文档类型
void content_type(const std::string& extName, std::string& type);
//拆分URL
bool parse_url(const std::string& url, std::string& httpType, std::string& host, std::string& ipaddress, ushort& port, std::string& urlField);
//拆分URL
bool parse_url_host(const std::string& url, std::string& host);
//INT IP 转 字符串IP
void to_string(uint32 int_ip, std::string& ipaddress);
struct TcpConf
{
TcpConf()
{
local_port = 0;
remote_port = 0;
__local_ipaddress = 0;
__remote_ipaddress = 0;
}
void local_ipaddress(std::string& ipaddress) const
{
to_string(__local_ipaddress, ipaddress);
}
void remote_ipaddress(std::string& ipaddress) const
{
to_string(__remote_ipaddress, ipaddress);
}
uint32 __local_ipaddress;
uint32 __remote_ipaddress;
uint32 local_port;
uint32 remote_port;
};
//URL转IP地址
std::string to_ip(const std::string& url);
// 端口是否占用
bool is_occupy(uint32 port);
/*
取大小名称
B/KB/MB/GB
*/
std::string size_name(double size, uint32 fixe = 0);
// 是否为IPV4
bool is_ipv4(const std::string& value);
// 是否为IPV6
bool is_ipv6(const std::string& value);
// 是否为域名
bool is_domain(const std::string& value);
}
}
#endif

View File

@@ -1,31 +0,0 @@
#pragma once
#include "base/define.h"
#include "base/buffer.h"
#include "util/map.hpp"
class ITcpAgent;
class TcpAgentListener;
class UdpServerListener;
namespace ylib
{
namespace network
{
class utt_server
{
public:
struct Packages : public std::vector<ylib::buffer> {};
public:
utt_server();
~utt_server();
bool start(const ylib::AddressPort& bind_ap, const ylib::AddressPort& remote_ap);
void stop();
public:
ylib::AddressPort m_remote_ap;
void* m_udp_server = nullptr;
UdpServerListener* m_udp_server_listener = nullptr;
ITcpAgent* m_agent = nullptr;
TcpAgentListener* m_agent_listener = nullptr;
// 待发送
ylib::map<uint64/*TcpAgentConnID*/, Packages*> m_wait_send_data;
};
}
}

View File

@@ -1,539 +0,0 @@
///*
// * Copyright 2001-2004 Unicode, Inc.
// *
// * Disclaimer
// *
// * This source code is provided as is by Unicode, Inc. No claims are
// * made as to fitness for any particular purpose. No warranties of any
// * kind are expressed or implied. The recipient agrees to determine
// * applicability of information provided. If this file has been
// * purchased on magnetic or optical media from Unicode, Inc., the
// * sole remedy for any claim will be exchange of defective media
// * within 90 days of receipt.
// *
// * Limitations on Rights to Redistribute This Code
// *
// * Unicode, Inc. hereby grants the right to freely use the information
// * supplied in this file in the creation of products supporting the
// * Unicode Standard, and to make copies of this file in any form
// * for internal or external distribution as long as this notice
// * remains attached.
// */
//
///* ---------------------------------------------------------------------
//
// Conversions between UTF32, UTF-16, and UTF-8. Source code file.
// Author: Mark E. Davis, 1994.
// Rev History: Rick McGowan, fixes & updates May 2001.
// Sept 2001: fixed const & error conditions per
// mods suggested by S. Parent & A. Lillich.
// June 2002: Tim Dodd added detection and handling of incomplete
// source sequences, enhanced error detection, added casts
// to eliminate compiler warnings.
// July 2003: slight mods to back out aggressive FFFE detection.
// Jan 2004: updated switches in from-UTF8 conversions.
// Oct 2004: updated to use UNI_MAX_LEGAL_UTF32 in UTF-32 conversions.
//
// See the header file "ConvertUTF.h" for complete documentation.
//
//------------------------------------------------------------------------ */
//
//
//#include "simpleini/ConvertUTF.h"
//#ifdef CVTUTF_DEBUG
//#include <stdio.h>
//#endif
//
//static const int halfShift = 10; /* used for shifting by 10 bits */
//
//static const UTF32 halfBase = 0x0010000UL;
//static const UTF32 halfMask = 0x3FFUL;
//
//#define UNI_SUR_HIGH_START (UTF32)0xD800
//#define UNI_SUR_HIGH_END (UTF32)0xDBFF
//#define UNI_SUR_LOW_START (UTF32)0xDC00
//#define UNI_SUR_LOW_END (UTF32)0xDFFF
//#define false 0
//#define true 1
//
///* --------------------------------------------------------------------- */
//
//ConversionResult ConvertUTF32toUTF16 (
// const UTF32** sourceStart, const UTF32* sourceEnd,
// UTF16** targetStart, UTF16* targetEnd, ConversionFlags flags) {
// ConversionResult result = conversionOK;
// const UTF32* source = *sourceStart;
// UTF16* target = *targetStart;
// while (source < sourceEnd) {
// UTF32 ch;
// if (target >= targetEnd) {
// result = targetExhausted; break;
// }
// ch = *source++;
// if (ch <= UNI_MAX_BMP) { /* Target is a character <= 0xFFFF */
// /* UTF-16 surrogate values are illegal in UTF-32; 0xffff or 0xfffe are both reserved values */
// if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) {
// if (flags == strictConversion) {
// --source; /* return to the illegal value itself */
// result = sourceIllegal;
// break;
// } else {
// *target++ = UNI_REPLACEMENT_CHAR;
// }
// } else {
// *target++ = (UTF16)ch; /* normal case */
// }
// } else if (ch > UNI_MAX_LEGAL_UTF32) {
// if (flags == strictConversion) {
// result = sourceIllegal;
// } else {
// *target++ = UNI_REPLACEMENT_CHAR;
// }
// } else {
// /* target is a character in range 0xFFFF - 0x10FFFF. */
// if (target + 1 >= targetEnd) {
// --source; /* Back up source pointer! */
// result = targetExhausted; break;
// }
// ch -= halfBase;
// *target++ = (UTF16)((ch >> halfShift) + UNI_SUR_HIGH_START);
// *target++ = (UTF16)((ch & halfMask) + UNI_SUR_LOW_START);
// }
// }
// *sourceStart = source;
// *targetStart = target;
// return result;
//}
//
///* --------------------------------------------------------------------- */
//
//ConversionResult ConvertUTF16toUTF32 (
// const UTF16** sourceStart, const UTF16* sourceEnd,
// UTF32** targetStart, UTF32* targetEnd, ConversionFlags flags) {
// ConversionResult result = conversionOK;
// const UTF16* source = *sourceStart;
// UTF32* target = *targetStart;
// UTF32 ch, ch2;
// while (source < sourceEnd) {
// const UTF16* oldSource = source; /* In case we have to back up because of target overflow. */
// ch = *source++;
// /* If we have a surrogate pair, convert to UTF32 first. */
// if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_HIGH_END) {
// /* If the 16 bits following the high surrogate are in the source buffer... */
// if (source < sourceEnd) {
// ch2 = *source;
// /* If it's a low surrogate, convert to UTF32. */
// if (ch2 >= UNI_SUR_LOW_START && ch2 <= UNI_SUR_LOW_END) {
// ch = ((ch - UNI_SUR_HIGH_START) << halfShift)
// + (ch2 - UNI_SUR_LOW_START) + halfBase;
// ++source;
// } else if (flags == strictConversion) { /* it's an unpaired high surrogate */
// --source; /* return to the illegal value itself */
// result = sourceIllegal;
// break;
// }
// } else { /* We don't have the 16 bits following the high surrogate. */
// --source; /* return to the high surrogate */
// result = sourceExhausted;
// break;
// }
// } else if (flags == strictConversion) {
// /* UTF-16 surrogate values are illegal in UTF-32 */
// if (ch >= UNI_SUR_LOW_START && ch <= UNI_SUR_LOW_END) {
// --source; /* return to the illegal value itself */
// result = sourceIllegal;
// break;
// }
// }
// if (target >= targetEnd) {
// source = oldSource; /* Back up source pointer! */
// result = targetExhausted; break;
// }
// *target++ = ch;
// }
// *sourceStart = source;
// *targetStart = target;
//#ifdef CVTUTF_DEBUG
//if (result == sourceIllegal) {
// fprintf(stderr, "ConvertUTF16toUTF32 illegal seq 0x%04x,%04x\n", ch, ch2);
// fflush(stderr);
//}
//#endif
// return result;
//}
//
///* --------------------------------------------------------------------- */
//
///*
// * Index into the table below with the first byte of a UTF-8 sequence to
// * get the number of trailing bytes that are supposed to follow it.
// * Note that *legal* UTF-8 values can't have 4 or 5-bytes. The table is
// * left as-is for anyone who may want to do such conversion, which was
// * allowed in earlier algorithms.
// */
//static const char trailingBytesForUTF8[256] = {
// 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
// 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
// 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
// 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
// 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
// 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
// 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
// 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5
//};
//
///*
// * Magic values subtracted from a buffer value during UTF8 conversion.
// * This table contains as many values as there might be trailing bytes
// * in a UTF-8 sequence.
// */
//static const UTF32 offsetsFromUTF8[6] = { 0x00000000UL, 0x00003080UL, 0x000E2080UL,
// 0x03C82080UL, 0xFA082080UL, 0x82082080UL };
//
///*
// * Once the bits are split out into bytes of UTF-8, this is a mask OR-ed
// * into the first byte, depending on how many bytes follow. There are
// * as many entries in this table as there are UTF-8 sequence types.
// * (I.e., one byte sequence, two byte... etc.). Remember that sequences
// * for *legal* UTF-8 will be 4 or fewer bytes total.
// */
//static const UTF8 firstByteMark[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC };
//
///* --------------------------------------------------------------------- */
//
///* The interface converts a whole buffer to avoid function-call overhead.
// * Constants have been gathered. Loops & conditionals have been removed as
// * much as possible for efficiency, in favor of drop-through switches.
// * (See "Note A" at the bottom of the file for equivalent code.)
// * If your compiler supports it, the "isLegalUTF8" call can be turned
// * into an inline function.
// */
//
///* --------------------------------------------------------------------- */
//
//ConversionResult ConvertUTF16toUTF8 (
// const UTF16** sourceStart, const UTF16* sourceEnd,
// UTF8** targetStart, UTF8* targetEnd, ConversionFlags flags) {
// ConversionResult result = conversionOK;
// const UTF16* source = *sourceStart;
// UTF8* target = *targetStart;
// while (source < sourceEnd) {
// UTF32 ch;
// unsigned short bytesToWrite = 0;
// const UTF32 byteMask = 0xBF;
// const UTF32 byteMark = 0x80;
// const UTF16* oldSource = source; /* In case we have to back up because of target overflow. */
// ch = *source++;
// /* If we have a surrogate pair, convert to UTF32 first. */
// if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_HIGH_END) {
// /* If the 16 bits following the high surrogate are in the source buffer... */
// if (source < sourceEnd) {
// UTF32 ch2 = *source;
// /* If it's a low surrogate, convert to UTF32. */
// if (ch2 >= UNI_SUR_LOW_START && ch2 <= UNI_SUR_LOW_END) {
// ch = ((ch - UNI_SUR_HIGH_START) << halfShift)
// + (ch2 - UNI_SUR_LOW_START) + halfBase;
// ++source;
// } else if (flags == strictConversion) { /* it's an unpaired high surrogate */
// --source; /* return to the illegal value itself */
// result = sourceIllegal;
// break;
// }
// } else { /* We don't have the 16 bits following the high surrogate. */
// --source; /* return to the high surrogate */
// result = sourceExhausted;
// break;
// }
// } else if (flags == strictConversion) {
// /* UTF-16 surrogate values are illegal in UTF-32 */
// if (ch >= UNI_SUR_LOW_START && ch <= UNI_SUR_LOW_END) {
// --source; /* return to the illegal value itself */
// result = sourceIllegal;
// break;
// }
// }
// /* Figure out how many bytes the result will require */
// if (ch < (UTF32)0x80) { bytesToWrite = 1;
// } else if (ch < (UTF32)0x800) { bytesToWrite = 2;
// } else if (ch < (UTF32)0x10000) { bytesToWrite = 3;
// } else if (ch < (UTF32)0x110000) { bytesToWrite = 4;
// } else { bytesToWrite = 3;
// ch = UNI_REPLACEMENT_CHAR;
// }
//
// target += bytesToWrite;
// if (target > targetEnd) {
// source = oldSource; /* Back up source pointer! */
// target -= bytesToWrite; result = targetExhausted; break;
// }
// switch (bytesToWrite) { /* note: everything falls through. */
// case 4: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6;
// case 3: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6;
// case 2: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6;
// case 1: *--target = (UTF8)(ch | firstByteMark[bytesToWrite]);
// }
// target += bytesToWrite;
// }
// *sourceStart = source;
// *targetStart = target;
// return result;
//}
//
///* --------------------------------------------------------------------- */
//
///*
// * Utility routine to tell whether a sequence of bytes is legal UTF-8.
// * This must be called with the length pre-determined by the first byte.
// * If not calling this from ConvertUTF8to*, then the length can be set by:
// * length = trailingBytesForUTF8[*source]+1;
// * and the sequence is illegal right away if there aren't that many bytes
// * available.
// * If presented with a length > 4, this returns false. The Unicode
// * definition of UTF-8 goes up to 4-byte sequences.
// */
//
//static Boolean isLegalUTF8(const UTF8 *source, int length) {
// UTF8 a;
// const UTF8 *srcptr = source+length;
// switch (length) {
// default: return false;
// /* Everything else falls through when "true"... */
// case 4: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return false;
// case 3: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return false;
// case 2: if ((a = (*--srcptr)) > 0xBF) return false;
//
// switch (*source) {
// /* no fall-through in this inner switch */
// case 0xE0: if (a < 0xA0) return false; break;
// case 0xED: if (a > 0x9F) return false; break;
// case 0xF0: if (a < 0x90) return false; break;
// case 0xF4: if (a > 0x8F) return false; break;
// default: if (a < 0x80) return false;
// }
//
// case 1: if (*source >= 0x80 && *source < 0xC2) return false;
// }
// if (*source > 0xF4) return false;
// return true;
//}
//
///* --------------------------------------------------------------------- */
//
///*
// * Exported function to return whether a UTF-8 sequence is legal or not.
// * This is not used here; it's just exported.
// */
//Boolean isLegalUTF8Sequence(const UTF8 *source, const UTF8 *sourceEnd) {
// int length = trailingBytesForUTF8[*source]+1;
// if (source+length > sourceEnd) {
// return false;
// }
// return isLegalUTF8(source, length);
//}
//
///* --------------------------------------------------------------------- */
//
//ConversionResult ConvertUTF8toUTF16 (
// const UTF8** sourceStart, const UTF8* sourceEnd,
// UTF16** targetStart, UTF16* targetEnd, ConversionFlags flags) {
// ConversionResult result = conversionOK;
// const UTF8* source = *sourceStart;
// UTF16* target = *targetStart;
// while (source < sourceEnd) {
// UTF32 ch = 0;
// unsigned short extraBytesToRead = trailingBytesForUTF8[*source];
// if (source + extraBytesToRead >= sourceEnd) {
// result = sourceExhausted; break;
// }
// /* Do this check whether lenient or strict */
// if (! isLegalUTF8(source, extraBytesToRead+1)) {
// result = sourceIllegal;
// break;
// }
// /*
// * The cases all fall through. See "Note A" below.
// */
// switch (extraBytesToRead) {
// case 5: ch += *source++; ch <<= 6; /* remember, illegal UTF-8 */
// case 4: ch += *source++; ch <<= 6; /* remember, illegal UTF-8 */
// case 3: ch += *source++; ch <<= 6;
// case 2: ch += *source++; ch <<= 6;
// case 1: ch += *source++; ch <<= 6;
// case 0: ch += *source++;
// }
// ch -= offsetsFromUTF8[extraBytesToRead];
//
// if (target >= targetEnd) {
// source -= (extraBytesToRead+1); /* Back up source pointer! */
// result = targetExhausted; break;
// }
// if (ch <= UNI_MAX_BMP) { /* Target is a character <= 0xFFFF */
// /* UTF-16 surrogate values are illegal in UTF-32 */
// if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) {
// if (flags == strictConversion) {
// source -= (extraBytesToRead+1); /* return to the illegal value itself */
// result = sourceIllegal;
// break;
// } else {
// *target++ = UNI_REPLACEMENT_CHAR;
// }
// } else {
// *target++ = (UTF16)ch; /* normal case */
// }
// } else if (ch > UNI_MAX_UTF16) {
// if (flags == strictConversion) {
// result = sourceIllegal;
// source -= (extraBytesToRead+1); /* return to the start */
// break; /* Bail out; shouldn't continue */
// } else {
// *target++ = UNI_REPLACEMENT_CHAR;
// }
// } else {
// /* target is a character in range 0xFFFF - 0x10FFFF. */
// if (target + 1 >= targetEnd) {
// source -= (extraBytesToRead+1); /* Back up source pointer! */
// result = targetExhausted; break;
// }
// ch -= halfBase;
// *target++ = (UTF16)((ch >> halfShift) + UNI_SUR_HIGH_START);
// *target++ = (UTF16)((ch & halfMask) + UNI_SUR_LOW_START);
// }
// }
// *sourceStart = source;
// *targetStart = target;
// return result;
//}
//
///* --------------------------------------------------------------------- */
//
//ConversionResult ConvertUTF32toUTF8 (
// const UTF32** sourceStart, const UTF32* sourceEnd,
// UTF8** targetStart, UTF8* targetEnd, ConversionFlags flags) {
// ConversionResult result = conversionOK;
// const UTF32* source = *sourceStart;
// UTF8* target = *targetStart;
// while (source < sourceEnd) {
// UTF32 ch;
// unsigned short bytesToWrite = 0;
// const UTF32 byteMask = 0xBF;
// const UTF32 byteMark = 0x80;
// ch = *source++;
// if (flags == strictConversion ) {
// /* UTF-16 surrogate values are illegal in UTF-32 */
// if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) {
// --source; /* return to the illegal value itself */
// result = sourceIllegal;
// break;
// }
// }
// /*
// * Figure out how many bytes the result will require. Turn any
// * illegally large UTF32 things (> Plane 17) into replacement chars.
// */
// if (ch < (UTF32)0x80) { bytesToWrite = 1;
// } else if (ch < (UTF32)0x800) { bytesToWrite = 2;
// } else if (ch < (UTF32)0x10000) { bytesToWrite = 3;
// } else if (ch <= UNI_MAX_LEGAL_UTF32) { bytesToWrite = 4;
// } else { bytesToWrite = 3;
// ch = UNI_REPLACEMENT_CHAR;
// result = sourceIllegal;
// }
//
// target += bytesToWrite;
// if (target > targetEnd) {
// --source; /* Back up source pointer! */
// target -= bytesToWrite; result = targetExhausted; break;
// }
// switch (bytesToWrite) { /* note: everything falls through. */
// case 4: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6;
// case 3: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6;
// case 2: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6;
// case 1: *--target = (UTF8) (ch | firstByteMark[bytesToWrite]);
// }
// target += bytesToWrite;
// }
// *sourceStart = source;
// *targetStart = target;
// return result;
//}
//
///* --------------------------------------------------------------------- */
//
//ConversionResult ConvertUTF8toUTF32 (
// const UTF8** sourceStart, const UTF8* sourceEnd,
// UTF32** targetStart, UTF32* targetEnd, ConversionFlags flags) {
// ConversionResult result = conversionOK;
// const UTF8* source = *sourceStart;
// UTF32* target = *targetStart;
// while (source < sourceEnd) {
// UTF32 ch = 0;
// unsigned short extraBytesToRead = trailingBytesForUTF8[*source];
// if (source + extraBytesToRead >= sourceEnd) {
// result = sourceExhausted; break;
// }
// /* Do this check whether lenient or strict */
// if (! isLegalUTF8(source, extraBytesToRead+1)) {
// result = sourceIllegal;
// break;
// }
// /*
// * The cases all fall through. See "Note A" below.
// */
// switch (extraBytesToRead) {
// case 5: ch += *source++; ch <<= 6;
// case 4: ch += *source++; ch <<= 6;
// case 3: ch += *source++; ch <<= 6;
// case 2: ch += *source++; ch <<= 6;
// case 1: ch += *source++; ch <<= 6;
// case 0: ch += *source++;
// }
// ch -= offsetsFromUTF8[extraBytesToRead];
//
// if (target >= targetEnd) {
// source -= (extraBytesToRead+1); /* Back up the source pointer! */
// result = targetExhausted; break;
// }
// if (ch <= UNI_MAX_LEGAL_UTF32) {
// /*
// * UTF-16 surrogate values are illegal in UTF-32, and anything
// * over Plane 17 (> 0x10FFFF) is illegal.
// */
// if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) {
// if (flags == strictConversion) {
// source -= (extraBytesToRead+1); /* return to the illegal value itself */
// result = sourceIllegal;
// break;
// } else {
// *target++ = UNI_REPLACEMENT_CHAR;
// }
// } else {
// *target++ = ch;
// }
// } else { /* i.e., ch > UNI_MAX_LEGAL_UTF32 */
// result = sourceIllegal;
// *target++ = UNI_REPLACEMENT_CHAR;
// }
// }
// *sourceStart = source;
// *targetStart = target;
// return result;
//}
//
///* ---------------------------------------------------------------------
//
// Note A.
// The fall-through switches in UTF-8 reading code save a
// temp variable, some decrements & conditionals. The switches
// are equivalent to the following loop:
// {
// int tmpBytesToRead = extraBytesToRead+1;
// do {
// ch += *source++;
// --tmpBytesToRead;
// if (tmpBytesToRead) ch <<= 6;
// } while (tmpBytesToRead > 0);
// }
// In UTF-8 writing code, the switches on "bytesToWrite" are
// similarly unrolled loops.
//
// --------------------------------------------------------------------- */

View File

@@ -1,191 +0,0 @@
#pragma once
#include "ybase/define.h"
#include "yutil/array.hpp"
#include <vector>
#include <map>
/*
* 结构体vector int 成员排序
*/
#define SORT_VECTOR_MEMBER(VECTOR,MEMBER,PS) \
{ \
for (uint32 i = 0; i < VECTOR.size(); i++) \
{ \
for (uint32 x = i; x < VECTOR.size(); x++) \
{ \
if (PS == true ? (uint64)VECTOR[i].MEMBER > (uint64)VECTOR[x].MEMBER:VECTOR[i].MEMBER < (uint64)VECTOR[x].MEMBER) \
{ \
auto temp = VECTOR[i]; \
VECTOR[i] = VECTOR[x]; \
VECTOR[x] = temp; \
} \
} \
} \
}
/*
* 结构体vector int 成员排序
*/
#define SORT_VECTOR_MEMBER_PTR(VECTOR,MEMBER,PS) \
{ \
for (uint32 i = 0; i < VECTOR.size(); i++) \
{ \
for (uint32 x = i; x < VECTOR.size(); x++) \
{ \
if (PS == true ? VECTOR[i]->MEMBER > VECTOR[x]->MEMBER:VECTOR[i]->MEMBER < VECTOR[x]->MEMBER) \
{ \
auto temp = VECTOR[i]; \
VECTOR[i] = VECTOR[x]; \
VECTOR[x] = temp; \
} \
} \
} \
}
/*
* 结构体vector int 成员排序
*/
#define SORT_VECTOR_MEMBER_PPTR(VECTOR,MEMBER,PS) \
{ \
for (uint32 i = 0; i < VECTOR->size(); i++) \
{ \
for (uint32 x = i; x < VECTOR->size(); x++) \
{ \
if (PS == true ? (*VECTOR)[i]->MEMBER > (*VECTOR)[x]->MEMBER:(*VECTOR)[i]->MEMBER < (*VECTOR)[x]->MEMBER) \
{ \
auto temp = VECTOR[i]; \
VECTOR[i] = VECTOR[x]; \
VECTOR[x] = temp; \
} \
} \
} \
}
namespace newobj
{
namespace stl
{
/*
* 排序
* @ps 正序
*/
inline void sort(std::vector<int>& value,bool ps)
{
int temp = 0;
for (size_t i = 0; i < value.size(); i++)
{
for (size_t x = i; x < value.size(); x++)
{
if (ps==true?value[i] > value[x]:value[i] < value[x])
{
temp = value[i];
value[i] = value[x];
value[x] = temp;
}
}
}
}
/*
* 排序
* @ps 正序
*/
template<typename T>
inline void sort(std::vector<int>& value,std::vector<T> &extra, bool ps)
{
int temp = 0;
for (uint32 i = 0; i < value.size(); i++)
{
for (uint32 x = i; x < value.size(); x++)
{
if (ps == true ? value[i] > value[x]:value[i] < value[x])
{
temp = value[i];
value[i] = value[x];
value[x] = temp;
auto t = extra[i];
extra[i] = extra[x];
extra[x] = t;
}
}
}
}
/*
* 分页专用
* @ps 排序
*/
template<typename KEY, typename VAL>
inline std::map<KEY, VAL> limit(const std::map<KEY, VAL>& value,uint32 start,uint32 length,bool ps)
{
std::map<KEY, VAL> result;
uint32 idx = 0;
if (ps)
{
for_iter(iter, value)
{
if (idx >= start && idx < start + length)
result.insert(std::pair<KEY, VAL>(iter->first, iter->second));
else if (idx > start + length)
break;
idx++;
}
}
else
{
for_riter(iter, value)
{
if (idx >= start && idx < start + length)
result.insert(std::pair<KEY, VAL>(iter->first, iter->second));
else if (idx > start + length)
break;
idx++;
}
}
return result;
}
template<typename T>
inline std::vector<T> limit(const std::vector<T>& value, uint32 start, uint32 length, bool ps)
{
std::vector<T> result;
uint32 idx = 0;
if (ps)
{
for_iter(iter, value)
{
if (idx >= start && idx < start + length)
result.push_back(*iter);
else if (idx > start + length)
break;
idx++;
}
}
else
{
for_riter(iter, value)
{
if (idx >= start && idx < start + length)
result.push_back(*iter);
else if (idx > start + length)
break;
idx++;
}
}
return result;
}
/*
* std::map转std::vector
*/
template<typename KEY,typename VAL>
inline std::vector<VAL> to_vector_val(const std::map<KEY, VAL>& value)
{
std::vector<VAL> result;
for_iter(iter, value)
result.push_back(iter->second);
return result;
}
}
}

View File

@@ -1,53 +0,0 @@
#pragma once
#include <vector>
namespace ylib
{
template<typename T>
struct nolock_array
{
nolock_array() {
m_array = nullptr;
m_count = 0;
}
~nolock_array(){
free();
}
void free(){
if(m_array != nullptr)
delete[] m_array;
m_array = nullptr;
m_count = 0;
}
void init(const std::vector<T>& value){
if(value.size() == 0)
return;
m_array = new T[value.size()];
m_count = value.size();
for(size_t i=0;i<value.size();i++){
m_array[i] = value[i];
}
}
size_t append(const T& value){
std::vector<T> v;
v.resize(m_count+1);
for(size_t i=0;i<m_count;i++){
v[i] = m_array[i];
}
v[m_count] = value;
free();
init(v);
return m_count-1;
}
inline T get(size_t index){
if(index >= m_count){
printf("Unlocked array index is too long");
abort();
}
return m_array[index];
}
T* m_array;
size_t m_count;
};
}

View File

@@ -1,107 +0,0 @@
#pragma once
#include "base/define.h"
#include "base/error.h"
#include "util/thread.h"
#include <mutex>
#include <list>
namespace ylib
{
/*********************************************************************
* class缓存
*********************************************************************/
class cache:public ylib::error_base,private ylib::ithread
{
public:
struct cache_info
{
cache_info()
{
update_sec = 0;
timeout_sec = 0;
update = false;
}
// 创建时间
timestamp update_sec;
// 过期时间
uint32 timeout_sec;
// 内容
std::string value;
// 更新
bool update;
};
cache();
~cache();
/***************************************************************************************************
* function启动
* param
* local_path 缓存保存路径[默认=空],空则不保存本地。
****************************************************************************************************/
bool start(const std::string& local_path);
/***************************************************************************************************
* function停止
****************************************************************************************************/
void stop();
/***************************************************************************************************
* function
* param
* name
* value
****************************************************************************************************/
bool read(const std::string& name,std::string& value);
/***************************************************************************************************
* function
* param
* name
* value
* timeout_sec 过期时间 -2=不设置
****************************************************************************************************/
bool write(const std::string& name, const std::string& value,int32 timeout_sec = -2);
bool write(const std::string& name, const std::string& value,timestamp update_sec,int32 timeout_sec);
/***************************************************************************************************
* function是否存在
* param
* name
****************************************************************************************************/
bool exist(const std::string& name);
/***************************************************************************************************
* function失效时间
* param
* name
* return
* >=0 则为失效时间,-1=永不过期 -2=无此键
****************************************************************************************************/
int32 expire(const std::string& name);
/***************************************************************************************************
* function删除
* param
* name
****************************************************************************************************/
bool remove(const std::string& name);
/***************************************************************************************************
* function更新过期
****************************************************************************************************/
bool update(const std::string& name);
/***************************************************************************************************
* function清空
****************************************************************************************************/
void clear();
/***************************************************************************************************
* function取MAP
****************************************************************************************************/
std::map<std::string,cache_info*> *list();
std::mutex* mutex();
private:
bool _exist(const std::string& name,bool lock);
// 通过 ithread 继承
virtual bool run() override;
private:
// 本地缓存路径
std::string m_local_path;
// 读写锁
std::mutex m_mutex;
// 缓存数据
std::map<std::string, cache_info*> m_cache;
};
}

View File

@@ -1,49 +0,0 @@
#pragma once
#include <string>
#include "base/buffer.h"
namespace ylib
{
namespace codec
{
std::string md5(const ylib::buffer& data);
std::string to_utf8(const std::string& gbk);
std::string to_gbk(const std::string& utf8);
namespace gzip
{
ylib::buffer en(const ylib::buffer& data);
ylib::buffer de(const ylib::buffer& data);
}
namespace base64 {
std::string en(const ylib::buffer& data);
ylib::buffer de(const std::string& data);
}
namespace url {
std::string en(const ylib::buffer& data);
ylib::buffer de(const std::string& data);
}
#if 1
namespace des3 {
ylib::buffer en(const ylib::buffer& data, const std::string& key);
ylib::buffer de(const ylib::buffer& data, const std::string& key);
}
#endif
namespace aes {
enum class variant {
AES128 = 16,
AES192 = 24,
AES256 = 32
};
enum class mode {
CBC,
ECB
};
ylib::buffer en(const ylib::buffer& data, const std::string& key, ylib::codec::aes::variant variant, ylib::codec::aes::mode mode);
ylib::buffer de(const ylib::buffer& ciphertext, const std::string& key, variant var, mode mod);
}
}
}

View File

@@ -1,81 +0,0 @@
#pragma once
#if 0
#include <coroutine>
#include <iostream>
#include <thread>
#include <chrono>
#include "util/thread.h"
#include "util/queue.hpp"
class co_thread_pool;
namespace ylib::co
{
class coroutine {
public:
struct promise_type {
coroutine get_return_object() {
return coroutine{ std::coroutine_handle<promise_type>::from_promise(*this) };
}
std::suspend_always initial_suspend() { return {}; } // 协程初始化时挂起
std::suspend_never final_suspend() noexcept { return {}; } // 协程结束时挂起
void return_void() {}
void unhandled_exception() { std::exit(1); }
};
coroutine(std::coroutine_handle<promise_type> h) : coro(h) {}
~coroutine() { if (coro) coro.destroy(); }
std::coroutine_handle<promise_type> coro;
};
/// <summary>
/// 协程调度器
/// </summary>
class scheduler :public ylib::ithread {
public:
// 任务信息
struct task_info {
// 任务回调
std::function<void(void*,ylib::co::scheduler*)> callback;
// 任务参数
void* param = nullptr;
// 唤醒协程coco
std::coroutine_handle<>* coco = nullptr;
};
public:
scheduler();
~scheduler();
/// <summary>
/// 启动
/// </summary>
/// <param name="thread_size">挂起协程执行任务线程池大小</param>
/// <returns></returns>
bool start(uint32 thread_size);
void stop();
/// <summary>
/// 投递协程
/// </summary>
/// <param name="info"></param>
void push(const task_info& info);
/// <summary>
/// 投递线程任务
/// </summary>
/// <param name="callback"></param>
void push_t(std::function<void()> callback);
/// <summary>
/// 唤醒协程
/// </summary>
/// <param name="continuation"></param>
void resume(std::coroutine_handle<>* continuation);
private:
// 通过 ithread 继承
bool run() override;
/// <summary>
/// 处理队列
/// </summary>
void exec_queue();
private:
// 协程处理队列
ylib::queue<task_info> m_queue;
// 线程池
co_thread_pool* m_pool = nullptr;
};
}
#endif

View File

@@ -1,17 +0,0 @@
#pragma once
#include <mutex>
namespace ylib {
template<typename T>
class counter{
public:
counter(const T& default_value = 0){m_value = default_value;}
~counter() {}
T make(){
std::unique_lock<std::mutex> guard(m_mutex);
return ++m_value;
}
private:
T m_value;
std::mutex m_mutex;
};
}

View File

@@ -1,14 +0,0 @@
#pragma once
#include <string>
namespace ylib
{
namespace debug
{
// 检测异常产生DUMP文件
void detect_exception();
#ifdef _WIN32
// 打印VS控制台
void vs_console_println(const std::string& value);
#endif
}
}

View File

@@ -1,67 +0,0 @@
#pragma once
#ifdef _WIN32
#include <vector>
#include "util/system.h"
#include "util/process.h"
#include "base/define.h"
namespace ylib
{
/*********************************************************************************
* Class桌面
*********************************************************************************/
class desktop
{
public:
desktop(const std::string& name,bool create_new,bool destory = true);
desktop(size_t handle,bool destory = true);
~desktop();
//显示桌面
bool show();
//执行程序
bool exec(const std::string& filepath, const std::string& path = "");
//置为本桌面
void current();
//关闭所有创建进程
void destoryAllProcesses(bool subproc = true);
//取句柄
size_t handle();
//取桌面句柄
size_t winhandle();
private:
//结束子进程
void desktorySubProcesses(const std::list<ylib::process::proc_info>& list, size_t pid);
private:
// 桌面句柄
size_t m_desktop;
// 桌面名称
std::string m_name;
// 执行程序句柄
std::vector<size_t> m_exec_hds;
// 销毁句柄
bool m_destory;
public:
/*************************************[ 公开静态函数 ]******************************************/
struct DesktopInfo
{
DesktopInfo()
{
handle = 0;
}
std::string name;
size_t handle;
};
//取所有桌面
static std::vector<DesktopInfo> all(const std::string& winsta);
//取当前桌面
static size_t get_current();
//显示桌面
static void show(size_t handle);
//名称取桌面
static size_t get_desktop(const std::string& name);
//关闭桌面
static bool close(size_t desktop);
};
}
#endif

View File

@@ -1,151 +0,0 @@
#pragma once
#include <string>
#include <fstream>
#include <map>
#include "base/define.h"
#include "base/error.h"
#include "base/buffer.h"
namespace ylib
{
namespace file
{
/**
* @brief 删除文件
* @param filepath
* @return
*/
bool remove(const std::string& filepath);
/**
* @brief 删除目录
* @param dirpath
* @param recycle
* @return
*/
bool remove_dir(const std::string& dirpath
#if _WIN32
, bool recycle = false
#endif
);
/**
* @brief 创建目录
* @param dirpath
* @return
*/
bool create_dir(const std::string& dirpath, bool create_parent_dir = true);
/**
* @brief 读取文件
* @param filepath
* @return
*/
ylib::buffer read(const std::string& filepath);
bool read(const std::string& filepath, ylib::buffer& data);
/**
* @brief 写到文件
* @param filepath
* @param data
* @return
*/
bool write(const std::string& filepath, const ylib::buffer& data);
bool write(const std::string& filepath, const char* data, size_t len);
#ifdef _WIN32
/**
* @brief 列出目录文件
* @param rootPath
* @param list<std::string,bool[文件夹]>
* @return
*/
bool list(const std::string& rootPath, std::map<std::string, bool>& list);
#endif
/**
* @brief 取扩展名
* @param path
* @return
*/
std::string ext(const std::string& path);
/**
* @brief 是否存在文件
* @param filepath
* @return
*/
bool exist(const std::string& filepath);
/**
* @brief 是否存在目录
* @param filepath
* @return
*/
bool exist_dir(const std::string& dirpath);
/**
* @brief 取文件大小
* @param filepath
* @return
* 成功>=0 失败=-1
*/
int64 size(const std::string& filepath);
/**
* @brief 取上级目录
* @param path
* @return
*/
std::string parent_dir(const std::string& path);
/**
* @brief 取文件名
* @param path
* @param have_ext
* @return
*/
std::string filename(const std::string& path, bool have_ext = true);
/**
* @brief 复制文件
*/
bool copy(const std::string& src, const std::string& dst);
/**
* @brief 复制目录
*/
void copy_dir(const std::string& src, const std::string& dst);
// 遍历目录
std::map<std::string, ylib::FileType> traverse(const std::string& dirpath, const std::string& regex_pattern = "(.*\\.txt$)");
// 生成一个临时文件路径
std::string temp_filepath();
// 格式化目录
std::string format_separator(const std::string& filepath);
// 最后修改时间
timestamp last_write_time(const std::string& filepath);
}
class file_io :public ylib::error_base
{
public:
file_io();
~file_io();
bool open(const std::string& filepath, bool only_read = false, bool auto_create = true);
void close();
bool appead(const char* data, int64 len);
bool appead(const ylib::buffer& data);
bool write(const char* data, int64 len);
bool write(const ylib::buffer& data);
ylib::buffer read(int64 size);
bool read(int64 size, ylib::buffer& data);
void jump(int64 offset, std::ios_base::seekdir way = std::ios::cur);
std::streampos cur();
bool clear();
std::streamsize size();
bool is_open();
inline const std::string& filepath() { return m_filepath; }
private:
std::string m_filepath;
std::fstream* m_stream = nullptr;
bool m_only_read = false;
};
}

View File

@@ -1,108 +0,0 @@
#pragma once
#include <string>
#include <vector>
#include <functional>
#include "QtCore/qobject.h"
#include "ybase/error.h"
#include "ybase/singleton.hpp"
#include "yutil/thread.h"
#include "yutil/queue.hpp"
#include "yutil/system.h"
namespace ylib
{
template<typename DATA> class IHandler;
template<typename DATA>
class Handler: public ylib::error_base, public ylib::singleton<ylib::Handler<DATA>>, public ylib::ithread
{
friend class ylib::singleton<ylib::Handler<DATA>>;
public:
struct QueueInfo
{
int type = 0;
int cmd = 0;
DATA data;
uint32 index = 0;
};
public:
void start() {
ylib::ithread::start();
}
void stop() {
ylib::ithread::stop();
ylib::ithread::wait();
}
void regist(std::function<ylib::IHandler<DATA>*(int type)> callback) {
m_callback = callback;
};
uint32 push(int type, int cmd,const DATA& data = DATA())
{
uint32 index = ++m_queue_index;
QueueInfo info;
info.index = index;
info.type = (int)type;
info.cmd = (int)cmd;
info.data = data;
m_queue.push(info);
return index;
}
void wait(uint32 index, uint32 wait_sec = 10){
for (size_t i = 0; i < wait_sec * 10; i++)
{
if (index <= m_current_queue_index)
return;
system::sleep_msec(100);
}
}
// 获取已处理到的类型索引号
uint32 currentIndex() {
return m_current_queue_index;
}
virtual bool run() override {
QueueInfo info;
IHandler<DATA>* handler = nullptr;
while (m_queue.pop(info))
{
handler = m_callback((int)info.type);
handler->exec(info);
delete handler;
m_current_queue_index = info.index;
}
system::sleep_msec(100);
return true;
}
private:
Handler()
{
}
~Handler()
{
}
private:
// 任务队列
ylib::queue<QueueInfo> m_queue;
// 已处理索引号
uint32 m_current_queue_index = 0;
// 索引号
uint32 m_queue_index = 0;
// 回调
std::function<ylib::IHandler<DATA>*(int type)> m_callback;
};
template<typename DATA>
class IHandler
{
public:
virtual void exec(const struct ylib::Handler<DATA>::QueueInfo& info) = 0;
};
}

View File

@@ -1,13 +0,0 @@
#pragma once
#include "base/define.h"
#include "base/buffer.h"
namespace ylib
{
namespace img
{
//生成验证码
ylib::buffer make_code(uint32 width,uint32 height,uint32 code_length, std::string& captcha);
}
}

View File

@@ -1,34 +0,0 @@
#pragma once
#include <string>
#include <vector>
#include "util/json.h"
namespace ylib
{
class ini
{
public:
ini();
~ini();
bool open(const std::string& filepath);
void close();
std::string read(const std::string& name,const std::string& key,const std::string& default_value = "") const;
bool write(const std::string& name,const std::string& key,const std::string& value);
#ifndef _WIN321
bool del(const std::string& name, const std::string& key);
// 一级NAME
std::vector<std::string> names();
// 二级KEY
std::vector<std::string> keys(const std::string& name);
bool exist_key(const std::string& name,const std::string& key);
bool exist_name(const std::string& name);
ylib::json to_json();
#endif
private:
std::string m_filepath;
void* m_point = nullptr;
};
}

View File

@@ -1,32 +0,0 @@
#pragma once
#include <mutex>
#include "yutil/time.h"
namespace ylib {
class interval {
public:
interval(timestamp msec):m_interval_msec(msec),m_pre_msec(0){
m_pre_msec = time::now_msec();
}
~interval() {}
/// <summary>
/// 是否超市
/// </summary>
/// <returns></returns>
bool isTimeout() {
auto now_msec = time::now_msec();
if (m_pre_msec + m_interval_msec < now_msec)
return true;
return false;
}
void timeout() {
m_pre_msec = time::now_msec() - m_interval_msec - 1;
}
void update() {
m_pre_msec = time::now_msec();
}
private:
timestamp m_interval_msec = 0;
timestamp m_pre_msec = 0;
};
}

View File

@@ -1,477 +0,0 @@
#pragma once
#include <vector>
#include <string>
#include <iostream>
#include <sstream>
#include <map>
#include "base/define.h"
#include "base/conversion.h"
/* project version */
#define CJSON_VERSION_MAJOR 1
#define CJSON_VERSION_MINOR 7
#define CJSON_VERSION_PATCH 15
#include <stddef.h>
/* cJSON Types: */
#define cJSON_Invalid (0)
#define cJSON_False (1 << 0)
#define cJSON_True (1 << 1)
#define cJSON_NULL (1 << 2)
#define cJSON_Number (1 << 3)
#define cJSON_String (1 << 4)
#define cJSON_Array (1 << 5)
#define cJSON_Object (1 << 6)
#define cJSON_Raw (1 << 7) /* raw json */
#define cJSON_IsReference 256
#define cJSON_StringIsConst 512
/* The cJSON structure: */
typedef struct cJSON
{
/* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */
struct cJSON* next;
struct cJSON* prev;
/* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */
struct cJSON* child;
/* The type of the item, as above. */
int type;
/* The item's string, if type==cJSON_String and type == cJSON_Raw */
char* valuestring;
/* writing to valueint is DEPRECATED, use cJSON_SetNumberValue instead */
int valueint;
/* The item's number, if type==cJSON_Number */
double valuedouble;
/* The item's name string, if this item is the child of, or is in the list of subitems of an object. */
char* string;
} cJSON;
typedef struct cJSON_Hooks
{
/* malloc/free are CDECL on Windows regardless of the default calling convention of the compiler, so ensure the hooks allow passing those functions directly. */
void* (*malloc_fn)(size_t sz);
void (*free_fn)(void* ptr);
} cJSON_Hooks;
typedef int cJSON_bool;
#define CJSON_NESTING_LIMIT 1000
/* Supply malloc, realloc and free functions to cJSON */
void cJSON_InitHooks(cJSON_Hooks* hooks);
/* Memory Management: the caller is always responsible to free the results from all variants of cJSON_Parse (with cJSON_Delete) and cJSON_Print (with stdlib free, cJSON_Hooks.free_fn, or cJSON_free as appropriate). The exception is cJSON_PrintPreallocated, where the caller has full responsibility of the buffer. */
/* Supply a block of JSON, and this returns a cJSON object you can interrogate. */
cJSON* cJSON_Parse(const char* value);
cJSON* cJSON_ParseWithLength(const char* value, size_t buffer_length);
/* ParseWithOpts allows you to require (and check) that the JSON is null terminated, and to retrieve the pointer to the final byte parsed. */
/* If you supply a ptr in return_parse_end and parsing fails, then return_parse_end will contain a pointer to the error so will match cJSON_GetErrorPtr(). */
cJSON* cJSON_ParseWithOpts(const char* value, const char** return_parse_end, cJSON_bool require_null_terminated);
cJSON* cJSON_ParseWithLengthOpts(const char* value, size_t buffer_length, const char** return_parse_end, cJSON_bool require_null_terminated);
/* Render a cJSON entity to text for transfer/storage. */
char* cJSON_Print(const cJSON* item);
/* Render a cJSON entity to text for transfer/storage without any formatting. */
char* cJSON_PrintUnformatted(const cJSON* item);
/* Render a cJSON entity to text using a buffered strategy. prebuffer is a guess at the final size. guessing well reduces reallocation. fmt=0 gives unformatted, =1 gives formatted */
char* cJSON_PrintBuffered(const cJSON* item, int prebuffer, cJSON_bool fmt);
/* Render a cJSON entity to text using a buffer already allocated in memory with given length. Returns 1 on success and 0 on failure. */
/* NOTE: cJSON is not always 100% accurate in estimating how much memory it will use, so to be safe allocate 5 bytes more than you actually need */
cJSON_bool cJSON_PrintPreallocated(cJSON* item, char* buffer, const int length, const cJSON_bool format);
/* Delete a cJSON entity and all subentities. */
void cJSON_Delete(cJSON* item);
/* Returns the number of items in an array (or object). */
int cJSON_GetArraySize(const cJSON* array);
/* Retrieve item number "index" from array "array". Returns NULL if unsuccessful. */
cJSON* cJSON_GetArrayItem(const cJSON* array, int index);
/* Get item "string" from object. Case insensitive. */
cJSON* cJSON_GetObjectItem(const cJSON* const object, const char* const string);
cJSON* cJSON_GetObjectItemCaseSensitive(const cJSON* const object, const char* const string);
cJSON_bool cJSON_HasObjectItem(const cJSON* object, const char* string);
/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */
const char* cJSON_GetErrorPtr(void);
/* Check item type and return its value */
char* cJSON_GetStringValue(const cJSON* const item);
double cJSON_GetNumberValue(const cJSON* const item);
/* These functions check the type of an item */
cJSON_bool cJSON_IsInvalid(const cJSON* const item);
cJSON_bool cJSON_IsFalse(const cJSON* const item);
cJSON_bool cJSON_IsTrue(const cJSON* const item);
cJSON_bool cJSON_IsBool(const cJSON* const item);
cJSON_bool cJSON_IsNull(const cJSON* const item);
cJSON_bool cJSON_IsNumber(const cJSON* const item);
cJSON_bool cJSON_IsString(const cJSON* const item);
cJSON_bool cJSON_IsArray(const cJSON* const item);
cJSON_bool cJSON_IsObject(const cJSON* const item);
cJSON_bool cJSON_IsRaw(const cJSON* const item);
/* These calls create a cJSON item of the appropriate type. */
cJSON* cJSON_CreateNull(void);
cJSON* cJSON_CreateTrue(void);
cJSON* cJSON_CreateFalse(void);
cJSON* cJSON_CreateBool(cJSON_bool boolean);
cJSON* cJSON_CreateNumber(double num);
cJSON* cJSON_CreateString(const char* string);
/* raw json */
cJSON* cJSON_CreateRaw(const char* raw);
cJSON* cJSON_CreateArray(void);
cJSON* cJSON_CreateObject(void);
/* Create a string where valuestring references a string so
* it will not be freed by cJSON_Delete */
cJSON* cJSON_CreateStringReference(const char* string);
/* Create an object/array that only references it's elements so
* they will not be freed by cJSON_Delete */
cJSON* cJSON_CreateObjectReference(const cJSON* child);
cJSON* cJSON_CreateArrayReference(const cJSON* child);
/* These utilities create an Array of count items.
* The parameter count cannot be greater than the number of elements in the number array, otherwise array access will be out of bounds.*/
cJSON* cJSON_CreateIntArray(const int* numbers, int count);
cJSON* cJSON_CreateFloatArray(const float* numbers, int count);
cJSON* cJSON_CreateDoubleArray(const double* numbers, int count);
cJSON* cJSON_CreateStringArray(const char* const* strings, int count);
/* Append item to the specified array/object. */
cJSON_bool cJSON_AddItemToArray(cJSON* array, cJSON* item);
cJSON_bool cJSON_AddItemToObject(cJSON* object, const char* string, cJSON* item);
/* Use this when string is definitely const (i.e. a literal, or as good as), and will definitely survive the cJSON object.
* WARNING: When this function was used, make sure to always check that (item->type & cJSON_StringIsConst) is zero before
* writing to `item->string` */
cJSON_bool cJSON_AddItemToObjectCS(cJSON* object, const char* string, cJSON* item);
/* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new cJSON, but don't want to corrupt your existing cJSON. */
cJSON_bool cJSON_AddItemReferenceToArray(cJSON* array, cJSON* item);
cJSON_bool cJSON_AddItemReferenceToObject(cJSON* object, const char* string, cJSON* item);
/* Remove/Detach items from Arrays/Objects. */
cJSON* cJSON_DetachItemViaPointer(cJSON* parent, cJSON* const item);
cJSON* cJSON_DetachItemFromArray(cJSON* array, int which);
void cJSON_DeleteItemFromArray(cJSON* array, int which);
cJSON* cJSON_DetachItemFromObject(cJSON* object, const char* string);
cJSON* cJSON_DetachItemFromObjectCaseSensitive(cJSON* object, const char* string);
void cJSON_DeleteItemFromObject(cJSON* object, const char* string);
void cJSON_DeleteItemFromObjectCaseSensitive(cJSON* object, const char* string);
/* Update array items. */
cJSON_bool cJSON_InsertItemInArray(cJSON* array, int which, cJSON* newitem); /* Shifts pre-existing items to the right. */
cJSON_bool cJSON_ReplaceItemViaPointer(cJSON* const parent, cJSON* const item, cJSON* replacement);
cJSON_bool cJSON_ReplaceItemInArray(cJSON* array, int which, cJSON* newitem);
cJSON_bool cJSON_ReplaceItemInObject(cJSON* object, const char* string, cJSON* newitem);
cJSON_bool cJSON_ReplaceItemInObjectCaseSensitive(cJSON* object, const char* string, cJSON* newitem);
/* Duplicate a cJSON item */
cJSON* cJSON_Duplicate(const cJSON* item, cJSON_bool recurse);
/* Duplicate will create a new, identical cJSON item to the one you pass, in new memory that will
* need to be released. With recurse!=0, it will duplicate any children connected to the item.
* The item->next and ->prev pointers are always zero on return from Duplicate. */
/* Recursively compare two cJSON items for equality. If either a or b is NULL or invalid, they will be considered unequal.
* case_sensitive determines if object keys are treated case sensitive (1) or case insensitive (0) */
cJSON_bool cJSON_Compare(const cJSON* const a, const cJSON* const b, const cJSON_bool case_sensitive);
/* Minify a strings, remove blank characters(such as ' ', '\t', '\r', '\n') from strings.
* The input pointer json cannot point to a read-only address area, such as a string constant,
* but should point to a readable and writable address area. */
void cJSON_Minify(char* json);
/* Helper functions for creating and adding items to an object at the same time.
* They return the added item or NULL on failure. */
cJSON* cJSON_AddNullToObject_(cJSON* const object, const char* const name);
cJSON* cJSON_AddTrueToObject_(cJSON* const object, const char* const name);
cJSON* cJSON_AddFalseToObject_(cJSON* const object, const char* const name);
cJSON* cJSON_AddBoolToObject(cJSON* const object, const char* const name, const cJSON_bool boolean);
cJSON* cJSON_AddNumberToObject_(cJSON* const object, const char* const name, const double number);
cJSON* cJSON_AddStringToObject_(cJSON* const object, const char* const name, const char* const string);
cJSON* cJSON_AddRawToObject(cJSON* const object, const char* const name, const char* const raw);
cJSON* cJSON_AddObjectToObject(cJSON* const object, const char* const name);
cJSON* cJSON_AddArrayToObject(cJSON* const object, const char* const name);
#define cJSON_SetIntValue(object, number) ((object) ? (object)->valueint = (object)->valuedouble = (number) : (number))
double cJSON_SetNumberHelper(cJSON* object, double number);
#define cJSON_SetNumberValue(object, number) ((object != NULL) ? cJSON_SetNumberHelper(object, (double)number) : (number))
char* cJSON_SetValuestring(cJSON* object, const char* valuestring);
#define cJSON_ArrayForEach(element, array) for(element = (array != NULL) ? (array)->child : NULL; element != NULL; element = element->next)
void* cJSON_malloc(size_t size);
void cJSON_free(void* object);
namespace ylib
{
class json
{
public:
enum type
{
null,
obj,
empty,
array,
boolean,
number,
string
};
public:
json();
json(const ylib::json& value);
json(cJSON* json,const std::string& name);
json(const std::vector<uint32>& value);
json(const std::vector<int32>& value);
json(const std::vector<uint64>& value);
json(const std::vector<int64>& value);
json(const std::vector<const char*>& value);
json(const std::vector<std::string>& value);
json(const std::vector<bool>& value);
json(const std::vector<double>& value);
json(const std::vector<float>& value);
json(const std::vector<ylib::json>& value);
//json(const std::initializer_list<ylib::json>& value);
//json(std::map<const char*, ylib::json> value);
json(const uint32& value);
json(const int32& value);
json(const uint64& value);
json(const int64& value);
json(const std::string& value);
json(const bool& value);
json(const double& value);
json(const float& value);
json(const char* value);
~json() ;
bool parse(const std::string& value);
void path(const std::string& path);
void safe(bool safe);
bool safe();
static ylib::json from(const std::string& value);
uint32 size() const;
void resize(uint32 size);
bool is_empty() const;
bool is_null() const;
bool is_obj() const;
bool is_array() const;
bool is_bool() const;
bool is_number() const;
bool is_string() const;
bool exist(const std::string& name) const;
void erase(const std::string& key);
void erase(uint32 index);
std::vector<std::string> keys() const;
const std::string& to_string(bool format = false) const;
ylib::json& operator[](const std::string name);
const ylib::json& operator[](const std::string name) const;
ylib::json& operator[](const size_t idx);
const ylib::json& operator[](const size_t idx) const;
//
void operator=(const std::vector<uint32>& value);
void operator=(const std::vector<int32>& value);
void operator=(const std::vector<uint64>& value);
void operator=(const std::vector<int64>& value);
void operator=(const std::vector<const char*>& value);
void operator=(const std::vector<std::string>& value);
void operator=(const std::vector<bool>& value);
void operator=(const std::vector<double>& value);
void operator=(const std::vector<float>& value);
void operator=(const std::vector<ylib::json>& value);
#ifndef MSVC_2010
void operator=(std::initializer_list<ylib::json> value);
#endif
void operator=(std::map<const char*, ylib::json> value);
void operator=(uint32 value);
void operator=(int32 value);
void operator=(uint64 value);
void operator=(int64 value);
void operator=(std::string value);
void operator=(const bool value);
void operator=(double value);
void operator=(float value);
void operator=(const char* value);
void operator=(ylib::json::type value);
void operator=(const ylib::json& value);
void push_back(uint32 value);
void push_back(int32 value);
void push_back(uint64 value);
void push_back(int64 value);
void push_back(std::string value);
void push_back(const bool value);
void push_back(double value);
void push_back(float value);
void push_back(const char* value);
void push_back(const ylib::json& value);
void clear();
template<typename T_TO>
T_TO to(bool check = false) const
{
if (check)
{
if (is_empty())
{
//trw_str("JSON is empty !!! Name:"+m_name);
}
}
#define RETURN_T(PARAM) return *((T_TO*)&PARAM)
#define CASE_T(TYPE) std::is_same<TYPE,T_TO>::value
if (CASE_T(std::vector<std::string>))
{
std::vector<std::string> result;
if (is_array() == false)
RETURN_T(result);
for (uint32 i = 0;i < size();i++)
result.push_back(this->operator[](i).to<std::string>());
RETURN_T(result);
}
else if (CASE_T(std::vector<ylib::json>))
{
std::vector<ylib::json> result;
if (is_array() == false)
RETURN_T(result);
for (uint32 i = 0;i < size();i++)
result.push_back(this->operator[](i));
RETURN_T(result);
}
else if (CASE_T(std::vector<int>) || CASE_T(std::vector<unsigned int>) || CASE_T(std::vector<long>))
{
std::vector<uint32> result;
if (is_array() == false)
RETURN_T(result);
for (uint32 i = 0;i < size();i++)
result.push_back(this->operator[](i).to<int>());
RETURN_T(result);
}
else if (CASE_T(std::vector<double>))
{
std::vector<double> result;
if (is_array() == false)
RETURN_T(result);
for (uint32 i = 0;i < size();i++)
result.push_back(this->operator[](i).to<double>());
RETURN_T(result);
}
else if (CASE_T(std::vector<long long>) || CASE_T(std::vector<unsigned long long>))
{
std::vector<unsigned long long> result;
if (is_array() == false)
RETURN_T(result);
for (uint32 i = 0;i < size();i++)
result.push_back(this->operator[](i).to<unsigned long long>());
RETURN_T(result);
}
else if (CASE_T(std::vector<float>))
{
std::vector<float> result;
if (is_array() == false)
RETURN_T(result);
for (uint32 i = 0;i < size();i++)
result.push_back(this->operator[](i).to<float>());
RETURN_T(result);
}
else if (CASE_T(int) || CASE_T(unsigned int) || CASE_T(long))
{
static int result = 0;
if (m_number)
result = (int)this->m_value_double;
else
result = ylib::stoi(m_value_string);
RETURN_T(result);
}
else if (CASE_T(short) || CASE_T(unsigned short))
{
static short result = 0;
if (m_number)
result = (short)this->m_value_double;
else
result = (short)ylib::stoi(m_value_string);
RETURN_T(result);
}
else if (CASE_T(std::string))
{
RETURN_T(this->m_value_string);
}
else if (CASE_T(double))
{
RETURN_T(this->m_value_double);
}
else if (CASE_T(long long) || CASE_T(unsigned long long))
{
static uint64 result = 0;
if (m_number)
result = (int)this->m_value_double;
else
{
result = ylib::stoull(m_value_string);
}
RETURN_T(result);
}
else if (CASE_T(float))
{
static float result = (float)this->m_value_double;
RETURN_T(result);
}
else if (CASE_T(bool))
{
RETURN_T(this->m_value_bool);
}
else
{
throw ylib::exception("not exception");
}
return T_TO();
}
private:
void init(cJSON* item);
void erase();
cJSON* arrangement() const;
bool is_newobj();
void clear_type();
bool __parse(const char* value,uint32 length);
private:
std::map<std::string, json*> m_objs;
std::vector<json*> m_arrs;
std::string m_name;
std::string m_value_string;
bool m_safe = false;
double m_value_double = 0.0f;
bool m_value_bool = false;
bool m_empty = false;
bool m_bool = false;
bool m_array = false;
bool m_obj = false;
bool m_string = false;
bool m_number = false;
bool m_null = false;
std::string m_jsonstring;
};
}

View File

@@ -1,77 +0,0 @@
#pragma once
#include <string>
#include <vector>
#include "util/json.h"
#include "util/counter.hpp"
namespace leveldb
{
class DB;
}
namespace ylib
{
/// <summary>
/// 本地存储(LevelDB)
/// </summary>
class local_storage
{
public:
local_storage();
~local_storage();
/// <summary>
/// 打开
/// </summary>
/// <param name="dirpath">目录</param>
/// <returns></returns>
bool open(const std::string& dirpath);
/// <summary>
/// 关闭
/// </summary>
void close();
/// <summary>
/// 清空数据库
/// </summary>
void clear();
/// <summary>
/// 写
/// </summary>
/// <param name="name"></param>
/// <param name="value"></param>
/// <returns></returns>
bool write(const std::string& name,const std::string& value);
/// <summary>
/// 读
/// </summary>
/// <param name="name"></param>
/// <param name="value"></param>
/// <returns></returns>
bool read(const std::string& name, std::string& value);
/// <summary>
/// 删除
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
bool del(const std::string& name);
/// <summary>
/// 是否存在
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
bool exist(const std::string& name);
/// <summary>
/// [测试] 生成GUID
/// </summary>
/// <returns></returns>
std::string test_make_guid();
private:
// 目录
std::string m_dirpath;
// DB指针
leveldb::DB* m_db = nullptr;
// GUID索引器
ylib::counter<uint32> m_guid_counter;
};
}

View File

@@ -1,157 +0,0 @@
#pragma once
#include <map>
#include <mutex>
#include <functional>
namespace ylib
{
template <typename KEY, typename VAL>
class map:private std::map<KEY,VAL>
{
public:
map() {}
~map() {}
const std::map<KEY, VAL> to_stl()
{
std::unique_lock<std::mutex> __guard_lock__(m_mutex);
return *this;
}
bool add(const KEY& key_, const VAL val, bool lock = true)
{
if (lock)
this->m_mutex.lock();
typename std::map<KEY, VAL>::iterator iter = ::std::map<KEY,VAL>::find(key_);
if (iter != ::std::map<KEY, VAL>::end()) {
if (lock)
this->m_mutex.unlock();
return false;
}
::std::map<KEY, VAL>::insert(std::pair<KEY, VAL>(key_, val));
if (lock)
this->m_mutex.unlock();
return true;
}
bool exist(const KEY& key_, bool lock = true)
{
if (lock)
this->m_mutex.lock();
auto iter = ::std::map<KEY,VAL>::find(key_);
bool ret = iter != ::std::map<KEY, VAL>::end();
if (lock)
this->m_mutex.unlock();
return ret;
}
bool set(const KEY& key_, VAL val, bool insert = false)
{
std::unique_lock<std::mutex> __guard_lock__(m_mutex);
typename std::map<KEY, VAL>::iterator iter = ::std::map<KEY, VAL>::find(key_);
if (iter == ::std::map<KEY, VAL>::end())
{
if (insert == true)
{
::std::map<KEY, VAL>::insert(std::pair<KEY, VAL>(key_, val));
return true;
}
else
{
return false;
}
}
else
{
iter->second = val;
return true;
}
}
bool get(const KEY& key_, VAL& val, bool lock = true)
{
if (lock)
this->m_mutex.lock();
typename std::map<KEY, VAL>::iterator iter = ::std::map<KEY, VAL>::find(key_);
if (iter == ::std::map<KEY, VAL>::end()) {
if (lock)
this->m_mutex.unlock();
return false;
}
val = iter->second;
if (lock)
this->m_mutex.unlock();
return true;
}
bool del(const KEY& key_,bool locked = true)
{
if(locked)
m_mutex.lock();
typename std::map<KEY, VAL>::iterator iter = ::std::map<KEY, VAL>::find(key_);
if (iter == ::std::map<KEY, VAL>::end()){
if(locked)
m_mutex.unlock();
return false;
}
::std::map<KEY, VAL>::erase(iter);
if(locked)
m_mutex.unlock();
return true;
}
void clear()
{
std::unique_lock<std::mutex> __guard_lock__(m_mutex);
//::std::map<KEY,VAL>::swap();
::std::map<KEY,VAL>::clear();
}
size_t size()
{
std::unique_lock<std::mutex> __guard_lock__(m_mutex);
return ::std::map<KEY,VAL>::size();
}
void lock()
{
this->m_mutex.lock();
}
void unlock()
{
this->m_mutex.unlock();
}
VAL operator[](const KEY& key)
{
std::unique_lock<std::mutex> __guard_lock__(m_mutex);
VAL val;
get(key, val,false);
return val;
}
bool find(std::function<bool(const KEY& key, const VAL& value)> delegate)
{
std::unique_lock<std::mutex> __guard_lock__(m_mutex);
for_iter(iter, (*this))
{
if (delegate(iter->first, iter->second))
return true;
}
return false;
}
void loop(std::function<void(const KEY& key,const VAL& value)> callback)
{
std::unique_lock<std::mutex> __guard_lock__(m_mutex);
for_iter(iter, (*this))
{
callback(iter->first,iter->second);
}
}
std::map<KEY, VAL>* parent()
{
return this;
}
public:
std::mutex m_mutex;
};
}

View File

@@ -1,2 +0,0 @@
#pragma once
#include "base/define.h"

View File

@@ -1,16 +0,0 @@
#pragma once
#include <stdio.h>
#include "base/define.h"
namespace ylib
{
namespace mem
{
const static uint32 __big_size = 1024 * 1024 * 10;
void* malloc(size_t size);
void free(void* src);
void* realloc(void* src, size_t length);
}
}

View File

@@ -1,31 +0,0 @@
#pragma once
#include "base/buffer.h"
#include "util/map.hpp"
namespace ylib
{
class package
{
public:
struct packstruct
{
std::string name;
ylib::buffer data;
};
public:
package();
~package();
bool parse(const ylib::buffer& data);
bool add(const std::string& name, const ylib::buffer& data);
void to(const std::string& password, ylib::buffer& data);
bool get(const std::string& name, ylib::buffer& data);
void clear();
void ___test__c_to_utf8();
private:
void free();
private:
ylib::map<std::string, packstruct*> m_list;
ylib::map<std::string, ylib::buffer*> m_parse_list;
};
}

View File

@@ -1,210 +0,0 @@
#pragma once
#include <iostream>
#include <mutex>
#include <memory>
#include "base/error.h"
#include "base/exception.h"
#include "util/queue.hpp"
namespace ylib {
class example_core{
public:
virtual void recover() = 0;
virtual void task_out() = 0;
};
class poolcore:public ylib::error_base
{
public:
void recover(void* example)
{
if(example == NULL)
return;
((ylib::example_core*)example)->recover();
std::unique_lock<std::mutex> sp(m_mutex);
m_pop_size--;
m_queue.push(example);
}
public:
void* env = nullptr;
protected:
ylib::queue<void*> m_queue;
std::mutex m_mutex;
bool m_closing;
size_t m_max_size;
size_t m_pop_size;
};
enum EXAMPLE_START_RESULT
{
SR_TIMEOUT,
SR_FAILED,
SR_SUCCESS
};
template<typename INFO>
class example:public example_core
{
public:
public:
example()
{
m_pool = nullptr;
}
virtual EXAMPLE_START_RESULT start(const INFO& info) = 0;
virtual void close() = 0;
inline void pool(poolcore *pool)
{
m_pool = pool;
}
inline poolcore *pool()
{
return m_pool;
}
protected:
poolcore *m_pool;
};
template<typename EXAMPLE>
//自动连接释放器
class conn_autofree
{
public:
conn_autofree(EXAMPLE* conn){
m_conn = conn;
}
~conn_autofree(){
if (m_conn != nullptr)
{
m_conn->pool()->recover(m_conn);
}
}
EXAMPLE* operator->() {
if (m_conn == nullptr)
{
throw ylib::exception("The connection is nullptr and an exception is thrown");
}
return m_conn;
}
EXAMPLE* get(){
if(m_conn == nullptr){
throw ylib::exception("conn is nullptr");
}
return m_conn;
}
private:
EXAMPLE* m_conn;
};
template<typename EXAMPLE,typename INFO>
class pool :public poolcore
{
public:
pool()
{
m_max_size = 0;
m_pop_size = 0;
m_closing = false;
}
~pool()
{
close();
}
bool start(const INFO& info,size_t size)
{
m_closing = false;
m_info = info;
m_max_size = size;
return true;
}
void close()
{
std::unique_lock<std::mutex> sp(m_mutex);
m_closing = true;
for (size_t i = 0; i < m_queue.size(); i++)
{
void* example = NULL;
if (m_queue.pop(example) == false)
break;
EXAMPLE*f = ((EXAMPLE*)example);
((EXAMPLE*)example)->pool(nullptr);
delete ((EXAMPLE*)example);
}
}
void* get_ptr() { return (void*)get(); }
EXAMPLE* get()
{
std::unique_lock<std::mutex> sp(m_mutex);
if (m_closing)
{
throw ylib::exception("pool is shutting down");
}
void* example = nullptr;
if (m_queue.pop(example) == false)
{
if (m_pop_size < m_max_size)
{
bool init_success = false;
example = new EXAMPLE;
//example->pool((void*)this);
((EXAMPLE*)example)->pool(this);
for (uint32 i = 0; i < 3; i++)
{
auto SR = ((EXAMPLE*)example)->start(m_info);
if (SR == SR_SUCCESS)
{
init_success = true;
break;
}
else if (SR == SR_TIMEOUT)
{
std::cout << "start failed." << ((EXAMPLE*)example)->last_error().c_str() << std::endl;
std::cout << "restart " << std::to_string(i + 1).c_str() << "." << std::endl;
}
else if (SR == SR_FAILED)
{
break;
}
}
if (init_success)
{
m_pop_size++;
((EXAMPLE*)example)->task_out();
return ((EXAMPLE*)example);
}
else
{
std::string last_error = ((EXAMPLE*)example)->last_error();
delete ((EXAMPLE*)example);
throw ylib::exception(last_error);
}
}
else
{
throw ylib::exception("maximum capacity exceeded");
}
}
else
{
m_pop_size++;
((EXAMPLE*)example)->pool(this);
((EXAMPLE*)example)->task_out();
return ((EXAMPLE*)example);
}
}
size_t size()
{
return m_max_size-m_pop_size;
}
public:
INFO m_info;
};
}

View File

@@ -1,10 +0,0 @@
#pragma once
#include <string>
#include "base/define.h"
namespace ylib
{
void println(const std::string& text,ylib::ConsoleTextColor color = ylib::ConsoleTextColor::DEFAULT);
void print(const std::string& text, ylib::ConsoleTextColor color = ylib::ConsoleTextColor::DEFAULT);
}

View File

@@ -1,43 +0,0 @@
#pragma once
#include <functional>
#include <list>
#include <string>
#include <vector>
#include "base/define.h"
namespace ylib
{
namespace process
{
#ifdef _WIN32
// 取进程路径
std::string getpath(uint32 process_id);
/*进程信息*/
struct proc_info
{
std::string path()
{
if (__filepath.empty())
return ylib::process::getpath(pid);
return __filepath;
}
std::string __filepath;
std::string name;
uint32 parent_pid = 0;
uint32 pid = 0;
};
// 创建进程
bool create(const std::string& filepath, const std::string& working_directory = "", const std::vector<std::string>& args = {}, bool wait_close = false, bool show_window = true, size_t* pid = nullptr);
// 销毁进程
bool destory(uint32 process_id);
// 系统进程列表
std::list<ylib::process::proc_info> list();
// 是否存在
bool exist(const std::string& filepath);
// 检测多开
bool already_running(const std::string& name);
// 设置为启动
bool running(const std::string& name);
#endif
}
}

View File

@@ -1,94 +0,0 @@
#pragma once
#include <queue>
#include <stdio.h>
#include <mutex>
namespace ylib
{
template<typename T>
class queue
{
public:
struct node
{
T value;
node* next;
};
public:
queue()
{
m_first = nullptr;
m_end = nullptr;
m_size = 0;
}
~queue()
{
clear();
}
inline void clear()
{
m_mutex.lock();
T value;
while(pop(value,false));
m_mutex.unlock();
}
inline void push(const T& value, bool locked = true)
{
if(locked){
m_mutex.lock();
}
m_size++;
if(m_first ==nullptr)
{
m_first = new node();
m_first->next = nullptr;
m_first->value = value;
m_end = m_first;
if(locked){
m_mutex.unlock();
}
return;
}
m_end->next = new node;
m_end->next->next = nullptr;
m_end->next->value = value;
m_end = m_end->next;
if(locked){
m_mutex.unlock();
}
}
inline bool pop(T& value,bool locked = true)
{
if(m_first == nullptr)
return false;
if(locked){
m_mutex.lock();
}
if(m_first == nullptr)
{
if(locked){
m_mutex.unlock();
}
return false;
}
m_size--;
value = m_first->value;
node* temp = m_first->next;
delete m_first;
m_first = temp;
if(locked){
m_mutex.unlock();
}
return true;
}
inline size_t size(){return m_size;}
node* m_first;
node* m_end;
std::mutex m_mutex;
size_t m_size;
};
}

View File

@@ -1,25 +0,0 @@
#pragma once
#include "sqlite3/sqlite3.h"
#include "base/define.h"
#include "base/error.h"
#include <vector>
#include <map>
#define SQLITE_RESULT std::vector<std::map<std::string, std::string>>
namespace ylib
{
class sqlite3:public ylib::error_base
{
public:
sqlite3();
~sqlite3();
bool open(const std::string& filepath,const std::string& username ="",const std::string& password = "");
void close();
bool exec(const std::string& sql);
bool query(const std::string& sql, std::vector<std::map<std::string, std::string>>& data);
int64 count(const std::string& sql);
int64 last_insert_id();
private:
struct ::sqlite3* m_db;
};
}

View File

@@ -1,117 +0,0 @@
#pragma once
#include <string>
#include <vector>
#include "base/define.h"
namespace ylib
{
namespace strutils{
/**
* @brief 删除子字符串
* @param str
* @param sub
* @return
*/
std::string remove(std::string str, const std::string& sub);
/**
* @brief 大小写转换
* @param input
* @param toUpperCase
* @return
*/
std::string change_case(const std::string& input, bool toUpperCase/*true=大写,false=小写*/);
/**
* @brief 分割字符串
* @param str
* @param delim
* @return
*/
std::vector<std::string> split(const std::string& str, const std::string& delim);
std::vector<std::string> split(const std::string& str,char delim);
/**
* @brief 去首尾字符
* @param str
* @param chars
* @return
*/
std::string trim(std::string s,const std::vector<char>& trim_chars);
/**
* @brief 去首字符
* @param str
* @param chars
* @return
*/
std::string trim_begin(std::string s,const std::vector<char>& trim_chars);
/**
* @brief 去尾字符
* @param str
* @param chars
* @param loop = 循环匹配
* @return
*/
std::string trim_end(std::string s,const std::vector<char>& trim_chars,bool loop = false);
/**
* @brief 左边
* @param str
* @param len
* @return
*/
std::string left(const std::string& str,size_t len);
/**
* @brief 右边
* @param str
* @param len
* @return
*/
std::string right(const std::string& str,size_t len);
/**
* @brief 是否为数字
* @return
*/
bool is_num(const std::string& str);
bool is_num_code(char value);
/**
* @brief 是否为英文
* @return
*/
bool is_en_code(char value);
/**
* @brief 取中间
* @param str
* @param begin
* @param end
* @return
*/
std::string between(const std::string& str,const std::string& begin,const std::string& end);
/**
* @brief 替换
* @param str
* @param search
* @param value
* @return
*/
std::string replace(const std::string& str, const std::string& search, const std::string& value);
std::string replace(const std::string& str, uchar search,uchar value);
/**
* @brief 空值
*/
std::string F(const char* value);
#ifdef _WIN32
std::wstring to_wstring(const std::string& value);
std::string wto_string(const std::wstring& value);
#endif
/// <summary>
/// 填补
/// </summary>
/// <param name="value">输入</param>
/// <param name="fixed_length">固定长度</param>
/// <param name="pad">填补字符</param>
/// <returns></returns>
std::string pad_with_begin(const std::string& value,size_t fixed_length,char pad);
std::string pad_with_end(const std::string& value, size_t fixed_length, char pad);
}
}

View File

@@ -1,44 +0,0 @@
#pragma once
#include <vector>
#include "base/define.h"
namespace ylib
{
namespace system
{
//睡眠
void sleep_msec(uint32 msec);
//取随机数
int64 random(int64 min, int64 max);
//取运行目录
std::string current_dir();
//取运行全路径
std::string current_filepath();
//取临时目录
std::string temp_path();
//桌面路径
std::string desktop_path();
//取当前用户目录
std::string currentuser_path();
//系统通知
void notification(const std::string& title, const std::string& message);
//mac地址
std::vector<std::string> mac();
#ifdef _WIN32
//打开浏览器
void open_browser(const std::string& url);
//磁盘列表
std::vector<char> disk_list();
//取磁盘信息
ylib::DiskCapacity disk_capacity(char disk_name);
//取容量最大磁盘号
char disk_max_capacity();
//系统版本
std::string version();
//取系统最后错误描述
std::string last_error();
#endif
}
}

View File

@@ -1,56 +0,0 @@
#pragma once
#include <functional>
#include <thread>
#include "json.h"
namespace ylib
{
/****************************************************
* Class线程工具类
* DateTime2019-10-29
****************************************************/
class ithread
{
public:
ithread();
~ithread();
/***************************************************************************
* Function开启线程
* Return:
* == true : 成功
* == false : 失败
****************************************************************************/
bool start();
void wait();
/***************************************************************************
* Function停止线程
* Return:
* == true : 成功
* == false : 失败
****************************************************************************/
bool stop();
/// <summary>
/// 等待关闭
/// </summary>
bool wait_stop();
/// <summary>
/// 睡眠等待
/// </summary>
void sleep(int32 msec);
private:
/***************************************************************************
* Function纯虚函数 需要子类实现
* Description本类会线程内调用该类,间歇时间由 Run() 内自行实现
* Return:
* == true : 继续执行下一循环
* == false : 终止循环,退出线程
****************************************************************************/
virtual bool run() = 0;
public:
void* __thread_handle(void* param);
public:
// 0=启动中 1=停止信号已发送 2=已停止
unsigned int m_state;
bool m_thread;
};
}

View File

@@ -1,100 +0,0 @@
#pragma once
#include <map>
#include "base/define.h"
namespace ylib
{
namespace time
{
struct datetime
{
datetime() {
year = 0;
month = 0;
day = 0;
hour = 0;
minute = 0;
second = 0;
}
short year;
char month;
char day;
char hour;
char minute;
char second;
};
//网络时间
timestamp network_msec();
//标准字符串时间转时间戳
timestamp to_ts(const std::string& timestr, const std::string& formart = "%d-%d-%d %d:%d:%d");
timestamp to_ts(struct ylib::time::datetime& datetime);
//当前时间戳
uint32 now_sec();
timestamp now_msec();
timestamp now_usec();
/*
%a 星期几的简写
%A 星期几的全称
%b 月分的简写
%B 月份的全称
%c 标准的日期的时间串
%C 年份的后两位数字
%d 十进制表示的每月的第几天
%D 月/天/年
%e 在两字符域中,十进制表示的每月的第几天
%F 年-月-日
%g 年份的后两位数字,使用基于周的年
%G 年分,使用基于周的年
%h 简写的月份名
%H 24小时制的小时
%I 12小时制的小时
%j 十进制表示的每年的第几天
%m 十进制表示的月份
%M 十时制表示的分钟数
%n 新行符
%p 本地的AM或PM的等价显示
%r 12小时的时间
%R 显示小时和分钟hh:mm
%S 十进制的秒数
%t 水平制表符
%T 显示时分秒hh:mm:ss
%u 每周的第几天,星期一为第一天 值从0到6星期一为0
%U 第年的第几周把星期日做为第一天值从0到53
%V 每年的第几周,使用基于周的年
%w 十进制表示的星期几值从0到6星期天为0
%W 每年的第几周把星期一做为第一天值从0到53
%x 标准的日期串
%X 标准的时间串
%y 不带世纪的十进制年份值从0到99
%Y 带世纪部分的十进制年份
%z%Z 时区名称,如果不能得到时区名称则返回空字符。
%% 百分号
取时间字符串*/
std::string now_time(const std::string& format = "%Y-%m-%d %H:%M:%S");
std::string format(timestamp time, const std::string& format = "%Y-%m-%d %H:%M:%S");
void format(timestamp time, struct ylib::time::datetime& datetime);
ylib::time::datetime now_time2();
//获取当前时区
int32 now_zone();
//获取当前GMT时间
void now_gmt(std::string& gmt);
//时间戳转GMT时间
void to_gmt(const timestamp& timestamp, std::string& gmt);
//取当前凌晨时间
timestamp now_zero_sec();
std::string now_zero_time();
}
}

View File

@@ -1,106 +0,0 @@
#pragma once
#include <iostream>
#include <functional>
#include <string>
#include <thread>
#include <chrono>
#include <mutex>
#include <list>
#include "ybase/define.h"
#include "yutil/time.h"
namespace ylib
{
class timeout {
public:
timeout() : running_(false) {}
~timeout() {
stop();
}
void add(std::function<void(void*, const std::string&)> callback, const std::string& name, uint64_t timeout_msec, void* extra = nullptr) {
uint64_t endTime = time::now_msec() + timeout_msec;
TimerTask newTask = { callback, name, endTime, extra };
{
std::lock_guard<std::mutex> lock(mutex_);
tasks_.push_back(newTask);
}
}
void remove(const std::string& name) {
std::lock_guard<std::mutex> lock(mutex_);
auto it = tasks_.begin();
while (it != tasks_.end()) {
if (it->name == name) {
it = tasks_.erase(it);
}
else {
++it;
}
}
}
void start() {
std::lock_guard<std::mutex> lock(mutex_);
if (!running_) {
running_ = true;
schedulerThread_ = std::thread(&timeout::scheduler, this);
}
}
void stop() {
{
std::lock_guard<std::mutex> lock(mutex_);
running_ = false;
}
if (schedulerThread_.joinable()) {
schedulerThread_.join();
}
}
private:
struct TimerTask {
std::function<void(void*, const std::string&)> callback;
std::string name;
uint64_t endTime;
void* extra;
};
std::list<TimerTask> tasks_;
std::mutex mutex_;
std::thread schedulerThread_;
bool running_;
void scheduler() {
while (running_) {
std::this_thread::sleep_for(std::chrono::seconds(1));
uint64_t now = time::now_msec();
std::list<TimerTask> tasksToExecute;
{
std::lock_guard<std::mutex> lock(mutex_);
auto it = tasks_.begin();
while (it != tasks_.end()) {
if (it->endTime <= now) {
tasksToExecute.push_back(*it);
it = tasks_.erase(it);
}
else {
++it;
}
}
}
for (auto& task : tasksToExecute) {
task.callback(task.extra, task.name);
}
}
}
};
}

View File

@@ -1,79 +0,0 @@
#pragma once
#include <vector>
#include <functional>
namespace ylib
{
template<typename T>
class vector:public std::vector<T>
{
public:
vector(const std::vector<T>& value):std::vector<T>()
{
operator=(value);
}
vector() : std::vector<T>()
{
}
~vector()
{
}
void operator=(const std::vector<T>& value)
{
*((std::vector<T>*)this) = value;
}
bool find(std::function<bool(T& value, size_t idx)> callback)
{
for (size_t i = 0; i < this->size(); i++)
{
if (callback((*this)[i], i))
return true;
}
return false;
}
bool find(const T& value)
{
for (size_t i = 0; i < this->size(); i++)
{
if(value == this->at(i))
return true;
}
return false;
}
bool find(std::function<bool(T& value, size_t idx)> callback,T& value)
{
for (size_t i = 0; i < this->size(); i++)
{
if (callback((*this)[i], i))
{
value =this->at(i);
return true;
}
}
return false;
}
void loop(std::function<void(const T& value)> callback)
{
for (size_t i = 0; i < this->size(); i++)
callback(this->at(i));
}
void loop_fl(std::function<void(const T& value,bool first,bool last)> callback)
{
for (size_t i = 0; i < this->size(); i++)
callback(this->at(i),i==0,i==this->size()-1);
}
void rloop(std::function<void(const T& value)> callback)
{
size_t size = this->size();
for (size_t i = 0; i < this->size(); i++)
callback(this->at(size-i-1));
}
void rloop_fl(std::function<void(const T& value, bool first, bool last)> callback)
{
size_t size = this->size();
for (size_t i = 0; i < this->size(); i++)
callback(this->at(size - i - 1), i == size - 1, i == 0);
}
};
}

View File

@@ -1,62 +0,0 @@
#pragma once
#ifdef _WIN32
#include <vector>
#include "base/define.h"
namespace ylib{
namespace window
{
//取父句柄
size_t parent(size_t handle);
//取窗口类名
std::string class_name(size_t handle);
//取窗口标题
std::string title_name(size_t handle);
//置窗口标题
bool title_name(size_t handle, const std::string& name);
// 查找
size_t find(const std::string& class_name, const std::string& title_name = "");
std::vector<size_t> find(size_t parent = 0, const std::string& class_name = "", const std::string& title_name = "", const std::string& filepath = "");
// 取矩形
ylib::Rect rect(size_t handle);
// 设置父句柄
void set_parent(size_t handle, size_t parent);
// 取进程路径
std::string path(size_t handle);
// 关闭
void close(size_t handle);
// 内容
void content(size_t handle, const std::string& value);
std::string content(size_t handle);
namespace menu
{
bool click(size_t handle, size_t menu_child_handle, uint32 menu_item_idx);
size_t get(size_t handle);
size_t child(size_t menu_handle, uint32 menu_childs_idx);
}
namespace checkbox
{
bool checked(size_t handle);
bool checked(size_t handle, bool checked);
}
namespace tab
{
void current(size_t handle, uint32 idx);
}
namespace button
{
bool click(size_t handle);
bool click(size_t parent, const std::string& class_name, const std::string& title_name = "");
}
namespace list
{
void insert(size_t handle, uint32 index, const std::string& value);
}
void rect_sort(std::vector<size_t>& list, uint32 type, bool ps = true);
bool enable(size_t win_handle, bool enable);
}
}
#endif

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.