Belle II Software  release-08-01-10
BufferedReader.cc
1 /**************************************************************************
2  * basf2 (Belle II Analysis Software Framework) *
3  * Author: The Belle II Collaboration *
4  * *
5  * See git log for contributors and copyright holders. *
6  * This file is licensed under LGPL-3.0, see LICENSE.md. *
7  **************************************************************************/
8 #include "daq/slc/system/BufferedReader.h"
9 
10 #include <daq/slc/base/IOException.h>
11 
12 #include <cstring>
13 
14 using namespace Belle2;
15 
16 BufferedReader::BufferedReader()
17  : m_memory(NULL), m_size(0), m_pos(0), m_allocated(false) {}
18 
19 BufferedReader::BufferedReader(const BufferedReader& reader)
20  : m_memory(NULL), m_size(reader.m_size),
21  m_pos(reader.m_pos), m_allocated(reader.m_allocated)
22 {
23  if (m_allocated) {
24  m_memory = new unsigned char [reader.m_size];
25  ::memcpy(m_memory, reader.m_memory, reader.m_size);
26  } else {
27  m_memory = reader.m_memory;
28  }
29  m_size = reader.m_size;
30  m_pos = reader.m_pos;
31 }
32 
33 BufferedReader::BufferedReader(size_t size, unsigned char* memory)
34  : m_memory(memory), m_size(size), m_pos(0), m_allocated(false)
35 {
36  if (memory == NULL) {
37  m_memory = new unsigned char[size];
38  m_allocated = true;
39  }
40 }
41 
42 BufferedReader::~BufferedReader()
43 {
44  if (m_allocated && m_memory != NULL) {
45  delete [] m_memory;
46  }
47 }
48 
49 const BufferedReader& BufferedReader::operator=(const BufferedReader& reader)
50 {
51  if (m_allocated) {
52  delete [] m_memory;
53  }
54  m_allocated = reader.m_allocated;
55  if (m_allocated) {
56  m_memory = new unsigned char [reader.m_size];
57  ::memcpy(m_memory, reader.m_memory, reader.m_size);
58  } else {
59  m_memory = reader.m_memory;
60  }
61  m_size = reader.m_size;
62  m_pos = reader.m_pos;
63  return *this;
64 }
65 
66 void BufferedReader::copy(const void* buffer, size_t count)
67 {
68  if (count < m_size) {
69  memcpy(m_memory, buffer, count);
70  m_pos = 0;
71  } else {
72  throw (IOException("Out of buffer range: %d > %d",
73  (int)count, (int)m_size));
74  }
75 }
76 
77 size_t BufferedReader::read(void* buf, const size_t count)
78 {
79  if (m_pos + count > size()) {
80  throw (IOException("Out of buffer range: %d + %d > %d",
81  (int)m_pos, (int)count, (int)m_size));
82  }
83  memcpy(buf, (m_memory + m_pos), count);
84  m_pos += count;
85  return count;
86 }
87 
Abstract base class for different kinds of events.