1
2/*
3 * Copyright 2011 Google Inc.
4 *
5 * Use of this source code is governed by a BSD-style license that can be
6 * found in the LICENSE file.
7 */
8#include "SkTypes.h"
9#include <stdio.h>
10#include <stdlib.h>
11
12#define SK_DEBUGFAILF(fmt, ...) \
13    SkASSERT((SkDebugf(fmt"\n", __VA_ARGS__), false))
14
15static inline void sk_out_of_memory(size_t size) {
16    SK_DEBUGFAILF("sk_out_of_memory (asked for " SK_SIZE_T_SPECIFIER " bytes)",
17                  size);
18    abort();
19}
20
21static inline void* throw_on_failure(size_t size, void* p) {
22    if (size > 0 && p == NULL) {
23        // If we've got a NULL here, the only reason we should have failed is running out of RAM.
24        sk_out_of_memory(size);
25    }
26    return p;
27}
28
29void sk_throw() {
30    SkDEBUGFAIL("sk_throw");
31    abort();
32}
33
34void sk_out_of_memory(void) {
35    SkDEBUGFAIL("sk_out_of_memory");
36    abort();
37}
38
39void* sk_malloc_throw(size_t size) {
40    return sk_malloc_flags(size, SK_MALLOC_THROW);
41}
42
43void* sk_realloc_throw(void* addr, size_t size) {
44    return throw_on_failure(size, realloc(addr, size));
45}
46
47void sk_free(void* p) {
48    if (p) {
49        free(p);
50    }
51}
52
53void* sk_malloc_flags(size_t size, unsigned flags) {
54    void* p = malloc(size);
55    if (flags & SK_MALLOC_THROW) {
56        return throw_on_failure(size, p);
57    } else {
58        return p;
59    }
60}
61
62void* sk_calloc(size_t size) {
63    return calloc(size, 1);
64}
65
66void* sk_calloc_throw(size_t size) {
67    return throw_on_failure(size, sk_calloc(size));
68}
69