p4-spec
p4-spec copied to clipboard
hash algorithms and HashAlgorithm in the PSA
The current mechanism of specifying hash algorithms via an enum that describes a fixed (and resonably small) set of possible hash functions seems inadequate. Some targets may support things like CRC functions with arbitrary polynomial coefficients, and some may even support arbitrary user-defined functions.
Allowing the language to express architectures that could support such things is tricky.
One possibility is to keep the current enum HashAlgorithm
, but allow an architecture to define extern functions that return a HashAlgorithm
that does not necessarily correspond to any named member of the enum:
extern HashAlgorithm crc_poly<T>(in T coef); // CRC with arbitrary polynomial coefficients
This works out through type checking -- the return value of such a function can be provided to an extern function or constructor that expects a HashAlgorithm, but feels a bit hacky to me.
Another possibility is just making HashAlgorithm
an extern. It would be nice to allow predefined instances of the extern in its namespace (currently not allowed by the language) and possibly factory methods that return instances (like constructors, but using names). Something like:
extern HashAlgorithm {
HashAlgorithm();
static HashAlgorithm() crc32; // default 32-bit crc
static HashAlgorithm() crc16; // default 16-bit crc
static HashAlgorithm crc<T>(in T coeff); // crc with arbitrary polynomial
static HashAlgorithm() identity;
abstract O hash<O, T>(int T data); // user-defined hash function
};
I'm here using static
like it is used in C++ -- to define class instances and methods.
The hard requirement in P4 is for all values with type extern to be evaluated at compile-time. They are allocated statically by the compiler. If the factory method is evaluated at compile-time then probably we could make this work.
Yes, the idea is that all of these things should be evaluated at compile time. Maybe const
is a better descriptive work than static
?
The only potentially runtime evaluated thing above is the abstract hash
method.
Still, if you do this, how do you allow architectures to add new HashAlgorithm implementations to this list?