utils.h revision 3fb3ca8c7ca439d408449a395897395c0faae8d1
1// Copyright 2011 the V8 project authors. 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 31#include <stdlib.h> 32#include <string.h> 33 34#include "globals.h" 35#include "checks.h" 36#include "allocation.h" 37 38namespace v8 { 39namespace internal { 40 41// ---------------------------------------------------------------------------- 42// General helper functions 43 44#define IS_POWER_OF_TWO(x) (((x) & ((x) - 1)) == 0) 45 46// Returns true iff x is a power of 2 (or zero). Cannot be used with the 47// maximally negative value of the type T (the -1 overflows). 48template <typename T> 49static inline bool IsPowerOf2(T x) { 50 return IS_POWER_OF_TWO(x); 51} 52 53 54// X must be a power of 2. Returns the number of trailing zeros. 55static inline int WhichPowerOf2(uint32_t x) { 56 ASSERT(IsPowerOf2(x)); 57 ASSERT(x != 0); 58 int bits = 0; 59#ifdef DEBUG 60 int original_x = x; 61#endif 62 if (x >= 0x10000) { 63 bits += 16; 64 x >>= 16; 65 } 66 if (x >= 0x100) { 67 bits += 8; 68 x >>= 8; 69 } 70 if (x >= 0x10) { 71 bits += 4; 72 x >>= 4; 73 } 74 switch (x) { 75 default: UNREACHABLE(); 76 case 8: bits++; // Fall through. 77 case 4: bits++; // Fall through. 78 case 2: bits++; // Fall through. 79 case 1: break; 80 } 81 ASSERT_EQ(1 << bits, original_x); 82 return bits; 83 return 0; 84} 85 86 87// The C++ standard leaves the semantics of '>>' undefined for 88// negative signed operands. Most implementations do the right thing, 89// though. 90static inline int ArithmeticShiftRight(int x, int s) { 91 return x >> s; 92} 93 94 95// Compute the 0-relative offset of some absolute value x of type T. 96// This allows conversion of Addresses and integral types into 97// 0-relative int offsets. 98template <typename T> 99static inline intptr_t OffsetFrom(T x) { 100 return x - static_cast<T>(0); 101} 102 103 104// Compute the absolute value of type T for some 0-relative offset x. 105// This allows conversion of 0-relative int offsets into Addresses and 106// integral types. 107template <typename T> 108static inline T AddressFrom(intptr_t x) { 109 return static_cast<T>(static_cast<T>(0) + x); 110} 111 112 113// Return the largest multiple of m which is <= x. 114template <typename T> 115static inline T RoundDown(T x, int m) { 116 ASSERT(IsPowerOf2(m)); 117 return AddressFrom<T>(OffsetFrom(x) & -m); 118} 119 120 121// Return the smallest multiple of m which is >= x. 122template <typename T> 123static inline T RoundUp(T x, int m) { 124 return RoundDown(x + m - 1, m); 125} 126 127 128template <typename T> 129static int Compare(const T& a, const T& b) { 130 if (a == b) 131 return 0; 132 else if (a < b) 133 return -1; 134 else 135 return 1; 136} 137 138 139template <typename T> 140static int PointerValueCompare(const T* a, const T* b) { 141 return Compare<T>(*a, *b); 142} 143 144 145// Returns the smallest power of two which is >= x. If you pass in a 146// number that is already a power of two, it is returned as is. 147// Implementation is from "Hacker's Delight" by Henry S. Warren, Jr., 148// figure 3-3, page 48, where the function is called clp2. 149static inline uint32_t RoundUpToPowerOf2(uint32_t x) { 150 ASSERT(x <= 0x80000000u); 151 x = x - 1; 152 x = x | (x >> 1); 153 x = x | (x >> 2); 154 x = x | (x >> 4); 155 x = x | (x >> 8); 156 x = x | (x >> 16); 157 return x + 1; 158} 159 160 161 162template <typename T> 163static inline bool IsAligned(T value, T alignment) { 164 ASSERT(IsPowerOf2(alignment)); 165 return (value & (alignment - 1)) == 0; 166} 167 168 169// Returns true if (addr + offset) is aligned. 170static inline bool IsAddressAligned(Address addr, 171 intptr_t alignment, 172 int offset) { 173 intptr_t offs = OffsetFrom(addr + offset); 174 return IsAligned(offs, alignment); 175} 176 177 178// Returns the maximum of the two parameters. 179template <typename T> 180static T Max(T a, T b) { 181 return a < b ? b : a; 182} 183 184 185// Returns the minimum of the two parameters. 186template <typename T> 187static T Min(T a, T b) { 188 return a < b ? a : b; 189} 190 191 192inline int StrLength(const char* string) { 193 size_t length = strlen(string); 194 ASSERT(length == static_cast<size_t>(static_cast<int>(length))); 195 return static_cast<int>(length); 196} 197 198 199// ---------------------------------------------------------------------------- 200// BitField is a help template for encoding and decode bitfield with 201// unsigned content. 202template<class T, int shift, int size> 203class BitField { 204 public: 205 // Tells whether the provided value fits into the bit field. 206 static bool is_valid(T value) { 207 return (static_cast<uint32_t>(value) & ~((1U << (size)) - 1)) == 0; 208 } 209 210 // Returns a uint32_t mask of bit field. 211 static uint32_t mask() { 212 // To use all bits of a uint32 in a bitfield without compiler warnings we 213 // have to compute 2^32 without using a shift count of 32. 214 return ((1U << shift) << size) - (1U << shift); 215 } 216 217 // Returns a uint32_t with the bit field value encoded. 218 static uint32_t encode(T value) { 219 ASSERT(is_valid(value)); 220 return static_cast<uint32_t>(value) << shift; 221 } 222 223 // Returns a uint32_t with the bit field value updated. 224 static uint32_t update(uint32_t previous, T value) { 225 return (previous & ~mask()) | encode(value); 226 } 227 228 // Extracts the bit field from the value. 229 static T decode(uint32_t value) { 230 return static_cast<T>((value & mask()) >> shift); 231 } 232 233 // Value for the field with all bits set. 234 static T max() { 235 return decode(mask()); 236 } 237}; 238 239 240// ---------------------------------------------------------------------------- 241// Hash function. 242 243// Thomas Wang, Integer Hash Functions. 244// http://www.concentric.net/~Ttwang/tech/inthash.htm 245static inline uint32_t ComputeIntegerHash(uint32_t key) { 246 uint32_t hash = key; 247 hash = ~hash + (hash << 15); // hash = (hash << 15) - hash - 1; 248 hash = hash ^ (hash >> 12); 249 hash = hash + (hash << 2); 250 hash = hash ^ (hash >> 4); 251 hash = hash * 2057; // hash = (hash + (hash << 3)) + (hash << 11); 252 hash = hash ^ (hash >> 16); 253 return hash; 254} 255 256 257static inline uint32_t ComputePointerHash(void* ptr) { 258 return ComputeIntegerHash( 259 static_cast<uint32_t>(reinterpret_cast<intptr_t>(ptr))); 260} 261 262 263// ---------------------------------------------------------------------------- 264// Miscellaneous 265 266// A static resource holds a static instance that can be reserved in 267// a local scope using an instance of Access. Attempts to re-reserve 268// the instance will cause an error. 269template <typename T> 270class StaticResource { 271 public: 272 StaticResource() : is_reserved_(false) {} 273 274 private: 275 template <typename S> friend class Access; 276 T instance_; 277 bool is_reserved_; 278}; 279 280 281// Locally scoped access to a static resource. 282template <typename T> 283class Access { 284 public: 285 explicit Access(StaticResource<T>* resource) 286 : resource_(resource) 287 , instance_(&resource->instance_) { 288 ASSERT(!resource->is_reserved_); 289 resource->is_reserved_ = true; 290 } 291 292 ~Access() { 293 resource_->is_reserved_ = false; 294 resource_ = NULL; 295 instance_ = NULL; 296 } 297 298 T* value() { return instance_; } 299 T* operator -> () { return instance_; } 300 301 private: 302 StaticResource<T>* resource_; 303 T* instance_; 304}; 305 306 307template <typename T> 308class Vector { 309 public: 310 Vector() : start_(NULL), length_(0) {} 311 Vector(T* data, int length) : start_(data), length_(length) { 312 ASSERT(length == 0 || (length > 0 && data != NULL)); 313 } 314 315 static Vector<T> New(int length) { 316 return Vector<T>(NewArray<T>(length), length); 317 } 318 319 // Returns a vector using the same backing storage as this one, 320 // spanning from and including 'from', to but not including 'to'. 321 Vector<T> SubVector(int from, int to) { 322 ASSERT(to <= length_); 323 ASSERT(from < to); 324 ASSERT(0 <= from); 325 return Vector<T>(start() + from, to - from); 326 } 327 328 // Returns the length of the vector. 329 int length() const { return length_; } 330 331 // Returns whether or not the vector is empty. 332 bool is_empty() const { return length_ == 0; } 333 334 // Returns the pointer to the start of the data in the vector. 335 T* start() const { return start_; } 336 337 // Access individual vector elements - checks bounds in debug mode. 338 T& operator[](int index) const { 339 ASSERT(0 <= index && index < length_); 340 return start_[index]; 341 } 342 343 const T& at(int index) const { return operator[](index); } 344 345 T& first() { return start_[0]; } 346 347 T& last() { return start_[length_ - 1]; } 348 349 // Returns a clone of this vector with a new backing store. 350 Vector<T> Clone() const { 351 T* result = NewArray<T>(length_); 352 for (int i = 0; i < length_; i++) result[i] = start_[i]; 353 return Vector<T>(result, length_); 354 } 355 356 void Sort(int (*cmp)(const T*, const T*)) { 357 typedef int (*RawComparer)(const void*, const void*); 358 qsort(start(), 359 length(), 360 sizeof(T), 361 reinterpret_cast<RawComparer>(cmp)); 362 } 363 364 void Sort() { 365 Sort(PointerValueCompare<T>); 366 } 367 368 void Truncate(int length) { 369 ASSERT(length <= length_); 370 length_ = length; 371 } 372 373 // Releases the array underlying this vector. Once disposed the 374 // vector is empty. 375 void Dispose() { 376 DeleteArray(start_); 377 start_ = NULL; 378 length_ = 0; 379 } 380 381 inline Vector<T> operator+(int offset) { 382 ASSERT(offset < length_); 383 return Vector<T>(start_ + offset, length_ - offset); 384 } 385 386 // Factory method for creating empty vectors. 387 static Vector<T> empty() { return Vector<T>(NULL, 0); } 388 389 template<typename S> 390 static Vector<T> cast(Vector<S> input) { 391 return Vector<T>(reinterpret_cast<T*>(input.start()), 392 input.length() * sizeof(S) / sizeof(T)); 393 } 394 395 protected: 396 void set_start(T* start) { start_ = start; } 397 398 private: 399 T* start_; 400 int length_; 401}; 402 403 404// A pointer that can only be set once and doesn't allow NULL values. 405template<typename T> 406class SetOncePointer { 407 public: 408 SetOncePointer() : pointer_(NULL) { } 409 410 bool is_set() const { return pointer_ != NULL; } 411 412 T* get() const { 413 ASSERT(pointer_ != NULL); 414 return pointer_; 415 } 416 417 void set(T* value) { 418 ASSERT(pointer_ == NULL && value != NULL); 419 pointer_ = value; 420 } 421 422 private: 423 T* pointer_; 424}; 425 426 427template <typename T, int kSize> 428class EmbeddedVector : public Vector<T> { 429 public: 430 EmbeddedVector() : Vector<T>(buffer_, kSize) { } 431 432 explicit EmbeddedVector(T initial_value) : Vector<T>(buffer_, kSize) { 433 for (int i = 0; i < kSize; ++i) { 434 buffer_[i] = initial_value; 435 } 436 } 437 438 // When copying, make underlying Vector to reference our buffer. 439 EmbeddedVector(const EmbeddedVector& rhs) 440 : Vector<T>(rhs) { 441 memcpy(buffer_, rhs.buffer_, sizeof(T) * kSize); 442 set_start(buffer_); 443 } 444 445 EmbeddedVector& operator=(const EmbeddedVector& rhs) { 446 if (this == &rhs) return *this; 447 Vector<T>::operator=(rhs); 448 memcpy(buffer_, rhs.buffer_, sizeof(T) * kSize); 449 this->set_start(buffer_); 450 return *this; 451 } 452 453 private: 454 T buffer_[kSize]; 455}; 456 457 458template <typename T> 459class ScopedVector : public Vector<T> { 460 public: 461 explicit ScopedVector(int length) : Vector<T>(NewArray<T>(length), length) { } 462 ~ScopedVector() { 463 DeleteArray(this->start()); 464 } 465 466 private: 467 DISALLOW_IMPLICIT_CONSTRUCTORS(ScopedVector); 468}; 469 470 471inline Vector<const char> CStrVector(const char* data) { 472 return Vector<const char>(data, StrLength(data)); 473} 474 475inline Vector<char> MutableCStrVector(char* data) { 476 return Vector<char>(data, StrLength(data)); 477} 478 479inline Vector<char> MutableCStrVector(char* data, int max) { 480 int length = StrLength(data); 481 return Vector<char>(data, (length < max) ? length : max); 482} 483 484 485/* 486 * A class that collects values into a backing store. 487 * Specialized versions of the class can allow access to the backing store 488 * in different ways. 489 * There is no guarantee that the backing store is contiguous (and, as a 490 * consequence, no guarantees that consecutively added elements are adjacent 491 * in memory). The collector may move elements unless it has guaranteed not 492 * to. 493 */ 494template <typename T, int growth_factor = 2, int max_growth = 1 * MB> 495class Collector { 496 public: 497 explicit Collector(int initial_capacity = kMinCapacity) 498 : index_(0), size_(0) { 499 if (initial_capacity < kMinCapacity) { 500 initial_capacity = kMinCapacity; 501 } 502 current_chunk_ = Vector<T>::New(initial_capacity); 503 } 504 505 virtual ~Collector() { 506 // Free backing store (in reverse allocation order). 507 current_chunk_.Dispose(); 508 for (int i = chunks_.length() - 1; i >= 0; i--) { 509 chunks_.at(i).Dispose(); 510 } 511 } 512 513 // Add a single element. 514 inline void Add(T value) { 515 if (index_ >= current_chunk_.length()) { 516 Grow(1); 517 } 518 current_chunk_[index_] = value; 519 index_++; 520 size_++; 521 } 522 523 // Add a block of contiguous elements and return a Vector backed by the 524 // memory area. 525 // A basic Collector will keep this vector valid as long as the Collector 526 // is alive. 527 inline Vector<T> AddBlock(int size, T initial_value) { 528 ASSERT(size > 0); 529 if (size > current_chunk_.length() - index_) { 530 Grow(size); 531 } 532 T* position = current_chunk_.start() + index_; 533 index_ += size; 534 size_ += size; 535 for (int i = 0; i < size; i++) { 536 position[i] = initial_value; 537 } 538 return Vector<T>(position, size); 539 } 540 541 542 // Add a contiguous block of elements and return a vector backed 543 // by the added block. 544 // A basic Collector will keep this vector valid as long as the Collector 545 // is alive. 546 inline Vector<T> AddBlock(Vector<const T> source) { 547 if (source.length() > current_chunk_.length() - index_) { 548 Grow(source.length()); 549 } 550 T* position = current_chunk_.start() + index_; 551 index_ += source.length(); 552 size_ += source.length(); 553 for (int i = 0; i < source.length(); i++) { 554 position[i] = source[i]; 555 } 556 return Vector<T>(position, source.length()); 557 } 558 559 560 // Write the contents of the collector into the provided vector. 561 void WriteTo(Vector<T> destination) { 562 ASSERT(size_ <= destination.length()); 563 int position = 0; 564 for (int i = 0; i < chunks_.length(); i++) { 565 Vector<T> chunk = chunks_.at(i); 566 for (int j = 0; j < chunk.length(); j++) { 567 destination[position] = chunk[j]; 568 position++; 569 } 570 } 571 for (int i = 0; i < index_; i++) { 572 destination[position] = current_chunk_[i]; 573 position++; 574 } 575 } 576 577 // Allocate a single contiguous vector, copy all the collected 578 // elements to the vector, and return it. 579 // The caller is responsible for freeing the memory of the returned 580 // vector (e.g., using Vector::Dispose). 581 Vector<T> ToVector() { 582 Vector<T> new_store = Vector<T>::New(size_); 583 WriteTo(new_store); 584 return new_store; 585 } 586 587 // Resets the collector to be empty. 588 virtual void Reset(); 589 590 // Total number of elements added to collector so far. 591 inline int size() { return size_; } 592 593 protected: 594 static const int kMinCapacity = 16; 595 List<Vector<T> > chunks_; 596 Vector<T> current_chunk_; // Block of memory currently being written into. 597 int index_; // Current index in current chunk. 598 int size_; // Total number of elements in collector. 599 600 // Creates a new current chunk, and stores the old chunk in the chunks_ list. 601 void Grow(int min_capacity) { 602 ASSERT(growth_factor > 1); 603 int growth = current_chunk_.length() * (growth_factor - 1); 604 if (growth > max_growth) { 605 growth = max_growth; 606 } 607 int new_capacity = current_chunk_.length() + growth; 608 if (new_capacity < min_capacity) { 609 new_capacity = min_capacity + growth; 610 } 611 Vector<T> new_chunk = Vector<T>::New(new_capacity); 612 int new_index = PrepareGrow(new_chunk); 613 if (index_ > 0) { 614 chunks_.Add(current_chunk_.SubVector(0, index_)); 615 } else { 616 // Can happen if the call to PrepareGrow moves everything into 617 // the new chunk. 618 current_chunk_.Dispose(); 619 } 620 current_chunk_ = new_chunk; 621 index_ = new_index; 622 ASSERT(index_ + min_capacity <= current_chunk_.length()); 623 } 624 625 // Before replacing the current chunk, give a subclass the option to move 626 // some of the current data into the new chunk. The function may update 627 // the current index_ value to represent data no longer in the current chunk. 628 // Returns the initial index of the new chunk (after copied data). 629 virtual int PrepareGrow(Vector<T> new_chunk) { 630 return 0; 631 } 632}; 633 634 635/* 636 * A collector that allows sequences of values to be guaranteed to 637 * stay consecutive. 638 * If the backing store grows while a sequence is active, the current 639 * sequence might be moved, but after the sequence is ended, it will 640 * not move again. 641 * NOTICE: Blocks allocated using Collector::AddBlock(int) can move 642 * as well, if inside an active sequence where another element is added. 643 */ 644template <typename T, int growth_factor = 2, int max_growth = 1 * MB> 645class SequenceCollector : public Collector<T, growth_factor, max_growth> { 646 public: 647 explicit SequenceCollector(int initial_capacity) 648 : Collector<T, growth_factor, max_growth>(initial_capacity), 649 sequence_start_(kNoSequence) { } 650 651 virtual ~SequenceCollector() {} 652 653 void StartSequence() { 654 ASSERT(sequence_start_ == kNoSequence); 655 sequence_start_ = this->index_; 656 } 657 658 Vector<T> EndSequence() { 659 ASSERT(sequence_start_ != kNoSequence); 660 int sequence_start = sequence_start_; 661 sequence_start_ = kNoSequence; 662 if (sequence_start == this->index_) return Vector<T>(); 663 return this->current_chunk_.SubVector(sequence_start, this->index_); 664 } 665 666 // Drops the currently added sequence, and all collected elements in it. 667 void DropSequence() { 668 ASSERT(sequence_start_ != kNoSequence); 669 int sequence_length = this->index_ - sequence_start_; 670 this->index_ = sequence_start_; 671 this->size_ -= sequence_length; 672 sequence_start_ = kNoSequence; 673 } 674 675 virtual void Reset() { 676 sequence_start_ = kNoSequence; 677 this->Collector<T, growth_factor, max_growth>::Reset(); 678 } 679 680 private: 681 static const int kNoSequence = -1; 682 int sequence_start_; 683 684 // Move the currently active sequence to the new chunk. 685 virtual int PrepareGrow(Vector<T> new_chunk) { 686 if (sequence_start_ != kNoSequence) { 687 int sequence_length = this->index_ - sequence_start_; 688 // The new chunk is always larger than the current chunk, so there 689 // is room for the copy. 690 ASSERT(sequence_length < new_chunk.length()); 691 for (int i = 0; i < sequence_length; i++) { 692 new_chunk[i] = this->current_chunk_[sequence_start_ + i]; 693 } 694 this->index_ = sequence_start_; 695 sequence_start_ = 0; 696 return sequence_length; 697 } 698 return 0; 699 } 700}; 701 702 703// Compare ASCII/16bit chars to ASCII/16bit chars. 704template <typename lchar, typename rchar> 705static inline int CompareChars(const lchar* lhs, const rchar* rhs, int chars) { 706 const lchar* limit = lhs + chars; 707#ifdef V8_HOST_CAN_READ_UNALIGNED 708 if (sizeof(*lhs) == sizeof(*rhs)) { 709 // Number of characters in a uintptr_t. 710 static const int kStepSize = sizeof(uintptr_t) / sizeof(*lhs); // NOLINT 711 while (lhs <= limit - kStepSize) { 712 if (*reinterpret_cast<const uintptr_t*>(lhs) != 713 *reinterpret_cast<const uintptr_t*>(rhs)) { 714 break; 715 } 716 lhs += kStepSize; 717 rhs += kStepSize; 718 } 719 } 720#endif 721 while (lhs < limit) { 722 int r = static_cast<int>(*lhs) - static_cast<int>(*rhs); 723 if (r != 0) return r; 724 ++lhs; 725 ++rhs; 726 } 727 return 0; 728} 729 730 731// Calculate 10^exponent. 732static inline int TenToThe(int exponent) { 733 ASSERT(exponent <= 9); 734 ASSERT(exponent >= 1); 735 int answer = 10; 736 for (int i = 1; i < exponent; i++) answer *= 10; 737 return answer; 738} 739 740 741// The type-based aliasing rule allows the compiler to assume that pointers of 742// different types (for some definition of different) never alias each other. 743// Thus the following code does not work: 744// 745// float f = foo(); 746// int fbits = *(int*)(&f); 747// 748// The compiler 'knows' that the int pointer can't refer to f since the types 749// don't match, so the compiler may cache f in a register, leaving random data 750// in fbits. Using C++ style casts makes no difference, however a pointer to 751// char data is assumed to alias any other pointer. This is the 'memcpy 752// exception'. 753// 754// Bit_cast uses the memcpy exception to move the bits from a variable of one 755// type of a variable of another type. Of course the end result is likely to 756// be implementation dependent. Most compilers (gcc-4.2 and MSVC 2005) 757// will completely optimize BitCast away. 758// 759// There is an additional use for BitCast. 760// Recent gccs will warn when they see casts that may result in breakage due to 761// the type-based aliasing rule. If you have checked that there is no breakage 762// you can use BitCast to cast one pointer type to another. This confuses gcc 763// enough that it can no longer see that you have cast one pointer type to 764// another thus avoiding the warning. 765 766// We need different implementations of BitCast for pointer and non-pointer 767// values. We use partial specialization of auxiliary struct to work around 768// issues with template functions overloading. 769template <class Dest, class Source> 770struct BitCastHelper { 771 STATIC_ASSERT(sizeof(Dest) == sizeof(Source)); 772 773 INLINE(static Dest cast(const Source& source)) { 774 Dest dest; 775 memcpy(&dest, &source, sizeof(dest)); 776 return dest; 777 } 778}; 779 780template <class Dest, class Source> 781struct BitCastHelper<Dest, Source*> { 782 INLINE(static Dest cast(Source* source)) { 783 return BitCastHelper<Dest, uintptr_t>:: 784 cast(reinterpret_cast<uintptr_t>(source)); 785 } 786}; 787 788template <class Dest, class Source> 789INLINE(Dest BitCast(const Source& source)); 790 791template <class Dest, class Source> 792inline Dest BitCast(const Source& source) { 793 return BitCastHelper<Dest, Source>::cast(source); 794} 795 796 797template<typename ElementType, int NumElements> 798class EmbeddedContainer { 799 public: 800 EmbeddedContainer() : elems_() { } 801 802 int length() { return NumElements; } 803 ElementType& operator[](int i) { 804 ASSERT(i < length()); 805 return elems_[i]; 806 } 807 808 private: 809 ElementType elems_[NumElements]; 810}; 811 812 813template<typename ElementType> 814class EmbeddedContainer<ElementType, 0> { 815 public: 816 int length() { return 0; } 817 ElementType& operator[](int i) { 818 UNREACHABLE(); 819 static ElementType t = 0; 820 return t; 821 } 822}; 823 824 825// Helper class for building result strings in a character buffer. The 826// purpose of the class is to use safe operations that checks the 827// buffer bounds on all operations in debug mode. 828// This simple base class does not allow formatted output. 829class SimpleStringBuilder { 830 public: 831 // Create a string builder with a buffer of the given size. The 832 // buffer is allocated through NewArray<char> and must be 833 // deallocated by the caller of Finalize(). 834 explicit SimpleStringBuilder(int size); 835 836 SimpleStringBuilder(char* buffer, int size) 837 : buffer_(buffer, size), position_(0) { } 838 839 ~SimpleStringBuilder() { if (!is_finalized()) Finalize(); } 840 841 int size() const { return buffer_.length(); } 842 843 // Get the current position in the builder. 844 int position() const { 845 ASSERT(!is_finalized()); 846 return position_; 847 } 848 849 // Reset the position. 850 void Reset() { position_ = 0; } 851 852 // Add a single character to the builder. It is not allowed to add 853 // 0-characters; use the Finalize() method to terminate the string 854 // instead. 855 void AddCharacter(char c) { 856 ASSERT(c != '\0'); 857 ASSERT(!is_finalized() && position_ < buffer_.length()); 858 buffer_[position_++] = c; 859 } 860 861 // Add an entire string to the builder. Uses strlen() internally to 862 // compute the length of the input string. 863 void AddString(const char* s); 864 865 // Add the first 'n' characters of the given string 's' to the 866 // builder. The input string must have enough characters. 867 void AddSubstring(const char* s, int n); 868 869 // Add character padding to the builder. If count is non-positive, 870 // nothing is added to the builder. 871 void AddPadding(char c, int count); 872 873 // Add the decimal representation of the value. 874 void AddDecimalInteger(int value); 875 876 // Finalize the string by 0-terminating it and returning the buffer. 877 char* Finalize(); 878 879 protected: 880 Vector<char> buffer_; 881 int position_; 882 883 bool is_finalized() const { return position_ < 0; } 884 private: 885 DISALLOW_IMPLICIT_CONSTRUCTORS(SimpleStringBuilder); 886}; 887 888} } // namespace v8::internal 889 890#endif // V8_UTILS_H_ 891