Advertisement
Guest User

Untitled

a guest
Feb 28th, 2019
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.60 KB | None | 0 0
  1. fn hasType(comptime CheckType: type, comptime rec: bool) TraitFn {
  2.     const Closure = struct {
  3.         pub fn trait(comptime T: type) bool {
  4.             const info = @typeInfo(T);
  5.             const fields = switch(info) {
  6.                 builtin.TypeId.Struct => |s| s.fields,
  7.                 builtin.TypeId.Union => |u| u.fields,
  8.                 builtin.TypeId.Enum => |e| e.fields,
  9.                 else => return false,
  10.             };
  11.  
  12.             inline for(fields) |field| {
  13.                 if (mem.eql(u8, @typeName(field.field_type), @typeName(CheckType))) return true;
  14.  
  15.                 if (rec) {
  16.                     if (hasType(CheckType, rec)(field.field_type)) return true;
  17.                 }
  18.             }
  19.            
  20.             return false;
  21.         }
  22.     };
  23.  
  24.     return Closure.trait;
  25. }
  26.  
  27. pub const Pinned = struct {};
  28.  
  29. pub fn pin(comptime P: type) type {
  30.     return struct {
  31.         pointer: P,
  32.  
  33.         const Self = @This();
  34.        
  35.         fn init(p: P) Self {
  36.             return Self { .pointer = p};
  37.         }
  38.         fn deref(self: *const Self) *const P {
  39.             return &self.pointer;
  40.         }
  41.  
  42.         fn deref_mut(self: *Self) *P {
  43.             if(comptime hasType(Pinned, true)(P)) {
  44.                 @compileError(@typeName(P) ++ " can not be moved, or mutable dereferenced");
  45.             }
  46.  
  47.             return &self.pointer;
  48.         }
  49.     };
  50. }
  51.  
  52. test "pinn" {
  53.     const pinned = struct {
  54.        marker: Pinned,
  55.         n: u32,
  56.     };
  57.  
  58.     var x = pinned { .marker = Pinned{}, .n = 0};
  59.  
  60.     var p = pin(pinned).init(x);
  61.  
  62.     _ = p.deref_mut();
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement