1 /**************************************************************************
2 *
3 * Copyright 2015 VMware, Inc.
4 * Copyright 2011 Zack Rusin
5 * All Rights Reserved.
6 *
7 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
13 *
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 * THE SOFTWARE.
24 *
25 **************************************************************************/
26
27
28 #include "trace_ostream.hpp"
29
30
31 #include <assert.h>
32 #include <string.h>
33
34 #include <zlib.h>
35
36 #include "os.hpp"
37
38 #include <iostream>
39
40
41 using namespace trace;
42
43
44 class ZLibOutStream : public OutStream {
45 public:
46 ZLibOutStream(gzFile file);
47 virtual ~ZLibOutStream();
48
49 protected:
50 virtual bool write(const void *buffer, size_t length) override;
51 virtual void flush(void) override;
52 private:
53 gzFile m_gzFile;
54 };
55
ZLibOutStream(gzFile file)56 ZLibOutStream::ZLibOutStream(gzFile file)
57 : m_gzFile(file)
58 {
59 }
60
~ZLibOutStream()61 ZLibOutStream::~ZLibOutStream()
62 {
63 if (m_gzFile) {
64 gzclose(m_gzFile);
65 m_gzFile = nullptr;
66 }
67 }
68
write(const void * buffer,size_t length)69 bool ZLibOutStream::write(const void *buffer, size_t length)
70 {
71 return gzwrite(m_gzFile, buffer, unsigned(length)) != -1;
72 }
73
flush(void)74 void ZLibOutStream::flush(void)
75 {
76 gzflush(m_gzFile, Z_SYNC_FLUSH);
77 }
78
79
80 OutStream *
createZLibStream(const char * filename)81 trace::createZLibStream(const char *filename)
82 {
83 gzFile file = gzopen(filename, "wb");
84 if (!file) {
85 return nullptr;
86 }
87
88 // Currently we only use gzip for offline compression, so aim for maximum
89 // compression
90 gzsetparams(file, Z_BEST_COMPRESSION, Z_DEFAULT_STRATEGY);
91
92 return new ZLibOutStream(file);
93 }
94