Drizzled Public API Documentation

global_buffer.h
00001 /* -*- mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; -*-
00002  *  vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
00003  *
00004  *  Copyright (C) 2010 Andrew Hutchings
00005  *
00006  *  This program is free software; you can redistribute it and/or modify
00007  *  it under the terms of the GNU General Public License as published by
00008  *  the Free Software Foundation; version 2 of the License.
00009  *
00010  *  This program is distributed in the hope that it will be useful,
00011  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
00012  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00013  *  GNU General Public License for more details.
00014  *
00015  *  You should have received a copy of the GNU General Public License
00016  *  along with this program; if not, write to the Free Software
00017  *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
00018  */
00019 
00020 #pragma once
00021 
00022 #include <drizzled/atomics.h>
00023 
00024 namespace drizzled
00025 {
00026 template <class T>
00027 class global_buffer_constraint
00028 {
00029 public:
00030   global_buffer_constraint(T max)
00031   {
00032     setMaxSize(max); 
00033   }
00034 
00035   T getMaxSize() const { return max_size; }
00036   void setMaxSize(T new_size) 
00037   {
00038     if (new_size == 0) new_size = std::numeric_limits<T>::max(); 
00039     max_size= new_size;
00040   }
00041 
00042   bool add(T addition)
00043   {
00044     if (current_size.add_and_fetch(addition) > max_size)
00045     {
00046       current_size.add_and_fetch(T(0) - addition);
00047       return false;
00048     }
00049     return true;
00050   }
00051 
00052   bool sub(T subtract)
00053   {
00054     if (current_size < subtract)
00055       return false;
00056     else
00057       current_size.add_and_fetch(T(0) - subtract);
00058 
00059     return true;
00060   }
00061 
00062 private:
00063   atomic<T> current_size;
00064   T max_size;
00065 };
00066 
00067 }