Guest User

Untitled

a guest
Jul 15th, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.19 KB | None | 0 0
  1. MINKEY = -1
  2. EOO = 0
  3. NUMBER = 1
  4. STRING = 2
  5. OBJECT = 3
  6. ARRAY = 4
  7. BINARY = 5
  8. UNDEFINED = 6
  9. OID = 7
  10. BOOLEAN = 8
  11. DATE = 9
  12. NULL = 10
  13. REGEX = 11
  14. REF = 12
  15. CODE = 13
  16. SYMBOL = 14
  17. CODE_W_SCOPE = 15
  18. NUMBER_INT = 16
  19. TIMESTAMP = 17
  20. NUMBER_LONG = 18
  21. MAXKEY = 127
  22.  
  23.  
  24. def bson_type(o)
  25. case o
  26. when nil
  27. NULL
  28. when Integer
  29. NUMBER_INT
  30. when Float
  31. NUMBER
  32. when ByteBuffer
  33. BINARY
  34. when Code
  35. CODE_W_SCOPE
  36. when String
  37. STRING
  38. when Array
  39. ARRAY
  40. when Regexp
  41. REGEX
  42. when ObjectId
  43. OID
  44. when DBRef
  45. REF
  46. when true, false
  47. BOOLEAN
  48. when Time
  49. DATE
  50. when Hash
  51. OBJECT
  52. when Symbol
  53. SYMBOL
  54. when MaxKey
  55. MAXKEY
  56. when MinKey
  57. MINKEY
  58. when Numeric
  59. raise Exception, "Cannot serialize the Numeric type #{o.class} as BSON; only Fixum, Bignum, and Float are supported."
  60. when Date, DateTime
  61. raise Exception, "#{o.class} is not currently supported; " +
  62. "use a UTC Time instance instead."
  63. else
  64. if defined?(ActiveSupport::TimeWithZone) && o.is_a?(ActiveSupport::TimeWithZone)
  65. raise Exception, "ActiveSupport::TimeWithZone is not currently supported; " +
  66. "use a UTC Time instance instead."
  67. else
  68. raise Exception, "Cannot serialize #{o.class} as a BSON type; it either isn't supported or won't translate to BSON."
  69. end
  70. end
  71. end
  72.  
  73.  
  74. def serialize_number_element(val, type)
  75. if type == NUMBER
  76. puts "#{val} is type #{type} and written as a double"
  77. else
  78. if val > 2**64 / 2 - 1 or val < -2**64 / 2
  79. raise RangeError.new("MongoDB can only handle 8-byte ints")
  80. end
  81. if val > 2**32 / 2 - 1 or val < -2**32 / 2
  82. puts "#{val} is type #{type} and written as a int64"
  83. else
  84. puts "#{val} is type #{type} and written as a int32"
  85. end
  86. end
  87. end
  88.  
  89. a = [1, 32767, 2**32 / 2 -1, 2**32, 2**33, 2**63 / 2, 2**63]
  90.  
  91. a.each do |number|
  92. puts "type #{bson_type(number)}"
  93. serialize_number_element(number, bson_type(number))
  94. end
Add Comment
Please, Sign In to add comment