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
15
16import base64
17
18
19class BytesRule:
20 """A marshal between Python strings and protobuf bytes.
21
22 Note: this conversion is asymmetric because Python does have a bytes type.
23 It is sometimes necessary to convert proto bytes fields to strings, e.g. for
24 JSON encoding, marshalling a message to a dict. Because bytes fields can
25 represent arbitrary data, bytes fields are base64 encoded when they need to
26 be represented as strings.
27
28 It is necessary to have the conversion be bidirectional, i.e.
29 my_message == MyMessage(MyMessage.to_dict(my_message))
30
31 To accomplish this, we need to intercept assignments from strings and
32 base64 decode them back into bytes.
33 """
34
35 def to_python(self, value, *, absent: bool = None):
36 return value
37
38 def to_proto(self, value):
39 if isinstance(value, str):
40 value = value.encode("utf-8")
41 value += b"=" * (4 - len(value) % 4) # padding
42 value = base64.urlsafe_b64decode(value)
43
44 return value