blob: 95a2da333a3f3925c08da62b49922a3647798d14 [file] [log] [blame]
yunhanw-google90ea3142020-10-01 13:53:26 -07001#
2# Copyright (c) 2020 Project CHIP Authors
3# Copyright (c) 2020 Google LLC.
4# All rights reserved.
5#
6# Licensed under the Apache License, Version 2.0 (the "License");
7# you may not use this file except in compliance with the License.
8# You may obtain a copy of the License at
9#
10# http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS,
14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15# See the License for the specific language governing permissions and
16# limitations under the License.
17#
18
19#
20# @file
21# This file is utility for Chip
22#
23
Arkadiusz Bokowyd5bfb4b2023-01-09 16:15:00 +010024from __future__ import absolute_import, print_function
25
yunhanw-google90ea3142020-10-01 13:53:26 -070026import binascii
Damian Michalak-Szmaciński79cebcf2023-07-05 23:08:29 +020027from ctypes import c_byte, c_void_p, cast, memmove
yunhanw-google90ea3142020-10-01 13:53:26 -070028
29
30class ChipUtility(object):
31 @staticmethod
32 def Hexlify(val):
33 return binascii.hexlify(val).decode()
34
35 @staticmethod
36 def VoidPtrToByteArray(ptr, len):
37 if ptr:
38 v = bytearray(len)
39 memmove((c_byte * len).from_buffer(v), ptr, len)
40 return v
Victor Morales47aed242021-09-13 08:31:02 -070041 return None
yunhanw-google90ea3142020-10-01 13:53:26 -070042
43 @staticmethod
44 def ByteArrayToVoidPtr(array):
Damian Michalak-Szmaciński79cebcf2023-07-05 23:08:29 +020045 if array is not None:
yunhanw-google90ea3142020-10-01 13:53:26 -070046 if not (isinstance(array, bytes) or isinstance(array, bytearray)):
47 raise TypeError("Array must be an str or a bytearray")
48 return cast((c_byte * len(array)).from_buffer_copy(array), c_void_p)
Victor Morales47aed242021-09-13 08:31:02 -070049 return c_void_p(0)
yunhanw-google90ea3142020-10-01 13:53:26 -070050
51 @staticmethod
52 def IsByteArrayAllZeros(array):
Victor Morales47aed242021-09-13 08:31:02 -070053 for i in array:
54 if i != 0:
yunhanw-google90ea3142020-10-01 13:53:26 -070055 return False
56 return True
57
58 @staticmethod
59 def ByteArrayToHex(array):
60 return ChipUtility.Hexlify(bytes(array))
61
62 @staticmethod
63 def CStringToString(s):
64 return None if s is None else s.decode()
65
66 @staticmethod
67 def StringToCString(s):
68 return None if s is None else s.encode()
Song GUO22d0be22021-10-18 22:09:53 +080069
70# To support Python 3.8 and older versions, which does not support @classmethod + @property
71
72
73class classproperty(property):
74 def __get__(self, cls, owner):
75 return classmethod(self.fget).__get__(None, owner)()