Skip to content

Are we sure in_use will be initialised to false? #17

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
malcolmstill opened this issue May 7, 2020 · 1 comment
Open

Are we sure in_use will be initialised to false? #17

malcolmstill opened this issue May 7, 2020 · 1 comment

Comments

@malcolmstill
Copy link
Owner

No description provided.

@malcolmstill
Copy link
Owner Author

I wonder if this might be a interesting use of arbitrary size integers and @popCount:

const std = @import("std");

const MAX_CLIENTS = @bitSizeOf(u512);
var CLIENTS: [MAX_CLIENTS]Client = undefined;
var CLIENTS_POP: u512 = 0;

pub const Client = struct {
    index: usize,
    data: u32,

    pub fn deinit(self: *Client) void {
        var mask: u512 = 1;
        std.debug.warn("deinit index: {}\n", .{self.index});
        mask <<= @intCast(u9, self.index);
        CLIENTS_POP ^= mask;
    }
};

fn newClient() !*Client {
    var mask: u512 = 1;
    var i: usize = 0;
    while (i < MAX_CLIENTS) {
        // std.debug.warn("i: {}\n", .{i});
        if (mask & CLIENTS_POP == 0) {
            // std.debug.warn("mask {b}, pop {b}\n", .{mask, CLIENTS_POP});
            CLIENTS_POP = CLIENTS_POP | mask;
            CLIENTS[i].index = i;
            return &CLIENTS[i];
        } else {
            mask = mask << 1;
            i = i + 1;
            continue;
        }
    }
    return error.ClientsExhausted;
}

pub fn main() anyerror!void {
    CLIENTS_POP -%= 1;
    CLIENTS_POP ^= 0b00001000000000000000000000000000000000000000000000000000000;
    std.debug.warn("initial population: {}\n", .{@popCount(u512, CLIENTS_POP)});
    var c1: *Client = try newClient();
    std.debug.warn("after c({}) new population: {}\n", .{c1.index, @popCount(u512, CLIENTS_POP)});
    // std.debug.warn("pop {b}\n", .{CLIENTS_POP});

    var save: *Client = undefined;
    var i: usize = 0;
    while (i < 7) {
        std.debug.warn("derp i: {}\n", .{i});
        var c = try newClient();
        if (i == 5) {
            save = c;
        }
        i = i + 1;
    }

    c1.deinit();
    std.debug.warn("after c1 deinit: {}\n", .{@popCount(u512, CLIENTS_POP)});
    // std.debug.warn("pop {b}\n", .{CLIENTS_POP});

    save.deinit();
    std.debug.warn("after save deinit: {}\n", .{@popCount(u512, CLIENTS_POP)});
    // std.debug.warn("pop {b}\n", .{CLIENTS_POP});    
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant