field_struct-protobuf 1.0.0.pre1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 39ab88febfcc3bb4b10aee1f58af0a03558236a27baf0057ae1de8e6ddf97686
4
+ data.tar.gz: 26d44fdb19832898643ad328b55aa4426d70671b1c40346b80d081407c66d653
5
+ SHA512:
6
+ metadata.gz: 1b3e77ab3c5dba9b3863f087c9b3d02965995ab33d77fb92cc12c9726b98555a1c1353c3b0135eca03be66d80170dc10bb638e019be7bdcf7cf794c473136897
7
+ data.tar.gz: fed883caab65c198d457cc9d1b06c31cd57ee309261ee02d8b695188980537c4c7d66d3933f3c346b5e444aaa257b00d8393d2d63756add319ff8ae64c3aafee
data/CHANGELOG.md ADDED
@@ -0,0 +1,26 @@
1
+ # Changelog
2
+
3
+ ## [Unreleased]
4
+
5
+ ### Added
6
+
7
+ - Requiring the adapter registers `proto:` with `FieldStruct.register_option`, so field_struct accepts the key and
8
+ refuses a non-Hash value when the field is declared.
9
+ - `:hash, of: X` maps to `map<string, X>`, encoded and decoded with String keys. Array and map values are refused,
10
+ since proto3 has no repeated or map values, and a `nil` value is refused on encode.
11
+
12
+ ### Fixed
13
+
14
+ - Refusals say what to do: an unusable field number names the allowed range, and a union says to split it into one
15
+ field per member type or declare it `:value`.
16
+ - `proto:` refuses a key other than `number:`, with a did-you-mean when the key is close.
17
+
18
+ ## 1.0.0.pre1
19
+
20
+ - Preview release: Protocol Buffers for field_struct classes, with no `protoc` step.
21
+ - `FieldStruct::Protobuf.proto` and `file_descriptor`: the `.proto` text and descriptor of a class (proto3, explicit presence for
22
+ scalars, one file per class), equivalent to what `protoc` compiles from the text.
23
+ - `message_class`, `to_message`, `from_message`, `encode`, `decode`: runtime messages registered with `google-protobuf`, binary
24
+ round trips with `Timestamp` and `Value` support, and `zone:` restored on decode.
25
+ - Field numbers are declared with `proto: {number: n}` and never inferred; anything without an exact mapping raises
26
+ `ArgumentError` naming the class and field.
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Adrian Madrid
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,147 @@
1
+ # field_struct-protobuf
2
+
3
+ > Preview: `1.0.0.pre1`. The API is settled, but nothing here has had a release yet.
4
+
5
+ Protocol Buffers for [field_struct](../../gems/field_struct) classes, and no `protoc` run to set up. From one class you can
6
+ print `.proto` source for other teams, get a message class registered with `google-protobuf`, and move instances between
7
+ structs, messages and wire bytes.
8
+
9
+ Field numbers are yours: every field says `proto: {number: n}`. Numbering by declaration order would make reordering a silent
10
+ wire-format break, so the gem never guesses. Anything without an exact mapping (a union, an array of arrays, a custom type)
11
+ raises `ArgumentError` naming the class and field, never a lossy default. It does not validate (`format:`, `in:`), and it
12
+ builds proto3 only: no `oneof`, enums, services or options. Requiring the adapter registers `proto:` with
13
+ `FieldStruct.register_option`, so require it before the classes that number their fields. An unknown key inside `proto:`
14
+ raises when the message is built, with a did-you-mean: `proto: has no key numbr: (did you mean number:?)`.
15
+
16
+ ## Install
17
+
18
+ ```ruby
19
+ gem 'field_struct-protobuf'
20
+ ```
21
+
22
+ ```ruby
23
+ require 'field_struct/protobuf'
24
+ ```
25
+
26
+ ## Quick start
27
+
28
+ ```ruby run
29
+ require 'field_struct/protobuf'
30
+
31
+ module Velo
32
+ class Bike < FieldStruct::Base
33
+ required :id, :uuid, proto: {number: 1}
34
+ required :fare, :big_decimal, round: 2, proto: {number: 2}
35
+ required :started, :time, zone: 'America/Denver', proto: {number: 3}
36
+ required :grade, :symbol, enum: %i[standard electric], proto: {number: 4}
37
+ optional :labels, :array, of: :string, proto: {number: 5}
38
+ end
39
+ end
40
+
41
+ bike = Velo::Bike.new(id: '3f6f2c3e-1111-4222-8333-444455556666', fare: '19.9',
42
+ started: Time.utc(2026, 10, 27, 15, 30), grade: :electric, labels: %w[commuter])
43
+
44
+ bytes = FieldStruct::Protobuf.encode(bike)
45
+ bytes.encoding # => #<Encoding:BINARY (ASCII-8BIT)>
46
+ FieldStruct::Protobuf.decode(Velo::Bike, bytes) == bike # => true
47
+ FieldStruct::Protobuf.decode(Velo::Bike, bytes).started.utc_offset # => -21600
48
+ ```
49
+
50
+ ## The `.proto` text
51
+
52
+ `proto` prints the file for one class. The text is printed from the descriptor that gets registered, so the two cannot
53
+ disagree; compiling it with `protoc` gives an equivalent descriptor.
54
+
55
+ ```ruby run
56
+ require 'field_struct/protobuf'
57
+
58
+ module Velo
59
+ class Station < FieldStruct::Base
60
+ required :district, :string, proto: {number: 1}
61
+ optional :dock, :string, proto: {number: 2}
62
+ end
63
+ end
64
+
65
+ print FieldStruct::Protobuf.proto(Velo::Station)
66
+ FieldStruct::Protobuf.proto(Velo::Station).lines.last(4).join # => "message Station {\n optional string district = 1;\n optional string dock = 2;\n}\n"
67
+ FieldStruct::Protobuf.file_name(Velo::Station) # => "field_struct/velo/station.proto"
68
+ FieldStruct::Protobuf.full_name(Velo::Station) # => ".velo.Station"
69
+ FieldStruct::Protobuf.message_name(Velo::Station) # => "Station"
70
+ FieldStruct::Protobuf.file_descriptor(Velo::Station).name # => "field_struct/velo/station.proto"
71
+ ```
72
+
73
+ It prints:
74
+
75
+ ```proto
76
+ // field_struct/velo/station.proto: generated by field_struct-protobuf from Velo::Station.
77
+ // Field numbers come from each field's proto: {number:} option.
78
+
79
+ syntax = "proto3";
80
+
81
+ package velo;
82
+
83
+ message Station {
84
+ optional string district = 1;
85
+ optional string dock = 2;
86
+ }
87
+ ```
88
+
89
+ One file per class, one message per file. A struct's file imports the files of the structs it refers to; a struct may refer to
90
+ itself, but two structs may not refer to each other.
91
+
92
+ ## Type mapping
93
+
94
+ | FieldStruct type | Protobuf |
95
+ |---|---|
96
+ | `:binary` | `bytes` |
97
+ | `:string`, `:immutable_string`, `:uuid`, `:email`, `:url`, `:symbol` | `string` |
98
+ | `:big_decimal`, `:decimal` | `string` (exact: `19.9`) |
99
+ | `:date` | `string` (`2026-11-01`) |
100
+ | `:boolean` | `bool` |
101
+ | `:integer` | `int64` |
102
+ | `:float` | `double` |
103
+ | `:time`, `:datetime` | `.google.protobuf.Timestamp` (the `zone:` offset is restored on decode) |
104
+ | `:value` | `.google.protobuf.Value` (numbers come back as Floats) |
105
+ | a struct class | its message |
106
+ | `:array, of: X` | `repeated` X |
107
+ | `:hash, of: X` | `map<string, X>`; X can't be an array or a map, and a `nil` value is refused on encode |
108
+
109
+ Every singular scalar is `optional` (explicit presence), so an unset field reads back `nil`, not `0` or `""`. An unset
110
+ `:array` reads back `[]` and an unset `:hash` reads back `{}`: empty and unset are the same on the wire.
111
+
112
+ ## Messages
113
+
114
+ `message_class` builds the class's message once and registers it with `google-protobuf`'s generated pool; `to_message` and
115
+ `from_message` convert one instance.
116
+
117
+ ```ruby run
118
+ require 'field_struct/protobuf'
119
+
120
+ module Velo
121
+ class Station < FieldStruct::Base
122
+ required :district, :string, proto: {number: 1}
123
+ optional :dock, :string, proto: {number: 2}
124
+ end
125
+ end
126
+
127
+ message = FieldStruct::Protobuf.to_message(Velo::Station.new(district: 'Harbor'))
128
+ message.district # => "Harbor"
129
+ message.has_dock? # => false
130
+ FieldStruct::Protobuf.message_class(Velo::Station).equal?(message.class) # => true
131
+ FieldStruct::Protobuf.from_message(Velo::Station, message) # => Velo::Station.new(district: 'Harbor')
132
+ ```
133
+
134
+ Field names in the message are the `serialize :protobuf` names, unconverted. Pass `serialization:` to use another format's
135
+ names.
136
+
137
+ ## Limits
138
+
139
+ - Registration is permanent and per process. Changing a class's fields after its message was built is not noticed (the stale
140
+ message rejects the new field); code reloading needs a restart.
141
+ - A class registers with one `serialization:` only; asking for a second raises.
142
+ - `decode` lets `Google::Protobuf::ParseError` through for malformed bytes.
143
+ - Integers past 64 bits raise `RangeError`.
144
+
145
+ ## Docs
146
+
147
+ The guide on the docs site, with every example run in CI: https://gliders-rb.github.io/adapters/protobuf/
@@ -0,0 +1,44 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FieldStruct
4
+ module Protobuf
5
+ # Argument checking shared by the public functions (section 4).
6
+ module Check
7
+ module_function
8
+
9
+ # @param klass [::Object] the class to check
10
+ # @return [::Class] the class
11
+ # @raise [::ArgumentError] when it is not a named FieldStruct::Base subclass
12
+ def call(klass)
13
+ unless klass.is_a?(::Class) && klass < FieldStruct::Base
14
+ raise ::ArgumentError, "FieldStruct::Protobuf expects a FieldStruct::Base subclass, got #{klass.inspect}"
15
+ end
16
+ return klass if FieldStruct::Introspection.named?(klass)
17
+
18
+ raise ::ArgumentError,
19
+ 'FieldStruct::Protobuf needs a named class (assign it to a constant): its message and package are named after it'
20
+ end
21
+
22
+ # @param bytes [::Object]
23
+ # @return [::String] the bytes
24
+ # @raise [::ArgumentError] when they are not a String
25
+ def bytes!(bytes)
26
+ return bytes if bytes.is_a?(::String)
27
+
28
+ raise ::ArgumentError, "FieldStruct::Protobuf.decode expects the bytes as a String, got #{bytes.class}"
29
+ end
30
+
31
+ # @param klass [::Class] the struct class
32
+ # @param message [::Object] what was given as a message
33
+ # @param expected [::Class] the registered message class of +klass+
34
+ # @return [::Object] the message
35
+ # @raise [::ArgumentError] when it is not an instance of +expected+
36
+ def message!(klass, message, expected)
37
+ return message if message.instance_of?(expected)
38
+
39
+ got = message.class.respond_to?(:descriptor) ? message.class.descriptor.name : message.class
40
+ raise ::ArgumentError, "FieldStruct::Protobuf.from_message(#{klass}) expects a #{klass} message, got #{got}"
41
+ end
42
+ end
43
+ end
44
+ end
@@ -0,0 +1,53 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FieldStruct
4
+ module Protobuf
5
+ # Turns a message instance into a struct (PB-B51..B53).
6
+ class Decoder
7
+ # @param serialization [::Symbol]
8
+ def initialize(serialization)
9
+ @serialization = serialization
10
+ end
11
+
12
+ # @param klass [::Class<FieldStruct::Base>] a checked struct class
13
+ # @param message [::Object] a message instance of the class's message
14
+ # @return [FieldStruct::Base]
15
+ def call(klass, message)
16
+ descriptor = message.class.descriptor
17
+ attrs = {}
18
+ Properties.for(klass, @serialization).each do |property|
19
+ attrs[property.field.name] = property_value(property, descriptor.lookup(property.key), message)
20
+ end
21
+ klass.new(attrs)
22
+ end
23
+
24
+ private
25
+
26
+ def property_value(property, field, message)
27
+ node = property.node
28
+ return field.get(message).map { |item| item_value(node.element, item) } if node.is_a?(Introspection::ArrayNode)
29
+ return map_value(node.element, field.get(message)) if node.is_a?(Introspection::MapNode)
30
+ return nil unless field.has?(message)
31
+
32
+ item_value(node, field.get(message))
33
+ end
34
+
35
+ # Google::Protobuf::Map#to_h turns message values into Hashes, so the entries are walked one by one.
36
+ def map_value(node, map)
37
+ result = {}
38
+ map.each { |name, item| result[name] = item_value(node, item) }
39
+ result
40
+ end
41
+
42
+ def item_value(node, item)
43
+ return call(node.klass, item) if node.is_a?(Introspection::StructNode)
44
+
45
+ case node.type
46
+ when Types::Time, Types::DateTime then Zone.apply(::Time.at(item.seconds, item.nanos, :nsec, in: 'UTC'), node.options[:zone])
47
+ when Types::Value then item.to_ruby(true)
48
+ else item
49
+ end
50
+ end
51
+ end
52
+ end
53
+ end
@@ -0,0 +1,135 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FieldStruct
4
+ module Protobuf
5
+ # Builds the +FileDescriptorProto+ of one struct class (PB-B5..B9).
6
+ class DescriptorBuilder
7
+ # @param klass [::Class<FieldStruct::Base>] a checked, named struct class
8
+ # @param serialization [::Symbol] the +serialize+ format that names the fields
9
+ def initialize(klass, serialization)
10
+ @klass = klass
11
+ @serialization = serialization
12
+ @oneofs = []
13
+ @imports = []
14
+ @entries = []
15
+ end
16
+
17
+ # @return [::Object] a +Google::Protobuf::FileDescriptorProto+
18
+ # @raise [::ArgumentError] for a bad number or name, or a field with no exact mapping
19
+ def call
20
+ properties = Introspection.properties(@klass, serialization: @serialization)
21
+ numbers = Numbers.call(@klass, properties)
22
+ properties.each { |property| field_name!(property.key) }
23
+ unique_names!(properties)
24
+ fields = properties.map { |property| field(property, numbers.fetch(property.key)) }
25
+ message = Google::Protobuf::DescriptorProto.new(name: Names.message_name(@klass), field: fields, oneof_decl: @oneofs,
26
+ nested_type: @entries)
27
+ Google::Protobuf::FileDescriptorProto.new(
28
+ name: Names.file_name(@klass), package: Names.package(@klass), syntax: 'proto3', dependency: @imports, message_type: [message]
29
+ )
30
+ end
31
+
32
+ private
33
+
34
+ NAME = /\A[A-Za-z_][A-Za-z0-9_]*\z/
35
+ # How to get past a union refusal (PB-B9).
36
+ UNION_WAY_OUT = '; split it into one field per member type, or declare it :value (a google.protobuf.Value)'
37
+ private_constant :NAME, :UNION_WAY_OUT
38
+
39
+ def field_name!(key)
40
+ return if NAME.match?(key)
41
+
42
+ raise ::ArgumentError, "#{@klass}: #{key.inspect} isn't a protobuf field name; " \
43
+ "rename it with `serialize #{@serialization.inspect}, field: \"name\"`"
44
+ end
45
+
46
+ def unique_names!(properties)
47
+ clashes = properties.group_by(&:key).select { |_, group| group.size > 1 }
48
+ return if clashes.empty?
49
+
50
+ text = clashes.map do |key, group|
51
+ "fields #{group.map do |p|
52
+ p.field.name
53
+ end.join(', ')} are both named #{key.inspect} in the message"
54
+ end
55
+ raise ::ArgumentError, "#{@klass}: #{text.join('; ')}"
56
+ end
57
+
58
+ def field(property, number)
59
+ node = property.node
60
+ return map_field(property, number) if node.is_a?(Introspection::MapNode)
61
+
62
+ repeated = node.is_a?(Introspection::ArrayNode)
63
+ type, type_name = repeated ? element_type(property) : scalar_type(node, property.field)
64
+ attrs = { name: property.key, number: number, type: type, label: repeated ? :LABEL_REPEATED : :LABEL_OPTIONAL }
65
+ attrs[:type_name] = type_name if type_name
66
+ attrs.merge!(explicit_presence(property.key)) unless repeated || type_name
67
+ Google::Protobuf::FieldDescriptorProto.new(**attrs)
68
+ end
69
+
70
+ # A +:hash+ field: a repeated entry message, as protoc writes +map<string, T>+ (PB-B7a).
71
+ def map_field(property, number)
72
+ entry = "#{property.key.split('_').map { |part| part[0] ? part[0].upcase + part[1..] : part }.join}Entry"
73
+ type, type_name = map_value_type(property)
74
+ value = { name: 'value', number: 2, type: type, label: :LABEL_OPTIONAL }
75
+ value[:type_name] = type_name if type_name
76
+ @entries << Google::Protobuf::DescriptorProto.new(
77
+ name: entry, options: Google::Protobuf::MessageOptions.new(map_entry: true),
78
+ field: [Google::Protobuf::FieldDescriptorProto.new(name: 'key', number: 1, type: :TYPE_STRING, label: :LABEL_OPTIONAL),
79
+ Google::Protobuf::FieldDescriptorProto.new(**value)]
80
+ )
81
+ Google::Protobuf::FieldDescriptorProto.new(name: property.key, number: number, type: :TYPE_MESSAGE, label: :LABEL_REPEATED,
82
+ type_name: "#{Names.full_name(@klass)}.#{entry}")
83
+ end
84
+
85
+ def map_value_type(property)
86
+ element = property.node.element
87
+ return refuse(property.field, 'a map of unions', UNION_WAY_OUT) if element.nil?
88
+ if element.is_a?(Introspection::ArrayNode) || element.is_a?(Introspection::MapNode)
89
+ return refuse(property.field, "a map of arrays or maps (protobuf map values can't be repeated or maps)")
90
+ end
91
+
92
+ scalar_type(element, property.field)
93
+ end
94
+
95
+ def explicit_presence(key)
96
+ @oneofs << Google::Protobuf::OneofDescriptorProto.new(name: "_#{key}")
97
+ { proto3_optional: true, oneof_index: @oneofs.size - 1 }
98
+ end
99
+
100
+ def element_type(property)
101
+ element = property.node.element
102
+ return refuse(property.field, 'an array of unions', UNION_WAY_OUT) if element.nil?
103
+ return refuse(property.field, 'an array of arrays (protobuf has no repeated repeated)') if element.is_a?(Introspection::ArrayNode)
104
+
105
+ scalar_type(element, property.field)
106
+ end
107
+
108
+ # @return [Array(Symbol, String)] the protobuf type and, for a message, its full name
109
+ def scalar_type(node, field)
110
+ return refuse(field, 'a union', UNION_WAY_OUT) if node.is_a?(Introspection::UnionNode)
111
+ return struct_type(node.klass, field) if node.is_a?(Introspection::StructNode)
112
+
113
+ well_known = ScalarTypes.well_known(node.type)
114
+ return message_type(*well_known) if well_known
115
+
116
+ [ScalarTypes.type_for(node.type) || refuse(field, "a #{node.type.class} (no protobuf mapping)")]
117
+ end
118
+
119
+ def struct_type(klass, field)
120
+ refuse(field, 'an anonymous struct (assign it to a constant)') unless Introspection.named?(klass)
121
+
122
+ message_type(Names.full_name(klass), (Names.file_name(klass) unless klass == @klass))
123
+ end
124
+
125
+ def message_type(type_name, import)
126
+ @imports << import unless import.nil? || @imports.include?(import)
127
+ [:TYPE_MESSAGE, type_name]
128
+ end
129
+
130
+ def refuse(field, what, way_out = nil)
131
+ raise ::ArgumentError, "#{@klass}##{field.name} is #{what}, which field_struct-protobuf can't map yet#{way_out}"
132
+ end
133
+ end
134
+ end
135
+ end
@@ -0,0 +1,65 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FieldStruct
4
+ module Protobuf
5
+ # Turns a struct into a message instance (PB-B40..B42).
6
+ class Encoder
7
+ # @param serialization [::Symbol]
8
+ def initialize(serialization)
9
+ @serialization = serialization
10
+ end
11
+
12
+ # @param struct [FieldStruct::Base] an instance of a checked struct class
13
+ # @return [::Object] a message instance
14
+ def call(struct)
15
+ klass = struct.class
16
+ hash = {}
17
+ Properties.for(klass, @serialization).each do |property|
18
+ value = struct.public_send(property.field.name)
19
+ hash[property.key] = node_value(property.node, value, property.key) unless value.nil?
20
+ end
21
+ Registry.message_class(klass, @serialization).new(hash)
22
+ end
23
+
24
+ private
25
+
26
+ def node_value(node, value, key)
27
+ case node
28
+ when Introspection::ArrayNode then value.map { |item| element(node.element, item, key) }
29
+ when Introspection::MapNode then value.to_h { |name, item| [name.to_s, entry_value(node.element, item, key)] }
30
+ when Introspection::StructNode then call(value)
31
+ else scalar(node.type, value, key)
32
+ end
33
+ end
34
+
35
+ def element(node, item, key)
36
+ raise ::ArgumentError, "#{key}: protobuf repeated fields can't hold nil" if item.nil?
37
+
38
+ node_value(node, item, key)
39
+ end
40
+
41
+ def entry_value(node, item, key)
42
+ raise ::ArgumentError, "#{key}: protobuf map values can't be nil" if item.nil?
43
+
44
+ node_value(node, item, key)
45
+ end
46
+
47
+ def scalar(type, value, key)
48
+ case type
49
+ when Types::Binary then value.b
50
+ when Types::BigDecimal then value.to_s('F')
51
+ when Types::Date then value.iso8601
52
+ when Types::Time, Types::DateTime then timestamp(value)
53
+ when Types::Value then Google::Protobuf::Value.from_ruby(JsonValue.call(value, key))
54
+ when Types::String, Types::Symbol then value.to_s
55
+ else value
56
+ end
57
+ end
58
+
59
+ def timestamp(value)
60
+ time = value.respond_to?(:to_time) ? value.to_time : value
61
+ Google::Protobuf::Timestamp.new(seconds: time.to_i, nanos: time.nsec)
62
+ end
63
+ end
64
+ end
65
+ end
@@ -0,0 +1,40 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FieldStruct
4
+ module Protobuf
5
+ # Checks and normalizes the content of a +:value+ field for +Google::Protobuf::Value.from_ruby+ (PB-B42).
6
+ module JsonValue
7
+ module_function
8
+
9
+ # @param value [::Object] what the field holds
10
+ # @param key [::String] the property key, for the error
11
+ # @return [::Object] the same JSON value with Symbol hash keys turned into Strings
12
+ # @raise [::ArgumentError] for anything that is not a JSON value
13
+ def call(value, key)
14
+ case value
15
+ when nil, true, false, ::String, ::Integer, ::Float then value
16
+ when ::Array then value.map { |item| call(item, key) }
17
+ when ::Hash then value.to_h { |name, item| [text(name, key), call(item, key)] }
18
+ else refuse(value, key)
19
+ end
20
+ end
21
+
22
+ # @param name [::Object] a hash key
23
+ # @param key [::String]
24
+ # @return [::String]
25
+ def text(name, key)
26
+ return name.to_s if name.is_a?(::String) || name.is_a?(::Symbol)
27
+
28
+ refuse(name, key)
29
+ end
30
+
31
+ # @param value [::Object]
32
+ # @param key [::String]
33
+ # @raise [::ArgumentError] always
34
+ def refuse(value, key)
35
+ raise ::ArgumentError, "#{key}: a :value field holds JSON values (Hash, Array, String, Numeric, true, false, nil); " \
36
+ "got #{value.class}"
37
+ end
38
+ end
39
+ end
40
+ end
@@ -0,0 +1,45 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FieldStruct
4
+ module Protobuf
5
+ # Package, message, file and full names of a struct class (PB-B4, section 3).
6
+ module Names
7
+ module_function
8
+
9
+ # @param word [::String] a constant name segment
10
+ # @return [::String] the segment underscored (+XMLThing+ gives +xml_thing+)
11
+ def underscore(word)
12
+ word.gsub(/(?<=[a-z\d])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/, '_').downcase
13
+ end
14
+
15
+ # @param klass [::Class]
16
+ # @return [::String] the module path underscored and joined with dots; empty for a top-level class
17
+ def package(klass)
18
+ segments_of(klass).first(segments_of(klass).size - 1).map { underscore(_1) }.join('.')
19
+ end
20
+
21
+ # @param klass [::Class]
22
+ # @return [::String] the last constant segment
23
+ def message_name(klass)
24
+ segments_of(klass).last
25
+ end
26
+
27
+ # @param klass [::Class]
28
+ # @return [::String] a leading dot, the package and the message name
29
+ def full_name(klass)
30
+ [package(klass), message_name(klass)].reject(&:empty?).join('.').prepend('.')
31
+ end
32
+
33
+ # @param klass [::Class]
34
+ # @return [::String] +field_struct/<underscored path>.proto+
35
+ def file_name(klass)
36
+ path = segments_of(klass).map { underscore(_1) }
37
+ File.join('field_struct', "#{path.join('/')}.proto")
38
+ end
39
+
40
+ def segments_of(klass)
41
+ klass.name.split('::')
42
+ end
43
+ end
44
+ end
45
+ end
@@ -0,0 +1,83 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FieldStruct
4
+ module Protobuf
5
+ # Reads and validates the +proto: {number:}+ option of every field before anything is built (PB-B1, PB-B2).
6
+ module Numbers
7
+ # The usable range of a field number.
8
+ # @return [::Range]
9
+ RANGE = (1..536_870_911)
10
+ # The range protobuf reserves for its own use.
11
+ # @return [::Range]
12
+ RESERVED = (19_000..19_999)
13
+ # The keys a +proto:+ Hash may hold (PB-B2a).
14
+ # @return [::Array<::Symbol>]
15
+ KEYS = %i[number].freeze
16
+
17
+ module_function
18
+
19
+ # @param klass [::Class<FieldStruct::Base>]
20
+ # @param properties [::Array<FieldStruct::Introspection::Property>]
21
+ # @return [::Hash{::String=>::Integer}] number by property key, in declaration order
22
+ # @raise [::ArgumentError] for an unusable, missing or duplicated number (in that order)
23
+ def call(klass, properties)
24
+ numbers = properties.to_h { |property| [property.key, read(klass, property.field)] }
25
+ missing = numbers.select { |_, number| number.nil? }.keys
26
+ unless missing.empty?
27
+ raise ::ArgumentError,
28
+ "#{klass}: give every field a protobuf field number, e.g. `proto: {number: 1}`; missing on #{missing.join(', ')}"
29
+ end
30
+
31
+ twice = numbers.values.tally.select { |_, count| count > 1 }.keys
32
+ raise ::ArgumentError, "#{klass}: field numbers #{twice.join(', ')} are used twice" unless twice.empty?
33
+
34
+ numbers
35
+ end
36
+
37
+ # @param klass [::Class]
38
+ # @param field [FieldStruct::Field]
39
+ # @return [::Integer, nil] nil when the field declares no number
40
+ def read(klass, field)
41
+ option = field.options[:proto]
42
+ return nil if option.nil?
43
+
44
+ unless option.is_a?(::Hash)
45
+ raise ::ArgumentError, "#{klass}##{field.name}: proto: takes a Hash like {number: 1}, got #{option.inspect}"
46
+ end
47
+
48
+ check_keys(klass, field, option)
49
+ number = option[:number]
50
+ return nil if number.nil?
51
+ return number if number.is_a?(::Integer) && RANGE.cover?(number) && !RESERVED.cover?(number)
52
+
53
+ raise ::ArgumentError, "#{klass}##{field.name}: #{number.inspect} isn't a usable protobuf field number; " \
54
+ "use an Integer in #{RANGE}, outside #{RESERVED}"
55
+ end
56
+
57
+ # @param klass [::Class]
58
+ # @param field [FieldStruct::Field]
59
+ # @param option [::Hash{::Object=>::Object}]
60
+ # @return [void]
61
+ # @raise [::ArgumentError] for a key other than +number:+
62
+ def check_keys(klass, field, option)
63
+ unknown = option.keys.find { |key| !KEYS.include?(key) }
64
+ return if unknown.nil?
65
+
66
+ raise ::ArgumentError, "#{klass}##{field.name}: proto: has no key #{key_label(unknown)}#{key_hint(unknown)}; " \
67
+ "it takes #{KEYS.map { |key| "#{key}:" }.join(', ')}"
68
+ end
69
+
70
+ # @param key [::Object]
71
+ # @return [::String] +number:+ for a Symbol, the inspected key otherwise
72
+ def key_label(key) = key.is_a?(::Symbol) ? "#{key}:" : key.inspect
73
+
74
+ # @param key [::Object]
75
+ # @return [::String] the did-you-mean clause; a String spelled like a known key suggests the Symbol
76
+ def key_hint(key)
77
+ return " (did you mean #{key}:?)" if !key.is_a?(::Symbol) && KEYS.include?(key.to_s.to_sym)
78
+
79
+ FieldStruct::Suggestion.clause(key, KEYS, sigil: '', suffix: ':')
80
+ end
81
+ end
82
+ end
83
+ end
@@ -0,0 +1,77 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FieldStruct
4
+ module Protobuf
5
+ # Prints the +.proto+ source of a file descriptor (PB-B20, PB-B21). The text comes from the descriptor that is
6
+ # registered, so the two cannot disagree (PB-I2).
7
+ class Printer
8
+ SCALARS = {
9
+ TYPE_STRING: 'string', TYPE_BYTES: 'bytes', TYPE_BOOL: 'bool', TYPE_INT64: 'int64', TYPE_DOUBLE: 'double'
10
+ }.freeze
11
+ private_constant :SCALARS
12
+
13
+ # @param file [::Object] a +Google::Protobuf::FileDescriptorProto+
14
+ # @param klass [::Class] the struct class the file was built from (named in the header)
15
+ def initialize(file, klass)
16
+ @file = file
17
+ @klass = klass
18
+ end
19
+
20
+ # @return [::String] the +.proto+ source, newline-terminated
21
+ def call
22
+ sections = [header, package, imports, message(@file.message_type.first)]
23
+ sections.flatten.join("\n") << "\n"
24
+ end
25
+
26
+ private
27
+
28
+ def header
29
+ [
30
+ "// #{@file.name}: generated by field_struct-protobuf from #{@klass}.",
31
+ "// Field numbers come from each field's proto: {number:} option.",
32
+ '', 'syntax = "proto3";', ''
33
+ ]
34
+ end
35
+
36
+ def package
37
+ @file.package.empty? ? [] : ["package #{@file.package};", '']
38
+ end
39
+
40
+ def imports
41
+ return [] if @file.dependency.empty?
42
+
43
+ [*@file.dependency.map { |name| %(import "#{name}";) }, '']
44
+ end
45
+
46
+ def message(message)
47
+ entries = message.nested_type.to_h { |entry| [entry.name, entry] }
48
+ body = message.field.map { |field| " #{field_line(field, entries)}" }
49
+ ["message #{message.name} {", *body, '}']
50
+ end
51
+
52
+ def field_line(field, entries)
53
+ entry = map_entry(field, entries)
54
+ return "map<string, #{type_text(entry.field[1])}> #{field.name} = #{field.number};" if entry
55
+
56
+ modifier = if field.label == :LABEL_REPEATED
57
+ 'repeated'
58
+ elsif field.proto3_optional
59
+ 'optional'
60
+ end
61
+ [modifier, type_text(field), field.name, '=', "#{field.number};"].compact.join(' ')
62
+ end
63
+
64
+ # The entry message a +map<string, T>+ field points at, or nil for any other field.
65
+ def map_entry(field, entries)
66
+ return nil unless field.label == :LABEL_REPEATED && field.type == :TYPE_MESSAGE
67
+
68
+ entry = entries[field.type_name.split('.').last]
69
+ entry if entry&.options&.map_entry
70
+ end
71
+
72
+ def type_text(field)
73
+ field.type == :TYPE_MESSAGE ? field.type_name : SCALARS.fetch(field.type)
74
+ end
75
+ end
76
+ end
77
+ end
@@ -0,0 +1,60 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FieldStruct
4
+ module Protobuf
5
+ # Property lists per (serialization, class), so a conversion does not rebuild the node tree of every field.
6
+ # An entry remembers the Field objects and the +serialize+ mapping it was read from and is dropped as soon as
7
+ # either changed (FS-B159), so a field added after registration still reaches the message and fails as before
8
+ # (PB-B31). Entries are immutable and swapped whole, so readers need no lock.
9
+ module Properties
10
+ Entry = Struct.new(:list, :fields, :mapping)
11
+ private_constant :Entry
12
+
13
+ @entries = {}
14
+
15
+ class << self
16
+ # @param klass [::Class<FieldStruct::Base>]
17
+ # @param serialization [::Symbol]
18
+ # @return [::Array<FieldStruct::Introspection::Property>] the frozen list, shared between calls
19
+ def for(klass, serialization)
20
+ table = @entries[serialization]
21
+ entry = table && table[klass]
22
+ return entry.list if entry && fresh?(entry, klass.metadata, serialization)
23
+
24
+ build(klass, serialization)
25
+ end
26
+
27
+ # @return [nil]
28
+ def clear
29
+ @entries = {}
30
+ nil
31
+ end
32
+
33
+ private
34
+
35
+ def fresh?(entry, metadata, serialization)
36
+ return false unless entry.mapping.equal?(metadata.serialization(serialization))
37
+
38
+ fields = entry.fields
39
+ index = 0
40
+ metadata.each do |field|
41
+ return false unless fields[index].equal?(field)
42
+
43
+ index += 1
44
+ end
45
+ index == fields.size
46
+ end
47
+
48
+ def build(klass, serialization)
49
+ metadata = klass.metadata
50
+ entry = Entry.new(
51
+ FieldStruct::Introspection.properties(klass, serialization: serialization).freeze,
52
+ metadata.to_a.freeze, metadata.serialization(serialization)
53
+ )
54
+ (@entries[serialization] ||= {}.compare_by_identity)[klass] = entry
55
+ entry.list
56
+ end
57
+ end
58
+ end
59
+ end
60
+ end
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FieldStruct
4
+ module Protobuf
5
+ # The struct classes a class refers to, as a field or as an array element (PB-B30).
6
+ module References
7
+ module_function
8
+
9
+ # @param klass [::Class<FieldStruct::Base>]
10
+ # @param serialization [::Symbol]
11
+ # @return [::Array<::Class>] distinct referenced classes in field order, without +klass+ itself
12
+ def call(klass, serialization)
13
+ found = []
14
+ Introspection.properties(klass, serialization: serialization).each do |property|
15
+ other = target(property.node)
16
+ found << other if other && other != klass && !found.include?(other)
17
+ end
18
+ found
19
+ end
20
+
21
+ # @param node [FieldStruct::Introspection::ScalarNode, FieldStruct::Introspection::ArrayNode, FieldStruct::Introspection::StructNode]
22
+ # @return [::Class, nil]
23
+ def target(node)
24
+ node = node.element if node.is_a?(Introspection::ArrayNode) || node.is_a?(Introspection::MapNode)
25
+ node.klass if node.is_a?(Introspection::StructNode)
26
+ end
27
+ end
28
+ end
29
+ end
@@ -0,0 +1,66 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'monitor'
4
+
5
+ module FieldStruct
6
+ module Protobuf
7
+ # The process-wide registry of message classes, keyed by +[class, serialization]+ behind one monitor (PB-B30..B32).
8
+ # Registration into google-protobuf's generated pool is permanent (PB-I7), so nothing here is ever removed.
9
+ module Registry
10
+ @lock = Monitor.new
11
+ @messages = {}
12
+ @by_serialization = {}
13
+ @serializations = {}
14
+
15
+ class << self
16
+ # The registered message class of a struct, built and registered (with the messages of every struct it refers to)
17
+ # on first use.
18
+ #
19
+ # @param klass [::Class<FieldStruct::Base>] a checked, named struct class
20
+ # @param serialization [::Symbol]
21
+ # @return [::Class] the message class
22
+ # @raise [::ArgumentError] for a bad field, a cycle or a second serialization
23
+ def message_class(klass, serialization)
24
+ known = @by_serialization[serialization]&.[](klass)
25
+ return known if known
26
+
27
+ @lock.synchronize { register(klass, serialization, []) }
28
+ end
29
+
30
+ private
31
+
32
+ def register(klass, serialization, trail)
33
+ first = @serializations[klass]
34
+ if first && first != serialization
35
+ raise ::ArgumentError, "#{klass} is already registered with serialization #{first.inspect}; " \
36
+ "it can't also be registered with #{serialization.inspect}"
37
+ end
38
+ known = @messages[[klass, serialization]]
39
+ return known if known
40
+
41
+ build(klass, serialization, trail + [klass])
42
+ end
43
+
44
+ def build(klass, serialization, trail)
45
+ file = DescriptorBuilder.new(klass, serialization).call
46
+ References.call(klass, serialization).each do |ref|
47
+ cycle!(trail, ref) if trail.include?(ref)
48
+ register(Check.call(ref), serialization, trail)
49
+ end
50
+ pool = Google::Protobuf::DescriptorPool.generated_pool
51
+ pool.add_serialized_file(Google::Protobuf::FileDescriptorProto.encode(file))
52
+ message = pool.lookup(Names.full_name(klass).delete_prefix('.')).msgclass
53
+ @serializations[klass] = serialization
54
+ (@by_serialization[serialization] ||= {}.compare_by_identity)[klass] = message
55
+ @messages[[klass, serialization]] = message
56
+ end
57
+
58
+ def cycle!(trail, repeat)
59
+ chain = (trail + [repeat]).join(' -> ')
60
+ raise ::ArgumentError, "#{chain}: structs that refer to each other would be protobuf files that import each other, " \
61
+ "which protobuf doesn't allow"
62
+ end
63
+ end
64
+ end
65
+ end
66
+ end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FieldStruct
4
+ module Protobuf
5
+ # Maps a scalar type instance to its protobuf type (PB-B5).
6
+ module ScalarTypes
7
+ # Checked in order, so a subclass wins (+Binary+ is a +String+).
8
+ MAPPING = [
9
+ [Types::Binary, :TYPE_BYTES], [Types::String, :TYPE_STRING], [Types::Symbol, :TYPE_STRING],
10
+ [Types::BigDecimal, :TYPE_STRING], [Types::Date, :TYPE_STRING], [Types::Boolean, :TYPE_BOOL],
11
+ [Types::Integer, :TYPE_INT64], [Types::Float, :TYPE_DOUBLE]
12
+ ].freeze
13
+ private_constant :MAPPING
14
+
15
+ TIMESTAMP = ['.google.protobuf.Timestamp', 'google/protobuf/timestamp.proto'].freeze
16
+ VALUE = ['.google.protobuf.Value', 'google/protobuf/struct.proto'].freeze
17
+ WELL_KNOWN = [[Types::Time, TIMESTAMP], [Types::DateTime, TIMESTAMP], [Types::Value, VALUE]].freeze
18
+ private_constant :TIMESTAMP, :VALUE, :WELL_KNOWN
19
+
20
+ module_function
21
+
22
+ # @param type [FieldStruct::Types::Base] a type instance
23
+ # @return [::Symbol, nil] the protobuf type, nil when there is no mapping
24
+ def type_for(type)
25
+ MAPPING.find { |klass, _| type.is_a?(klass) }&.last
26
+ end
27
+
28
+ # @param type [FieldStruct::Types::Base] a type instance
29
+ # @return [::Array(::String, ::String), nil] the message's full name and the file to import, nil when not a well-known type
30
+ def well_known(type)
31
+ WELL_KNOWN.find { |klass, _| type.is_a?(klass) }&.last
32
+ end
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FieldStruct
4
+ # Protocol Buffers for field_struct classes.
5
+ module Protobuf
6
+ # The gem version.
7
+ # @return [::String]
8
+ VERSION = '1.0.0.pre1'
9
+ end
10
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FieldStruct
4
+ module Protobuf
5
+ # Puts a decoded time back in the field's +zone:+ (PB-B53); a Timestamp carries no offset.
6
+ module Zone
7
+ module_function
8
+
9
+ # @param time [::Time] a UTC time
10
+ # @param zone [::Object] the field's +zone:+; anything but a String leaves the time in UTC
11
+ # @return [::Time] a new Time at the same instant
12
+ def apply(time, zone)
13
+ case zone
14
+ when ::String
15
+ return time.getutc if zone == 'UTC'
16
+ return time.getlocal(zone) unless zone.include?('/')
17
+
18
+ require 'tzinfo'
19
+ seconds = TZInfo::Timezone.get(zone).period_for_utc(time.getutc).utc_total_offset
20
+ time.getlocal(seconds)
21
+ else
22
+ time
23
+ end
24
+ end
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,133 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bigdecimal'
4
+ require 'google/protobuf'
5
+ require 'google/protobuf/descriptor_pb'
6
+ require 'google/protobuf/timestamp_pb'
7
+ require 'google/protobuf/struct_pb'
8
+ require 'google/protobuf/well_known_types'
9
+ require 'field_struct'
10
+
11
+ unless defined?(FieldStruct::Introspection)
12
+ raise LoadError, 'field_struct-protobuf needs FieldStruct::Introspection (field_struct >= 1.0.0.pre1); ' \
13
+ 'upgrade field_struct or check that its version is loaded'
14
+ end
15
+
16
+ require_relative 'protobuf/version'
17
+ require_relative 'protobuf/names'
18
+ require_relative 'protobuf/check'
19
+ require_relative 'protobuf/numbers'
20
+ require_relative 'protobuf/scalar_types'
21
+ require_relative 'protobuf/descriptor_builder'
22
+ require_relative 'protobuf/printer'
23
+ require_relative 'protobuf/references'
24
+ require_relative 'protobuf/properties'
25
+ require_relative 'protobuf/registry'
26
+ require_relative 'protobuf/zone'
27
+ require_relative 'protobuf/json_value'
28
+ require_relative 'protobuf/encoder'
29
+ require_relative 'protobuf/decoder'
30
+
31
+ # The field_struct namespace.
32
+ module FieldStruct
33
+ # Protocol Buffers support for field_struct classes: `.proto` text, runtime messages, and the binary wire format.
34
+ module Protobuf
35
+ class << self
36
+ # Describes the protobuf file for a struct class.
37
+ #
38
+ # @param klass [::Class<FieldStruct::Base>] a named +FieldStruct::Base+ subclass
39
+ # @param serialization [::Symbol] the +serialize+ format whose names become field names
40
+ # @return [::Object] a +Google::Protobuf::FileDescriptorProto+
41
+ # @raise [::ArgumentError] for a bad argument or an unmappable field
42
+ def file_descriptor(klass, serialization: :protobuf)
43
+ checked = Check.call(klass)
44
+ DescriptorBuilder.new(checked, serialization).call
45
+ end
46
+
47
+ # Prints the `.proto` text for a struct class.
48
+ #
49
+ # @param klass [::Class<FieldStruct::Base>]
50
+ # @param serialization [::Symbol]
51
+ # @return [::String]
52
+ def proto(klass, serialization: :protobuf)
53
+ descriptor = file_descriptor(klass, serialization: serialization)
54
+ Printer.new(descriptor, klass).call
55
+ end
56
+
57
+ # Looks up (building and registering it the first time) the message class for a struct class.
58
+ #
59
+ # @param klass [::Class<FieldStruct::Base>] a named +FieldStruct::Base+ subclass
60
+ # @param serialization [::Symbol] the +serialize+ format whose names become field names
61
+ # @return [::Class] a +Google::Protobuf+ message class
62
+ # @raise [::ArgumentError] for a bad argument, an unmappable field, a cycle or a second serialization
63
+ def message_class(klass, serialization: :protobuf)
64
+ Registry.message_class(Check.call(klass), serialization)
65
+ end
66
+
67
+ # Converts a struct to an instance of its message class.
68
+ #
69
+ # @param struct [FieldStruct::Base] an instance of a struct class
70
+ # @param serialization [::Symbol]
71
+ # @return [::Object] a message instance
72
+ # @raise [::ArgumentError] for a bad argument or a value that cannot be written
73
+ def to_message(struct, serialization: :protobuf)
74
+ Check.call(struct.class)
75
+ Encoder.new(serialization).call(struct)
76
+ end
77
+
78
+ # Converts a message instance back to a struct.
79
+ #
80
+ # @param klass [::Class<FieldStruct::Base>] a named +FieldStruct::Base+ subclass
81
+ # @param message [::Object] a message instance of the class's message
82
+ # @param serialization [::Symbol]
83
+ # @return [FieldStruct::Base]
84
+ def from_message(klass, message, serialization: :protobuf)
85
+ expected = message_class(klass, serialization: serialization)
86
+ Check.message!(klass, message, expected)
87
+ Decoder.new(serialization).call(klass, message)
88
+ end
89
+
90
+ # Serializes a struct to protobuf wire bytes.
91
+ #
92
+ # @param struct [FieldStruct::Base] an instance of a struct class
93
+ # @param serialization [::Symbol]
94
+ # @return [::String] ASCII-8BIT bytes
95
+ def encode(struct, serialization: :protobuf)
96
+ built = to_message(struct, serialization: serialization)
97
+ built.class.encode(built)
98
+ end
99
+
100
+ # Parses protobuf wire bytes into a struct.
101
+ #
102
+ # @param klass [::Class<FieldStruct::Base>] a named +FieldStruct::Base+ subclass
103
+ # @param bytes [::String] protobuf binary
104
+ # @param serialization [::Symbol]
105
+ # @return [FieldStruct::Base]
106
+ # @raise [::Google::Protobuf::ParseError] for malformed bytes
107
+ def decode(klass, bytes, serialization: :protobuf)
108
+ raw = Check.bytes!(bytes)
109
+ parsed = message_class(klass, serialization: serialization).decode(raw)
110
+ from_message(klass, parsed, serialization: serialization)
111
+ end
112
+
113
+ # @param klass [::Class] a named class
114
+ # @return [::String] the package; empty for a top-level class
115
+ def package(klass) = Names.package(klass)
116
+
117
+ # @param klass [::Class] a named class
118
+ # @return [::String] the message name
119
+ def message_name(klass) = Names.message_name(klass)
120
+
121
+ # @param klass [::Class] a named class
122
+ # @return [::String] the full name with a leading dot
123
+ def full_name(klass) = Names.full_name(klass)
124
+
125
+ # @param klass [::Class] a named class
126
+ # @return [::String] the file name
127
+ def file_name(klass) = Names.file_name(klass)
128
+ end
129
+ end
130
+ end
131
+
132
+ # The field option this adapter reads; registering it lets fields declare it (FS-B10a).
133
+ FieldStruct.register_option(:proto, type: Hash, owner: 'field_struct-protobuf')
@@ -0,0 +1,103 @@
1
+ # The field_struct namespace.
2
+ module FieldStruct
3
+ # Protocol Buffers for field_struct classes.
4
+ module Protobuf
5
+ VERSION: ::String
6
+
7
+ # Describes the protobuf file for a struct class.
8
+ #
9
+ # _@param_ `klass` — a named +FieldStruct::Base+ subclass
10
+ #
11
+ # _@param_ `serialization` — the +serialize+ format whose names become field names
12
+ #
13
+ # _@return_ — a +Google::Protobuf::FileDescriptorProto+
14
+ def self.file_descriptor: (singleton(FieldStruct::Base) klass, ?serialization: ::Symbol) -> ::Object
15
+
16
+ # Prints the `.proto` text for a struct class.
17
+ #
18
+ # _@param_ `klass`
19
+ #
20
+ # _@param_ `serialization`
21
+ def self.proto: (singleton(FieldStruct::Base) klass, ?serialization: ::Symbol) -> ::String
22
+
23
+ # Looks up (building and registering it the first time) the message class for a struct class.
24
+ #
25
+ # _@param_ `klass` — a named +FieldStruct::Base+ subclass
26
+ #
27
+ # _@param_ `serialization` — the +serialize+ format whose names become field names
28
+ #
29
+ # _@return_ — a +Google::Protobuf+ message class
30
+ def self.message_class: (singleton(FieldStruct::Base) klass, ?serialization: ::Symbol) -> ::Class
31
+
32
+ # Converts a struct to an instance of its message class.
33
+ #
34
+ # _@param_ `struct` — an instance of a struct class
35
+ #
36
+ # _@param_ `serialization`
37
+ #
38
+ # _@return_ — a message instance
39
+ def self.to_message: (FieldStruct::Base struct, ?serialization: ::Symbol) -> ::Object
40
+
41
+ # Converts a message instance back to a struct.
42
+ #
43
+ # _@param_ `klass` — a named +FieldStruct::Base+ subclass
44
+ #
45
+ # _@param_ `message` — a message instance of the class's message
46
+ #
47
+ # _@param_ `serialization`
48
+ def self.from_message: (singleton(FieldStruct::Base) klass, ::Object message, ?serialization: ::Symbol) -> FieldStruct::Base
49
+
50
+ # Serializes a struct to protobuf wire bytes.
51
+ #
52
+ # _@param_ `struct` — an instance of a struct class
53
+ #
54
+ # _@param_ `serialization`
55
+ #
56
+ # _@return_ — ASCII-8BIT bytes
57
+ def self.encode: (FieldStruct::Base struct, ?serialization: ::Symbol) -> ::String
58
+
59
+ # Parses protobuf wire bytes into a struct.
60
+ #
61
+ # _@param_ `klass` — a named +FieldStruct::Base+ subclass
62
+ #
63
+ # _@param_ `bytes` — protobuf binary
64
+ #
65
+ # _@param_ `serialization`
66
+ def self.decode: (singleton(FieldStruct::Base) klass, ::String bytes, ?serialization: ::Symbol) -> FieldStruct::Base
67
+
68
+ # _@param_ `klass` — a named class
69
+ #
70
+ # _@return_ — the package; empty for a top-level class
71
+ def self.package: (::Class klass) -> ::String
72
+
73
+ # _@param_ `klass` — a named class
74
+ #
75
+ # _@return_ — the message name
76
+ def self.message_name: (::Class klass) -> ::String
77
+
78
+ # _@param_ `klass` — a named class
79
+ #
80
+ # _@return_ — the full name with a leading dot
81
+ def self.full_name: (::Class klass) -> ::String
82
+
83
+ # _@param_ `klass` — a named class
84
+ #
85
+ # _@return_ — the file name
86
+ def self.file_name: (::Class klass) -> ::String
87
+
88
+ # Property lists per (serialization, class), so a conversion does not rebuild the node tree of every field.
89
+ # An entry remembers the Field objects and the +serialize+ mapping it was read from and is dropped as soon as
90
+ # either changed (FS-B159), so a field added after registration still reaches the message and fails as before
91
+ # (PB-B31). Entries are immutable and swapped whole, so readers need no lock.
92
+ module Properties
93
+ # _@param_ `klass`
94
+ #
95
+ # _@param_ `serialization`
96
+ #
97
+ # _@return_ — the frozen list, shared between calls
98
+ def self.for: (singleton(FieldStruct::Base) klass, ::Symbol serialization) -> ::Array[FieldStruct::Introspection::Property]
99
+
100
+ def self.clear: () -> void
101
+ end
102
+ end
103
+ end
metadata ADDED
@@ -0,0 +1,112 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: field_struct-protobuf
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0.pre1
5
+ platform: ruby
6
+ authors:
7
+ - Adrian Madrid
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: bigdecimal
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - ">="
17
+ - !ruby/object:Gem::Version
18
+ version: '3.1'
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - ">="
24
+ - !ruby/object:Gem::Version
25
+ version: '3.1'
26
+ - !ruby/object:Gem::Dependency
27
+ name: field_struct
28
+ requirement: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - ">="
31
+ - !ruby/object:Gem::Version
32
+ version: 1.0.0.pre1
33
+ - - "<"
34
+ - !ruby/object:Gem::Version
35
+ version: '2'
36
+ type: :runtime
37
+ prerelease: false
38
+ version_requirements: !ruby/object:Gem::Requirement
39
+ requirements:
40
+ - - ">="
41
+ - !ruby/object:Gem::Version
42
+ version: 1.0.0.pre1
43
+ - - "<"
44
+ - !ruby/object:Gem::Version
45
+ version: '2'
46
+ - !ruby/object:Gem::Dependency
47
+ name: google-protobuf
48
+ requirement: !ruby/object:Gem::Requirement
49
+ requirements:
50
+ - - "~>"
51
+ - !ruby/object:Gem::Version
52
+ version: '4.30'
53
+ type: :runtime
54
+ prerelease: false
55
+ version_requirements: !ruby/object:Gem::Requirement
56
+ requirements:
57
+ - - "~>"
58
+ - !ruby/object:Gem::Version
59
+ version: '4.30'
60
+ description: Turns a FieldStruct class into a proto3 message while the program runs,
61
+ with no protoc step. It prints the matching .proto source and moves instances between
62
+ structs, messages and protobuf bytes. You declare the field numbers.
63
+ email:
64
+ - adrian.madrid@timeworxs.com
65
+ executables: []
66
+ extensions: []
67
+ extra_rdoc_files: []
68
+ files:
69
+ - CHANGELOG.md
70
+ - LICENSE.txt
71
+ - README.md
72
+ - lib/field_struct/protobuf.rb
73
+ - lib/field_struct/protobuf/check.rb
74
+ - lib/field_struct/protobuf/decoder.rb
75
+ - lib/field_struct/protobuf/descriptor_builder.rb
76
+ - lib/field_struct/protobuf/encoder.rb
77
+ - lib/field_struct/protobuf/json_value.rb
78
+ - lib/field_struct/protobuf/names.rb
79
+ - lib/field_struct/protobuf/numbers.rb
80
+ - lib/field_struct/protobuf/printer.rb
81
+ - lib/field_struct/protobuf/properties.rb
82
+ - lib/field_struct/protobuf/references.rb
83
+ - lib/field_struct/protobuf/registry.rb
84
+ - lib/field_struct/protobuf/scalar_types.rb
85
+ - lib/field_struct/protobuf/version.rb
86
+ - lib/field_struct/protobuf/zone.rb
87
+ - sig/field_struct-protobuf.rbs
88
+ homepage: https://github.com/gliders-rb/gems
89
+ licenses:
90
+ - MIT
91
+ metadata:
92
+ source_code_uri: https://github.com/gliders-rb/gems/tree/main/adapters/field_struct-protobuf
93
+ changelog_uri: https://github.com/gliders-rb/gems/blob/main/adapters/field_struct-protobuf/CHANGELOG.md
94
+ rubygems_mfa_required: 'true'
95
+ rdoc_options: []
96
+ require_paths:
97
+ - lib
98
+ required_ruby_version: !ruby/object:Gem::Requirement
99
+ requirements:
100
+ - - ">="
101
+ - !ruby/object:Gem::Version
102
+ version: '3.3'
103
+ required_rubygems_version: !ruby/object:Gem::Requirement
104
+ requirements:
105
+ - - ">="
106
+ - !ruby/object:Gem::Version
107
+ version: '0'
108
+ requirements: []
109
+ rubygems_version: 3.6.9
110
+ specification_version: 4
111
+ summary: proto3 messages, .proto source and wire-format bytes for field_struct classes.
112
+ test_files: []