encode.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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. from . import number_types as N
  15. from . import packer
  16. from .compat import memoryview_type
  17. from .compat import NumpyRequiredForThisFeature, import_numpy
  18. np = import_numpy()
  19. FILE_IDENTIFIER_LENGTH = 4
  20. def Get(packer_type, buf, head):
  21. """Get decodes a value at buf[head] using `packer_type`."""
  22. return packer_type.unpack_from(memoryview_type(buf), head)[0]
  23. def GetVectorAsNumpy(numpy_type, buf, count, offset):
  24. """GetVecAsNumpy decodes values starting at buf[head] as
  25. `numpy_type`, where `numpy_type` is a numpy dtype.
  26. """
  27. if np is not None:
  28. # TODO: could set .flags.writeable = False to make users jump through
  29. # hoops before modifying...
  30. return np.frombuffer(buf, dtype=numpy_type, count=count, offset=offset)
  31. else:
  32. raise NumpyRequiredForThisFeature('Numpy was not found.')
  33. def Write(packer_type, buf, head, n):
  34. """Write encodes `n` at buf[head] using `packer_type`."""
  35. packer_type.pack_into(buf, head, n)