xref: /aosp_15_r20/external/flatbuffers/python/flatbuffers/encode.py (revision 890232f25432b36107d06881e0a25aaa6b473652)
1 # Copyright 2014 Google Inc. All rights reserved.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #     http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 
15 from . import number_types as N
16 from . import packer
17 from .compat import memoryview_type
18 from .compat import import_numpy, NumpyRequiredForThisFeature
19 
20 np = import_numpy()
21 
22 FILE_IDENTIFIER_LENGTH=4
23 
24 def Get(packer_type, buf, head):
25     """ Get decodes a value at buf[head] using `packer_type`. """
26     return packer_type.unpack_from(memoryview_type(buf), head)[0]
27 
28 
29 def GetVectorAsNumpy(numpy_type, buf, count, offset):
30     """ GetVecAsNumpy decodes values starting at buf[head] as
31     `numpy_type`, where `numpy_type` is a numpy dtype. """
32     if np is not None:
33         # TODO: could set .flags.writeable = False to make users jump through
34         #       hoops before modifying...
35         return np.frombuffer(buf, dtype=numpy_type, count=count, offset=offset)
36     else:
37         raise NumpyRequiredForThisFeature('Numpy was not found.')
38 
39 
40 def Write(packer_type, buf, head, n):
41     """ Write encodes `n` at buf[head] using `packer_type`. """
42     packer_type.pack_into(buf, head, n)
43