CernVM-FS  2.12.0
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
sink_mem.cc
Go to the documentation of this file.
1 
5 #include <cassert>
6 #include <cstring>
7 #include <string>
8 
9 #include "util/smalloc.h"
10 #include "util/string.h"
11 
12 #include "sink_mem.h"
13 
14 namespace cvmfs {
15 
16 MemSink::MemSink(size_t size) : Sink(true), size_(size),
17  pos_(0), max_size_(kMaxMemSize) {
18  data_ = static_cast<unsigned char *>(smalloc(size));
19 }
20 
30 int64_t MemSink::Write(const void *buf, uint64_t sz) {
31  if (pos_ + sz > size_) {
32  if (is_owner_) {
33  size_t new_size = pos_ + sz < size_ * 2 ? size_ * 2 : pos_ + sz + 1;
34  data_ = static_cast<unsigned char *>(srealloc(data_, new_size));
35  size_ = new_size;
36  } else {
37  return -ENOSPC;
38  }
39  }
40 
41  memcpy(data_ + pos_, buf, sz);
42  pos_ += sz;
43  return static_cast<int64_t>(sz);
44 }
45 
53  if (is_owner_) {
54  free(data_);
55  data_ = NULL;
56  size_ = 0;
57  }
58 
59  pos_ = 0;
60 
61  return 0;
62 }
63 
68  return (size_ == 0 && pos_ == 0 && data_ == NULL) ||
69  (size_ > 0 && pos_ >= 0 && data_ != NULL);
70 }
71 
88 bool MemSink::Reserve(size_t size) {
89  if (size <= size_) {
90  pos_ = 0;
91  return true;
92  }
93  if (!is_owner_ || size > max_size_) {
94  return false;
95  }
96 
97  FreeData();
98 
99  size_ = size;
100  pos_ = 0;
101  if (size == 0) {
102  data_ = NULL;
103  } else {
104  data_ = static_cast<unsigned char *>(smalloc(size));
105  }
106  return true;
107 }
108 
112 std::string MemSink::Describe() {
113  std::string result = "Memory sink with ";
114  result += "size: " + StringifyUint(size_);
115  result += " - current pos: " + StringifyUint(pos_);
116  return result;
117 }
118 
123 void MemSink::Adopt(size_t size, size_t pos, unsigned char *data,
124  bool is_owner) {
125  assert(size >= pos);
126 
127  FreeData();
128 
129  is_owner_ = is_owner;
130  size_ = size;
131  pos_ = pos;
132  data_ = data;
133 }
134 
135 } // namespace cvmfs
virtual std::string Describe()
Definition: sink_mem.cc:112
size_t pos_
Definition: sink_mem.h:137
unsigned char * data()
Definition: sink_mem.h:122
virtual bool Reserve(size_t size)
Definition: sink_mem.cc:88
virtual bool IsValid()
Definition: sink_mem.cc:67
assert((mem||(size==0))&&"Out Of Memory")
std::string StringifyUint(const uint64_t value)
Definition: string.cc:84
size_t size()
Definition: sink_mem.h:120
const size_t max_size_
Definition: sink_mem.h:139
virtual int64_t Write(const void *buf, uint64_t sz)
Definition: sink_mem.cc:30
void Adopt(size_t size, size_t pos, unsigned char *data, bool is_owner=true)
Definition: sink_mem.cc:123
size_t size_
Definition: sink_mem.h:136
unsigned char * data_
Definition: sink_mem.h:138
void FreeData()
Definition: sink_mem.h:130
size_t pos()
Definition: sink_mem.h:121
virtual int Reset()
Definition: sink_mem.cc:52
static void size_t size
Definition: smalloc.h:54
bool is_owner_
Definition: sink.h:99