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.

47 lines
1.6KB

  1. using Svelto.Common;
  2. using Svelto.ECS.Internal;
  3. namespace Svelto.ECS.Serialization
  4. {
  5. public class DefaultSerializer<T> : IComponentSerializer<T> where T : unmanaged, _IInternalEntityComponent
  6. {
  7. static DefaultSerializer()
  8. {
  9. var _type = typeof(T);
  10. foreach (var field in _type.GetFields())
  11. {
  12. var fieldFieldType = field.FieldType;
  13. if (fieldFieldType.ContainsCustomAttribute(typeof(DoNotSerializeAttribute)) &&
  14. field.IsPrivate == false)
  15. throw new ECSException($"field cannot be serialised {fieldFieldType} in {_type.FullName}");
  16. }
  17. #if SLOW_SVELTO_SUBMISSION
  18. if (_type.GetProperties().Length > (ComponentBuilder<T>.HAS_EGID ? 1 : 0))
  19. throw new ECSException("serializable entity struct must be property less ".FastConcat(_type.FullName));
  20. #endif
  21. }
  22. public uint size => (uint)MemoryUtilities.SizeOf<T>();
  23. public bool Serialize(in T value, ISerializationData serializationData)
  24. {
  25. DefaultSerializerUtils.CopyToByteArray(value, serializationData.data.ToArrayFast(out _),
  26. serializationData.dataPos);
  27. serializationData.dataPos += (uint)size;
  28. return true;
  29. }
  30. public bool Deserialize(ref T value, ISerializationData serializationData)
  31. {
  32. value = DefaultSerializerUtils.CopyFromByteArray<T>(serializationData.data.ToArrayFast(out _),
  33. serializationData.dataPos);
  34. serializationData.dataPos += (uint)size;
  35. return true;
  36. }
  37. }
  38. }