ByteString.h

Go to the documentation of this file.
00001 
00022 #ifndef HYPERTABLE_BYTESTRING_H
00023 #define HYPERTABLE_BYTESTRING_H
00024 
00025 #include <iostream>
00026 
00027 #include <boost/shared_array.hpp>
00028 #include <boost/shared_ptr.hpp>
00029 
00030 #include "DynamicBuffer.h"
00031 #include "Serialization.h"
00032 
00033 namespace Hypertable {
00034 
00035   class ByteString {
00036   public:
00037     ByteString() : ptr(0) { return; }
00038     ByteString(const uint8_t *buf) : ptr(buf) { return; }
00039 
00040     size_t length() const {
00041       if (ptr == 0)
00042         return 1;
00043       const uint8_t *tmp_ptr = ptr;
00044       uint32_t len = Serialization::decode_vi32(&tmp_ptr);
00045       return (tmp_ptr - ptr) + len;
00046     }
00047 
00048     uint8_t *next() {
00049       uint8_t *rptr = (uint8_t *)ptr;
00050       uint32_t len = Serialization::decode_vi32(&ptr);
00051       ptr += len;
00052       return rptr;
00053     }
00054 
00055     size_t decode_length(const uint8_t **dptr) const {
00056       *dptr = ptr;
00057       return Serialization::decode_vi32(dptr);
00058     }
00059 
00060     size_t write(uint8_t *dst) const {
00061       size_t len = length();
00062       if (ptr == 0)
00063         Serialization::encode_vi32(&dst, 0);
00064       else
00065         memcpy(dst, ptr, len);
00066       return len;
00067     }
00068 
00069     const char *str() const {
00070       const uint8_t *rptr = ptr;
00071       Serialization::decode_vi32(&rptr);
00072       return (const char *)rptr;
00073     }
00074 
00075     operator bool () const {
00076       return ptr != 0;
00077     }
00078 
00079     const uint8_t *ptr;
00080   };
00081 
00082   inline void append_as_byte_string(DynamicBuffer &dst_buf, const char *str) {
00083     size_t value_len = strlen(str);
00084     dst_buf.ensure(7 + value_len);
00085     Serialization::encode_vi32(&dst_buf.ptr, value_len);
00086     if (value_len > 0) {
00087       memcpy(dst_buf.ptr, str, value_len);
00088       dst_buf.ptr += value_len;
00089       *dst_buf.ptr = 0;
00090     }
00091   }
00092 
00093   inline void
00094   append_as_byte_string(DynamicBuffer &dst_buf, const void *value,
00095                         uint32_t value_len) {
00096     dst_buf.ensure(7 + value_len);
00097     Serialization::encode_vi32(&dst_buf.ptr, value_len);
00098     if (value_len > 0) {
00099       memcpy(dst_buf.ptr, value, value_len);
00100       dst_buf.ptr += value_len;
00101       *dst_buf.ptr = 0;
00102     }
00103   }
00104 }
00105 
00106 
00107 #endif // HYPERTABLE_BYTESTRING_H
00108