Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

自己動手做一個跨平台 C++ 序列化庫:archive 的設計與用法

C++ 標準庫沒有現成的序列化機制,於是社群裡出現了各種方案:Boost.Serialization、Google 的 Protocol Buffers、FlatBuffers 等等。但它們多半伴隨可觀的相依重量,光是為了存幾個欄位就得拖進一整座函式庫。

所以這次分享一個我自己寫的序列化庫。設計時我只有一條驗收標準:別人用我的庫,需要寫幾行程式碼? 答案是三個運算子——<<、>>、&。它只依賴 C++ 標準語法,理論上跨平台;實作上借用了上一篇提到的 traits 庫來做型別分派。

性能方面,早期版本曾與 Boost/Google 的實作比過,大約慢一倍;後來定位到多了一次不必要的複製,可見仍有可觀的改善空間。原始設計提供兩類 archive:以 string/wstring 為後端,以及以 fstream 為後端;XML 與二進位格式則因故未能補完,留待擴充。

使用方式:自訂型別只要一個 serialize 方法

#include <iostream>
#include "../../traits/traits.hpp"
#include "../../serialization/archive.hpp"

using namespace std;

struct Student
{
    int _idx;
    float _weigth;
    std::string _name;
    std::list<std::string> _familyName_list;

    // 必須是 public 的
    template<typename Arch>
    void serialize(Arch& arch, unsigned int ver)
    {
        // ver 是版本號
        arch & _idx
             & _weigth
             & _name
             & _familyName_list;
    }
};

int main()
{
    Student stu;
    stu._idx = 1;
    stu._weigth = 120.45f;   // 浮點精度可由宏 SERIALIZATION_FLOAT_PRECISION 控制
    stu._name = "小明";
    stu._familyName_list.push_back("爸爸");
    stu._familyName_list.push_back("媽媽");
    stu._familyName_list.push_back("姐姐");

    // 序列化到字串
    std::string ostr;
    serialization::default_string_oarchive oarch(ostr);
    oarch & stu;             // 也可以寫 oarch << stu;
    cout << ostr << endl;

    // 反序列化
    Student stu2;
    serialization::default_string_iarchive iarch(ostr);
    iarch & stu2;            // 也可以寫 iarch >> stu2;

    // 指標的序列化:存的是「位址」而非位址所指的值。
    // 因為序列化的對象是變數本身的值,若改存指向的值,
    // 反序列化時就得面臨記憶體該由誰配置的尷尬問題。
    std::string ostr2;
    serialization::default_string_oarchive oarch2(ostr2);
    char* pchar = "fdsfdsfsf";
    oarch2 & pchar;

    return 0;
}

一個型別只要能提供 serialize(Arch&, unsigned int),就自動取得序列化能力;基本型別、字串與常見 STL 容器則由庫內建支援,不在支援清單上的容器可以自己補一份特化。

archive.hpp:把後端與型別綁在一起

// archive.hpp
#ifndef ARCHIVE_INCLUDE
#define ARCHIVE_INCLUDE
#include "string_archive.hpp"
#include "wstring_archive.hpp"
#include "stream_archive.hpp"
#include "wstream_archive.hpp"
#include "xml_archive.hpp"
#include <string>
#include <fstream>

NAMESPACE_SERIALIZATION_BEGIN

typedef serialization::string_iarchive<std::string>  default_string_iarchive;
typedef serialization::string_oarchive<std::string>  default_string_oarchive;
typedef serialization::wstring_iarchive<std::wstring> default_wstring_iarchive;
typedef serialization::wstring_oarchive<std::wstring> default_wstring_oarchive;
typedef serialization::stream_iarchive<std::ifstream> file_stream_iarchive;
typedef serialization::stream_oarchive<std::ofstream> file_stream_oarchive;
typedef serialization::wstream_iarchive<std::wifstream> file_wstream_iarchive;
typedef serialization::wstream_oarchive<std::wofstream> file_wstream_oarchive;

NAMESPACE_SERIALIZATION_END
#endif

archive_config.hpp:版本號、精度與位置型別

