blob: e008c85f59a7799db75e73b1d5adc15886fe8db8 [file] [log] [blame]
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001// Copyright 2006-2008 the V8 project authors. All rights reserved.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002// 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
ager@chromium.orga74f0da2008-12-03 16:05:52 +000031#include <stdlib.h>
32
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000033namespace v8 { namespace internal {
34
35// ----------------------------------------------------------------------------
36// General helper functions
37
38// Returns true iff x is a power of 2. Does not work for zero.
39template <typename T>
40static inline bool IsPowerOf2(T x) {
41 return (x & (x - 1)) == 0;
42}
43
44
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000045
46
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +000047// The C++ standard leaves the semantics of '>>' undefined for
48// negative signed operands. Most implementations do the right thing,
49// though.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000050static 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.
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +000056// This allows conversion of Addresses and integral types into
57// 0-relative int offsets.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000058template <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.
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +000065// This allows conversion of 0-relative int offsets into Addresses and
66// integral types.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000067template <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
ager@chromium.orga74f0da2008-12-03 16:05:52 +000088template <typename T>
89static int Compare(const T& a, const T& b) {
90 if (a == b)
91 return 0;
92 else if (a < b)
93 return -1;
94 else
95 return 1;
96}
97
98
99template <typename T>
100static int PointerValueCompare(const T* a, const T* b) {
101 return Compare<T>(*a, *b);
102}
103
104
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +0000105// Returns the smallest power of two which is >= x. If you pass in a
106// number that is already a power of two, it is returned as is.
107uint32_t RoundUpToPowerOf2(uint32_t x);
108
109
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000110template <typename T>
111static inline bool IsAligned(T value, T alignment) {
112 ASSERT(IsPowerOf2(alignment));
113 return (value & (alignment - 1)) == 0;
114}
115
116
117// Returns true if (addr + offset) is aligned.
118static inline bool IsAddressAligned(Address addr, int alignment, int offset) {
119 int offs = OffsetFrom(addr + offset);
120 return IsAligned(offs, alignment);
121}
122
123
124// Returns the maximum of the two parameters.
125template <typename T>
126static T Max(T a, T b) {
127 return a < b ? b : a;
128}
129
130
131// Returns the minimum of the two parameters.
132template <typename T>
133static T Min(T a, T b) {
134 return a < b ? a : b;
135}
136
137
138// ----------------------------------------------------------------------------
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +0000139// BitField is a help template for encoding and decode bitfield with
140// unsigned content.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000141template<class T, int shift, int size>
142class BitField {
143 public:
144 // Tells whether the provided value fits into the bit field.
145 static bool is_valid(T value) {
146 return (static_cast<uint32_t>(value) & ~((1U << (size)) - 1)) == 0;
147 }
148
149 // Returns a uint32_t mask of bit field.
150 static uint32_t mask() {
151 return (1U << (size + shift)) - (1U << shift);
152 }
153
154 // Returns a uint32_t with the bit field value encoded.
155 static uint32_t encode(T value) {
156 ASSERT(is_valid(value));
157 return static_cast<uint32_t>(value) << shift;
158 }
159
160 // Extracts the bit field from the value.
161 static T decode(uint32_t value) {
162 return static_cast<T>((value >> shift) & ((1U << (size)) - 1));
163 }
164};
165
166
167// ----------------------------------------------------------------------------
168// Support for compressed, machine-independent encoding
169// and decoding of integer values of arbitrary size.
170
171// Encoding and decoding from/to a buffer at position p;
172// the result is the position after the encoded integer.
173// Small signed integers in the range -64 <= x && x < 64
174// are encoded in 1 byte; larger values are encoded in 2
175// or more bytes. At most sizeof(int) + 1 bytes are used
176// in the worst case.
177byte* EncodeInt(byte* p, int x);
178byte* DecodeInt(byte* p, int* x);
179
180
181// Encoding and decoding from/to a buffer at position p - 1
182// moving backward; the result is the position of the last
183// byte written. These routines are useful to read/write
184// into a buffer starting at the end of the buffer.
185byte* EncodeUnsignedIntBackward(byte* p, unsigned int x);
186
187// The decoding function is inlined since its performance is
188// important to mark-sweep garbage collection.
189inline byte* DecodeUnsignedIntBackward(byte* p, unsigned int* x) {
190 byte b = *--p;
191 if (b >= 128) {
192 *x = static_cast<unsigned int>(b) - 128;
193 return p;
194 }
195 unsigned int r = static_cast<unsigned int>(b);
196 unsigned int s = 7;
197 b = *--p;
198 while (b < 128) {
199 r |= static_cast<unsigned int>(b) << s;
200 s += 7;
201 b = *--p;
202 }
203 // b >= 128
204 *x = r | ((static_cast<unsigned int>(b) - 128) << s);
205 return p;
206}
207
208
209// ----------------------------------------------------------------------------
210// I/O support.
211
212// Our version of printf(). Avoids compilation errors that we get
213// with standard printf when attempting to print pointers, etc.
214// (the errors are due to the extra compilation flags, which we
215// want elsewhere).
216void PrintF(const char* format, ...);
217
218// Our version of fflush.
219void Flush();
220
221
222// Read a line of characters after printing the prompt to stdout. The resulting
223// char* needs to be disposed off with DeleteArray by the caller.
224char* ReadLine(const char* prompt);
225
226
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000227// Read and return the raw bytes in a file. the size of the buffer is returned
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000228// in size.
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000229// The returned buffer must be freed by the caller.
230byte* ReadBytes(const char* filename, int* size, bool verbose = true);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000231
232
233// Write size chars from str to the file given by filename.
234// The file is overwritten. Returns the number of chars written.
235int WriteChars(const char* filename,
236 const char* str,
237 int size,
238 bool verbose = true);
239
240
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000241// Write size bytes to the file given by filename.
242// The file is overwritten. Returns the number of bytes written.
243int WriteBytes(const char* filename,
244 const byte* bytes,
245 int size,
246 bool verbose = true);
247
248
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000249// Write the C code
250// const char* <varname> = "<str>";
251// const int <varname>_len = <len>;
252// to the file given by filename. Only the first len chars are written.
253int WriteAsCFile(const char* filename, const char* varname,
254 const char* str, int size, bool verbose = true);
255
256
257// ----------------------------------------------------------------------------
258// Miscellaneous
259
260// A static resource holds a static instance that can be reserved in
261// a local scope using an instance of Access. Attempts to re-reserve
262// the instance will cause an error.
263template <typename T>
264class StaticResource {
265 public:
266 StaticResource() : is_reserved_(false) {}
267
268 private:
269 template <typename S> friend class Access;
270 T instance_;
271 bool is_reserved_;
272};
273
274
275// Locally scoped access to a static resource.
276template <typename T>
277class Access {
278 public:
279 explicit Access(StaticResource<T>* resource)
280 : resource_(resource)
281 , instance_(&resource->instance_) {
282 ASSERT(!resource->is_reserved_);
283 resource->is_reserved_ = true;
284 }
285
286 ~Access() {
287 resource_->is_reserved_ = false;
288 resource_ = NULL;
289 instance_ = NULL;
290 }
291
292 T* value() { return instance_; }
293 T* operator -> () { return instance_; }
294
295 private:
296 StaticResource<T>* resource_;
297 T* instance_;
298};
299
300
301template <typename T>
302class Vector {
303 public:
kasper.lund7276f142008-07-30 08:49:36 +0000304 Vector() : start_(NULL), length_(0) {}
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000305 Vector(T* data, int length) : start_(data), length_(length) {
306 ASSERT(length == 0 || (length > 0 && data != NULL));
307 }
308
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000309 static Vector<T> New(int length) {
310 return Vector<T>(NewArray<T>(length), length);
311 }
312
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000313 // Returns a vector using the same backing storage as this one,
314 // spanning from and including 'from', to but not including 'to'.
315 Vector<T> SubVector(int from, int to) {
316 ASSERT(from < length_);
317 ASSERT(to <= length_);
318 ASSERT(from < to);
319 return Vector<T>(start() + from, to - from);
320 }
321
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000322 // Returns the length of the vector.
323 int length() const { return length_; }
324
325 // Returns whether or not the vector is empty.
326 bool is_empty() const { return length_ == 0; }
327
328 // Returns the pointer to the start of the data in the vector.
329 T* start() const { return start_; }
330
331 // Access individual vector elements - checks bounds in debug mode.
332 T& operator[](int index) const {
333 ASSERT(0 <= index && index < length_);
334 return start_[index];
335 }
336
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000337 T& first() { return start_[0]; }
338
339 T& last() { return start_[length_ - 1]; }
340
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000341 // Returns a clone of this vector with a new backing store.
342 Vector<T> Clone() const {
343 T* result = NewArray<T>(length_);
344 for (int i = 0; i < length_; i++) result[i] = start_[i];
345 return Vector<T>(result, length_);
346 }
347
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000348 void Sort(int (*cmp)(const T*, const T*)) {
349 typedef int (*RawComparer)(const void*, const void*);
350 qsort(start(),
351 length(),
352 sizeof(T),
353 reinterpret_cast<RawComparer>(cmp));
354 }
355
356 void Sort() {
357 Sort(PointerValueCompare<T>);
358 }
359
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000360 // Releases the array underlying this vector. Once disposed the
361 // vector is empty.
362 void Dispose() {
kasper.lund7276f142008-07-30 08:49:36 +0000363 if (is_empty()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000364 DeleteArray(start_);
365 start_ = NULL;
366 length_ = 0;
367 }
368
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000369 inline Vector<T> operator+(int offset) {
370 ASSERT(offset < length_);
371 return Vector<T>(start_ + offset, length_ - offset);
372 }
373
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000374 // Factory method for creating empty vectors.
375 static Vector<T> empty() { return Vector<T>(NULL, 0); }
376
377 private:
378 T* start_;
379 int length_;
380};
381
382
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000383// A temporary assignment sets a (non-local) variable to a value on
384// construction and resets it the value on destruction.
385template <typename T>
386class TempAssign {
387 public:
388 TempAssign(T* var, T value): var_(var), old_value_(*var) {
389 *var = value;
390 }
391
392 ~TempAssign() { *var_ = old_value_; }
393
394 private:
395 T* var_;
396 T old_value_;
397};
398
399
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000400template <typename T, int kSize>
401class EmbeddedVector : public Vector<T> {
402 public:
403 EmbeddedVector() : Vector<T>(buffer_, kSize) { }
404 private:
405 T buffer_[kSize];
406};
407
408
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000409template <typename T>
410class ScopedVector : public Vector<T> {
411 public:
412 explicit ScopedVector(int length) : Vector<T>(NewArray<T>(length), length) { }
413 ~ScopedVector() {
414 DeleteArray(this->start());
415 }
416};
417
418
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000419inline Vector<const char> CStrVector(const char* data) {
420 return Vector<const char>(data, strlen(data));
421}
422
423inline Vector<char> MutableCStrVector(char* data) {
424 return Vector<char>(data, strlen(data));
425}
426
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000427inline Vector<char> MutableCStrVector(char* data, int max) {
428 int length = strlen(data);
429 return Vector<char>(data, (length < max) ? length : max);
430}
431
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000432template <typename T>
433inline Vector< Handle<Object> > HandleVector(v8::internal::Handle<T>* elms,
434 int length) {
435 return Vector< Handle<Object> >(
436 reinterpret_cast<v8::internal::Handle<Object>*>(elms), length);
437}
438
439
440// Simple support to read a file into a 0-terminated C-string.
441// The returned buffer must be freed by the caller.
ager@chromium.org32912102009-01-16 10:38:43 +0000442// On return, *exits tells whether the file existed.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000443Vector<const char> ReadFile(const char* filename,
444 bool* exists,
445 bool verbose = true);
446
447
448// Simple wrapper that allows an ExternalString to refer to a
449// Vector<const char>. Doesn't assume ownership of the data.
450class AsciiStringAdapter: public v8::String::ExternalAsciiStringResource {
451 public:
452 explicit AsciiStringAdapter(Vector<const char> data) : data_(data) {}
453
454 virtual const char* data() const { return data_.start(); }
455
456 virtual size_t length() const { return data_.length(); }
457
458 private:
459 Vector<const char> data_;
460};
461
462
kasper.lund7276f142008-07-30 08:49:36 +0000463// Helper class for building result strings in a character buffer. The
464// purpose of the class is to use safe operations that checks the
465// buffer bounds on all operations in debug mode.
466class StringBuilder {
467 public:
468 // Create a string builder with a buffer of the given size. The
469 // buffer is allocated through NewArray<char> and must be
470 // deallocated by the caller of Finalize().
471 explicit StringBuilder(int size);
472
473 StringBuilder(char* buffer, int size)
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000474 : buffer_(buffer, size), position_(0) { }
kasper.lund7276f142008-07-30 08:49:36 +0000475
476 ~StringBuilder() { if (!is_finalized()) Finalize(); }
477
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000478 int size() const { return buffer_.length(); }
kasper.lund7276f142008-07-30 08:49:36 +0000479
480 // Get the current position in the builder.
481 int position() const {
482 ASSERT(!is_finalized());
483 return position_;
484 }
485
486 // Reset the position.
487 void Reset() { position_ = 0; }
488
489 // Add a single character to the builder. It is not allowed to add
490 // 0-characters; use the Finalize() method to terminate the string
491 // instead.
492 void AddCharacter(char c) {
493 ASSERT(c != '\0');
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000494 ASSERT(!is_finalized() && position_ < buffer_.length());
kasper.lund7276f142008-07-30 08:49:36 +0000495 buffer_[position_++] = c;
496 }
497
498 // Add an entire string to the builder. Uses strlen() internally to
499 // compute the length of the input string.
500 void AddString(const char* s);
501
502 // Add the first 'n' characters of the given string 's' to the
503 // builder. The input string must have enough characters.
504 void AddSubstring(const char* s, int n);
505
506 // Add formatted contents to the builder just like printf().
507 void AddFormatted(const char* format, ...);
508
509 // Add character padding to the builder. If count is non-positive,
510 // nothing is added to the builder.
511 void AddPadding(char c, int count);
512
513 // Finalize the string by 0-terminating it and returning the buffer.
514 char* Finalize();
515
516 private:
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000517 Vector<char> buffer_;
kasper.lund7276f142008-07-30 08:49:36 +0000518 int position_;
519
520 bool is_finalized() const { return position_ < 0; }
mads.s.ager31e71382008-08-13 09:32:07 +0000521
522 DISALLOW_IMPLICIT_CONSTRUCTORS(StringBuilder);
kasper.lund7276f142008-07-30 08:49:36 +0000523};
524
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000525
526// Copy from ASCII/16bit chars to ASCII/16bit chars.
527template <typename sourcechar, typename sinkchar>
528static inline void CopyChars(sinkchar* dest, const sourcechar* src, int chars) {
529 sinkchar* limit = dest + chars;
530#ifdef CAN_READ_UNALIGNED
531 if (sizeof(*dest) == sizeof(*src)) {
532 // Number of characters in a uint32_t.
533 static const int kStepSize = sizeof(uint32_t) / sizeof(*dest); // NOLINT
534 while (dest <= limit - kStepSize) {
535 *reinterpret_cast<uint32_t*>(dest) =
536 *reinterpret_cast<const uint32_t*>(src);
537 dest += kStepSize;
538 src += kStepSize;
539 }
540 }
541#endif
542 while (dest < limit) {
543 *dest++ = static_cast<sinkchar>(*src++);
544 }
545}
546
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000547
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000548} } // namespace v8::internal
549
550#endif // V8_UTILS_H_