1# Copyright (C) 2021  Google LLC
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#     http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15from proto.primitives import ProtoType
16
17
18class StringyNumberRule:
19    """A marshal between certain numeric types and strings
20
21    This is a necessary hack to allow round trip conversion
22    from messages to dicts back to messages.
23
24    See https://github.com/protocolbuffers/protobuf/issues/2679
25    and
26    https://developers.google.com/protocol-buffers/docs/proto3#json
27    for more details.
28    """
29
30    def to_python(self, value, *, absent: bool = None):
31        return value
32
33    def to_proto(self, value):
34        return self._python_type(value)
35
36
37class Int64Rule(StringyNumberRule):
38    _python_type = int
39    _proto_type = ProtoType.INT64
40
41
42class UInt64Rule(StringyNumberRule):
43    _python_type = int
44    _proto_type = ProtoType.UINT64
45
46
47class SInt64Rule(StringyNumberRule):
48    _python_type = int
49    _proto_type = ProtoType.SINT64
50
51
52class Fixed64Rule(StringyNumberRule):
53    _python_type = int
54    _proto_type = ProtoType.FIXED64
55
56
57class SFixed64Rule(StringyNumberRule):
58    _python_type = int
59    _proto_type = ProtoType.SFIXED64
60
61
62STRINGY_NUMBER_RULES = [
63    Int64Rule,
64    UInt64Rule,
65    SInt64Rule,
66    Fixed64Rule,
67    SFixed64Rule,
68]
69