Coverage for linuxpy/ctypes.py: 76%
70 statements
« prev ^ index » next coverage.py v7.6.1, created at 2024-10-21 07:58 +0200
« prev ^ index » next coverage.py v7.6.1, created at 2024-10-21 07:58 +0200
1#
2# This file is part of the linuxpy project
3#
4# Copyright (c) 2023 Tiago Coutinho
5# Distributed under the GPLv3 license. See LICENSE for more info.
7import collections
8import ctypes
9import struct
10import time
12from .constants import MICROSEC_PER_SEC, NANOSEC_PER_MICROSEC
14i8 = ctypes.c_int8
15i16 = ctypes.c_int16
16i32 = ctypes.c_int32
17i64 = ctypes.c_int64
19u8 = ctypes.c_uint8
20u16 = ctypes.c_uint16
21u32 = ctypes.c_uint32
22u64 = ctypes.c_uint64
25cint = ctypes.c_int
26cuint = ctypes.c_uint
27clong = ctypes.c_long
28culong = ctypes.c_ulong
29clonglong = ctypes.c_longlong
30culonglong = ctypes.c_ulonglong
32cchar = ctypes.c_char
33ccharp = ctypes.c_char_p
35cenum = cuint
36cvoidp = ctypes.c_void_p
38fsword = cuint
39fsblkcnt = culong
40fsfilcnt = culong
42cast = ctypes.cast
43sizeof = ctypes.sizeof
44byref = ctypes.byref
45addressof = ctypes.addressof
46string_at = ctypes.string_at
48calcsize = struct.calcsize
50Union = ctypes.Union
52pointer = ctypes.pointer
53POINTER = ctypes.POINTER
55create_string_buffer = ctypes.create_string_buffer
56cast = ctypes.cast
57memmove = ctypes.memmove
60def memcpy(dst, src):
61 typ = type(dst)
62 return memmove(byref(dst), byref(src), sizeof(typ))
65class Struct(ctypes.Structure):
66 def __repr__(self):
67 name = type(self).__name__
68 fields = filter(lambda field: field[0] != "reserved", self._fields_)
69 fields = ", ".join(f"{field[0]}={getattr(self, field[0])}" for field in fields)
70 return f"{name}({fields})"
72 def __iter__(self):
73 for fname, ftype in self._fields_:
74 yield fname, ftype, getattr(self, fname)
76 def asdict(self):
77 r = collections.OrderedDict()
78 for name, _, value in self:
79 if hasattr(value, "_fields_"):
80 value = value.asdict()
81 r[name] = value
82 return r
85class timeval(Struct):
86 _fields_ = [
87 ("secs", ctypes.c_long),
88 ("usecs", ctypes.c_long),
89 ]
91 def set_ns(self, value=None):
92 if value is None: 92 ↛ 94line 92 didn't jump to line 94 because the condition on line 92 was always true
93 value = time.time_ns()
94 microsecs = time.time_ns() // NANOSEC_PER_MICROSEC
95 self.secs = microsecs // MICROSEC_PER_SEC
96 self.usecs = microsecs % MICROSEC_PER_SEC
99class timespec(Struct):
100 _fields_ = [
101 ("secs", ctypes.c_long),
102 ("nsecs", ctypes.c_long),
103 ]
105 def timestamp(self):
106 return self.secs + self.nsecs * 1e-9
109c = ctypes.cdll.LoadLibrary("libc.so.6")