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 def Get(packer_type, buf, head): 23 """ Get decodes a value at buf[head] using `packer_type`. """ 24 return packer_type.unpack_from(memoryview_type(buf), head)[0] 25 26 27 def GetVectorAsNumpy(numpy_type, buf, count, offset): 28 """ GetVecAsNumpy decodes values starting at buf[head] as 29 `numpy_type`, where `numpy_type` is a numpy dtype. """ 30 if np is not None: 31 # TODO: could set .flags.writeable = False to make users jump through 32 # hoops before modifying... 33 return np.frombuffer(buf, dtype=numpy_type, count=count, offset=offset) 34 else: 35 raise NumpyRequiredForThisFeature('Numpy was not found.') 36 37 38 def Write(packer_type, buf, head, n): 39 """ Write encodes `n` at buf[head] using `packer_type`. """ 40 packer_type.pack_into(buf, head, n) 41