]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/pyzfs/libzfs_core/ctypes.py
Vendor import of openzfs master @ 184df27eef0abdc7ab2105b21257f753834b936b
[FreeBSD/FreeBSD.git] / contrib / pyzfs / libzfs_core / ctypes.py
1 #
2 # Copyright 2015 ClusterHQ
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 #    http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15 #
16
17 """
18 Utility functions for casting to a specific C type.
19 """
20 from __future__ import absolute_import, division, print_function
21
22 from .bindings.libnvpair import ffi as _ffi
23
24
25 def _ffi_cast(type_name):
26     type_info = _ffi.typeof(type_name)
27
28     def _func(value):
29         # this is for overflow / underflow checking only
30         if type_info.kind == 'enum':
31             try:
32                 type_info.elements[value]
33             except KeyError as e:
34                 raise OverflowError('Invalid enum <%s> value %s: %s' %
35                                     (type_info.cname, value, e))
36         else:
37             _ffi.new(type_name + '*', value)
38         return _ffi.cast(type_name, value)
39     _func.__name__ = type_name
40     return _func
41
42
43 uint8_t = _ffi_cast('uint8_t')
44 int8_t = _ffi_cast('int8_t')
45 uint16_t = _ffi_cast('uint16_t')
46 int16_t = _ffi_cast('int16_t')
47 uint32_t = _ffi_cast('uint32_t')
48 int32_t = _ffi_cast('int32_t')
49 uint64_t = _ffi_cast('uint64_t')
50 int64_t = _ffi_cast('int64_t')
51 boolean_t = _ffi_cast('boolean_t')
52 uchar_t = _ffi_cast('uchar_t')
53
54
55 # First element of the value tuple is a suffix for a single value function
56 # while the second element is for an array function
57 _type_to_suffix = {
58     _ffi.typeof('uint8_t'):     ('uint8', 'uint8'),
59     _ffi.typeof('int8_t'):      ('int8', 'int8'),
60     _ffi.typeof('uint16_t'):    ('uint16', 'uint16'),
61     _ffi.typeof('int16_t'):     ('int16', 'int16'),
62     _ffi.typeof('uint32_t'):    ('uint32', 'uint32'),
63     _ffi.typeof('int32_t'):     ('int32', 'int32'),
64     _ffi.typeof('uint64_t'):    ('uint64', 'uint64'),
65     _ffi.typeof('int64_t'):     ('int64', 'int64'),
66     _ffi.typeof('boolean_t'):   ('boolean_value', 'boolean'),
67     _ffi.typeof('uchar_t'):     ('byte', 'byte'),
68 }
69
70
71 # vim: softtabstop=4 tabstop=4 expandtab shiftwidth=4