Class: Gitlab::Utils::JsonSizeEstimator

Inherits:
Object
  • Object
show all
Defined in:
lib/gitlab/utils/json_size_estimator.rb

Overview

This class estimates the JSON blob byte size of a ruby object using as little allocations as possible. The estimation should be quite accurate when using simple objects.

Example:

Gitlab::Utils::JsonSizeEstimator.estimate([“a”, { b: 12, c: nil }])

Constant Summary collapse

ARRAY_BRACKETS_SIZE =
2
OBJECT_BRACKETS_SIZE =

{}

2
DOUBLEQUOTE_SIZE =

“”

2
COLON_SIZE =

: character size from 1

1
MINUS_SIGN_SIZE =
  • character size from -1

1
NULL_SIZE =

null

4

Class Method Summary collapse

Class Method Details

.estimate(object) ⇒ Object

Returns: integer (number of bytes)


22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/gitlab/utils/json_size_estimator.rb', line 22

def estimate(object)
  case object
  when Hash
    estimate_hash(object)
  when Array
    estimate_array(object)
  when String
    estimate_string(object)
  when Integer
    estimate_integer(object)
  when Float
    estimate_float(object)
  when DateTime, Time
    estimate_time(object)
  when NilClass
    NULL_SIZE
  else
    # might be incorrect, but #to_s is safe, #to_json might be disabled for some objects: User
    estimate_string(object.to_s)
  end
end