Rot-13: Difference between revisions

Content added Content deleted
(Add Uxntal)
(→‎{{header|Zig}}: Rewrite to not modify input argument, add output and supported versions.)
Line 6,873: Line 6,873:


=={{header|Zig}}==
=={{header|Zig}}==

<syntaxhighlight lang="zig">
{{Works with|Zig|0.11.x}}
// Warning: modifies the buffer in-place (returns pointer to in)
{{Works with|Zig|0.12.0-dev.1643+91329ce94}}
fn rot13(in: [] u8) []u8 {

for (in) |*c| {
<syntaxhighlight lang="zig">const std = @import("std");
var d : u8 = c.*;

var x : u8 = d;
pub const Rot13 = struct {
x = if (@subWithOverflow(u8, d | 32, 97, &x) ) x else x;
if (x < 26) {
pub fn char(ch: u8) u8 {
x = (x + 13) % 26 + 65 + (d & 32);
return switch (ch) {
c.* = x;
'a'...'m', 'A'...'M' => |c| c + 13,
}
'n'...'z', 'N'...'Z' => |c| c - 13,
else => |c| c,
};
}
}
return in;
}


/// Caller owns returned memory.
const msg: [:0] const u8 =
pub fn slice(allocator: std.mem.Allocator, input: []const u8) error{OutOfMemory}![]u8 {
\\Lbh xabj vg vf tbvat gb or n onq qnl
const output = try allocator.alloc(u8, input.len);
\\ jura gur yrggref va lbhe nycunorg fbhc
errdefer allocator.free(output);
\\ fcryy Q-V-F-N-F-G-R-E.
;


for (input, output) |input_ch, *output_ch| {
// need to copy the const string to a buffer
output_ch.* = char(input_ch);
// before we can modify it in-place
}
//https://zig.news/kristoff/what-s-a-string-literal-in-zig-31e9


return output;
var buf: [500]u8 = undefined;
fn assignStr(out: []u8, str: [:0]const u8) void {
for (str) |c, i| {
out[i] = c;
}
}
};
out[str.len] = 0;

}
pub fn main() error{OutOfMemory}!void {
var gpa: std.heap.GeneralPurposeAllocator(.{}) = .{};
defer _ = gpa.deinit();
const allocator = gpa.allocator();

const message_input =
\\@@@111@@@ Lbh xabj vg vf tbvat gb or n onq qnl
\\ jura gur yrggref va lbhe nycunorg fbhc
\\ fcryy Q-V-F-N-F-G-R-E.
;
const message_decoded = try Rot13.slice(allocator, message_input);
defer allocator.free(message_decoded);

std.debug.print(
\\{s}
\\=== Decoded to ===
\\{s}
\\
, .{
message_input,
message_decoded,
});

std.debug.print("\n", .{});

const message_encoded = try Rot13.slice(allocator, message_decoded);
defer allocator.free(message_encoded);

std.debug.print(
\\{s}
\\=== Encoded to ===
\\{s}
\\
, .{
message_decoded,
message_encoded,
});
}</syntaxhighlight>

{{out}}
<pre>
@@@111@@@ Lbh xabj vg vf tbvat gb or n onq qnl
jura gur yrggref va lbhe nycunorg fbhc
fcryy Q-V-F-N-F-G-R-E.
=== Decoded to ===
@@@111@@@ You know it is going to be a bad day
when the letters in your alphabet soup
spell D-I-S-A-S-T-E-R.


@@@111@@@ You know it is going to be a bad day
const print = @import("std").debug.print;
when the letters in your alphabet soup
spell D-I-S-A-S-T-E-R.
=== Encoded to ===
@@@111@@@ Lbh xabj vg vf tbvat gb or n onq qnl
jura gur yrggref va lbhe nycunorg fbhc
fcryy Q-V-F-N-F-G-R-E.


</pre>
pub fn main() void {
assignStr(&buf, msg);
print("rot13={s}\n",.{rot13(&buf)});
}
</syntaxhighlight>


=={{header|zkl}}==
=={{header|zkl}}==