blob: 137e2c4f0cf20c5f33040bada8e92a4a12e99303 [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
kasperl@chromium.org71affb52009-05-26 05:44:31 +000033namespace v8 {
34namespace internal {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000035
36// ----------------------------------------------------------------------------
37// General helper functions
38
39// Returns true iff x is a power of 2. Does not work for zero.
40template <typename T>
41static inline bool IsPowerOf2(T x) {
42 return (x & (x - 1)) == 0;
43}
44
45
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +000046// The C++ standard leaves the semantics of '>>' undefined for
47// negative signed operands. Most implementations do the right thing,
48// though.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000049static inline int ArithmeticShiftRight(int x, int s) {
50 return x >> s;
51}
52
53
54// Compute the 0-relative offset of some absolute value x of type T.
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +000055// This allows conversion of Addresses and integral types into
56// 0-relative int offsets.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000057template <typename T>
kasperl@chromium.org71affb52009-05-26 05:44:31 +000058static inline intptr_t OffsetFrom(T x) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000059 return x - static_cast<T>(0);
60}
61
62
63// Compute the absolute value of type T for some 0-relative offset x.
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +000064// This allows conversion of 0-relative int offsets into Addresses and
65// integral types.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000066template <typename T>
kasperl@chromium.org71affb52009-05-26 05:44:31 +000067static inline T AddressFrom(intptr_t x) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000068 return static_cast<T>(0) + x;
69}
70
71
72// Return the largest multiple of m which is <= x.
73template <typename T>
74static inline T RoundDown(T x, int m) {
75 ASSERT(IsPowerOf2(m));
76 return AddressFrom<T>(OffsetFrom(x) & -m);
77}
78
79
80// Return the smallest multiple of m which is >= x.
81template <typename T>
82static inline T RoundUp(T x, int m) {
83 return RoundDown(x + m - 1, m);
84}
85
86
ager@chromium.orga74f0da2008-12-03 16:05:52 +000087template <typename T>
88static int Compare(const T& a, const T& b) {
89 if (a == b)
90 return 0;
91 else if (a < b)
92 return -1;
93 else
94 return 1;
95}
96
97
98template <typename T>
99static int PointerValueCompare(const T* a, const T* b) {
100 return Compare<T>(*a, *b);
101}
102
103
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +0000104// Returns the smallest power of two which is >= x. If you pass in a
105// number that is already a power of two, it is returned as is.
106uint32_t RoundUpToPowerOf2(uint32_t x);
107
108
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000109template <typename T>
110static inline bool IsAligned(T value, T alignment) {
111 ASSERT(IsPowerOf2(alignment));
112 return (value & (alignment - 1)) == 0;
113}
114
115
116// Returns true if (addr + offset) is aligned.
117static inline bool IsAddressAligned(Address addr, int alignment, int offset) {
118 int offs = OffsetFrom(addr + offset);
119 return IsAligned(offs, alignment);
120}
121
122
123// Returns the maximum of the two parameters.
124template <typename T>
125static T Max(T a, T b) {
126 return a < b ? b : a;
127}
128
129
130// Returns the minimum of the two parameters.
131template <typename T>
132static T Min(T a, T b) {
133 return a < b ? a : b;
134}
135
136
137// ----------------------------------------------------------------------------
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +0000138// BitField is a help template for encoding and decode bitfield with
139// unsigned content.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000140template<class T, int shift, int size>
141class BitField {
142 public:
143 // Tells whether the provided value fits into the bit field.
144 static bool is_valid(T value) {
145 return (static_cast<uint32_t>(value) & ~((1U << (size)) - 1)) == 0;
146 }
147
148 // Returns a uint32_t mask of bit field.
149 static uint32_t mask() {
150 return (1U << (size + shift)) - (1U << shift);
151 }
152
153 // Returns a uint32_t with the bit field value encoded.
154 static uint32_t encode(T value) {
155 ASSERT(is_valid(value));
156 return static_cast<uint32_t>(value) << shift;
157 }
158
159 // Extracts the bit field from the value.
160 static T decode(uint32_t value) {
161 return static_cast<T>((value >> shift) & ((1U << (size)) - 1));
162 }
163};
164
165
166// ----------------------------------------------------------------------------
167// Support for compressed, machine-independent encoding
168// and decoding of integer values of arbitrary size.
169
170// Encoding and decoding from/to a buffer at position p;
171// the result is the position after the encoded integer.
172// Small signed integers in the range -64 <= x && x < 64
173// are encoded in 1 byte; larger values are encoded in 2
174// or more bytes. At most sizeof(int) + 1 bytes are used
175// in the worst case.
176byte* EncodeInt(byte* p, int x);
177byte* DecodeInt(byte* p, int* x);
178
179
180// Encoding and decoding from/to a buffer at position p - 1
181// moving backward; the result is the position of the last
182// byte written. These routines are useful to read/write
183// into a buffer starting at the end of the buffer.
184byte* EncodeUnsignedIntBackward(byte* p, unsigned int x);
185
186// The decoding function is inlined since its performance is
187// important to mark-sweep garbage collection.
188inline byte* DecodeUnsignedIntBackward(byte* p, unsigned int* x) {
189 byte b = *--p;
190 if (b >= 128) {
191 *x = static_cast<unsigned int>(b) - 128;
192 return p;
193 }
194 unsigned int r = static_cast<unsigned int>(b);
195 unsigned int s = 7;
196 b = *--p;
197 while (b < 128) {
198 r |= static_cast<unsigned int>(b) << s;
199 s += 7;
200 b = *--p;
201 }
202 // b >= 128
203 *x = r | ((static_cast<unsigned int>(b) - 128) << s);
204 return p;
205}
206
207
208// ----------------------------------------------------------------------------
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000209// Hash function.
210
211uint32_t ComputeIntegerHash(uint32_t key);
212
213
214// ----------------------------------------------------------------------------
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000215// I/O support.
216
217// Our version of printf(). Avoids compilation errors that we get
218// with standard printf when attempting to print pointers, etc.
219// (the errors are due to the extra compilation flags, which we
220// want elsewhere).
221void PrintF(const char* format, ...);
222
223// Our version of fflush.
224void Flush();
225
226
227// Read a line of characters after printing the prompt to stdout. The resulting
228// char* needs to be disposed off with DeleteArray by the caller.
229char* ReadLine(const char* prompt);
230
231
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000232// Read and return the raw bytes in a file. the size of the buffer is returned
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000233// in size.
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000234// The returned buffer must be freed by the caller.
235byte* ReadBytes(const char* filename, int* size, bool verbose = true);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000236
237
238// Write size chars from str to the file given by filename.
239// The file is overwritten. Returns the number of chars written.
240int WriteChars(const char* filename,
241 const char* str,
242 int size,
243 bool verbose = true);
244
245
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000246// Write size bytes to the file given by filename.
247// The file is overwritten. Returns the number of bytes written.
248int WriteBytes(const char* filename,
249 const byte* bytes,
250 int size,
251 bool verbose = true);
252
253
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000254// Write the C code
255// const char* <varname> = "<str>";
256// const int <varname>_len = <len>;
257// to the file given by filename. Only the first len chars are written.
258int WriteAsCFile(const char* filename, const char* varname,
259 const char* str, int size, bool verbose = true);
260
261
262// ----------------------------------------------------------------------------
263// Miscellaneous
264
265// A static resource holds a static instance that can be reserved in
266// a local scope using an instance of Access. Attempts to re-reserve
267// the instance will cause an error.
268template <typename T>
269class StaticResource {
270 public:
271 StaticResource() : is_reserved_(false) {}
272
273 private:
274 template <typename S> friend class Access;
275 T instance_;
276 bool is_reserved_;
277};
278
279
280// Locally scoped access to a static resource.
281template <typename T>
282class Access {
283 public:
284 explicit Access(StaticResource<T>* resource)
285 : resource_(resource)
286 , instance_(&resource->instance_) {
287 ASSERT(!resource->is_reserved_);
288 resource->is_reserved_ = true;
289 }
290
291 ~Access() {
292 resource_->is_reserved_ = false;
293 resource_ = NULL;
294 instance_ = NULL;
295 }
296
297 T* value() { return instance_; }
298 T* operator -> () { return instance_; }
299
300 private:
301 StaticResource<T>* resource_;
302 T* instance_;
303};
304
305
306template <typename T>
307class Vector {
308 public:
kasper.lund7276f142008-07-30 08:49:36 +0000309 Vector() : start_(NULL), length_(0) {}
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000310 Vector(T* data, int length) : start_(data), length_(length) {
311 ASSERT(length == 0 || (length > 0 && data != NULL));
312 }
313
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000314 static Vector<T> New(int length) {
315 return Vector<T>(NewArray<T>(length), length);
316 }
317
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000318 // Returns a vector using the same backing storage as this one,
319 // spanning from and including 'from', to but not including 'to'.
320 Vector<T> SubVector(int from, int to) {
321 ASSERT(from < length_);
322 ASSERT(to <= length_);
323 ASSERT(from < to);
324 return Vector<T>(start() + from, to - from);
325 }
326
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000327 // Returns the length of the vector.
328 int length() const { return length_; }
329
330 // Returns whether or not the vector is empty.
331 bool is_empty() const { return length_ == 0; }
332
333 // Returns the pointer to the start of the data in the vector.
334 T* start() const { return start_; }
335
336 // Access individual vector elements - checks bounds in debug mode.
337 T& operator[](int index) const {
338 ASSERT(0 <= index && index < length_);
339 return start_[index];
340 }
341
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000342 T& first() { return start_[0]; }
343
344 T& last() { return start_[length_ - 1]; }
345
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000346 // Returns a clone of this vector with a new backing store.
347 Vector<T> Clone() const {
348 T* result = NewArray<T>(length_);
349 for (int i = 0; i < length_; i++) result[i] = start_[i];
350 return Vector<T>(result, length_);
351 }
352
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000353 void Sort(int (*cmp)(const T*, const T*)) {
354 typedef int (*RawComparer)(const void*, const void*);
355 qsort(start(),
356 length(),
357 sizeof(T),
358 reinterpret_cast<RawComparer>(cmp));
359 }
360
361 void Sort() {
362 Sort(PointerValueCompare<T>);
363 }
364
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000365 // Releases the array underlying this vector. Once disposed the
366 // vector is empty.
367 void Dispose() {
kasper.lund7276f142008-07-30 08:49:36 +0000368 if (is_empty()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000369 DeleteArray(start_);
370 start_ = NULL;
371 length_ = 0;
372 }
373
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000374 inline Vector<T> operator+(int offset) {
375 ASSERT(offset < length_);
376 return Vector<T>(start_ + offset, length_ - offset);
377 }
378
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000379 // Factory method for creating empty vectors.
380 static Vector<T> empty() { return Vector<T>(NULL, 0); }
381
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +0000382 protected:
383 void set_start(T* start) { start_ = start; }
384
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000385 private:
386 T* start_;
387 int length_;
388};
389
390
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000391// A temporary assignment sets a (non-local) variable to a value on
392// construction and resets it the value on destruction.
393template <typename T>
394class TempAssign {
395 public:
396 TempAssign(T* var, T value): var_(var), old_value_(*var) {
397 *var = value;
398 }
399
400 ~TempAssign() { *var_ = old_value_; }
401
402 private:
403 T* var_;
404 T old_value_;
405};
406
407
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000408template <typename T, int kSize>
409class EmbeddedVector : public Vector<T> {
410 public:
411 EmbeddedVector() : Vector<T>(buffer_, kSize) { }
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +0000412
413 // When copying, make underlying Vector to reference our buffer.
414 EmbeddedVector(const EmbeddedVector& rhs)
415 : Vector<T>(rhs) {
416 memcpy(buffer_, rhs.buffer_, sizeof(T) * kSize);
417 set_start(buffer_);
418 }
419
420 EmbeddedVector& operator=(const EmbeddedVector& rhs) {
421 if (this == &rhs) return *this;
422 Vector<T>::operator=(rhs);
423 memcpy(buffer_, rhs.buffer_, sizeof(T) * kSize);
424 set_start(buffer_);
425 return *this;
426 }
427
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000428 private:
429 T buffer_[kSize];
430};
431
432
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000433template <typename T>
434class ScopedVector : public Vector<T> {
435 public:
436 explicit ScopedVector(int length) : Vector<T>(NewArray<T>(length), length) { }
437 ~ScopedVector() {
438 DeleteArray(this->start());
439 }
440};
441
442
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000443inline Vector<const char> CStrVector(const char* data) {
444 return Vector<const char>(data, strlen(data));
445}
446
447inline Vector<char> MutableCStrVector(char* data) {
448 return Vector<char>(data, strlen(data));
449}
450
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000451inline Vector<char> MutableCStrVector(char* data, int max) {
452 int length = strlen(data);
453 return Vector<char>(data, (length < max) ? length : max);
454}
455
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000456template <typename T>
457inline Vector< Handle<Object> > HandleVector(v8::internal::Handle<T>* elms,
458 int length) {
459 return Vector< Handle<Object> >(
460 reinterpret_cast<v8::internal::Handle<Object>*>(elms), length);
461}
462
463
464// Simple support to read a file into a 0-terminated C-string.
465// The returned buffer must be freed by the caller.
ager@chromium.org32912102009-01-16 10:38:43 +0000466// On return, *exits tells whether the file existed.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000467Vector<const char> ReadFile(const char* filename,
468 bool* exists,
469 bool verbose = true);
470
471
472// Simple wrapper that allows an ExternalString to refer to a
473// Vector<const char>. Doesn't assume ownership of the data.
474class AsciiStringAdapter: public v8::String::ExternalAsciiStringResource {
475 public:
476 explicit AsciiStringAdapter(Vector<const char> data) : data_(data) {}
477
478 virtual const char* data() const { return data_.start(); }
479
480 virtual size_t length() const { return data_.length(); }
481
482 private:
483 Vector<const char> data_;
484};
485
486
kasper.lund7276f142008-07-30 08:49:36 +0000487// Helper class for building result strings in a character buffer. The
488// purpose of the class is to use safe operations that checks the
489// buffer bounds on all operations in debug mode.
490class StringBuilder {
491 public:
492 // Create a string builder with a buffer of the given size. The
493 // buffer is allocated through NewArray<char> and must be
494 // deallocated by the caller of Finalize().
495 explicit StringBuilder(int size);
496
497 StringBuilder(char* buffer, int size)
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000498 : buffer_(buffer, size), position_(0) { }
kasper.lund7276f142008-07-30 08:49:36 +0000499
500 ~StringBuilder() { if (!is_finalized()) Finalize(); }
501
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000502 int size() const { return buffer_.length(); }
kasper.lund7276f142008-07-30 08:49:36 +0000503
504 // Get the current position in the builder.
505 int position() const {
506 ASSERT(!is_finalized());
507 return position_;
508 }
509
510 // Reset the position.
511 void Reset() { position_ = 0; }
512
513 // Add a single character to the builder. It is not allowed to add
514 // 0-characters; use the Finalize() method to terminate the string
515 // instead.
516 void AddCharacter(char c) {
517 ASSERT(c != '\0');
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000518 ASSERT(!is_finalized() && position_ < buffer_.length());
kasper.lund7276f142008-07-30 08:49:36 +0000519 buffer_[position_++] = c;
520 }
521
522 // Add an entire string to the builder. Uses strlen() internally to
523 // compute the length of the input string.
524 void AddString(const char* s);
525
526 // Add the first 'n' characters of the given string 's' to the
527 // builder. The input string must have enough characters.
528 void AddSubstring(const char* s, int n);
529
530 // Add formatted contents to the builder just like printf().
531 void AddFormatted(const char* format, ...);
532
533 // Add character padding to the builder. If count is non-positive,
534 // nothing is added to the builder.
535 void AddPadding(char c, int count);
536
537 // Finalize the string by 0-terminating it and returning the buffer.
538 char* Finalize();
539
540 private:
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000541 Vector<char> buffer_;
kasper.lund7276f142008-07-30 08:49:36 +0000542 int position_;
543
544 bool is_finalized() const { return position_ < 0; }
mads.s.ager31e71382008-08-13 09:32:07 +0000545
546 DISALLOW_IMPLICIT_CONSTRUCTORS(StringBuilder);
kasper.lund7276f142008-07-30 08:49:36 +0000547};
548
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000549
550// Copy from ASCII/16bit chars to ASCII/16bit chars.
551template <typename sourcechar, typename sinkchar>
552static inline void CopyChars(sinkchar* dest, const sourcechar* src, int chars) {
553 sinkchar* limit = dest + chars;
ager@chromium.org9085a012009-05-11 19:22:57 +0000554#ifdef V8_HOST_CAN_READ_UNALIGNED
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000555 if (sizeof(*dest) == sizeof(*src)) {
556 // Number of characters in a uint32_t.
557 static const int kStepSize = sizeof(uint32_t) / sizeof(*dest); // NOLINT
558 while (dest <= limit - kStepSize) {
559 *reinterpret_cast<uint32_t*>(dest) =
560 *reinterpret_cast<const uint32_t*>(src);
561 dest += kStepSize;
562 src += kStepSize;
563 }
564 }
565#endif
566 while (dest < limit) {
567 *dest++ = static_cast<sinkchar>(*src++);
568 }
569}
570
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000571
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000572} } // namespace v8::internal
573
574#endif // V8_UTILS_H_