Skip to content

Chapter 4: confusement of summation and bitwise OR, _char_index reimplementation #210

@Centrix14

Description

@Centrix14

Hello! I'm sure you will find useful these small propositions about chapter 4.

First. In sections 4.4.1 and 4.5.2 you suggest using sum (+) to implement bit overlaying. Technically it will work, but semantically it's doubtful. In essence, overlaying is a bitwise OR operation, not summation. Summation may be very confusing for those (who like me) know how sum is implemented in a low-level. Additionally, bitwise OR will be more consistent (since you are introducing bitwise AND) and pedagogically useful (since this project is, in essence, an etude).

Second. In section 4.5.1 you introduce a "brute force" implementation of _char_index function. This is a probable but not appropriate suggestion. From a programmer's view, following code will be faster and, at the same time, more beautiful:

fn _char_at(self: Base64, char: u8) u8 {
    return switch (char) {
        48...57 => char + 4, // char is a digit
        65...90 => char - 65, // char is a capital letter
        97...122 => char - 71, // char is a small letter
        '+' => 62,
        '/' => 63,
        '=' => 64,
        else => unreachable
    };
}

This kind of implementation I used in my own code.

Another reason for this implementation is purely pedagogical nature. In previous chapters you have explained two key points about switches in Zig: (1) they can be expressions, (2) they can use ranges. So why won't apply this knowledge to a real case?

I'm not fighting for the full removal of the "brute force" variant. I think it will be better to show both ways: simple (which is an exercise in loops) and more sophisticated (which requires familiarity with the ASCII table and knowledge of Zig's switch powers).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions