PageRenderTime 25ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/pypy/rlib/longlong2float.py

https://bitbucket.org/jakelundy/pypy
Python | 55 lines | 52 code | 0 blank | 3 comment | 0 complexity | 7b4dce4ae3fac5bdd48982c01caa29e6 MD5 | raw file
  1. """
  2. This module exposes the functions longlong2float() and float2longlong(),
  3. which cast the bit pattern of a float into a long long and back.
  4. Warning: don't use in the other direction, i.e. don't cast a random
  5. long long to a float and back to a long long. There are corner cases
  6. in which it does not work.
  7. """
  8. from pypy.rpython.lltypesystem import lltype, rffi
  9. # -------- implement longlong2float and float2longlong --------
  10. DOUBLE_ARRAY_PTR = lltype.Ptr(lltype.Array(rffi.DOUBLE))
  11. LONGLONG_ARRAY_PTR = lltype.Ptr(lltype.Array(rffi.LONGLONG))
  12. # these definitions are used only in tests, when not translated
  13. def longlong2float_emulator(llval):
  14. d_array = lltype.malloc(DOUBLE_ARRAY_PTR.TO, 1, flavor='raw')
  15. ll_array = rffi.cast(LONGLONG_ARRAY_PTR, d_array)
  16. ll_array[0] = llval
  17. floatval = d_array[0]
  18. lltype.free(d_array, flavor='raw')
  19. return floatval
  20. def float2longlong_emulator(floatval):
  21. d_array = lltype.malloc(DOUBLE_ARRAY_PTR.TO, 1, flavor='raw')
  22. ll_array = rffi.cast(LONGLONG_ARRAY_PTR, d_array)
  23. d_array[0] = floatval
  24. llval = ll_array[0]
  25. lltype.free(d_array, flavor='raw')
  26. return llval
  27. from pypy.translator.tool.cbuild import ExternalCompilationInfo
  28. eci = ExternalCompilationInfo(includes=['string.h'],
  29. post_include_bits=["""
  30. static double pypy__longlong2float(long long x) {
  31. double dd;
  32. memcpy(&dd, &x, 8);
  33. return dd;
  34. }
  35. static long long pypy__float2longlong(double x) {
  36. long long ll;
  37. memcpy(&ll, &x, 8);
  38. return ll;
  39. }
  40. """])
  41. longlong2float = rffi.llexternal(
  42. "pypy__longlong2float", [rffi.LONGLONG], rffi.DOUBLE,
  43. _callable=longlong2float_emulator, compilation_info=eci,
  44. _nowrapper=True, pure_function=True)
  45. float2longlong = rffi.llexternal(
  46. "pypy__float2longlong", [rffi.DOUBLE], rffi.LONGLONG,
  47. _callable=float2longlong_emulator, compilation_info=eci,
  48. _nowrapper=True, pure_function=True)