Skip to content

Instantly share code, notes, and snippets.

@mgravell
Last active April 24, 2017 08:19
Show Gist options
  • Save mgravell/deffa76aeb52bc576e8f1268d29135bf to your computer and use it in GitHub Desktop.
Save mgravell/deffa76aeb52bc576e8f1268d29135bf to your computer and use it in GitHub Desktop.
// edit: hmmm, actually I can see cases where this would fail epicly, so
// probably best to ignore me here - for example:
// var span = GetSomeType().GetTags() - the SomeType value has now left the
// logical stack-frame, so our ref is undefined. It *could* perhaps
// work in the context of a "ref SomeType", but again: hard scoping
// so yeah, I'm mad - ignore me and ignore this!
===========================
// some crazy ideas about "ref T" and "Span<T>" in
// the context of "fixed" fields; I *think* I can
// emulate all of this at runtime using Unsafe and
// manually measuring the offset at runtime, and using
// hacks, but I *think* this is all actually pretty
// legal to work *without* all that hackery...
unsafe struct SomeType
{
private int _id;
// moar fields, etc
private fixed int _tags[10];
// moar fields, etc
// I **think** it is legit to talk about a
// ref directly into the fixed block (compiler
// doesn't allow it, though)
public ref int GetTag(int index)
{
// not shown, check range
return ref _tags[index];
}
// and by extension, if we can get a ref to that,
// and if we had the Span<T> semantics that allow
// us to pass *in* a ref T, then we could do:
public Span<int> GetTags()
{
// this "ref T, int" constructor doesn't
// exist, note
return new Span<int>(ref _tags[0], 10);
}
// although (and this is a stretch goal) the *compiler*
// already knows the length... how crazy is this?
public Span<int> GetTagsWithModestCompilerHelp()
{
// this is not a pre-existing legal "sizeof" usage,
// just spitballing here...
return new Span<int>(ref _tags[0], sizeof(_tags));
}
// or going fully crazy
public Span<int> GetTagsWithEpicCompilerHelp()
{
// lots of implicit stuff here...
return _tags;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment