-
Notifications
You must be signed in to change notification settings - Fork 309
/
number.py
359 lines (259 loc) · 11.6 KB
/
number.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
#
# spyne - Copyright (C) Spyne contributors.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
#
import math
import decimal
import platform
from spyne.model import SimpleModel
from spyne.model.primitive import NATIVE_MAP
from spyne.util import six
from spyne.util import memoize
class Decimal(SimpleModel):
"""The primitive that corresponds to the native python Decimal.
This is also the base class for denoting numbers.
Note that it is your responsibility to make sure that the scale and
precision constraints set in this type is consistent with the values in the
context of the decimal package. See the :func:`decimal.getcontext`
documentation for more information.
"""
__type_name__ = 'decimal'
Value = decimal.Decimal
# contrary to popular belief, Decimal hates float.
class Attributes(SimpleModel.Attributes):
"""Customizable attributes of the :class:`spyne.model.primitive.Decimal`
type."""
gt = decimal.Decimal('-inf') # minExclusive
"""The value should be greater than this number."""
ge = decimal.Decimal('-inf') # minInclusive
"""The value should be greater than or equal to this number."""
lt = decimal.Decimal('inf') # maxExclusive
"""The value should be lower than this number."""
le = decimal.Decimal('inf') # maxInclusive
"""The value should be lower than or equal to this number."""
max_str_len = 1024
"""The maximum length of string to be attempted to convert to number."""
format = None
"""A regular python string formatting string. See here:
http://docs.python.org/2/library/stdtypes.html#string-formatting"""
str_format = None
"""A regular python string formatting string used by invoking its
``format()`` function. See here:
http://docs.python.org/2/library/string.html#format-string-syntax"""
pattern = None
"""A regular expression that matches the whole field. See here for more
info: http://www.regular-expressions.info/xml.html"""
total_digits = decimal.Decimal('inf')
"""Maximum number of digits."""
fraction_digits = decimal.Decimal('inf')
"""Maximum number of digits after the decimal separator."""
min_bound = None
"""Hardware limit that determines the lowest value this type can
store."""
max_bound = None
"""Hardware limit that determines the highest value this type can
store."""
def __new__(cls, *args, **kwargs):
assert len(args) <= 2
if len(args) >= 1 and args[0] is not None:
kwargs['total_digits'] = args[0]
kwargs['fraction_digits'] = 0
if len(args) == 2 and args[1] is not None:
kwargs['fraction_digits'] = args[1]
assert args[0] > 0, "'total_digits' must be positive."
assert args[1] <= args[0], "'total_digits' must be greater than" \
" or equal to 'fraction_digits'." \
" %r ! <= %r" % (args[1], args[0])
# + 1 for decimal separator
# + 1 for negative sign
msl = kwargs.get('max_str_len', None)
if msl is None:
kwargs['max_str_len'] = (cls.Attributes.total_digits +
cls.Attributes.fraction_digits + 2)
else:
kwargs['max_str_len'] = msl
retval = SimpleModel.__new__(cls, ** kwargs)
return retval
@staticmethod
def is_default(cls):
return ( SimpleModel.is_default(cls)
and cls.Attributes.gt == Decimal.Attributes.gt
and cls.Attributes.ge == Decimal.Attributes.ge
and cls.Attributes.lt == Decimal.Attributes.lt
and cls.Attributes.le == Decimal.Attributes.le
and cls.Attributes.total_digits ==
Decimal.Attributes.total_digits
and cls.Attributes.fraction_digits ==
Decimal.Attributes.fraction_digits
)
@staticmethod
def validate_string(cls, value):
return SimpleModel.validate_string(cls, value) and (
value is None or (len(value) <= cls.Attributes.max_str_len)
)
@staticmethod
def validate_native(cls, value):
return SimpleModel.validate_native(cls, value) and (
value is None or (
value > cls.Attributes.gt and
value >= cls.Attributes.ge and
value < cls.Attributes.lt and
value <= cls.Attributes.le
))
class Double(Decimal):
"""This is serialized as the python ``float``. So this type comes with its
gotchas. Unless you really know what you're doing, you should use a
:class:`Decimal` with a pre-defined number of integer and decimal digits.
.. NOTE::
This class is not compatible with :class:`spyne.model.Decimal`. You can
get strange results if you're using a `decimal.Decimal` instance for a
field denoted as `Double` or `Float` and vice versa. Make sure you only
return instances of types compatible with designated types.
"""
__type_name__ = 'double'
Value = float
if platform.python_version_tuple()[:2] == ('2','6'):
class Attributes(Decimal.Attributes):
"""Customizable attributes of the :class:`spyne.model.primitive.Double`
type. This class is only here for Python 2.6: See this bug report
for more info: http://bugs.python.org/issue2531
"""
gt = float('-inf') # minExclusive
"""The value should be greater than this number."""
ge = float('-inf') # minInclusive
"""The value should be greater than or equal to this number."""
lt = float('inf') # maxExclusive
"""The value should be lower than this number."""
le = float('inf') # maxInclusive
"""The value should be lower than or equal to this number."""
@staticmethod
def is_default(cls):
return ( SimpleModel.is_default(cls)
and cls.Attributes.gt == Double.Attributes.gt
and cls.Attributes.ge == Double.Attributes.ge
and cls.Attributes.lt == Double.Attributes.lt
and cls.Attributes.le == Double.Attributes.le
)
class Float(Double):
"""Synonym for Double (as far as python side of things are concerned).
It's here for compatibility reasons."""
__type_name__ = 'float'
class Integer(Decimal):
"""The arbitrary-size signed integer."""
__type_name__ = 'integer'
Value = int
@staticmethod
def validate_native(cls, value):
return ( Decimal.validate_native(cls, value)
and (value is None or int(value) == value)
)
class UnsignedInteger(Integer):
"""The arbitrary-size unsigned integer, also known as nonNegativeInteger."""
__type_name__ = 'nonNegativeInteger'
@staticmethod
def validate_native(cls, value):
return ( Integer.validate_native(cls, value)
and (value is None or value >= 0)
)
NonNegativeInteger = UnsignedInteger
"""The arbitrary-size unsigned integer, alias for UnsignedInteger."""
class PositiveInteger(NonNegativeInteger):
"""The arbitrary-size positive integer (natural number)."""
__type_name__ = 'positiveInteger'
@staticmethod
def validate_native(cls, value):
return (Integer.validate_native(cls, value)
and (value is None or value > 0))
def TBoundedInteger(num_bits, type_name):
_min_b = -(0x8<<(num_bits-4)) # 0x8 is 4 bits.
_max_b = (0x8<<(num_bits-4)) - 1 # -1? c'est la vie
class _BoundedInteger(Integer):
__type_name__ = type_name
class Attributes(Integer.Attributes):
max_str_len = math.ceil(math.log(2**num_bits, 10))
min_bound = _min_b
max_bound = _max_b
@staticmethod
def validate_native(cls, value):
return (
Integer.validate_native(cls, value)
and (value is None or (_min_b <= value <= _max_b))
)
return _BoundedInteger
def TBoundedUnsignedInteger(num_bits, type_name):
_min_b = 0
_max_b = 2 ** num_bits - 1 # -1? c'est la vie ;)
class _BoundedUnsignedInteger(UnsignedInteger):
__type_name__ = type_name
class Attributes(UnsignedInteger.Attributes):
max_str_len = math.ceil(math.log(2**num_bits, 10))
min_bound = _min_b
max_bound = _max_b
@staticmethod
def validate_native(cls, value):
return (
UnsignedInteger.validate_native(cls, value)
and (value is None or (_min_b <= value < _max_b))
)
return _BoundedUnsignedInteger
Integer64 = TBoundedInteger(64, 'long')
"""The 64-bit signed integer, also known as ``long``."""
Long = Integer64
"""The 64-bit signed integer, alias for :class:`Integer64`."""
Integer32 = TBoundedInteger(32, 'int')
"""The 64-bit signed integer, also known as ``int``."""
Int = Integer32
"""The 32-bit signed integer, alias for :class:`Integer32`."""
Integer16 = TBoundedInteger(16, 'short')
"""The 16-bit signed integer, also known as ``short``."""
Short = Integer16
"""The 16-bit signed integer, alias for :class:`Integer16`."""
Integer8 = TBoundedInteger(8, 'byte')
"""The 8-bit signed integer, also known as ``byte``."""
Byte = Integer8
"""The 8-bit signed integer, alias for :class:`Integer8`."""
UnsignedInteger64 = TBoundedUnsignedInteger(64, 'unsignedLong')
"""The 64-bit unsigned integer, also known as ``unsignedLong``."""
UnsignedLong = UnsignedInteger64
"""The 64-bit unsigned integer, alias for :class:`UnsignedInteger64`."""
UnsignedInteger32 = TBoundedUnsignedInteger(32, 'unsignedInt')
"""The 64-bit unsigned integer, also known as ``unsignedInt``."""
UnsignedInt = UnsignedInteger32
"""The 32-bit unsigned integer, alias for :class:`UnsignedInteger32`."""
UnsignedInteger16 = TBoundedUnsignedInteger(16, 'unsignedShort')
"""The 16-bit unsigned integer, also known as ``unsignedShort``."""
UnsignedShort = UnsignedInteger16
"""The 16-bit unsigned integer, alias for :class:`UnsignedInteger16`."""
UnsignedInteger8 = TBoundedUnsignedInteger(8, 'unsignedByte')
"""The 8-bit unsigned integer, also known as ``unsignedByte``."""
UnsignedByte = UnsignedInteger8
"""The 8-bit unsigned integer, alias for :class:`UnsignedInteger8`."""
NATIVE_MAP.update({
float: Double,
decimal.Decimal: Decimal,
})
if not six.PY2:
NATIVE_MAP.update({
int: Integer,
})
else:
NATIVE_MAP.update({
long: Integer,
})
if isinstance(0x80000000, long): # 32-bit architecture
NATIVE_MAP[int] = Integer32
else: # not 32-bit (so most probably 64-bit) architecture
NATIVE_MAP[int] = Integer64