object.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /**
  2. ******************************************************************************
  3. * @file : object.cpp
  4. * @author : simon
  5. * @brief : None
  6. * @attention : None
  7. * @date : 2023/8/23
  8. ******************************************************************************
  9. */
  10. #include <stdio.h>
  11. #include <string.h>
  12. #include "memory.h"
  13. #include "table.h"
  14. #include "object.h"
  15. #include "vm.h"
  16. static Obj *allocateObject(size_t size, ObjType type);
  17. static uint32_t hashString(const char *key, int length);
  18. #define ALLOCATE_OBJ(type, objectType) \
  19. (type *) allocateObject(sizeof(type), objectType)
  20. static ObjString *allocateString(char *chars, int length,
  21. uint32_t hash) {
  22. ObjString *string = ALLOCATE_OBJ(ObjString, OBJ_STRING);
  23. string->length = length;
  24. string->chars = chars;
  25. string->hash = hash;
  26. tableSet(&vm.strings, string, NIL_VAL);
  27. return string;
  28. }
  29. ObjString *copyString(const char *chars, int length) {
  30. uint32_t hash = hashString(chars, length);
  31. ObjString *interned = tableFindString(&vm.strings, chars, length, hash);
  32. if (interned != NULL) return interned;
  33. char *heapChars = ALLOCATE(char, length + 1);
  34. memcpy(heapChars, chars, length);
  35. heapChars[length] = '\0';
  36. return allocateString(heapChars, length, hash);
  37. }
  38. void printObject(Value value) {
  39. switch (OBJ_TYPE(value)) {
  40. case OBJ_STRING:
  41. printf("%s", AS_CSTRING(value));
  42. break;
  43. }
  44. }
  45. ObjString *takeString(char *chars, int length) {
  46. uint32_t hash = hashString(chars, length);
  47. ObjString *interned = tableFindString(&vm.strings, chars, length, hash);
  48. if (interned != NULL) {
  49. FREE_ARRAY(char, chars, length + 1);
  50. return interned;
  51. }
  52. return allocateString(chars, length, hash);
  53. }
  54. static Obj *allocateObject(size_t size, ObjType type) {
  55. Obj *object = (Obj *) reallocate(NULL, 0, size);
  56. object->type = type;
  57. object->next = vm.objects;
  58. vm.objects = object;
  59. return object;
  60. }
  61. /// Hash 函数 -- 使用 FNV-1a 算法
  62. /// \param key
  63. /// \param length
  64. /// \return
  65. static uint32_t hashString(const char *key, int length) {
  66. uint32_t hash = 2166136261u;
  67. for (int i = 0; i < length; i++) {
  68. hash ^= (uint8_t) key[i];
  69. hash *= 16777619;
  70. }
  71. return hash;
  72. }