Module: TestBench::Telemetry::EventData::Serialization

Defined in:
lib/test_bench/telemetry/event_data/serialization.rb

Defined Under Namespace

Modules: Pattern

Constant Summary collapse

Error =
Class.new(RuntimeError)

Class Method Summary collapse

Class Method Details

.dump(event_data) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/test_bench/telemetry/event_data/serialization.rb', line 7

def self.dump(event_data)
  type = event_data.type.to_s
  process_id = dump_value(event_data.process_id)
  time = dump_value(event_data.time)
  data = event_data.data

  text = String.new(encoding: 'BINARY')

  text << type

  text << "\t"
  text << process_id

  text << "\t"
  text << time

  data.each do |value|
    text << "\t"
    text << dump_value(value)
  end

  text << "\r\n"
  text
end

.dump_value(value) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/test_bench/telemetry/event_data/serialization.rb', line 32

def self.dump_value(value)
  case value
  when Integer
    value.to_s
  when Time
    value.strftime('%Y-%m-%dT%H:%M:%S.%NZ')
  when NilClass
    ''
  when TrueClass, FalseClass
    value.to_s
  when String
    value.dump
  end
end

.load(text) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/test_bench/telemetry/event_data/serialization.rb', line 47

def self.load(text)
  match_data = Pattern.match(text)
  if match_data.nil?
    raise Error, "Cannot deserialize #{text.inspect}"
  end

  type = match_data['type'].to_sym
  process_id = load_value(match_data['process_id'])
  time = load_value(match_data['time_attribute'])

  event_data = EventData.new
  event_data.type = type
  event_data.process_id = process_id
  event_data.time = time
  event_data.data = []

  data_text = match_data['data']

  data_text.insert(0, "\t")
  data_text.scan(/\t([^\t]*)/) do |(value_text)|
    value = load_value(value_text)
    event_data.data << value
  end

  event_data
end

.load_value(value_text) ⇒ Object



74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# File 'lib/test_bench/telemetry/event_data/serialization.rb', line 74

def self.load_value(value_text)
  match_data = Pattern.match_value(value_text)

  if match_data['integer']
    Integer(value_text)
  elsif match_data['time']
    year = match_data['year'].to_i
    month = match_data['month'].to_i
    day = match_data['day'].to_i
    hour = match_data['hour'].to_i
    minute = match_data['minute'].to_i
    second = match_data['second'].to_i

    nanosecond = match_data['nanosecond'].to_i
    usec = Rational(nanosecond, 1_000)

    Time.utc(year, month, day, hour, minute, second, usec)
  elsif match_data['nil']
    nil
  elsif match_data['true']
    true
  elsif match_data['false']
    false
  elsif match_data['string']
    value_text.undump
  end
end