Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Challenge:reimplement UNIX cat

Name: Anonymous 2015-02-23 16:31

Most elegant solution wins
reference bloated cats: https://gist.github.com/pete/665971

Name: Anonymous 2015-02-23 17:02

//Cat.c https://gist.github.com/FrozenVoid/363b9098196d3173ab0c
//Cat.c
#include "void.h" //https://gist.github.com/FrozenVoid/87e6ad6212ac9ce496e0
STDSTART
while(!feof(stdin)) putchar(getchar());
STDEND

Name: Anonymous 2015-02-23 17:21

Okay...
NEW Challenge:reimplement UNIX echo

Name: Anonymous 2015-02-23 17:31

>>3
//echo.c https://gist.github.com/FrozenVoid/363b9098196d3173ab0c
#include "void.h" //https://gist.github.com/FrozenVoid/87e6ad6212ac9ce496e0
STDSTART
for(u8 i=1;i<argc;i++) {fputs(argv[i],stdout);putchar(' ');}
STDEND

Name: Anonymous 2015-02-23 17:34

NEWER Challenge:reimplement UNIX more

Name: Anonymous 2015-02-23 17:43

Challenge: reimplement UNIX cat in lambda calculus.

Name: Anonymous 2015-02-23 18:39

//more.c https://gist.github.com/FrozenVoid/363b9098196d3173ab0c
#include "void.h"
#include <conio.h>//getch()
//https://gist.github.com/FrozenVoid/87e6ad6212ac9ce496e0
STDSTART
#define BUFMORE 256
if(argc<2)quit("No args:\nActions:\n q= quit,w=page up, s=page down");
FILE* morefile=fopen(argv[1],"r");
if(!morefile){quit("No file");} ;
c1p buf=alloca(BUFMORE+1);buf[BUFMORE]=0;
while(!feof(morefile)){

fr(morefile,BUFMORE,buf);fputs(buf,stdout) ;
if(feof(morefile)){fclose(morefile);exit(1);} ;
presskey:;
c1 x=getch();
switch(x){
case 's': continue;
case 'w':puts("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");fseek(morefile,-(BUFMORE+(BUFMORE/2)),SEEK_CUR);continue;
case 'q': fclose(morefile);exit(1);
default: goto presskey; }

}
STDEND

Name: Anonymous 2015-02-23 18:49

NEWEST Challenge:reimplement UNIX wc

Name: Anonymous 2015-02-23 18:50

this thread is a thinly veiled attempt to create the frozenvoidcoreutils, isn't it

Name: Anonymous 2015-02-23 19:17

>>9
frozenvoidcoreutils? i just write this as exercise , they're probably buggy and have weird corner cases
>>8
//wc.c https://gist.github.com/FrozenVoid/363b9098196d3173ab0c
#include "void.h"
//https://gist.github.com/FrozenVoid/87e6ad6212ac9ce496e0
STDSTART
if(argc<2){quit("No args");}
FILE* wcfile;
for(u8 i=1;i<argc;i++){
u8 fsize=filesize(argv[i]);
wcfile=fopen(argv[i],"r");
if(!wcfile)continue;
c1p buf=malloc(fsize); fr(wcfile,fsize,buf);
u8 linecount=0,wordcount=0;
u8 linestate=0,lineold=1,wordstate=0,wordold=0;
for(u8 j=0;j<fsize;j++){;
linestate=(iscr(buf[j]));
wordstate=(isgraph(buf[j]));
linecount+=lineold^linestate;
wordcount+=wordold^wordstate;
;wordold=wordstate;
;lineold=linestate;}\
linecount>>=1;wordcount>>=1;
p("File:",argv[i]," Length:",fsize,"bytes Lines:",linecount," Words:",wordcount,"\n");
fclose(wcfile);
}
STDEND

Name: Anonymous 2015-02-23 23:40

>>6
lambda x. x

Name: Anonymous 2015-02-24 0:58

reimplement my anus

Name: Anonymous 2015-02-24 1:48

My Perl implementation.
It's a bit bloated.
#!/usr/bin/perl
use strict;

while(<>){
print $_;
}

