Last active
May 7, 2016 05:31
-
-
Save salortiz/051c7a81400522e30a7cf12377c02f70 to your computer and use it in GitHub Desktop.
POSIX strftime for Perl6
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use v6; | |
use NativeCall; | |
constant MAX_BUF_SIZE = 255; # Seems reasonable | |
constant time_t = size_t; # Best guess. | |
my class tm is repr('CStruct') { }; # Fields can be added when needed | |
my sub gmtime(time_t is rw -->tm) is native { * }; | |
my sub strftime(utf8, size_t, Str, tm -->size_t) is native { * }; | |
sub PosixFormat(DateTime:D $time, Str $format) is export { | |
my time_t $t = $time.posix; | |
my utf8 $b .= allocate(MAX_BUF_SIZE); | |
my $res = strftime($b, $b.bytes, $format, my $tm = gmtime($t)); | |
$b.subbuf(0,$res).decode; | |
} | |
# Test with: | |
#$ perl6 -I. -e 'use strftime; DateTime.now.&PosixFormat("%a, %d %b %Y %T GMT").say'; | |
# | |
# augmenting DateTime is left as an exercise to the reader. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment