convert.py revision 13663:9b64aeabf9a5
1# Copyright (c) 2005 The Regents of The University of Michigan
2# Copyright (c) 2010 Advanced Micro Devices, Inc.
3# All rights reserved.
4#
5# Redistribution and use in source and binary forms, with or without
6# modification, are permitted provided that the following conditions are
7# met: redistributions of source code must retain the above copyright
8# notice, this list of conditions and the following disclaimer;
9# redistributions in binary form must reproduce the above copyright
10# notice, this list of conditions and the following disclaimer in the
11# documentation and/or other materials provided with the distribution;
12# neither the name of the copyright holders nor the names of its
13# contributors may be used to endorse or promote products derived from
14# this software without specific prior written permission.
15#
16# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20# OWNER OR 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 USE,
23# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27#
28# Authors: Nathan Binkert
29#          Gabe Black
30
31# metric prefixes
32atto  = 1.0e-18
33femto = 1.0e-15
34pico  = 1.0e-12
35nano  = 1.0e-9
36micro = 1.0e-6
37milli = 1.0e-3
38
39kilo = 1.0e3
40mega = 1.0e6
41giga = 1.0e9
42tera = 1.0e12
43peta = 1.0e15
44exa  = 1.0e18
45
46# power of 2 prefixes
47kibi = 1024
48mebi = kibi * 1024
49gibi = mebi * 1024
50tebi = gibi * 1024
51pebi = tebi * 1024
52exbi = pebi * 1024
53
54metric_prefixes = {
55    'Ei': exbi,
56    'E': exa,
57    'Pi': pebi,
58    'P': peta,
59    'Ti': tebi,
60    'T': tera,
61    'Gi': gibi,
62    'G': giga,
63    'M': mega,
64    'ki': kibi,
65    'k': kilo,
66    'Mi': mebi,
67    'm': milli,
68    'u': micro,
69    'n': nano,
70    'p': pico,
71    'f': femto,
72    'a': atto,
73}
74
75binary_prefixes = {
76    'Ei': exbi,
77    'E' : exbi,
78    'Pi': pebi,
79    'P' : pebi,
80    'Ti': tebi,
81    'T' : tebi,
82    'Gi': gibi,
83    'G' : gibi,
84    'Mi': mebi,
85    'M' : mebi,
86    'ki': kibi,
87    'k' : kibi,
88}
89
90def assertStr(value):
91    if not isinstance(value, str):
92        raise TypeError("wrong type '%s' should be str" % type(value))
93
94
95# memory size configuration stuff
96def toFloat(value, target_type='float', units=None, prefixes=[]):
97    assertStr(value)
98
99    if units and not value.endswith(units):
100        units = None
101    if not units:
102        try:
103            return float(value)
104        except ValueError:
105            raise ValueError("cannot convert '%s' to %s" % \
106                             (value, target_type))
107
108    value = value[:-len(units)]
109
110    prefix = next((p for p in prefixes.keys() if value.endswith(p)), None)
111    if not prefix:
112        return float(value)
113    value = value[:-len(prefix)]
114
115    return float(value) * prefixes[prefix]
116
117def toMetricFloat(value, target_type='float', units=None):
118    return toFloat(value, target_type, units, metric_prefixes)
119
120def toBinaryFloat(value, target_type='float', units=None):
121    return toFloat(value, target_type, units, binary_prefixes)
122
123def toInteger(value, target_type='integer', units=None, prefixes=[]):
124    value = toFloat(value, target_type, units, prefixes)
125    result = long(value)
126    if value != result:
127        raise ValueError("cannot convert '%s' to integer %s" % \
128                (value, target_type))
129
130    return result
131
132def toMetricInteger(value, target_type='integer', units=None):
133    return toInteger(value, target_type, units, metric_prefixes)
134
135def toBinaryInteger(value, target_type='integer', units=None):
136    return toInteger(value, target_type, units, binary_prefixes)
137
138def toBool(value):
139    assertStr(value)
140
141    value = value.lower()
142    if value in ('true', 't', 'yes', 'y', '1'):
143        return True
144    if value in ('false', 'f', 'no', 'n', '0'):
145        return False
146    return result
147
148def toFrequency(value):
149    return toMetricFloat(value, 'frequency', 'Hz')
150
151def toLatency(value):
152    return toMetricFloat(value, 'latency', 's')
153
154def anyToLatency(value):
155    """result is a clock period"""
156    try:
157        return 1 / toFrequency(value)
158    except (ValueError, ZeroDivisionError):
159        pass
160
161    try:
162        return toLatency(value)
163    except ValueError:
164        pass
165
166    raise ValueError("cannot convert '%s' to clock period" % value)
167
168def anyToFrequency(value):
169    """result is a clock period"""
170    try:
171        return toFrequency(value)
172    except ValueError:
173        pass
174
175    try:
176        return 1 / toLatency(value)
177    except ValueError as ZeroDivisionError:
178        pass
179
180    raise ValueError("cannot convert '%s' to clock period" % value)
181
182def toNetworkBandwidth(value):
183    return toMetricFloat(value, 'network bandwidth', 'bps')
184
185def toMemoryBandwidth(value):
186    return toBinaryFloat(value, 'memory bandwidth', 'B/s')
187
188def toMemorySize(value):
189    return toBinaryInteger(value, 'memory size', 'B')
190
191def toIpAddress(value):
192    if not isinstance(value, str):
193        raise TypeError("wrong type '%s' should be str" % type(value))
194
195    bytes = value.split('.')
196    if len(bytes) != 4:
197        raise ValueError('invalid ip address %s' % value)
198
199    for byte in bytes:
200        if not 0 <= int(byte) <= 0xff:
201            raise ValueError('invalid ip address %s' % value)
202
203    return (int(bytes[0]) << 24) | (int(bytes[1]) << 16) | \
204           (int(bytes[2]) << 8)  | (int(bytes[3]) << 0)
205
206def toIpNetmask(value):
207    if not isinstance(value, str):
208        raise TypeError("wrong type '%s' should be str" % type(value))
209
210    (ip, netmask) = value.split('/')
211    ip = toIpAddress(ip)
212    netmaskParts = netmask.split('.')
213    if len(netmaskParts) == 1:
214        if not 0 <= int(netmask) <= 32:
215            raise ValueError('invalid netmask %s' % netmask)
216        return (ip, int(netmask))
217    elif len(netmaskParts) == 4:
218        netmaskNum = toIpAddress(netmask)
219        if netmaskNum == 0:
220            return (ip, 0)
221        testVal = 0
222        for i in range(32):
223            testVal |= (1 << (31 - i))
224            if testVal == netmaskNum:
225                return (ip, i + 1)
226        raise ValueError('invalid netmask %s' % netmask)
227    else:
228        raise ValueError('invalid netmask %s' % netmask)
229
230def toIpWithPort(value):
231    if not isinstance(value, str):
232        raise TypeError("wrong type '%s' should be str" % type(value))
233
234    (ip, port) = value.split(':')
235    ip = toIpAddress(ip)
236    if not 0 <= int(port) <= 0xffff:
237        raise ValueError('invalid port %s' % port)
238    return (ip, int(port))
239
240def toVoltage(value):
241    return toMetricFloat(value, 'voltage', 'V')
242
243def toCurrent(value):
244    return toMetricFloat(value, 'current', 'A')
245
246def toEnergy(value):
247    return toMetricFloat(value, 'energy', 'J')
248