Statistics
| Branch: | Tag: | Revision:

root / snf-common / synnefo / util / units.py @ 44f510e1

History | View | Annotate | Download (4 kB)

1
# Copyright 2013 GRNET S.A. All rights reserved.
2
#
3
# Redistribution and use in source and binary forms, with or
4
# without modification, are permitted provided that the following
5
# conditions are met:
6
#
7
#   1. Redistributions of source code must retain the above
8
#      copyright notice, this list of conditions and the following
9
#      disclaimer.
10
#
11
#   2. Redistributions in binary form must reproduce the above
12
#      copyright notice, this list of conditions and the following
13
#      disclaimer in the documentation and/or other materials
14
#      provided with the distribution.
15
#
16
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
17
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
20
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27
# POSSIBILITY OF SUCH DAMAGE.
28
#
29
# The views and conclusions contained in the software and
30
# documentation are those of the authors and should not be
31
# interpreted as representing official policies, either expressed
32
# or implied, of GRNET S.A.
33

    
34
from synnefo.lib.ordereddict import OrderedDict
35
import re
36

    
37
DEFAULT_PARSE_BASE = 1024
38
PARSE_EXPONENTS = {
39
    '':      0,
40
    'bytes': 0,
41
    'K':     1,
42
    'KB':    1,
43
    'KIB':   1,
44
    'M':     2,
45
    'MB':    2,
46
    'MIB':   2,
47
    'G':     3,
48
    'GB':    3,
49
    'GIB':   3,
50
    'T':     4,
51
    'TB':    4,
52
    'TIB':   4,
53
    'P':     5,
54
    'PB':    5,
55
    'PIB':   5,
56
}
57

    
58
_MATCHER = re.compile('^(\d+\.?\d*)(.*)$')
59

    
60

    
61
class ParseError(Exception):
62
    pass
63

    
64

    
65
def _parse_number_with_unit(s):
66
    match = _MATCHER.match(s)
67
    if not match:
68
        raise ParseError()
69
    number, unit = match.groups()
70
    try:
71
        number = long(number)
72
    except ValueError:
73
        number = float(number)
74

    
75
    return number, unit.strip().upper()
76

    
77

    
78
def parse_with_style(s):
79
    n, unit = _parse_number_with_unit(s)
80
    try:
81
        exponent = PARSE_EXPONENTS[unit]
82
    except KeyError:
83
        raise ParseError()
84
    multiplier = DEFAULT_PARSE_BASE ** exponent
85
    return long(n * multiplier), exponent
86

    
87

    
88
def parse(s):
89
    n, _ = parse_with_style(s)
90
    return n
91

    
92

    
93
UNITS = {
94
    'bytes': {
95
        'DISPLAY': ['bytes', 'kB', 'MB', 'GB', 'TB', 'PB'],
96
        'BASE': 1024,
97
    }
98
}
99

    
100
STYLE_TO_EXP = OrderedDict(
101
    [('b',  0),
102
     ('kb', 1),
103
     ('mb', 2),
104
     ('gb', 3),
105
     ('tb', 4),
106
     ('pb', 5),
107
     ]
108
)
109

    
110
STYLES = STYLE_TO_EXP.keys() + ['auto', 'none']
111

    
112

    
113
class StyleError(Exception):
114
    pass
115

    
116

    
117
def show_float(n):
118
    if n < 1:
119
        return "%.3f" % n
120
    if n < 10:
121
        return "%.2f" % n
122
    return "%.1f" % n
123

    
124

    
125
def get_exponent(style):
126
    if isinstance(style, (int, long)):
127
        if style in STYLE_TO_EXP.values():
128
            return style
129
        else:
130
            raise StyleError()
131
    else:
132
        try:
133
            return STYLE_TO_EXP[style]
134
        except KeyError:
135
            raise StyleError()
136

    
137

    
138
def show(n, unit, style=None):
139
    try:
140
        unit_dict = UNITS[unit]
141
    except KeyError:
142
        return str(n)
143

    
144
    if style == 'none':
145
        return str(n)
146

    
147
    BASE = unit_dict['BASE']
148
    DISPLAY = unit_dict['DISPLAY']
149

    
150
    if style is None or style == 'auto':
151
        if n < BASE:
152
            return "%d %s" % (n, DISPLAY[0])
153
        n = float(n)
154
        for i in DISPLAY[1:]:
155
            n = n / BASE
156
            if n < BASE:
157
                break
158
        return "%s %s" % (show_float(n), i)
159

    
160
    exponent = get_exponent(style)
161
    unit_display = DISPLAY[exponent]
162
    if exponent == 0:
163
        return "%d %s" % (n, unit_display)
164

    
165
    divisor = BASE ** exponent
166
    n = float(n)
167
    n = n / divisor
168
    return "%s %s" % (show_float(n), unit_display)