Fix for x86_64 build fail
[platform/upstream/connectedhomeip.git] / src / controller / python / chip / ChipUtility.py
1 #
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
24 from __future__ import absolute_import
25 from __future__ import print_function
26 import binascii
27 from ctypes import *
28
29
30 class 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
41         else:
42             return None
43
44     @staticmethod
45     def ByteArrayToVoidPtr(array):
46         if array != None:
47             if not (isinstance(array, bytes) or isinstance(array, bytearray)):
48                 raise TypeError("Array must be an str or a bytearray")
49             return cast((c_byte * len(array)).from_buffer_copy(array), c_void_p)
50         else:
51             return c_void_p(0)
52
53     @staticmethod
54     def IsByteArrayAllZeros(array):
55         for i in range(len(array)):
56             if array[i] != 0:
57                 return False
58         return True
59
60     @staticmethod
61     def ByteArrayToHex(array):
62         return ChipUtility.Hexlify(bytes(array))
63
64     @staticmethod
65     def CStringToString(s):
66         return None if s is None else s.decode()
67
68     @staticmethod
69     def StringToCString(s):
70         return None if s is None else s.encode()