muduo GzipFile

文章目录
  1. 1. 参考资料

对 zlib 进行了简单封装,主要欣赏代码风格和规范。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#pragma once

#include "muduo/base/StringPiece.h"
#include "muduo/base/noncopyable.h"
#include <zlib.h>

namespace muduo
{

class GzipFile : noncopyable
{
public:
GzipFile(GzipFile&& rhs) noexcept // move
: file_(rhs.file_)
{
rhs.file_ = NULL;
}

~GzipFile()
{
if (file_)
{
::gzclose(file_);
}
}

GzipFile& operator=(GzipFile&& rhs) noexcept
{
swap(rhs);
return *this;
}

bool valid() const { return file_ != NULL; }
void swap(GzipFile& rhs) { std::swap(file_, rhs.file_); }
#if ZLIB_VERNUM >= 0x1240
bool setBuffer(int size) { return ::gzbuffer(file_, size) == 0; }
#endif

// return the number of uncompressed bytes actually read, 0 for eof, -1 for error
int read(void* buf, int len) { return ::gzread(file_, buf, len); }

// return the number of uncompressed bytes actually written
int write(StringPiece buf) { return ::gzwrite(file_, buf.data(), buf.size()); }

// number of uncompressed bytes
off_t tell() const { return ::gztell(file_); }

#if ZLIB_VERNUM >= 0x1240
// number of compressed bytes
off_t offset() const { return ::gzoffset(file_); }
#endif

// int flush(int f) { return ::gzflush(file_, f); }

static GzipFile openForRead(StringArg filename)
{
return GzipFile(::gzopen(filename.c_str(), "rbe"));
}

static GzipFile openForAppend(StringArg filename)
{
return GzipFile(::gzopen(filename.c_str(), "abe"));
}

static GzipFile openForWriteExclusive(StringArg filename)
{
return GzipFile(::gzopen(filename.c_str(), "wbxe"));
}

static GzipFile openForWriteTruncate(StringArg filename)
{
return GzipFile(::gzopen(filename.c_str(), "wbe"));
}

private:
explicit GzipFile(gzFile file)
: file_(file)
{
}

gzFile file_;
};

} // namespace muduo

参考资料