Drizzled Public API Documentation

data_ref.h
00001 /* Drizzle
00002  * Copyright (C) 2011 Olaf van der Spek
00003  * 
00004  * This program is free software: you can redistribute it and/or modify
00005  * it under the terms of the GNU General Public License as published by
00006  * the Free Software Foundation, either version 2 of the License, or
00007  * (at your option) any later version.
00008  * 
00009  * This program is distributed in the hope that it will be useful,
00010  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00011  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
00012  * GNU General Public License for more details.
00013  * 
00014  * You should have received a copy of the GNU General Public License
00015  * along with this program. If not, see <http://www.gnu.org/licenses/>.
00016  */
00017 
00018 #pragma once
00019 
00020 #include <cstddef>
00021 #include <cstring>
00022 #include <ostream>
00023 #include <string>
00024 
00025 template <class T>
00026 class data_ref_basic
00027 {
00028 public:
00029   data_ref_basic()
00030   {
00031     clear();
00032   }
00033 
00034   template <class U>
00035   data_ref_basic(const U& c)
00036   {
00037     assign(&*c.begin(), &*c.end());
00038   }
00039 
00040   data_ref_basic(const void* b, const void* e)
00041   {
00042     assign(b, e);
00043   }
00044 
00045   data_ref_basic(const void* b, size_t sz)
00046   {
00047     assign(b, sz);
00048   }
00049 
00050   explicit data_ref_basic(const char* b)
00051   {
00052     assign(b, strlen(b));
00053   }
00054 
00055   void clear()
00056   {
00057     begin_ = end_ = reinterpret_cast<T>("");
00058   }
00059 
00060   void assign(const void* b, const void* e)
00061   {
00062     begin_ = reinterpret_cast<T>(b);
00063     end_ = reinterpret_cast<T>(e);
00064   }
00065 
00066   void assign(const void* b, size_t sz)
00067   {
00068     begin_ = reinterpret_cast<T>(b);
00069     end_ = begin_ + sz;
00070   }
00071 
00072   T begin() const
00073   {
00074     return begin_;
00075   }
00076 
00077   T end() const
00078   {
00079     return end_;
00080   }
00081 
00082   T data() const
00083   {
00084     return begin();
00085   }
00086 
00087   size_t size() const
00088   {
00089     return end() - begin();
00090   }
00091 
00092   bool empty() const
00093   {
00094     return begin() == end();
00095   }
00096 
00097   operator std::string() const
00098   {
00099     return to_string(*this);
00100   }
00101 private:
00102   T begin_;
00103   T end_;
00104 };
00105 
00106 typedef data_ref_basic<const unsigned char*> data_ref;
00107 typedef data_ref_basic<const char*> str_ref;
00108 
00109 inline std::ostream& operator<<(std::ostream& os, str_ref v)
00110 {
00111   return os.write(v.data(), v.size());
00112 }
00113 
00114 inline std::string to_string(str_ref v)
00115 {
00116   return std::string(v.data(), v.size());
00117 }