blob: 2d3b6534c2044a04fee7ee5b64c1bfbedceb012a [file] [log] [blame]
Jon Wayne Parrott8713a712016-10-04 14:19:01 -07001# Copyright 2015 Google Inc.
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"""Helper functions for commonly used utilities."""
16
17import six
18
19
20def to_bytes(value, encoding='utf-8'):
21 """Converts a string value to bytes, if necessary.
22
23 Unfortunately, ``six.b`` is insufficient for this task since in
24 Python 2 because it does not modify ``unicode`` objects.
25
26 Args:
27 value (Union[str, bytes]): The value to be converted.
28 encoding (str): The encoding to use to convert unicode to bytes.
29 Defaults to "utf-8".
30
31 Returns:
32 bytes: The original value converted to bytes (if unicode) or as
33 passed in if it started out as bytes.
34
35 Raises:
36 ValueError: If the value could not be converted to bytes.
37 """
38 result = (value.encode(encoding)
39 if isinstance(value, six.text_type) else value)
40 if isinstance(result, six.binary_type):
41 return result
42 else:
43 raise ValueError('{0!r} could not be converted to bytes'.format(value))
44
45
46def from_bytes(value):
47 """Converts bytes to a string value, if necessary.
48
49 Args:
50 value (Union[str, bytes]): The value to be converted.
51
52 Returns:
53 str: The original value converted to unicode (if bytes) or as passed in
54 if it started out as unicode.
55
56 Raises:
57 ValueError: If the value could not be converted to unicode.
58 """
59 result = (value.decode('utf-8')
60 if isinstance(value, six.binary_type) else value)
61 if isinstance(result, six.text_type):
62 return result
63 else:
64 raise ValueError(
65 '{0!r} could not be converted to unicode'.format(value))