Debian Codegraph @

src/python/bytesize.py

raw symbols SCIP
1 import ctypes
2 from ctypes import POINTER, byref
3
4 from decimal import Decimal
5
6 import locale
7
8 import gettext
9 _ = lambda x: gettext.translation("libbytesize", fallback=True).gettext(x) if x != "" else ""
10
11 """
12 Python bindings for the libbytesize library and it's BSSize "class". These
13 bindings provide a real Python class :class:`Size` which wraps the libbytesize
14 functionality and provides all the features one would expect from a numeric type
15 in Python.
16
17 .. note::
18 ``None`` is treated as ``Size(0)`` in mathematical operations.
19
20 """
21
22 c_bytesize = ctypes.CDLL("libbytesize.so.1")
23
24 B = 0
25 KiB = 1
26 MiB = 2
27 GiB = 3
28 TiB = 4
29 PiB = 5
30 EiB = 6
31 ZiB = 7
32 YiB = 8
33 KB = 21
34 MB = 22
35 GB = 23
36 TB = 24
37 PB = 25
38 EB = 26
39 ZB = 27
40 YB = 28
41
42 ROUND_UP = 0
43 ROUND_DOWN = 1
44 ROUND_HALF_UP = 2
45
46 MAXUINT64 = 2**64 - 1
47
48 unit_strs = {
49 "B": B, "KiB": KiB, "MiB": MiB, "GiB": GiB, "TiB": TiB, "PiB": PiB, "EiB": EiB, "ZiB": ZiB, "YiB": YiB,
50 "KB": KB, "MB": MB, "GB": GB, "TB": TB, "PB": PB, "EB": EB, "ZB": ZB, "YB": YB,
51 }
52
53 def unit_str(unit, xlate=False):
54 for (u_str, u) in unit_strs.items():
55 if u == unit:
56 return _(u_str) if xlate else u_str
57
58 class SizeErrorStruct(ctypes.Structure):
59 _fields_ = [("code", ctypes.c_int),
60 ("msg", ctypes.c_char_p)]
61
62 class SizeError(Exception):
63 pass
64
65 class InvalidSpecError(SizeError):
66 pass
67
68 class OverflowError(SizeError):
69 pass
70
71 class ZeroDivisionError(SizeError):
72 pass
73
74 _error_code_clss = (InvalidSpecError, OverflowError, ZeroDivisionError)
75
76 def get_error(err):
77 if not err:
78 return None
79 msg = str(err.contents.msg, "utf-8")
80 ex = _error_code_clss[err.contents.code](msg)
81 c_bytesize.bs_clear_error(byref(err))
82 raise ex
83
84 class SizeStruct(ctypes.Structure):
85 @classmethod
86 def new(cls):
87 return c_bytesize.bs_size_new().contents
88
89 @classmethod
90 def new_from_bytes(cls, byts, sgn):
91 return c_bytesize.bs_size_new_from_bytes(byts, sgn).contents
92
93 @classmethod
94 def new_from_str(cls, s):
95 err = POINTER(SizeErrorStruct)()
96 s = bytes(s, "utf-8")
97 ret = c_bytesize.bs_size_new_from_str(s, byref(err))
98 get_error(err)
99 return ret.contents
100
101 @classmethod
102 def new_from_size(cls, sz):
103 return c_bytesize.bs_size_new_from_size(sz).contents
104
105 def __del__(self):
106 # XXX: For some reason c_bytesize may be None here (probably when python
107 # cleans up after itself) and loading it again doesn't work at that
108 # stage. Let's just prevent ignored exceptions from happening.
109 if c_bytesize:
110 c_bytesize.bs_size_free(self)
111
112 def get_bytes(self):
113 sgn = ctypes.c_int(0)
114 err = POINTER(SizeErrorStruct)()
115 ret = c_bytesize.bs_size_get_bytes(self, byref(sgn), byref(err))
116 get_error(err)
117 return (ret, sgn.value)
118
119 def get_bytes_str(self):
120 return str(c_bytesize.bs_size_get_bytes_str(self), "utf-8")
121
122 def add(self, sz):
123 return c_bytesize.bs_size_add(self, sz).contents
124
125 def add_bytes(self, b):
126 return c_bytesize.bs_size_add_bytes(self, b).contents
127
128 def grow(self, sz):
129 c_bytesize.bs_size_grow(self, sz)
130 return self
131
132 def grow_bytes(self, b):
133 c_bytesize.bs_size_grow_bytes(self, b)
134 return self
135
136 def sub(self, sz):
137 return c_bytesize.bs_size_sub(self, sz).contents
138
139 def sub_bytes(self, b):
140 return c_bytesize.bs_size_sub_bytes(self, b).contents
141
142 def shrink(self, sz):
143 c_bytesize.bs_size_shrink(self, sz)
144 return self
145
146 def shrink_bytes(self, b):
147 c_bytesize.bs_size_shrink_bytes(self, b)
148 return self
149
150 def cmp(self, sz, ign_sgn):
151 return c_bytesize.bs_size_cmp(self, sz, ign_sgn)
152
153 def cmp_bytes(self, b, ign_sgn):
154 return c_bytesize.bs_size_cmp_bytes(self, b, ign_sgn)
155
156 def convert_to(self, unit):
157 err = POINTER(SizeErrorStruct)()
158 ret = c_bytesize.bs_size_convert_to(self, unit, byref(err))
159 get_error(err)
160 ret = str(ret, "utf-8")
161 return ret
162
163 def div(self, sz):
164 sgn = ctypes.c_int(0)
165 err = POINTER(SizeErrorStruct)()
166 ret = c_bytesize.bs_size_div(self, sz, byref(sgn), byref(err))
167 get_error(err)
168 return (ret, sgn.value)
169
170 def div_int(self, div):
171 err = POINTER(SizeErrorStruct)()
172 ret = c_bytesize.bs_size_div_int(self, div, byref(err))
173 get_error(err)
174 return ret.contents
175
176 def shrink_div_int(self, div):
177 err = POINTER(SizeErrorStruct)()
178 c_bytesize.bs_size_shrink_div_int(self, div, byref(err))
179 get_error(err)
180 return self
181
182 def human_readable(self, min_unit, max_places, xlate):
183 return str(c_bytesize.bs_size_human_readable(self, min_unit, max_places, xlate), "utf-8")
184
185 def sgn(self):
186 return c_bytesize.bs_size_sgn(self)
187
188 def true_div(self, sz):
189 err = POINTER(SizeErrorStruct)()
190 ret = c_bytesize.bs_size_true_div(self, sz, byref(err))
191 get_error(err)
192 ret = str(ret, "utf-8")
193 return ret
194
195 def true_div_int(self, div):
196 err = POINTER(SizeErrorStruct)()
197 ret = c_bytesize.bs_size_true_div_int(self, div, byref(err))
198 get_error(err)
199 ret = str(ret, "utf-8")
200 return ret
201
202 def mod(self, sz):
203 err = POINTER(SizeErrorStruct)()
204 ret = c_bytesize.bs_size_mod(self, sz, byref(err))
205 get_error(err)
206 return ret.contents
207
208 def mul_float_str(self, fl_str):
209 err = POINTER(SizeErrorStruct)()
210 fl_str = bytes(fl_str, "utf-8")
211 ret = c_bytesize.bs_size_mul_float_str(self, fl_str, byref(err))
212 get_error(err)
213 return ret.contents
214
215 def grow_mul_float_str(self, fl_str):
216 err = POINTER(SizeErrorStruct)()
217 fl_str = bytes(fl_str, "utf-8")
218 c_bytesize.bs_size_grow_mul_float_str(self, fl_str, byref(err))
219 get_error(err)
220 return self
221
222 def mul_int(self, i):
223 err = POINTER(SizeErrorStruct)()
224 ret = c_bytesize.bs_size_mul_int(self, i)
225 get_error(err)
226 return ret.contents
227
228 def grow_mul_int(self, i):
229 err = POINTER(SizeErrorStruct)()
230 c_bytesize.bs_size_grow_mul_int(self, i)
231 get_error(err)
232 return self
233
234 def round_to_nearest(self, sz, dir):
235 err = POINTER(SizeErrorStruct)()
236 ret = c_bytesize.bs_size_round_to_nearest(self, sz, dir, byref(err))
237 get_error(err)
238 return ret.contents
239
240 def __repr__(self):
241 return "Size (%s)" % self.human_readable(B, -1, False)
242
243 ## Constructors
244 c_bytesize.bs_size_new.restype = POINTER(SizeStruct)
245 c_bytesize.bs_size_new.argtypes = []
246 c_bytesize.bs_size_new_from_bytes.restype = POINTER(SizeStruct)
247 c_bytesize.bs_size_new_from_bytes.argtypes = [ctypes.c_ulonglong, ctypes.c_int]
248 c_bytesize.bs_size_new_from_str.restype = POINTER(SizeStruct)
249 c_bytesize.bs_size_new_from_str.argtypes = [ctypes.c_char_p, POINTER(POINTER(SizeErrorStruct))]
250 c_bytesize.bs_size_new_from_size.restype = POINTER(SizeStruct)
251 c_bytesize.bs_size_new_from_size.argtypes = [POINTER(SizeStruct)]
252
253 ## Destructors
254 c_bytesize.bs_size_free.restype = None
255 c_bytesize.bs_size_free.argtypes = [POINTER(SizeStruct)]
256 c_bytesize.bs_clear_error.restype = None
257 c_bytesize.bs_clear_error.argtypes = [POINTER(POINTER(SizeErrorStruct))]
258
259 ## Query methods
260 c_bytesize.bs_size_get_bytes.restype = ctypes.c_ulonglong
261 c_bytesize.bs_size_get_bytes.argtypes = [POINTER(SizeStruct), POINTER(ctypes.c_int), POINTER(POINTER(SizeErrorStruct))]
262 c_bytesize.bs_size_sgn.restype = ctypes.c_int
263 c_bytesize.bs_size_sgn.argtypes = [POINTER(SizeStruct)]
264 c_bytesize.bs_size_get_bytes_str.restype = ctypes.c_char_p
265 c_bytesize.bs_size_get_bytes_str.argtypes = [POINTER(SizeStruct)]
266 c_bytesize.bs_size_convert_to.restype = ctypes.c_char_p
267 c_bytesize.bs_size_convert_to.argtypes = [POINTER(SizeStruct), ctypes.c_int, POINTER(POINTER(SizeErrorStruct))]
268 c_bytesize.bs_size_human_readable.restype = ctypes.c_char_p
269 c_bytesize.bs_size_human_readable.argtypes = [POINTER(SizeStruct), ctypes.c_int, ctypes.c_int, ctypes.c_bool]
270
271 ## Arithmetic
272 c_bytesize.bs_size_add.restype = POINTER(SizeStruct)
273 c_bytesize.bs_size_add.argtypes = [POINTER(SizeStruct), POINTER(SizeStruct)]
274 c_bytesize.bs_size_grow.restype = POINTER(SizeStruct)
275 c_bytesize.bs_size_grow.argtypes = [POINTER(SizeStruct), POINTER(SizeStruct)]
276 c_bytesize.bs_size_add_bytes.restype = POINTER(SizeStruct)
277 c_bytesize.bs_size_add_bytes.argtypes = [POINTER(SizeStruct), ctypes.c_ulonglong]
278 c_bytesize.bs_size_grow_bytes.restype = POINTER(SizeStruct)
279 c_bytesize.bs_size_grow_bytes.argtypes = [POINTER(SizeStruct), ctypes.c_ulonglong]
280 c_bytesize.bs_size_sub.restype = POINTER(SizeStruct)
281 c_bytesize.bs_size_sub.argtypes = [POINTER(SizeStruct), POINTER(SizeStruct)]
282 c_bytesize.bs_size_shrink.restype = POINTER(SizeStruct)
283 c_bytesize.bs_size_shrink.argtypes = [POINTER(SizeStruct), POINTER(SizeStruct)]
284 c_bytesize.bs_size_sub_bytes.restype = POINTER(SizeStruct)
285 c_bytesize.bs_size_sub_bytes.argtypes = [POINTER(SizeStruct), ctypes.c_ulonglong]
286 c_bytesize.bs_size_shrink_bytes.restype = POINTER(SizeStruct)
287 c_bytesize.bs_size_shrink_bytes.argtypes = [POINTER(SizeStruct), ctypes.c_ulonglong]
288 c_bytesize.bs_size_mul_int.restype = POINTER(SizeStruct)
289 c_bytesize.bs_size_mul_int.argtypes = [POINTER(SizeStruct), ctypes.c_ulonglong]
290 c_bytesize.bs_size_grow_mul_int.restype = POINTER(SizeStruct)
291 c_bytesize.bs_size_grow_mul_int.argtypes = [POINTER(SizeStruct), ctypes.c_ulonglong]
292 c_bytesize.bs_size_mul_float_str.restype = POINTER(SizeStruct)
293 c_bytesize.bs_size_mul_float_str.argtypes = [POINTER(SizeStruct), ctypes.c_char_p, POINTER(POINTER(SizeErrorStruct))]
294 c_bytesize.bs_size_grow_mul_float_str.restype = POINTER(SizeStruct)
295 c_bytesize.bs_size_grow_mul_float_str.argtypes = [POINTER(SizeStruct), ctypes.c_char_p, POINTER(POINTER(SizeErrorStruct))]
296 c_bytesize.bs_size_div.restype = ctypes.c_ulonglong
297 c_bytesize.bs_size_div.argtypes = [POINTER(SizeStruct), POINTER(SizeStruct), POINTER(ctypes.c_int), POINTER(POINTER(SizeErrorStruct))]
298 c_bytesize.bs_size_div_int.restype = POINTER(SizeStruct)
299 c_bytesize.bs_size_div_int.argtypes = [POINTER(SizeStruct), ctypes.c_ulonglong, POINTER(POINTER(SizeErrorStruct))]
300 c_bytesize.bs_size_shrink_div_int.restype = POINTER(SizeStruct)
301 c_bytesize.bs_size_shrink_div_int.argtypes = [POINTER(SizeStruct), ctypes.c_ulonglong, POINTER(POINTER(SizeErrorStruct))]
302 c_bytesize.bs_size_true_div.restype = ctypes.c_char_p
303 c_bytesize.bs_size_true_div.argtypes = [POINTER(SizeStruct), POINTER(SizeStruct), POINTER(POINTER(SizeErrorStruct))]
304 c_bytesize.bs_size_true_div_int.restype = ctypes.c_char_p
305 c_bytesize.bs_size_true_div_int.argtypes = [POINTER(SizeStruct), ctypes.c_ulonglong, POINTER(POINTER(SizeErrorStruct))]
306 c_bytesize.bs_size_mod.restype = POINTER(SizeStruct)
307 c_bytesize.bs_size_mod.argtypes = [POINTER(SizeStruct), POINTER(SizeStruct), POINTER(POINTER(SizeErrorStruct))]
308 c_bytesize.bs_size_round_to_nearest.restype = POINTER(SizeStruct)
309 c_bytesize.bs_size_round_to_nearest.argtypes = [POINTER(SizeStruct), POINTER(SizeStruct), ctypes.c_int, POINTER(POINTER(SizeErrorStruct))]
310
311 ## Comparisons
312 c_bytesize.bs_size_cmp.restype = ctypes.c_int
313 c_bytesize.bs_size_cmp.argtypes = [POINTER(SizeStruct), POINTER(SizeStruct), ctypes.c_bool]
314 c_bytesize.bs_size_cmp_bytes.restype = ctypes.c_int
315 c_bytesize.bs_size_cmp_bytes.argtypes = [POINTER(SizeStruct), ctypes.c_ulonglong, ctypes.c_bool]
316
317
318 def _str_to_decimal(num_str):
319 radix = locale.nl_langinfo(locale.RADIXCHAR)
320 if radix != '.':
321 num_str = num_str.replace(radix, '.')
322
323 return Decimal(num_str)
324
325 def neutralize_none_operand(fn):
326 def fn_with_neutralization(sz, other):
327 return fn(sz, Size(0) if other is None else other)
328 return fn_with_neutralization
329
330 class Size(object):
331 def __init__(self, spec=None):
332 self._c_size = None
333 try:
334 if isinstance(spec, str):
335 self._c_size = SizeStruct.new_from_str(spec)
336 elif isinstance(spec, int):
337 abs_val = abs(spec)
338 if abs_val == spec:
339 sgn = 1
340 else:
341 sgn = -1
342 if abs_val <= MAXUINT64:
343 self._c_size = SizeStruct.new_from_bytes(abs_val, sgn)
344 else:
345 self._c_size = SizeStruct.new_from_str(str(spec))
346 elif isinstance(spec, (Decimal, float)):
347 self._c_size = SizeStruct.new_from_str(str(spec))
348 elif isinstance(spec, SizeStruct):
349 self._c_size = SizeStruct.new_from_size(spec)
350 elif isinstance(spec, Size):
351 self._c_size = SizeStruct.new_from_size(spec._c_size)
352 elif spec is None:
353 self._c_size = SizeStruct.new()
354 else:
355 raise ValueError("Cannot construct new size from '%s'" % spec)
356 except SizeError as e:
357 raise ValueError(e)
358
359
360 ## METHODS ##
361 def get_bytes(self):
362 try:
363 val, sgn = self._c_size.get_bytes()
364 return val * sgn
365 except SizeError:
366 return int(self._c_size.get_bytes_str())
367
368 def convert_to(self, unit):
369 if isinstance(unit, str):
370 real_unit = unit_strs.get(unit)
371 if real_unit is None:
372 raise ValueError("Invalid unit specification: '%s'" % unit)
373 ret = self._c_size.convert_to(real_unit)
374 else:
375 ret = self._c_size.convert_to(unit)
376
377 return _str_to_decimal(ret)
378
379 def human_readable(self, min_unit=B, max_places=2, xlate=True):
380 if isinstance(min_unit, str):
381 if min_unit in unit_strs.keys():
382 min_unit = unit_strs[min_unit]
383 else:
384 raise ValueError("Invalid unit specification: '%s'" % min_unit)
385 if not isinstance(max_places, int):
386 raise ValueError("max_places has to be an integer number")
387 return self._c_size.human_readable(min_unit, max_places, xlate)
388
389 def round_to_nearest(self, round_to, rounding):
390 if isinstance(round_to, Size):
391 return Size(self._c_size.round_to_nearest(round_to._c_size, rounding))
392
393 size = None
394 # else try to create a SizeStruct instance from it
395 for (unit_str, unit) in unit_strs.items():
396 if round_to in (unit.real, unit_str):
397 size = SizeStruct.new_from_str("1 %s" % unit_str)
398 break
399 if size is not None:
400 return Size(self._c_size.round_to_nearest(size, rounding))
401 else:
402 raise ValueError("Invalid size specification: '%s'" % round_to)
403
404 def cmp(self, other, abs_vals=False):
405 if isinstance(other, int):
406 if (other < 0 and abs_vals):
407 other = abs(other)
408 if 0 <= other <= MAXUINT64:
409 return self._c_size.cmp_bytes(other, abs_vals)
410 else:
411 other = SizeStruct.new_from_str(str(other))
412 elif isinstance(other, (Decimal, float)):
413 other = SizeStruct.new_from_str(str(other))
414 elif isinstance(other, Size):
415 other = other._c_size
416 elif other is None:
417 return 1
418
419 return self._c_size.cmp(other, abs_vals)
420
421
422 ## INTERNAL METHODS ##
423 def __eq__(self, other):
424 return self.cmp(other, False) == 0
425
426 def __ne__(self, other):
427 return self.cmp(other, False) != 0
428
429 def __lt__(self, other):
430 return self.cmp(other, False) == -1
431
432 def __le__(self, other):
433 return self.cmp(other, False) in (-1, 0)
434
435 def __gt__(self, other):
436 return self.cmp(other, False) == 1
437
438 def __ge__(self, other):
439 return self.cmp(other, False) in (1, 0)
440
441 def __bool__(self):
442 return self.get_bytes() != 0
443
444 __nonzero__ = __bool__
445
446 def __abs__(self):
447 return Size(abs(self.get_bytes()))
448
449 def __neg__(self):
450 return self.__mul__(-1)
451
452 @neutralize_none_operand
453 def __add__(self, other):
454 if isinstance(other, int):
455 if other <= MAXUINT64:
456 return Size(self._c_size.add_bytes(other))
457 else:
458 other = SizeStruct.new_from_str(str(other))
459 elif isinstance(other, (Decimal, float)):
460 other = SizeStruct.new_from_str(str(other))
461 elif isinstance(other, Size):
462 other = other._c_size
463 return Size(self._c_size.add(other))
464
465 # needed to make sum() work with Size arguments
466 __radd__ = __add__
467
468 @neutralize_none_operand
469 def __sub__(self, other):
470 if isinstance(other, int):
471 if other <= MAXUINT64:
472 return Size(self._c_size.sub_bytes(other))
473 else:
474 other = SizeStruct.new_from_str(str(other))
475 elif isinstance(other, (Decimal, float)):
476 other = SizeStruct.new_from_str(str(other))
477 elif isinstance(other, Size):
478 other = other._c_size
479 return Size(self._c_size.sub(other))
480
481 @neutralize_none_operand
482 def __rsub__(self, other):
483 other = SizeStruct.new_from_str(str(other))
484 return Size(SizeStruct.sub(other, self._c_size))
485
486 @neutralize_none_operand
487 def __mul__(self, other):
488 if isinstance(other, (Size, SizeStruct)):
489 raise ValueError("Cannot multiply Size by Size. It just doesn't make sense.")
490 elif isinstance(other, (Decimal, float)) or (isinstance(other, int)
491 and other > MAXUINT64 or other < 0):
492 return Size(self._c_size.mul_float_str(str(other)))
493 else:
494 return Size(self._c_size.mul_int(other))
495
496 __rmul__ = __mul__
497
498 @neutralize_none_operand
499 def __truediv__(self, other):
500 if isinstance(other, int):
501 if other <= MAXUINT64:
502 return Size(self._c_size.true_div_int(other))
503 else:
504 other = SizeStruct.new_from_str(str(other))
505 return Size(self._c_size.true_div(other))
506 elif isinstance(other, (Decimal, float)):
507 return Size(self._c_size.mul_float_str(str(Decimal(1)/Decimal(other))))
508
509 return _str_to_decimal(self._c_size.true_div(other._c_size))
510
511 def _safe_floordiv(self, other):
512 try:
513 val, sgn = self._c_size.div(other._c_size)
514 return val * sgn
515 except OverflowError:
516 return int(float(self._c_size.true_div(other._c_size)))
517
518 def _safe_floordiv_int(self, other):
519 try:
520 return Size(self._c_size.div_int(other))
521 except OverflowError:
522 return Size(float(self._c_size.true_div_int(other)))
523
524 @neutralize_none_operand
525 def __floordiv__(self, other):
526 if isinstance(other, (Decimal, float)):
527 return Size(self._c_size.mul_float_str(str(Decimal(1)/Decimal(other))))
528 elif isinstance(other, int):
529 if other <= MAXUINT64:
530 return self._safe_floordiv_int(other)
531 else:
532 other = SizeStruct.new_from_str(str(other))
533 return Size(self._safe_floordiv(other))
534 return self._safe_floordiv(other)
535
536 @neutralize_none_operand
537 def __mod__(self, other):
538 if not isinstance(other, Size):
539 raise ValueError("modulo operation only supported between two Size instances")
540 return Size(self._c_size.mod(other._c_size))
541
542 @neutralize_none_operand
543 def __divmod__(self, other):
544 rdiv = self.__floordiv__(other)
545 if not isinstance(other, Size):
546 rmod = self.__mod__(rdiv)
547 else:
548 rmod = self.__mod__(other)
549
550 return (rdiv, rmod)
551
552 def __repr__(self):
553 return "Size (%s)" % self.human_readable(B, -1, False)
554
555 def __str__(self):
556 return self.human_readable()
557
558 def __int__(self):
559 return self.get_bytes()
560
561 def __index__(self):
562 return self.get_bytes()
563
564 def __float__(self):
565 return float(self.get_bytes())
566
567 def __deepcopy__(self, memo_dict):
568 return Size(self)
569
570 # pickling support for Size
571 # see https://docs.python.org/3/library/pickle.html#object.__reduce__
572 def __reduce__(self):
573 return (self.__class__, (self.get_bytes(),))
574
575 def __hash__(self):
576 return self.get_bytes()