// The HeapNumber class describes heap allocated numbers that cannot be // represented in a Smi (small integer) // 存储了数字的堆对象 class HeapNumber: public HeapObject { public: // [value]: number value. inline double value(); inline void set_value(double value);
Object* HeapNumber::HeapNumberToBoolean() { // NaN, +0, and -0 should return the false object switch (fpclassify(value())) { case FP_NAN: // fall through case FP_ZERO: return Heap::false_value(); default: return Heap::true_value(); } }
// Abstract super class arrays. It provides length behavior. class Array: public HeapObject { public: // [length]: length of the array. inline int length(); inline void set_length(int value);
// Convert an object to an array index. // Returns true if the conversion succeeded. static inline bool IndexFromObject(Object* object, uint32_t* index);
// Layout descriptor. static const int kLengthOffset = HeapObject::kSize; static const int kHeaderSize = kLengthOffset + kIntSize;
bool Array::IndexFromObject(Object* object, uint32_t* index) { if (object->IsSmi()) { int value = Smi::cast(object)->value(); if (value < 0) return false; *index = value; return true; } if (object->IsHeapNumber()) { double value = HeapNumber::cast(object)->value(); uint32_t uint_value = static_cast<uint32_t>(value); if (value == static_cast<double>(uint_value)) { *index = uint_value; return true; } } return false; }
该函数就是把一个对象(底层是表示数字的)转成一个数组索引。数组类也分析完了。我们继续。
3 ByteArray
// ByteArray represents fixed sized byte arrays. Used by the outside world, // such as PCRE, and also by the memory allocator and garbage collector to // fill in free blocks in the heap. class ByteArray: public Array { public: // Setter and getter. inline byte get(int index); inline void set(int index, byte value);
// Treat contents as an int array. inline int get_int(int index); /* ByteArray类没有定义自己的属性,他是根据length算出对象的大小, 然后在分配内存的时候,多分配一块存储数组元素的内存 const int kObjectAlignmentBits = 2; const int kObjectAlignmentMask = (1 << kObjectAlignmentBits) - 1; #define OBJECT_SIZE_ALIGN(value) ((value + kObjectAlignmentMask) & ~kObjectAlignmentMask) 由此可知,按四个字节对齐。OBJECT_SIZE_ALIGN的作用的是不够4字节的,会多分配几个字节,使得按四字节对齐。~kObjectAlignmentMask是低两位是0,即按四字节对齐。比如value已经4字节对齐了,则(4 + 0 +3) & ~3 =4,如果value没有对齐,假设是5,则(4 + 1 +3) & ~3 = 8;如果value等于6,(4 + 2 + 3) & ~3 = 8;以此类推。 */ static int SizeFor(int length) { return kHeaderSize + OBJECT_SIZE_ALIGN(length); } // We use byte arrays for free blocks in the heap. Given a desired size in // bytes that is a multiple of the word size and big enough to hold a byte // array, this function returns the number of elements a byte array should // have. static int LengthFor(int size_in_bytes) { ASSERT(IsAligned(size_in_bytes, kPointerSize)); ASSERT(size_in_bytes >= kHeaderSize); return size_in_bytes - kHeaderSize; }
// Returns data start address. inline Address GetDataStartAddress();
// Returns a pointer to the ByteArray object for a given data start address. static inline ByteArray* FromDataStartAddress(Address address);