summaryrefslogtreecommitdiffstats
path: root/chrome/browser/sync/notifier/base/fastalloc.h
blob: ac0fb4652adfd0c546db61de83bc815ba8ee482a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef CHROME_BROWSER_SYNC_NOTIFIER_BASE_FASTALLOC_H_
#define CHROME_BROWSER_SYNC_NOTIFIER_BASE_FASTALLOC_H_

#include <assert.h>

namespace notifier {

template<class T, size_t Size>
class FastAlloc {
 public:
  FastAlloc() : buffer_(NULL), size_(0) { }
  ~FastAlloc() { freeBuffer(); }
  T* get_buffer(size_t size) {
    if (size_ != 0) {
      // We only allow one call to get_buffer. This makes the logic here
      // simpler, and the user has to worry less about someone else calling
      // get_buffer again on the same FastAlloc object and invalidating the
      // memory they were using.
      assert(false && "get_buffer may one be called once");
      return NULL;
    }

    if (size <= Size) {
      buffer_ = internal_buffer_;
    } else {
      buffer_ = new T[size];
    }

    if (buffer_ != NULL) {
      size_ = size;
    }
    return buffer_;
  }

 private:
  void freeBuffer() {
#if defined(DEBUG)
    memset(buffer_, 0xCC, size_ * sizeof(T));
#endif

    if (buffer_ != NULL && buffer_ != internal_buffer_) {
      delete[] buffer_;
    }
    buffer_ = NULL;
    size_ = 0;
  }

  T* buffer_;
  T internal_buffer_[Size];
  size_t size_;
};

}

#endif  // CHROME_BROWSER_SYNC_NOTIFIER_BASE_FASTALLOC_H_