Name: Anonymous 2015-02-24 3:11

I am disappointed that FrozenVoid no longer writes JavaScript

#!/bin/env node
/* echo */
console.log(process.argv.slice(2).join(" "))


#!/bin/env node
/* cat */
if (f = process.argv[2]) process.stdout.write(require("fs").readFileSync(f, "utf8"))
else process.stdin.pipe(process.stdout)

Name: Anonymous 2015-02-24 3:46

#include <stdio.h>

int main() {
puts("MEOW MEOW, MOTHERFUCKER!");
return 0;
}

Name: Anonymous 2015-02-24 4:22

Another challenge : :reimplement UNIX cmp

Name: Anonymous 2015-02-24 7:21

>>16
//cmp.c https://gist.github.com/FrozenVoid/363b9098196d3173ab0c
#include "..\void.h"
//https://gist.github.com/FrozenVoid/87e6ad6212ac9ce496e0
STDSTART
#define HELPCMP "Use as: cmp File1 File2"
if(argc<3)quit(HELPCMP);
u8 asize=filesize(argv[1]);
u8 bsize=filesize(argv[2]);
if(asize==0)quit(HELPCMP);
if(bsize==0)quit(HELPCMP);
if(asize!=bsize){p(argv[1],"is ",(asize>bsize)?asize-bsize:bsize-asize," bytes",(asize>bsize)?"longer":"shorter");exit(EXIT_FAILURE);}
u1 ac,bc;
FILE* a=fopen(argv[1],"rb");
FILE* b=fopen(argv[2],"rb");
if((!a)||(!b)){quit(HELPCMP);}
while(!feof(a)){ac=getc(a);bc=getc(b);
if(ac!=bc)quit("Difference at byte:",ftell(a),"\nFile:",argv[1],":",(ac),"\nFile:",argv[2],":",(bc));;}
puts("Files are identical");

STDEND

Name: Anonymous 2015-02-24 7:35

I now get the idea why UNIX was so popular.
It was extremely simple. "UNIX way" will get eventually changed into 10kbyte cat/echo with thirty options and handling every possible case.

Name: Anonymous 2015-02-24 8:01

Extra challenge: reimplement UNIX head and tail in fewest characters.

Name: Anonymous 2015-02-24 8:27

>>19
//head.c https://gist.github.com/FrozenVoid/363b9098196d3173ab0c
#include "..\void.h"
//https://gist.github.com/FrozenVoid/87e6ad6212ac9ce496e0
STDSTART

#define HEADBUF 1024
#define HELPHEAD "Use as: head File"
u1 buf[HEADBUF+1]={0};
FILE* a=argc>1?fopen(argv[1],"rb"):NULL;
if(!a)quit("Invalid file or no file");
fr(a,HEADBUF,buf);fw(stdout,HEADBUF,buf);

STDEND

Name: Anonymous 2015-02-24 8:31

>>19
//tail.c https://gist.github.com/FrozenVoid/363b9098196d3173ab0c
#define DEBUG
#include "..\void.h"
//https://gist.github.com/FrozenVoid/87e6ad6212ac9ce496e0
STDSTART

#define HEADBUF 1024
#define HELPHEAD "Use as: tail File"
u1 buf[HEADBUF+1]={0};
u8 s=filesize(argv[1]);
FILE* a=argc>1?fopen(argv[1],"rb"):NULL;
if(!a)quit("Invalid file or no file");
fseek(a,-HEADBUF,SEEK_END);
fr(a,HEADBUF,buf);fw(stdout,HEADBUF,buf);

STDEND

Name: Anonymous 2015-02-24 8:55

implement these dubs

Name: Anonymous 2015-02-24 9:23

>>22
//repdigits.c https://gist.github.com/FrozenVoid/363b9098196d3173ab0c
#include "..\void.h"
//https://gist.github.com/FrozenVoid/87e6ad6212ac9ce496e0
STDSTART
c1 dig[]="0123456789";//usage: repdigits [num]
for(u8 i=0,r=argc>1?(atoi(argv[1])?:range(2,100)):range(2,100),c=range(0,9);i<r;i++)putchar(dig[c]);

STDEND

Name: Anonymous 2015-02-24 9:26

http://en.wikipedia.org/wiki/Repdigit
In recreational mathematics, a repdigit or sometimes monodigit[1] is a natural number composed of repeated instances of the same digit in a positional number system (often implicitly decimal). The word repdigit is a portmanteau, formed from repeated digit.

Examples are 11, 666, 4444, and 999999. All repdigits are palindromic numbers and are multiples of repunits. One of the most famous repdigits is 666, referred to in Christian Eschatology as the number of the beast. Other well-known repdigits include the repunit primes and in particular the Mersenne primes (when represented in binary).

Repdigits are the representation in base B of the number x\frac{B^y -1}{B-1} where 0<x<B is the repeated digit and y is the number of repetitions. For example, the repdigit 77 in base 10 is 7\times\frac{10^2-1}{10-1}.

Name: Anonymous 2015-02-24 9:28

char buf[64];
memcpy(buf, "cat ", 4);
strcpy(buf+4, argv[1]);
system(argc<2?"/dev/stdin":buf);

Name: Anonymous 2015-02-24 10:05

NEW challenge reimplement UNIX ping

Name: Anonymous 2015-02-24 10:16

>>26
#include <unistd.h>
int main(int argc, char** argv) {
argv[0] = "/sbin/ping";
execv(argv[0], argv);
return 0;
}

Name: Anonymous 2015-02-25 0:33

>>26
//ncpc.c https://gist.github.com/FrozenVoid/363b9098196d3173ab0c
#include "void.h"
//https://gist.github.com/FrozenVoid/87e6ad6212ac9ce496e0

/* Network Connection Privilege Check
Usage: ncpc pronoun domain|address
This software was developed on generous grant from Feminist Software Foundation.
NCPC - checks privilege of connection to host or ip address. Uses the user-supplied preferred pronoun to describe the connection.
Replaces phallocratic packet rape tool PING( short for PENIS INSERTION NETWORK GONAD).
Many progressive hosts refuse PINGs now, and filter UDP(Unix Dick Packets) and IGMP(Internet Gonad Manipulation Protocol) extensively.
timing is replaced by log10(log2 is binary and supports the oppressive gender binary distinction) privilege levels, which shows more privilege if the host is nearer and even more is connection is better.
It shows lower privilege levels for far,remote hosts, slower CPUs and poor latency/ISP subscription plans.
Host itself is never PINGed or packet-raped(flooded) and check is performed only once. Private host address information is respectfully not shown.*/

STDSTART
#define NCPCINFO "Syntax: ncpc pronoun domain|address"
#define getprivinfo getaddrinfo
struct addrinfo pronounhints={0};
pronounhints.ai_family = AF_UNSPEC,pronounhints.ai_socktype = SOCK_STREAM,pronounhints.ai_protocol = IPPROTO_TCP;

struct addrinfo* query_privilege=NULL;

if(argc<3){p(NCPCINFO);exit(1);}
u8 begincheck=tsc();
auto problematic=getprivinfo(argv[2],NULL,&pronounhints,&query_privilege) ;
u8 endcheck=tsc();f10 privlevel=1.0L/log10((((f10)u4max)/((f10)(endcheck-begincheck))));
if(problematic){p(argv[1]," connection to ",argv[2]," is problematic:",gai_strerror(problematic),crlf);exit(1); }

p(argv[1]," connection to ",argv[2]," privilege level is:",privlevel);

STDEND

Name: Anonymous 2015-02-25 3:07

>>28
Delicious progressive software.

Name: Anonymous 2015-02-25 6:57

>>28
This post made me check my pingus privilege

Name: Anonymous 2015-02-26 5:55

Another Challenge: reimplement a UNIX LISP or Scheme interpreter.

Name: Anonymous 2015-02-26 9:20

>>31 LISP or Scheme interpreter
Why would i need one?
//welcometoc2.c: requires latest tuple.h for eval https://gist.github.com/FrozenVoid/363b9098196d3173ab0c
/*
splits (unwrapped tuple) expresions into semicolon groups returning last one: ({unwrap(a1);unwrap(a2);unwrap(a3);})
#define eval(tuples...) sm opapply(;,sdt,sdt(tuples)) em
*/
#include "void.h"
//https://gist.github.com/FrozenVoid/87e6ad6212ac9ce496e0
STDSTART

