Extend basic support for serializing simple data types.
[cumulus.git] / store.h
1 /* LBS: An LFS-inspired filesystem backup system
2  * Copyright (C) 2006  Michael Vrable
3  *
4  * Backup data is stored in a collection of objects, which are grouped together
5  * into segments for storage purposes.  This file provides interfaces for
6  * reading and writing objects and segments. */
7
8 #include <stdint.h>
9
10 #include <exception>
11 #include <map>
12 #include <string>
13 #include <sstream>
14
15 typedef std::map<std::string, std::string> dictionary;
16
17 class IOException : public std::exception {
18 private:
19     std::string error;
20 public:
21     explicit IOException(const std::string &err) { error = err; }
22     virtual ~IOException() throw () { }
23     std::string getError() const { return error; }
24 };
25
26 class OutputStream {
27 public:
28     virtual ~OutputStream() { }
29     virtual void write(const void *data, size_t len) = 0;
30
31     /* Convenience functions for writing other data types.  Values are always
32      * written out in little-endian order. */
33     void write_u8(uint8_t val);
34     void write_u16(uint16_t val);
35     void write_u32(uint32_t val);
36     void write_u64(uint64_t val);
37
38     void write_s32(int32_t val) { write_u32((uint32_t)val); }
39     void write_s64(int64_t val) { write_u64((uint64_t)val); }
40
41     void write_varint(uint64_t val);
42
43     void write_string(const std::string &s);
44     void write_dictionary(const dictionary &d);
45 };
46
47 class StringOutputStream : public OutputStream {
48 private:
49     std::stringstream buf;
50 public:
51     StringOutputStream();
52
53     virtual void write(const void *data, size_t len);
54     std::string contents() const { return buf.str(); }
55 };
56
57 class FileOutputStream : public OutputStream {
58 private:
59     FILE *f;
60 public:
61     explicit FileOutputStream(FILE *file);
62     virtual ~FileOutputStream();
63
64     virtual void write(const void *data, size_t len);
65 };
66
67 std::string encode_u16(uint16_t val);
68 std::string encode_u32(uint32_t val);
69 std::string encode_u64(uint64_t val);