1 /****
2 DIAMOND protein aligner
3 Copyright (C) 2013-2018 Benjamin Buchfink <buchfink@gmail.com>
4
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 ****/
18
19 #include <algorithm>
20 #include <string.h>
21 #include "serializer.h"
22
Serializer(StreamEntity * buffer,int flags)23 Serializer::Serializer(StreamEntity *buffer, int flags) :
24 buffer_(buffer),
25 varint_(flags & VARINT)
26 {
27 reset_buffer();
28 }
29
flush()30 void Serializer::flush()
31 {
32 buffer_->flush(next_ - begin_);
33 }
34
close()35 void Serializer::close()
36 {
37 flush();
38 buffer_->close();
39 }
40
seek(size_t pos)41 void Serializer::seek(size_t pos)
42 {
43 flush();
44 buffer_->seek(pos);
45 reset_buffer();
46 }
47
rewind()48 void Serializer::rewind()
49 {
50 flush();
51 buffer_->rewind();
52 reset_buffer();
53 }
54
tell()55 size_t Serializer::tell()
56 {
57 flush();
58 reset_buffer();
59 return buffer_->tell();
60 }
61
file_name() const62 string Serializer::file_name() const
63 {
64 return buffer_->file_name();
65 }
66
file()67 FILE* Serializer::file()
68 {
69 return buffer_->file();
70 }
71
~Serializer()72 Serializer::~Serializer()
73 {
74 delete buffer_;
75 }
76
reset_buffer()77 void Serializer::reset_buffer()
78 {
79 pair<char*, char*> buf = buffer_->write_buffer();
80 begin_ = next_ = buf.first;
81 end_ = buf.second;
82 }
83
write_raw(const char * ptr,size_t count)84 void Serializer::write_raw(const char *ptr, size_t count)
85 {
86 do {
87 size_t n = std::min(avail(), count);
88 memcpy(next_, ptr, n);
89 next_ += n;
90 ptr += n;
91 count -= n;
92 if (avail() == 0) {
93 flush();
94 reset_buffer();
95 }
96 } while (count > 0);
97 }
98
set(int flag)99 void Serializer::set(int flag)
100 {
101 switch (flag) {
102 case VARINT:
103 varint_ = true;
104 default:
105 ;
106 }
107 }
108
unset(int flag)109 void Serializer::unset(int flag)
110 {
111 switch (flag) {
112 case VARINT:
113 varint_ = false;
114 default:
115 ;
116 }
117 }
118
consume(const char * ptr,size_t n)119 void Serializer::consume(const char *ptr, size_t n) {
120 write_raw(ptr, n);
121 }
122
finalize()123 void Serializer::finalize() {
124 close();
125 }