Vigenère cipher: Difference between revisions
m
→{{header|Zig}}: refactor parameter to use enum instead of bool
Recombinant (talk | contribs) m (→{{header|Zig}}: refactor parameter to use enum instead of bool) |
|||
Line 4,701:
=={{header|Zig}}==
{{works with|Zig|0.11.
<syntaxhighlight lang="zig">
const std = @import("std");
const Allocator = std.mem.Allocator;
</syntaxhighlight><syntaxhighlight lang="zig">
const Vigenere = enum {
<syntaxhighlight lang="zig">/// Caller owns the returned slice memory.▼
encode,
fn vigenere(allocator: Allocator, text: []const u8, key: []const u8, encrypt: bool) Allocator.Error![]u8 {▼
decode,
var dynamic_string = std.ArrayList(u8).init(allocator);▼
};
var key_index: usize = 0;▼
</syntaxhighlight><syntaxhighlight lang="zig">
for (text) |letter| {▼
const c = if (std.ascii.isLower(letter)) std.ascii.toUpper(letter) else letter;▼
// ------------------------------------------ allocator
if (std.ascii.isUpper(c)) {▼
const k = key[key_index];▼
const n = if (encrypt) ((c - 'A') + (k - 'A')) else 26 + c - k;▼
try dynamic_string.append(n % 26 + 'A'); // A-Z▼
key_index += 1;▼
key_index %= key.len;▼
}▼
}▼
return dynamic_string.toOwnedSlice();▼
}</syntaxhighlight>▼
▲<syntaxhighlight lang="zig">pub fn main() anyerror!void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer {
Line 4,729 ⟶ 4,719:
}
const allocator = gpa.allocator();
// --------------------------------------------- stdout
const stdout = std.io.getStdOut().writer();
// ----------------------------------------------------
const key = "VIGENERECIPHER";
const text = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!";
const encoded = try vigenere(allocator, text, key,
defer allocator.free(encoded);
try stdout.print("{s}\n", .{encoded});
const decoded = try vigenere(allocator, encoded, key,
defer allocator.free(decoded);
try stdout.print("{s}\n", .{decoded});
}
</syntaxhighlight><syntaxhighlight lang="zig">
▲fn vigenere(allocator: Allocator, text: []const u8, key: []const u8,
▲ var dynamic_string = std.ArrayList(u8).init(allocator);
▲ var key_index: usize = 0;
▲ for (text) |letter| {
▲ const c = if (std.ascii.isLower(letter)) std.ascii.toUpper(letter) else letter;
▲ if (std.ascii.isUpper(c)) {
▲ const k = key[key_index];
const n = switch (mode) {
.decode => 26 + c - k,
};
▲ try dynamic_string.append(n % 26 + 'A'); // A-Z
▲ key_index += 1;
▲ key_index %= key.len;
▲ }
▲ }
▲ return dynamic_string.toOwnedSlice();
}
<pre>WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH</pre>
|