版本號用高低 16 位元打包成一個 32 位元整數,浮點輸出精度由 SERIALIZATION_FLOAT_PRECISION 控制;storagepos 則是紀錄「目前讀寫到哪個位置」的游標,並針對不同平台 typedef 出 64 位元整數。

#define _SERIALIZATION_VERSION_H(h) ((unsigned short)(h)) << 16
#define _SERIALIZATION_VERSION_L(l) ((unsigned short)(l))
#define _SERIALIZATION_VERSION(h,l) (_SERIALIZATION_VERSION_H(h) | _SERIALIZATION_VERSION_L(l))
#define SERIALIZATION_VERSION       _SERIALIZATION_VERSION(1,0)
#define SERIALIZATION_FLOAT_PRECISION 16   // 浮點精度

NAMESPACE_SERIALIZATION_BEGIN

#ifdef _MSC_VER
typedef long long          _int64_;
typedef unsigned long long _uint64_;
#elif __GNUC__
typedef int64_t  _int64_;
typedef uint64_t _uint64_;
#else
typedef int          _int64_;
typedef unsigned int _uint64_;
#endif

class storagepos
{
public:
    storagepos(vehicleoff _off = 0) : m_vehicle_off(_off){}
    operator vehicleoff() const { return m_vehicle_off; }
    vehicleoff operator -(const storagepos& _right) const { return m_vehicle_off - (vehicleoff)_right; }
    vehicleoff operator +(const storagepos& _right) const { return m_vehicle_off + (vehicleoff)_right; }
    bool operator ==(const storagepos& _right) const { return m_vehicle_off == (vehicleoff)_right; }
    bool operator !=(const storagepos& _right) const { return !(*this == _right); }
private:
    vehicleoff m_vehicle_off;
};

struct storage_type
{
    typedef unsigned int VEHICLE_TYPE;
    enum
    {
        _ISTREAM_TYPE, _OSTREAM_TYPE,
        _ISTRING_TYPE, _OSTRING_TYPE,
        _WISTREAM_TYPE, _WOSTREAM_TYPE,
        _WISTRING_TYPE, _WOSTRING_TYPE,
        _IXML_TYPE, _OXML_TYPE
    };
};

NAMESPACE_SERIALIZATION_END

basic_archive 與 basic_iarchive/oarchive_impl:三個運算子的入口

basic_archive 只負責持有後端(storage)與游標;輸入/輸出各自再包一層 impl,把 & 實作成模板成員函式,並額外提供陣列的 & 重載,最後由 <</>> 轉呼 &,讓三種寫法完全等價。

template<typename storage_class>
class basic_archive
{
protected:
    storage_class* _storage;   // 倉庫
    storagepos     _storage_pos;
protected:
    basic_archive(const storage_class* sc) { _storage = const_cast<storage_class*>(sc); }
    basic_archive();
    basic_archive(const basic_archive&);
public:
    virtual ~basic_archive(){}
};

template<typename storage_class, typename storage_type::VEHICLE_TYPE _storage_type>
class basic_iarchive_impl : public basic_archive<storage_class>
{
public:
    typedef basic_iarchive_impl<storage_class,_storage_type> _My;
protected:
    basic_iarchive_impl(const storage_class& storage)
        : basic_archive<storage_class>(&storage){}
    virtual ~basic_iarchive_impl(){}
public:
    template<typename param_type>
    _My& operator &(param_type& param)
    {
        iarchive_param_deliverer<storage_class,_storage_type> param_helper;
        param_helper.m_bii = this;
        param_helper._storage = basic_archive<storage_class>::_storage;
        param_helper._storage_pos = &(basic_archive<storage_class>::_storage_pos);

        iarchive_impl_helper<param_type,storage_class,_storage_type> helper(param_helper, param);
        return (*this);
    }

    template<typename param_type,int NUM>
    _My& operator &(param_type (&param)[NUM])
    {
        /* 同上,改以 iarchive_impl_helper<param_type(&)[NUM], ...> 分派 */
    }

    template<typename param_type>
    _My& operator >>(param_type& param) { (*this)&param; return (*this); }

    void clear(){ basic_archive<storage_class>::_storage_pos = (storagepos)0; }
};

/* basic_oarchive_impl 與輸入版完全對稱:
   operator &(const param_type&)、陣列重載,以及 operator << 轉呼 &。 */

from_archive / to_archive:真正動手讀寫的地方

這兩個檔案是整套設計的「分派終點」:From_Archive_Helper 與 To_Archive_Helper 以 storage 的型別標籤(_ISTRING_TYPE、_OSTRING_TYPE、_WISTRING_TYPE…)做第一層偏特化,再以參數型別做第二層偏特化。字串先寫入長度再寫入內容,讀取時也照同樣順序還原,因此不需要分隔符即可安全解析;wstring 與 string 之間則透過 codecvt 轉換(UTF-16 ↔ 多-byte)。

/// 讀取:istring
template<typename storage_class,typename param_type>
struct From_Archive_Helper<storage_type::_ISTRING_TYPE,storage_class,param_type>
{
    From_Archive_Helper(storage_class& storage, param_type& param, storagepos& pos)
    {
        const char* pstorage = storage.c_str();
        pstorage += (int)pos;
        converter::lexical_cast<param_type> cast(param, pstorage);
        pos += (storagepos)(cast.length + 1);
    }
};

/// 讀取 string:先取長度,再取資料
template<typename storage_class>
struct From_Archive_Helper<storage_type::_ISTRING_TYPE,storage_class,std::string>
{
    From_Archive_Helper(storage_class& storage, std::string& param, storagepos& pos)
    {
        const char* pstorage = storage.c_str();
        pstorage += (int)pos;

        unsigned int size = 0;
        converter::lexical_cast<unsigned int> cast(size, pstorage);
        pos += (storagepos)(cast.length + 1);

        pstorage = storage.c_str();
        pstorage += (int)pos;
        param.append(pstorage, size);
        pos += (storagepos)(size + 1);
    }
};

/// 寫入:ostring
template<typename storage_class,typename param_type>
struct To_Archive_Helper<storage_type::_OSTRING_TYPE,storage_class,param_type>
{
    To_Archive_Helper(storage_class& storage, const param_type& param)
    {
        converter::lexical_cast<storage_class>(storage, param, true);
        storage.append(" ");
    }
};

/// 寫入 string:長度 + 內容
template<typename storage_class>
struct To_Archive_Helper<storage_type::_OSTRING_TYPE,storage_class,std::string>
{
    To_Archive_Helper(storage_class& storage, const std::string& param)
    {
        converter::lexical_cast<storage_class>(storage, (unsigned int)(param.length()), true);
        storage.append(" ");
        converter::lexical_cast<storage_class>(storage, param, true);
        storage.append(" ");
    }
};

/* wstring / wchar_t / char 的雙向轉換特化,以及 _WISTRING_TYPE、
   _WOSTRING_TYPE 版本,結構與上面一致,此處從略。
   注意:_ISTREAM_TYPE 與 _OSTREAM_TYPE 版本目前是空實作,
   也就是「串流後端」的骨架已就緒,真正的讀寫邏輯仍待補上。 */

iarchive_impl_helper / oarchive_impl_helper:型別分派的中樞

這兩個檔案是 Kuhn 樣板(tag dispatch)的實際應用:針對自訂型別走 serialize(),針對 STL 容器先讀/寫一個 unsigned int 記下元素個數,再逐一遞迴處理元素;針對指標則只處理位址;基本型別全部轉交給 From_Archive_Helper/To_Archive_Helper。另外還刻意保留了一個 const param_type 的特化,讓「試圖反序列化到 const 物件」在編譯階段就失敗。

// 自定義型別
template<typename param_type,typename storage_class,storage_type::VEHICLE_TYPE _storage_type>
struct iarchive_impl_helper
{
    inline iarchive_impl_helper(iarchive_param_deliverer<storage_class,_storage_type>& helper, param_type& param)
    {
        param_type& p = const_cast<param_type&>(param);
        unsigned int version = SERIALIZATION_VERSION;
        p.serialize(*helper.m_bii, version);
    }
};

// const 版本:故意保留,用來在編譯期報錯
template<typename param_type,typename storage_class,storage_type::VEHICLE_TYPE _storage_type>
struct iarchive_impl_helper<const param_type,storage_class,_storage_type>
{
    iarchive_impl_helper(iarchive_param_deliverer<storage_class,_storage_type>& helper, const param_type& param)
    {
        param_type p;
        param = p;   // 不能使用 const
    }
};

// 指標:只還原位址
template<typename param_type,typename storage_class,storage_type::VEHICLE_TYPE _storage_type>
struct iarchive_impl_helper<param_type*,storage_class,_storage_type>
{
    inline iarchive_impl_helper(iarchive_param_deliverer<storage_class,_storage_type>& helper, param_type*& param)
    {
        unsigned int addr;
        From_Archive_Helper<_storage_type,storage_class,unsigned int> f_a_h(*(helper._storage), addr, *helper._storage_pos);
        param = traits::pointer_integer_traits<param_type*>(addr);
    }
};

// std::vector:先讀 size,再逐一讀元素
template<typename param_type,typename storage_class,storage_type::VEHICLE_TYPE _storage_type>
struct iarchive_impl_helper<std::vector<param_type>,storage_class,_storage_type>
{
    inline iarchive_impl_helper(iarchive_param_deliverer<storage_class,_storage_type>& helper, std::vector<param_type>& param)
    {
        unsigned int size = 0;
        iarchive_impl_helper<unsigned int,storage_class,_storage_type> impl(helper, size);
        for (unsigned int i = 0; i < size; ++i)
        {
            param_type p;
            iarchive_impl_helper<param_type,storage_class,_storage_type> impl2(helper, p);
            param.push_back(p);
        }
    }
};

/* std::string、std::wstring、std::list、std::stack、std::queue、
   std::map、std::set、std::multiset、std::multimap、原生陣列,
   以及 char / unsigned char / wchar_t / float / double /
   int / unsigned int / long / unsigned long / _int64_ / _uint64_ /
   short / unsigned short / bool 的特化,皆為同一套模式的重複,此處從略。
   stack 與 queue 需先倒進暫存容器再還原,以保住原本的順序。 */

/* oarchive_impl_helper 是鏡像版本:
   自訂型別、指標(存位址)、STL 容器(先寫 size 再寫元素)、
   陣列與各基本型別,全部轉交 To_Archive_Helper 處理。 */

四個 archive 外殼:只差一個型別標籤

template<typename storage_class>
class string_iarchive : public basic_iarchive_impl<storage_class,storage_type::_ISTRING_TYPE>
{
public:
    string_iarchive(const storage_class& storage)
        : basic_iarchive_impl<storage_class,storage_type::_ISTRING_TYPE>(storage){}
    ~string_iarchive(){}
};

template<typename storage_class>
class string_oarchive : public basic_oarchive_impl<storage_class,storage_type::_OSTRING_TYPE>
{
public:
    string_oarchive(storage_class& storage)
        : basic_oarchive_impl<storage_class,storage_type::_OSTRING_TYPE>(storage){}
    ~string_oarchive(){}
};

/* wstring_archive / stream_archive / wstream_archive / xml_archive
   結構完全相同,只是把型別標籤換成 _WISTRING_TYPE、_ISTREAM_TYPE、
   _WISTREAM_TYPE、_IXML_TYPE 等。xml 版本另外預留了 tinyxml 的
   引入位置(由 USE_XML_ARCHIVE 巨集控制)。 */

設計上的取捨與待辦

優點是擴充成本極低:要支援新容器,只要再寫一個 iarchive_impl_helper/oarchive_impl_helper 的偏特化;要換後端格式,只要多一個型別標籤與一組 From/To_Archive_Helper 特化,上層的使用方式完全不變。

待改進之處也很清楚:一是前面提到的多餘複製,直接影響吞吐量;二是「指標存位址」雖然避開了記憶體配置的難題,但存下來的位址跨行程毫無意義,實務上應該改成「以物件 id 表達關聯」的做法;三是 _ISTREAM_TYPE/_OSTREAM_TYPE 與 XML 版本仍是空殼,串流與 XML 後端尚未真正可用;四是 unsigned int 存位址在 64 位元環境會截斷,該換成 uintptr_t。

如果你要拿去用,建議先把這四點處理掉,再依自己的容器清單補上特化。也歡迎把新支援的容器回饋回來,讓這套小庫慢慢長大。

Copyright © Linux教程網 All Rights Reserved