blob: 8e51d1475cebc33a0dac2abc8073a3caa29076f0 [file] [log] [blame]
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001// Copyright 2006-2008 Google Inc. All Rights Reserved.
2// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28#ifndef V8_UTILS_H_
29#define V8_UTILS_H_
30
31namespace v8 { namespace internal {
32
33// ----------------------------------------------------------------------------
34// General helper functions
35
36// Returns true iff x is a power of 2. Does not work for zero.
37template <typename T>
38static inline bool IsPowerOf2(T x) {
39 return (x & (x - 1)) == 0;
40}
41
42
43// Returns smallest power of 2 greater or equal to x (from Hacker's Delight).
44int32_t NextPowerOf2(uint32_t x);
45
46
47// The C++ standard leaves the semantics of '>>'
48// undefined for negative signed operands. Most
49// implementations do the right thing, though.
50static inline int ArithmeticShiftRight(int x, int s) {
51 return x >> s;
52}
53
54
55// Compute the 0-relative offset of some absolute value x of type T.
56// This allows conversion of Addresses and integral types into 0-relative
57// int offsets.
58template <typename T>
59static inline int OffsetFrom(T x) {
60 return x - static_cast<T>(0);
61}
62
63
64// Compute the absolute value of type T for some 0-relative offset x.
65// This allows conversion of 0-relative int offsets into Addresses
66// and integral types.
67template <typename T>
68static inline T AddressFrom(int x) {
69 return static_cast<T>(0) + x;
70}
71
72
73// Return the largest multiple of m which is <= x.
74template <typename T>
75static inline T RoundDown(T x, int m) {
76 ASSERT(IsPowerOf2(m));
77 return AddressFrom<T>(OffsetFrom(x) & -m);
78}
79
80
81// Return the smallest multiple of m which is >= x.
82template <typename T>
83static inline T RoundUp(T x, int m) {
84 return RoundDown(x + m - 1, m);
85}
86
87
88template <typename T>
89static inline bool IsAligned(T value, T alignment) {
90 ASSERT(IsPowerOf2(alignment));
91 return (value & (alignment - 1)) == 0;
92}
93
94
95// Returns true if (addr + offset) is aligned.
96static inline bool IsAddressAligned(Address addr, int alignment, int offset) {
97 int offs = OffsetFrom(addr + offset);
98 return IsAligned(offs, alignment);
99}
100
101
102// Returns the maximum of the two parameters.
103template <typename T>
104static T Max(T a, T b) {
105 return a < b ? b : a;
106}
107
108
109// Returns the minimum of the two parameters.
110template <typename T>
111static T Min(T a, T b) {
112 return a < b ? a : b;
113}
114
115
116// ----------------------------------------------------------------------------
117// BitField is a help template for encoding and decode bitfield with unsigned
118// content.
119template<class T, int shift, int size>
120class BitField {
121 public:
122 // Tells whether the provided value fits into the bit field.
123 static bool is_valid(T value) {
124 return (static_cast<uint32_t>(value) & ~((1U << (size)) - 1)) == 0;
125 }
126
127 // Returns a uint32_t mask of bit field.
128 static uint32_t mask() {
129 return (1U << (size + shift)) - (1U << shift);
130 }
131
132 // Returns a uint32_t with the bit field value encoded.
133 static uint32_t encode(T value) {
134 ASSERT(is_valid(value));
135 return static_cast<uint32_t>(value) << shift;
136 }
137
138 // Extracts the bit field from the value.
139 static T decode(uint32_t value) {
140 return static_cast<T>((value >> shift) & ((1U << (size)) - 1));
141 }
142};
143
144
145// ----------------------------------------------------------------------------
146// Support for compressed, machine-independent encoding
147// and decoding of integer values of arbitrary size.
148
149// Encoding and decoding from/to a buffer at position p;
150// the result is the position after the encoded integer.
151// Small signed integers in the range -64 <= x && x < 64
152// are encoded in 1 byte; larger values are encoded in 2
153// or more bytes. At most sizeof(int) + 1 bytes are used
154// in the worst case.
155byte* EncodeInt(byte* p, int x);
156byte* DecodeInt(byte* p, int* x);
157
158
159// Encoding and decoding from/to a buffer at position p - 1
160// moving backward; the result is the position of the last
161// byte written. These routines are useful to read/write
162// into a buffer starting at the end of the buffer.
163byte* EncodeUnsignedIntBackward(byte* p, unsigned int x);
164
165// The decoding function is inlined since its performance is
166// important to mark-sweep garbage collection.
167inline byte* DecodeUnsignedIntBackward(byte* p, unsigned int* x) {
168 byte b = *--p;
169 if (b >= 128) {
170 *x = static_cast<unsigned int>(b) - 128;
171 return p;
172 }
173 unsigned int r = static_cast<unsigned int>(b);
174 unsigned int s = 7;
175 b = *--p;
176 while (b < 128) {
177 r |= static_cast<unsigned int>(b) << s;
178 s += 7;
179 b = *--p;
180 }
181 // b >= 128
182 *x = r | ((static_cast<unsigned int>(b) - 128) << s);
183 return p;
184}
185
186
187// ----------------------------------------------------------------------------
188// I/O support.
189
190// Our version of printf(). Avoids compilation errors that we get
191// with standard printf when attempting to print pointers, etc.
192// (the errors are due to the extra compilation flags, which we
193// want elsewhere).
194void PrintF(const char* format, ...);
195
196// Our version of fflush.
197void Flush();
198
199
200// Read a line of characters after printing the prompt to stdout. The resulting
201// char* needs to be disposed off with DeleteArray by the caller.
202char* ReadLine(const char* prompt);
203
204
205// Read and return the raw chars in a file. the size of the buffer is returned
206// in size.
207// The returned buffer is not 0-terminated. It must be freed by the caller.
208char* ReadChars(const char* filename, int* size, bool verbose = true);
209
210
211// Write size chars from str to the file given by filename.
212// The file is overwritten. Returns the number of chars written.
213int WriteChars(const char* filename,
214 const char* str,
215 int size,
216 bool verbose = true);
217
218
219// Write the C code
220// const char* <varname> = "<str>";
221// const int <varname>_len = <len>;
222// to the file given by filename. Only the first len chars are written.
223int WriteAsCFile(const char* filename, const char* varname,
224 const char* str, int size, bool verbose = true);
225
226
227// ----------------------------------------------------------------------------
228// Miscellaneous
229
230// A static resource holds a static instance that can be reserved in
231// a local scope using an instance of Access. Attempts to re-reserve
232// the instance will cause an error.
233template <typename T>
234class StaticResource {
235 public:
236 StaticResource() : is_reserved_(false) {}
237
238 private:
239 template <typename S> friend class Access;
240 T instance_;
241 bool is_reserved_;
242};
243
244
245// Locally scoped access to a static resource.
246template <typename T>
247class Access {
248 public:
249 explicit Access(StaticResource<T>* resource)
250 : resource_(resource)
251 , instance_(&resource->instance_) {
252 ASSERT(!resource->is_reserved_);
253 resource->is_reserved_ = true;
254 }
255
256 ~Access() {
257 resource_->is_reserved_ = false;
258 resource_ = NULL;
259 instance_ = NULL;
260 }
261
262 T* value() { return instance_; }
263 T* operator -> () { return instance_; }
264
265 private:
266 StaticResource<T>* resource_;
267 T* instance_;
268};
269
270
271template <typename T>
272class Vector {
273 public:
274 Vector(T* data, int length) : start_(data), length_(length) {
275 ASSERT(length == 0 || (length > 0 && data != NULL));
276 }
277
278 // Returns the length of the vector.
279 int length() const { return length_; }
280
281 // Returns whether or not the vector is empty.
282 bool is_empty() const { return length_ == 0; }
283
284 // Returns the pointer to the start of the data in the vector.
285 T* start() const { return start_; }
286
287 // Access individual vector elements - checks bounds in debug mode.
288 T& operator[](int index) const {
289 ASSERT(0 <= index && index < length_);
290 return start_[index];
291 }
292
293 // Returns a clone of this vector with a new backing store.
294 Vector<T> Clone() const {
295 T* result = NewArray<T>(length_);
296 for (int i = 0; i < length_; i++) result[i] = start_[i];
297 return Vector<T>(result, length_);
298 }
299
300 // Releases the array underlying this vector. Once disposed the
301 // vector is empty.
302 void Dispose() {
303 DeleteArray(start_);
304 start_ = NULL;
305 length_ = 0;
306 }
307
308 // Factory method for creating empty vectors.
309 static Vector<T> empty() { return Vector<T>(NULL, 0); }
310
311 private:
312 T* start_;
313 int length_;
314};
315
316
317inline Vector<const char> CStrVector(const char* data) {
318 return Vector<const char>(data, strlen(data));
319}
320
321inline Vector<char> MutableCStrVector(char* data) {
322 return Vector<char>(data, strlen(data));
323}
324
325template <typename T>
326inline Vector< Handle<Object> > HandleVector(v8::internal::Handle<T>* elms,
327 int length) {
328 return Vector< Handle<Object> >(
329 reinterpret_cast<v8::internal::Handle<Object>*>(elms), length);
330}
331
332
333// Simple support to read a file into a 0-terminated C-string.
334// The returned buffer must be freed by the caller.
335// On return, *exits tells whether the file exisited.
336Vector<const char> ReadFile(const char* filename,
337 bool* exists,
338 bool verbose = true);
339
340
341// Simple wrapper that allows an ExternalString to refer to a
342// Vector<const char>. Doesn't assume ownership of the data.
343class AsciiStringAdapter: public v8::String::ExternalAsciiStringResource {
344 public:
345 explicit AsciiStringAdapter(Vector<const char> data) : data_(data) {}
346
347 virtual const char* data() const { return data_.start(); }
348
349 virtual size_t length() const { return data_.length(); }
350
351 private:
352 Vector<const char> data_;
353};
354
355
356} } // namespace v8::internal
357
358#endif // V8_UTILS_H_