Back to index

nordugrid-arc-nox  1.1.0~rc6
ByteArray.cpp
Go to the documentation of this file.
00001 // -*- indent-tabs-mode: nil -*-
00002 
00003 #ifdef HAVE_CONFIG_H
00004 #include <config.h>
00005 #endif
00006 
00007 #include <cstdlib>
00008 #include <cstring>
00009 #include <sstream>
00010 #include <iomanip>
00011 #include <iostream>
00012 
00013 #include "ByteArray.h"
00014 
00015 namespace Arc {
00016 
00017   void ByteArray::init(size_t length) {
00018     size_t new_length = length + BYTE_ARRAY_PAD_SIZE;
00019     data_ = (char*)calloc(new_length, sizeof(char));
00020     if (data_ == NULL)
00021       throw MemoryAllocationException();
00022     size_ = 0;
00023     length_ = new_length;
00024   }
00025 
00026   ByteArray::ByteArray(size_t length) {
00027     init(length);
00028   }
00029 
00030   ByteArray::ByteArray(void *buf, size_t s) {
00031     init(s);
00032     append(buf, s);
00033   }
00034 
00035   ByteArray::~ByteArray() {
00036     if (data_ != NULL)
00037       free(data_);
00038     size_ = 0;
00039     length_ = 0;
00040   }
00041 
00042   void ByteArray::resize(size_t new_size) {
00043     size_t new_length = new_size + BYTE_ARRAY_PAD_SIZE;
00044     char *new_data = (char*)calloc(new_length, sizeof(char));
00045     if (new_data == NULL)
00046       throw MemoryAllocationException();
00047     // memmove?
00048     memcpy(new_data, data_, size_);
00049     free(data_);
00050     data_ = new_data;
00051     length_ = new_length;
00052   }
00053 
00054   void ByteArray::append(const void *buf, size_t s) {
00055     unsigned int new_size = size_ + s;
00056     if (new_size > length_)
00057       resize(new_size);
00058     memcpy(data_ + size_, buf, s);
00059     size_ = new_size;
00060   }
00061 
00062   void ByteArray::append(const std::string& str) {
00063     append(str.c_str(), str.size() + 1);
00064   }
00065 
00066   void ByteArray::append(ByteArray& buf) {
00067     size_t s = buf.size();
00068     append(&s, sizeof(size_t));
00069     append(buf.data(), buf.size());
00070   }
00071 
00072   void ByteArray::clean(void) {
00073     memset(data_, 0, length_);
00074     size_ = 0;
00075   }
00076 
00077   ByteArray::operator std::string(void) const {
00078     std::ostringstream o;
00079     for (int i = 0; i < length_; i++) {
00080       o << std::hex << std::setiosflags(std::ios_base::showbase);
00081       o << (int)data_[i] << " ";
00082     }
00083     return o.str();
00084   }
00085 
00086 } // namespace Arc