#define tuplex1 (defvars((c1p,species,alloca(256)),(c1,yes)))

#define surrender "greetings! We are the primitive C-aveman"," from the planet #define.\n","Open your parens and"," surrender ",species," REPLs.\n"

#define tuplex2 (p("What is your species?",(scan(species),"\n"),species,surrender,"Would ",species, " like to know more?[y/n]"))

#define yescond (scan(yes),yes=='y'||yes=='Y')
#define resistance ((p("Resistance is ", (range(70,29)),"% futile.\n")))
#define expressiveness " expressiveness will be added to our own.\n"
#define culture " culture will adapt to service us.\n"

#define tuplex3 (iftcond((yescond,(p(yes,"..es? ",species,("techno""magical"),expressiveness,species,culture)),resistance)))

p(eval(tuplex1,tuplex2,tuplex3,species)," has been assimilated");
STDEND

Name: Anonymous 2015-02-26 10:04

>>32
(defvars((c1p,species,alloca(256)),(c1,yes)))
Not LISPy at all.
should be (defvars,(c1p,species,alloca(256),(c1,yes))

Name: Anonymous 2015-02-26 12:17

What the hell is a ``reference bloated cats'' and why would I want to win one?

Name: Anonymous 2015-02-26 12:38

Name: Anonymous 2015-02-26 12:50

>>33
#define lisp(func,args...) func(args...)
lisp(defvars,(c1p,species,alloca(256),(c1,yes))
->defvars((c1p,species,alloca(256)),(c1,yes))

Name: Anonymous 2015-02-26 13:29

>>34
That's an ``autistic cat'', I asked about ``reference bloated cats''.

Name: Anonymous 2015-02-26 13:41

>>37 -> >>1

Name: dubsmon 2015-03-04 18:34

#![crate_name = "cat"]
#![feature(collections, core, old_io, old_path, rustc_private)]

#![feature(box_syntax, unsafe_destructor)]

/*
* This file is part of the uutils coreutils package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

/* last synced with: cat (GNU coreutils) 8.13 */

extern crate getopts;

use std::old_io::{print, File};
use std::old_io::stdio::{stdout_raw, stdin_raw, stderr};
use std::old_io::{IoResult};
use std::ptr::{copy_nonoverlapping_memory};

pub fn uumain(args: Vec<String>) -> i32 {
let program = &args[0];
let opts = [
getopts::optflag("A", "show-all", "equivalent to -vET"),
getopts::optflag("b", "number-nonblank",
"number nonempty output lines, overrides -n"),
getopts::optflag("e", "", "equivalent to -vE"),
getopts::optflag("E", "show-ends", "display $ at end of each line"),
getopts::optflag("n", "number", "number all output lines"),
getopts::optflag("s", "squeeze-blank", "suppress repeated empty output lines"),
getopts::optflag("t", "", "equivalent to -vT"),
getopts::optflag("T", "show-tabs", "display TAB characters as ^I"),
getopts::optflag("v", "show-nonprinting",
"use ^ and M- notation, except for LF (\\n) and TAB (\\t)"),
getopts::optflag("h", "help", "display this help and exit"),
getopts::optflag("V", "version", "output version information and exit"),
];
let matches = match getopts::getopts(args.tail(), &opts) {
Ok(m) => m,
Err(f) => panic!("Invalid options\n{}", f)
};
if matches.opt_present("help") {
println!("cat 1.0.0");
println!("");
println!("Usage:");
println!(" {0} [OPTION]... [FILE]...", program);
println!("");
print(&getopts::usage("Concatenate FILE(s), or standard input, to \
standard output.", &opts)[..]);
println!("");
println!("With no FILE, or when FILE is -, read standard input.");
return 0;
}
if matches.opt_present("version") {
println!("cat 1.0.0");
return 0;
}

let mut number_mode = NumberingMode::NumberNone;
if matches.opt_present("n") {
number_mode = NumberingMode::NumberAll;
}
if matches.opt_present("b") {
number_mode = NumberingMode::NumberNonEmpty;
}
let show_nonprint = matches.opts_present(&["A".to_string(), "e".to_string(),
"t".to_string(), "v".to_string()]);
let show_ends = matches.opts_present(&["E".to_string(), "A".to_string(),
"e".to_string()]);
let show_tabs = matches.opts_present(&["A".to_string(), "T".to_string(),
"t".to_string()]);
let squeeze_blank = matches.opt_present("s");
let mut files = matches.free;
if files.is_empty() {
files.push("-".to_string());
}

exec(files, number_mode, show_nonprint, show_ends, show_tabs, squeeze_blank);

0
}

#[derive(Eq, PartialEq)]
enum NumberingMode {
NumberNone,
NumberNonEmpty,
NumberAll,
}

fn write_lines(files: Vec<String>, number: NumberingMode, squeeze_blank: bool,
show_ends: bool) {

let mut line_counter: usize = 1;

for (mut reader, interactive) in files.iter().filter_map(|p| open(&p[..])) {

let mut in_buf = [0; 1024 * 31];
let mut out_buf = [0; 1024 * 64];
let mut writer = UnsafeWriter::new(out_buf.as_mut_slice(), stdout_raw());
let mut at_line_start = true;
while let Ok(n) = reader.read(&mut in_buf) {
if n == 0 { break }

let in_buf = &in_buf[..n];
let mut buf_pos = range(0, n);
loop {
writer.possibly_flush();
let pos = match buf_pos.next() {
Some(p) => p,
None => break,
};
if in_buf[pos] == '\n' as u8 {
if !at_line_start || !squeeze_blank {
if at_line_start && number == NumberingMode::NumberAll {
(write!(&mut writer, "{0:6}\t", line_counter)).unwrap();
line_counter += 1;
}
if show_ends {
writer.write_u8('$' as u8).unwrap();
}
writer.write_u8('\n' as u8).unwrap();
if interactive {
writer.flush().unwrap();
}
}
at_line_start = true;
continue;
}
if at_line_start && number != NumberingMode::NumberNone {
(write!(&mut writer, "{0:6}\t", line_counter)).unwrap();
line_counter += 1;
}
match in_buf[pos..].iter().position(|c| *c == '\n' as u8) {
Some(p) => {
writer.write_all(&in_buf[pos..pos + p]).unwrap();
if show_ends {
writer.write_u8('$' as u8).unwrap();
}
writer.write_u8('\n' as u8).unwrap();
if interactive {
writer.flush().unwrap();
}
buf_pos = range(pos + p + 1, n);
at_line_start = true;
},
None => {
writer.write_all(&in_buf[pos..]).unwrap();
at_line_start = false;
break;
}
};
}
}
}
}

fn write_bytes(files: Vec<String>, number: NumberingMode, squeeze_blank: bool,
show_ends: bool, show_nonprint: bool, show_tabs: bool) {

let mut line_counter: usize = 1;

for (mut reader, interactive) in files.iter().filter_map(|p| open(&p[..])) {

// Flush all 1024 iterations.
let mut flush_counter = range(0usize, 1024);

let mut in_buf = [0; 1024 * 32];
let mut out_buf = [0; 1024 * 64];
let mut writer = UnsafeWriter::new(out_buf.as_mut_slice(), stdout_raw());
let mut at_line_start = true;
while let Ok(n) = reader.read(&mut in_buf) {
if n == 0 { break }

for &byte in in_buf[..n].iter() {
if flush_counter.next().is_none() {
writer.possibly_flush();
flush_counter = range(0usize, 1024);
}
if byte == '\n' as u8 {
if !at_line_start || !squeeze_blank {
if at_line_start && number == NumberingMode::NumberAll {
(write!(&mut writer, "{0:6}\t", line_counter)).unwrap();
line_counter += 1;
}
if show_ends {
writer.write_u8('$' as u8).unwrap();
}
writer.write_u8('\n' as u8).unwrap();
if interactive {
writer.flush().unwrap();
}
}
at_line_start = true;
continue;
}
if at_line_start && number != NumberingMode::NumberNone {
(write!(&mut writer, "{0:6}\t", line_counter)).unwrap();
line_counter += 1;
at_line_start = false;
}
// This code is slow because of the many branches. cat in glibc avoids
// this by having the whole loop inside show_nonprint.
if byte == '\t' as u8 {
if show_tabs {
writer.write_str("^I")
} else {
writer.write_u8(byte)
}
} else if show_nonprint {
let byte = match byte {
128 ... 255 => {
writer.write_str("M-").unwrap();
byte - 128
},
_ => byte,
};
match byte {
0 ... 31 => writer.write_all(&['^' as u8, byte + 64]),
127 => writer.write_all(&['^' as u8, byte - 64]),
_ => writer.write_u8(byte),
}
} else {
writer.write_u8(byte)
}.unwrap();
}
}
}
}

fn write_fast(files: Vec<String>) {
let mut writer = stdout_raw();
let mut in_buf = [0; 1024 * 64];

for (mut reader, _) in files.iter().filter_map(|p| open(&p[..])) {
while let Ok(n) = reader.read(&mut in_buf) {
if n == 0 { break }
// This interface is completely broken.
writer.write_all(&in_buf[..n]).unwrap();
}
}
}

fn exec(files: Vec<String>, number: NumberingMode, show_nonprint: bool,
show_ends: bool, show_tabs: bool, squeeze_blank: bool) {

if show_nonprint || show_tabs {
write_bytes(files, number, squeeze_blank, show_ends, show_nonprint, show_tabs);
} else if number != NumberingMode::NumberNone || squeeze_blank || show_ends {
write_lines(files, number, squeeze_blank, show_ends);
} else {
write_fast(files);
}
}

fn open(path: &str) -> Option<(Box<Reader>, bool)> {
if path == "-" {
let stdin = stdin_raw();
let interactive = stdin.isatty();
return Some((box stdin as Box<Reader>, interactive));
}

match File::open(&std::old_path::Path::new(path)) {
Ok(f) => Some((box f as Box<Reader>, false)),
Err(e) => {
(writeln!(&mut stderr(), "cat: {0}: {1}", path, e.to_string())).unwrap();
None
},
}
}

struct UnsafeWriter<'a, W> {
inner: W,
buf: &'a mut [u8],
pos: usize,
threshold: usize,
}

impl<'a, W: Writer> UnsafeWriter<'a, W> {
fn new(buf: &'a mut [u8], inner: W) -> UnsafeWriter<'a, W> {
let threshold = buf.len()/2;
UnsafeWriter {
inner: inner,
buf: buf,
pos: 0,
threshold: threshold,
}
}

fn flush_buf(&mut self) -> IoResult<()> {
if self.pos != 0 {
let ret = self.inner.write_all(&self.buf[..self.pos]);
self.pos = 0;
ret
} else {
Ok(())
}
}

fn possibly_flush(&mut self) {
if self.pos > self.threshold {
self.inner.write_all(&self.buf[..self.pos]).unwrap();
self.pos = 0;
}
}
}

#[inline(never)]
fn fail() -> ! {
panic!("assertion failed");
}

impl<'a, W: Writer> Writer for UnsafeWriter<'a, W> {
fn write_all(&mut self, buf: &[u8]) -> IoResult<()> {
let dst = &mut self.buf[self.pos..];
if buf.len() > dst.len() {
fail();
}
unsafe {
copy_nonoverlapping_memory(dst.as_mut_ptr(), buf.as_ptr(), buf.len())
}
self.pos += buf.len();
Ok(())
}

fn flush(&mut self) -> IoResult<()> {
self.flush_buf().and_then(|()| self.inner.flush())
}
}

#[unsafe_destructor]
impl<'a, W: Writer> Drop for UnsafeWriter<'a, W> {
fn drop(&mut self) {
let _ = self.flush_buf();
}
}

/* vim: set ai ts=4 sw=4 sts=4 et : */

Name: Anonymous 2015-03-04 19:44

>>39
is this rust
youd be better off writing cobol

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List