网络通信数据处理 Xbytestring类

PS_Xbytestring

a byte string for store low level data type

文件夹[TOC]


base info

在基于TCP/UDP 或者串口通信底层的通信过程中。涉及到大量的字符串操作:存储拷贝传參 等。

xbytestring 类时面向底层通信,专门针对 unsigned char 字符串操作的而开发的。 相对于使用 字符指针的开发方式, xbytestring 具备 调用方便安全的特性,非常好的攻克了 字符串操作过程中遇到的诸多缺陷,于此同一时候 xbytestring 能够非常好的兼容 ST::stringunsigned char ,char 数据类型,方便开发人员更加在各个数据类型之间转化。

background

在低层次的网络通信过程中。全部的数据都是通过 ascii 码的形式接受和传输。使用char,或者unsigned char的数据类型 进行数据的存储或者传递 对于上层的开发时是非常不方便。

因为期间涉及到大量的动态内存创建删除指针传递拷贝内存溢出则是这其中最easy引发的问题,这是另无数开发头疼不已的问题,尽管非常多情况下能够用智能指针解决问题。可是对于字符的操作却不总是那么的安全友好

  • C 语言的特性 : 为了高效而牺牲了代码的安全
  • 高级的语言特性 : 牺牲代码的效率来换取 代码安全和开发效率

analysis

略微有开发经验的读者可能联想到了 STL库提供的 std::string来解决问题. string 能够非常好的做到 字符串数据的存储传递, 可是在实际的开发的过程中,基于UDP /TCP 协议的网络通信中,涉及到大量的使用0x00 这种字符代表的操作, 而string 天生对0x 00 敏感的特性(默觉得结束符),导致string会自己主动丢弃在接受到0x00字符后的全部的数据.
非常显然,这不是我们所希望看到的结果。

为了更好的兼容 0x00 。方便的存储和传參的需求。 在开发过程中急需一 相似于string的容器。能够非常好的存储网络其中给定长度的 字符串.

经过一番谷歌之后, 仅有的一点发现也只 是 java 平台下的 ByteString ,非常可惜,这不是给C++ 用的, 考虑再三,为什么不重造一个呢? 造轮子可是C++ 的专利啊。


feature

  • 操作方便安全,接口友好
  • 兼容 string 的接口
  • 默认存储 unsigned char
  • 高速实现 xbytestring 和 char ,string 数据类型的转化
  • 自由拓展字符串长度
  • 内存安全
///////////////////////////////////////////////////////////////
/*
File name   :   Xbytestring.h
Author      :   LEO
Date        :   2015-3-12
Email       :   lion_117@126.com
Description:
All Rights Reserved 
*/
///////////////////////////////////////////////////////////////


#pragma once
#include <string>
#include <vector>
using namespace  std;
typedef unsigned char u_char;
typedef unsigned int  u_int;



class Xbytestring
{

private:                // to realize the copy constructor fuction 
    vector<u_char>      list_datastring;

public:
    Xbytestring(void);
    Xbytestring(u_char *pchar , u_int nlenth);
    Xbytestring(string pstring);
    Xbytestring(const Xbytestring &obj_string);
    u_char &  operator[](u_int nindex);
    Xbytestring operator+(Xbytestring & obj_a );

    ~Xbytestring(void);

public:
    u_int   size();
    u_char  at( u_int nindex);
    bool    empty();
    void    clear();
    void    c_str( u_char  *pchar );
    string  tostring();
    string  tosafestring();
    void    setdata(u_char *pchar , u_int nlenth);
    void    setdata(string pstr);
    void    setdata(Xbytestring pobj);
    //**********abandon function interface ******//
    void    Set_data(u_char *pchar , u_int nlenth);
    void    Set_data(string pstr);
    //*******************************************//
    void    append(u_char *pchar , u_int nlenth);
    void    append(string pstring);
    void    append(u_char  pchar);
    void    append(Xbytestring pobj);

    void    erease(u_int nindex);



private:
    bool Copy_deep(u_char * pstr , u_int nlenth);
};

github

点击此链接下载源代码

posted @ 2018-03-22 14:01  llguanli  阅读(119)  评论(0)    收藏  举报