Mirror of Svelto.ECS because we're a fan of it
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
1.9KB

  1. using System;
  2. using Svelto.ECS.Internal;
  3. public static class DefaultSerializerUtils
  4. {
  5. public static unsafe void CopyToByteArray<T>(in T src, byte[] data, uint offsetDst) where T : unmanaged, _IInternalEntityComponent
  6. {
  7. #if DEBUG && !PROFILE_SVELTO
  8. if (data.Length - offsetDst < sizeof(T))
  9. {
  10. throw new IndexOutOfRangeException(
  11. $"Data out of bounds when copying struct {typeof(T).GetType().Name}. data.Length: {data.Length}, offsetDst: {offsetDst}");
  12. }
  13. #endif
  14. fixed (void* dstPtr = data)
  15. {
  16. void* dstOffsetPtr;
  17. if (IntPtr.Size == sizeof(int))
  18. {
  19. dstOffsetPtr = (void*) (((IntPtr) dstPtr).ToInt32() + ((IntPtr) offsetDst).ToInt32());
  20. }
  21. else
  22. {
  23. dstOffsetPtr = (void*) (((IntPtr) dstPtr).ToInt64() + ((IntPtr) offsetDst).ToInt64());
  24. }
  25. *(T*) dstOffsetPtr = src;
  26. }
  27. }
  28. public static unsafe T CopyFromByteArray<T>(byte[] data, uint offsetSrc) where T : unmanaged, _IInternalEntityComponent
  29. {
  30. T dst = default;
  31. #if DEBUG && !PROFILE_SVELTO
  32. if (data.Length - offsetSrc < sizeof(T))
  33. {
  34. throw new IndexOutOfRangeException(
  35. $"Data out of bounds when copying struct {dst.GetType().Name}. data.Length: {data.Length}, offsetSrc: {offsetSrc}");
  36. }
  37. #endif
  38. void* dstPtr = &dst;
  39. fixed (void* srcPtr = data)
  40. {
  41. void* srcOffsetPtr;
  42. if (IntPtr.Size == sizeof(int))
  43. {
  44. srcOffsetPtr = (void*) (((IntPtr) srcPtr).ToInt32() + ((IntPtr) offsetSrc).ToInt32());
  45. }
  46. else
  47. {
  48. srcOffsetPtr = (void*) (((IntPtr) srcPtr).ToInt64() + ((IntPtr) offsetSrc).ToInt64());
  49. }
  50. *(T*) dstPtr = *(T*) srcOffsetPtr;
  51. }
  52. return dst;
  53. }
  54. }