Package proton :: Module _common
[frames] | no frames]

Source Code for Module proton._common

 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   
21  # 
22  # Hacks to provide Python2 <---> Python3 compatibility 
23  # 
24  # The results are 
25  # |       |long|unicode| 
26  # |python2|long|unicode| 
27  # |python3| int|    str| 
28  try: 
29      long() 
30  except NameError: 
31      long = int 
32  try: 
33      unicode() 
34  except NameError: 
35      unicode = str 
36   
37   
38 -def isinteger(value):
39 return isinstance(value, (int, long))
40 41
42 -def isstring(value):
43 return isinstance(value, (str, unicode))
44 45
46 -class Constant(object):
47
48 - def __init__(self, name):
49 self.name = name
50
51 - def __repr__(self):
52 return self.name
53 54
55 -def secs2millis(secs):
56 return long(secs * 1000)
57 58
59 -def millis2secs(millis):
60 return float(millis) / 1000.0
61 62
63 -def unicode2utf8(string):
64 """Some Proton APIs expect a null terminated string. Convert python text 65 types to UTF8 to avoid zero bytes introduced by other multi-byte encodings. 66 This method will throw if the string cannot be converted. 67 """ 68 if string is None: 69 return None 70 elif isinstance(string, str): 71 # Must be py2 or py3 str 72 # The swig binding converts py3 str -> utf8 char* and back sutomatically 73 return string 74 elif isinstance(string, unicode): 75 # This must be python2 unicode as we already detected py3 str above 76 return string.encode('utf-8') 77 # Anything else illegal - specifically python3 bytes 78 raise TypeError("Unrecognized string type: %r (%s)" % (string, type(string)))
79
80 -def utf82unicode(string):
81 """Convert C strings returned from proton-c into python unicode""" 82 if string is None: 83 return None 84 elif isinstance(string, unicode): 85 # py2 unicode, py3 str (via hack definition) 86 return string 87 elif isinstance(string, bytes): 88 # py2 str (via hack definition), py3 bytes 89 return string.decode('utf8') 90 raise TypeError("Unrecognized string type")
91