Debian Codegraph @

python/proton/_common.py

raw
1 #
2 # Licensed to the Apache Software Foundation (ASF) under one
3 # or more contributor license agreements. See the NOTICE file
4 # distributed with this work for additional information
5 # regarding copyright ownership. The ASF licenses this file
6 # to you under the Apache License, Version 2.0 (the
7 # "License"); you may not use this file except in compliance
8 # with the License. You may obtain a copy of the License at
9 #
10 # http://www.apache.org/licenses/LICENSE-2.0
11 #
12 # Unless required by applicable law or agreed to in writing,
13 # software distributed under the License is distributed on an
14 # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 # KIND, either express or implied. See the License for the
16 # specific language governing permissions and limitations
17 # under the License.
18 #
19
20 from typing import Optional, Union, Any
21
22
23 def isinteger(value: Any) -> bool:
24 return isinstance(value, int)
25
26
27 def isstring(value: Any) -> bool:
28 return isinstance(value, str)
29
30
31 class Constant(object):
32
33 def __init__(self, name: str) -> None:
34 self.name = name
35
36 def __repr__(self) -> str:
37 return self.name
38
39
40 def secs2millis(secs: Union[float, int]) -> int:
41 return int(secs * 1000)
42
43
44 def millis2secs(millis: int) -> float:
45 return float(millis) / 1000.0
46
47
48 def unicode2utf8(string: Optional[str]) -> Optional[str]:
49 """Some Proton APIs expect a null terminated string. Convert python text
50 types to UTF8 to avoid zero bytes introduced by other multi-byte encodings.
51 This method will throw if the string cannot be converted.
52 """
53 if string is None:
54 return None
55 elif isinstance(string, str):
56 # The swig binding converts py3 str -> utf8 char* and back automatically
57 return string
58 # Anything else illegal - specifically python3 bytes
59 raise TypeError("Unrecognized string type: %r (%s)" % (string, type(string)))
60
61
62 def utf82unicode(string: Optional[Union[str, bytes]]) -> Optional[str]:
63 """Convert C strings returned from proton-c into python unicode"""
64 if string is None:
65 return None
66 elif isinstance(string, str):
67 return string
68 elif isinstance(string, bytes):
69 return string.decode('utf8')
70 raise TypeError("Unrecognized string type")