-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcobhan_module.rb
More file actions
80 lines (62 loc) · 2.12 KB
/
cobhan_module.rb
File metadata and controls
80 lines (62 loc) · 2.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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
73
74
75
76
77
78
79
80
# frozen_string_literal: true
module CobhanModule
module FFI
extend Cobhan
FUNCTIONS = [
[:addInt32, [:int32, :int32], :int32],
[:addInt64, [:int64, :int64], :int64],
[:addDouble, [:double, :double], :double],
[:toUpper, [:pointer, :pointer], :int32],
[:filterJson, [:pointer, :pointer, :pointer], :int32],
[:sleepTest, [:int32], :void, blocking: true],
[:base64Encode, [:pointer, :pointer], :int32]
].freeze
def self.init(lib_root_path, name)
load_library(lib_root_path, name, FUNCTIONS)
end
end
def add_int32(first, second)
FFI.addInt32(first, second)
end
def add_int64(first, second)
FFI.addInt64(first, second)
end
def add_double(first, second)
FFI.addDouble(first, second)
end
def to_upper(input)
in_buffer = FFI.string_to_cbuffer(input)
out_buffer = FFI.allocate_cbuffer(input.size)
result = FFI.toUpper(in_buffer, out_buffer)
raise 'Failed to convert toUpper' if result.negative?
FFI.cbuffer_to_string(out_buffer)
ensure
[in_buffer, out_buffer].compact.each(&:free)
end
def filter_json(json_input, disallowed_value)
json_input_buffer = FFI.string_to_cbuffer(json_input)
disallowed_value_buffer = FFI.string_to_cbuffer(disallowed_value)
json_output_buffer = FFI.allocate_cbuffer(json_input.bytesize)
result = FFI.filterJson(json_input_buffer, disallowed_value_buffer, json_output_buffer)
raise 'Failed to filter json' if result.negative?
FFI.cbuffer_to_string(json_output_buffer)
ensure
[json_input_buffer, disallowed_value_buffer, json_output_buffer].compact.each(&:free)
end
def base64_encode(input)
input_buffer = FFI.string_to_cbuffer(input)
output_buffer = FFI.allocate_cbuffer(base64_overhead(input.bytesize))
result = FFI.base64Encode(input_buffer, output_buffer)
raise 'Failed to base64 encode' if result.negative?
FFI.cbuffer_to_string(output_buffer)
ensure
[input_buffer, output_buffer].compact.each(&:free)
end
def sleep_test(seconds)
FFI.sleepTest(seconds)
end
private
def base64_overhead(size)
((4 * size / 3) + 3) & ~3
end
end