Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I ensure T is serializable in a fixed number of bytes?

I'm writing a generic DataStructure<T> which persists on the disk, and I need to write it such that T is guaranteed to be serializable in a fixed number of bytes. For example, int and char should be accepted, but string or int[] should not be. Likewise, a struct with a string member is not acceptable, but an unsafe struct with a fixed char array is.

I could write a runtime test in the initializer using reflection and sizeof to test each member, but that seems like a terrible hack. Is there any efficient and (relatively) safe way to do this?

like image 672
dlras2 Avatar asked Aug 11 '11 15:08

dlras2


2 Answers

There is no way to statically support a generic parameter which only have a fixed specific size. Constraints are limited to interfaces, ref / struct, base class and new.

What you can do though is use static factory methods to limit the uses of the generic to a known finite set of types which are suitable. For example

class DataStructure<T> { 
  private DataStructure(T value) { 
    ...
  }
}
static class DataStructure { 
  public static DataStructure<int> Create(int i) { 
    return new DataStructure<int>(i); 
  }
  public static DataStructure<char> Create(char c) { 
    return new DataStructure<char>(c); 
  }
}

This is limiting though because it requires you to list all comparable types ahead of time. If you want a more flexible solution that works with user defined types you'll need to implement a runtime check.

public static DataStructure<T> Create<T>(T value) { 
  RuntimeVerification(typeof(T));
  return new DataStructure<T>(value);
}
like image 162
JaredPar Avatar answered Nov 09 '22 13:11

JaredPar


Every valuetype that directly or indirectly contains only value types, but no reference types has a limited size. The only way to test that is at runtime using reflection.

If that is a good idea is a different question, and I'd say it's not a good idea. Serializing the raw data of a type is generally a bad idea IMO.

like image 1
CodesInChaos Avatar answered Nov 09 '22 14:11

CodesInChaos