summaryrefslogtreecommitdiffstats
path: root/base/ref_counted_memory.h
blob: fe7427e5ad093476da01b2c253922c95afa1cd11 (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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// Copyright (c) 2011 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 BASE_REF_COUNTED_MEMORY_H_
#define BASE_REF_COUNTED_MEMORY_H_
#pragma once

#include <vector>

#include "base/ref_counted.h"

// TODO(erg): The contents of this file should be in a namespace. This would
// require touching >100 files in chrome/ though.

// A generic interface to memory. This object is reference counted because one
// of its two subclasses own the data they carry, and we need to have
// heterogeneous containers of these two types of memory.
class RefCountedMemory : public base::RefCountedThreadSafe<RefCountedMemory> {
 public:
  // Retrieves a pointer to the beginning of the data we point to. If the data
  // is empty, this will return NULL.
  virtual const unsigned char* front() const = 0;

  // Size of the memory pointed to.
  virtual size_t size() const = 0;

 protected:
  friend class base::RefCountedThreadSafe<RefCountedMemory>;
  RefCountedMemory();
  virtual ~RefCountedMemory();
};

// An implementation of RefCountedMemory, where the ref counting does not
// matter.
class RefCountedStaticMemory : public RefCountedMemory {
 public:
  RefCountedStaticMemory()
      : data_(NULL), length_(0) {}
  RefCountedStaticMemory(const unsigned char* data, size_t length)
      : data_(data), length_(length) {}

  // Overriden from RefCountedMemory:
  virtual const unsigned char* front() const;
  virtual size_t size() const;

 private:
  const unsigned char* data_;
  size_t length_;

  DISALLOW_COPY_AND_ASSIGN(RefCountedStaticMemory);
};

// An implementation of RefCountedMemory, where we own our the data in a
// vector.
class RefCountedBytes : public RefCountedMemory {
 public:
  RefCountedBytes();

  // Constructs a RefCountedBytes object by _copying_ from |initializer|.
  RefCountedBytes(const std::vector<unsigned char>& initializer);

  // Constructs a RefCountedBytes object by performing a swap. (To non
  // destructively build a RefCountedBytes, use the constructor that takes a
  // vector.)
  static RefCountedBytes* TakeVector(std::vector<unsigned char>* to_destroy);

  // Overriden from RefCountedMemory:
  virtual const unsigned char* front() const;
  virtual size_t size() const;

  std::vector<unsigned char> data;

 protected:
  friend class base::RefCountedThreadSafe<RefCountedBytes>;
  virtual ~RefCountedBytes();

 private:
  DISALLOW_COPY_AND_ASSIGN(RefCountedBytes);
};

#endif  // BASE_REF_COUNTED_MEMORY_H_