1// Copyright 2013 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "cc/resources/shared_bitmap.h"
6
7#include "base/logging.h"
8#include "base/numerics/safe_math.h"
9#include "base/rand_util.h"
10
11namespace cc {
12
13SharedBitmap::SharedBitmap(
14    base::SharedMemory* memory,
15    const SharedBitmapId& id,
16    const base::Callback<void(SharedBitmap* bitmap)>& free_callback)
17    : memory_(memory),
18      pixels_(static_cast<uint8*>(memory_->memory())),
19      id_(id),
20      free_callback_(free_callback) {
21}
22
23SharedBitmap::SharedBitmap(
24    uint8* pixels,
25    const SharedBitmapId& id,
26    const base::Callback<void(SharedBitmap* bitmap)>& free_callback)
27    : memory_(NULL), pixels_(pixels), id_(id), free_callback_(free_callback) {
28}
29
30SharedBitmap::~SharedBitmap() { free_callback_.Run(this); }
31
32// static
33bool SharedBitmap::SizeInBytes(const gfx::Size& size, size_t* size_in_bytes) {
34  if (size.IsEmpty())
35    return false;
36  base::CheckedNumeric<size_t> s = 4;
37  s *= size.width();
38  s *= size.height();
39  if (!s.IsValid())
40    return false;
41  *size_in_bytes = s.ValueOrDie();
42  return true;
43}
44
45// static
46size_t SharedBitmap::CheckedSizeInBytes(const gfx::Size& size) {
47  CHECK(!size.IsEmpty());
48  base::CheckedNumeric<size_t> s = 4;
49  s *= size.width();
50  s *= size.height();
51  return s.ValueOrDie();
52}
53
54// static
55size_t SharedBitmap::UncheckedSizeInBytes(const gfx::Size& size) {
56  DCHECK(VerifySizeInBytes(size));
57  size_t s = 4;
58  s *= size.width();
59  s *= size.height();
60  return s;
61}
62
63// static
64bool SharedBitmap::VerifySizeInBytes(const gfx::Size& size) {
65  if (size.IsEmpty())
66    return false;
67  base::CheckedNumeric<size_t> s = 4;
68  s *= size.width();
69  s *= size.height();
70  return s.IsValid();
71}
72
73// static
74SharedBitmapId SharedBitmap::GenerateId() {
75  SharedBitmapId id;
76  // Needs cryptographically-secure random numbers.
77  base::RandBytes(id.name, sizeof(id.name));
78  return id;
79}
80
81}  // namespace cc
82