source: proiecte/swift/trunk/lib/hoard-371/src/heaplayers/ansiwrapper.h @ 176

Last change on this file since 176 was 176, checked in by (none), 14 years ago
  • imported repo from "guagal"
File size: 1.9 KB
Line 
1/* -*- C++ -*- */
2
3#ifndef _ANSIWRAPPER_H_
4#define _ANSIWRAPPER_H_
5
6#include <stdlib.h>
7#include <string.h>
8
9/*
10 * @class ANSIWrapper
11 * @brief Provide ANSI C behavior for malloc & free.
12 *
13 * Implements all prescribed ANSI behavior, including zero-sized
14 * requests & aligned request sizes to a double word (or long word).
15 */
16
17
18namespace HL {
19
20template <class SuperHeap>
21class ANSIWrapper : public SuperHeap {
22public:
23 
24  ANSIWrapper (void)
25    {}
26
27  inline void * malloc (size_t sz) {
28    if (sz < 2 * sizeof(size_t)) {
29      // Make sure it's at least big enough to hold two pointers (and
30      // conveniently enough, that's at least the size of a double, as
31      // required by ANSI).
32      sz = 2 * sizeof(size_t);
33    }
34    sz = align(sz);
35    void * ptr = SuperHeap::malloc (sz);
36    return ptr;
37  }
38 
39  inline void free (void * ptr) {
40    if (ptr != 0) {
41      SuperHeap::free (ptr);
42    }
43  }
44
45  inline void * calloc (const size_t s1, const size_t s2) {
46    void * ptr = malloc (s1 * s2);
47    if (ptr) {
48      memset (ptr, 0, s1 * s2);
49    }
50    return ptr;
51  }
52 
53  inline void * realloc (void * ptr, const size_t sz) {
54    if (ptr == 0) {
55      return malloc (sz);
56    }
57    if (sz == 0) {
58      free (ptr);
59      return 0;
60    }
61
62    size_t objSize = getSize (ptr);
63    if (objSize == sz) {
64      return ptr;
65    }
66
67    // Allocate a new block of size sz.
68    void * buf = malloc (sz);
69
70    // Copy the contents of the original object
71    // up to the size of the new block.
72
73    size_t minSize = (objSize < sz) ? objSize : sz;
74    if (buf) {
75      memcpy (buf, ptr, minSize);
76    }
77
78    // Free the old block.
79    free (ptr);
80    return buf;
81  }
82 
83  inline size_t getSize (void * ptr) {
84    if (ptr) {
85      return SuperHeap::getSize (ptr);
86    } else {
87      return 0;
88    }
89  }
90
91private:
92  inline static size_t align (size_t sz) {
93    return (sz + (sizeof(double) - 1)) & ~(sizeof(double) - 1);
94  }
95};
96
97}
98
99#endif
Note: See TracBrowser for help on using the repository browser.