Created
November 13, 2019 20:25
-
-
Save kdchambers/8c9e94dab25902c581564451ce2a4c18 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const WrappedType = struct { | |
// Assumption that this field would be taken out for runtime and therefore not affect the size of WrappedType | |
comptime const gaurantee: TypeProperties, | |
data: u64, | |
}; | |
const TypeProperties = enum { | |
isA, | |
isB | |
}; | |
fn makeGuaranteedTypeA(some_value: u64) WrappedType { | |
return WrappedType { | |
.gaurantee = .isA, // Literal, comptime known | |
.data = some_value; | |
}; | |
} | |
fn makeGuaranteedTypeB(some_value: u64) WrappedType { | |
return WrappedType { | |
.gaurantee = .isB, // Literal, comptime known | |
.data = some_value; | |
}; | |
} | |
fn doSomething(some_var: WrappedType) void { | |
comptime { | |
assert(some_var.gaurantee == .isA); | |
// Or | |
if(some_var.gaurantee != .isA) { | |
// Would probably want a version of this that doesn't block compilation | |
@compileLog("Warning: This may be bad and unintended"); | |
} | |
}; | |
// Do whatever with some_var | |
} | |
pub fn main() void { | |
var a = makeGuaranteedTypeA(55); | |
var b = makeGuaranteedTypeB(55); | |
doSomething(a); | |
doSomething(b); // Error / warning | |
} | |
// Example use case: | |
// In vulkan, VkBuffers can only be bound to VkDeviceMemory if they are compatiable. | |
// Both types are opaque so there is no way to determine compatability at runtime without retaining extra data. | |
// So, it would be quite easy to try to bind an incompatible VkBuffer to VkDeviceMemory at runtime | |
// even though this should be detectable at comptime |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment