Zig 0.17.0-dev (Split by item)

This is an example of documentation generated by ZigDoc, an alternative to Zig's built-in Auto Doc feature. See also examples in other modes/formats. The project being documented here (as the example) is the Zig library itself.

hasUniqueRepresentation

meta.hasUniqueRepresentation
pub inline fn hasUniqueRepresentation(comptime T: type) bool

File

lib/std/meta.zig:904

Code

pub inline fn hasUniqueRepresentation(comptime T: type) bool {
    return switch (@typeInfo(T)) {
        else => false, // TODO can we know if it's true for some of these types ?

        .@"anyframe",
        .error_set,
        .@"fn",
        => true,

        .bool => false,

        .@"enum" => |info| hasUniqueRepresentation(info.tag_type),
        .int => |info| @sizeOf(T) * 8 == info.bits,

        .pointer => |info| info.size != .slice,

        .optional => |info| switch (@typeInfo(info.child)) {
            .pointer => |ptr| !ptr.attrs.@"allowzero" and switch (ptr.size) {
                .slice, .c => false,
                .one, .many => true,
            },
            else => false,
        },

        .array => |info| hasUniqueRepresentation(info.child),

        .@"struct" => |info| {
            if (info.layout == .@"packed") return @sizeOf(T) * 8 == @bitSizeOf(T);

            var sum_size = @as(usize, 0);

            inline for (info.field_attrs, info.field_types) |field_attr, field_type| {
                if (field_attr.@"comptime") continue;
                if (!hasUniqueRepresentation(field_type)) return false;
                sum_size += @sizeOf(field_type);
            }

            return @sizeOf(T) == sum_size;
        },

        .@"union" => |info| {
            if (info.layout == .@"packed") return @sizeOf(T) * 8 == @bitSizeOf(T);
            inline for (info.field_types) |field_type| {
                if (@sizeOf(field_type) != @sizeOf(T)) return false;
                if (!hasUniqueRepresentation(field_type)) return false;
            }
            return true;
        },

        .vector => |info| hasUniqueRepresentation(info.child) and
            @sizeOf(T) == @sizeOf(info.child) * info.len,
    };
}