Add licence
[ilari-esolangs.git] / stdlibrary.c
blob60a0747ab6686d7f2cbedeee7beee1e7de21ea54
1 #include "stdlibrary.h"
2 #include "object.h"
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include "message.h"
6 #include "context.h"
7 #include "vat.h"
9 /*****************************************************************************/
10 static void capfuck_stdin_h(struct context* ctx, struct message* msg)
12 struct object* dummy;
13 struct object* o;
14 struct object* target;
16 if(!(target = message_read_slot(msg, 0)))
17 return;
19 struct message* message = message_create(target, 9);
21 int c = getchar();
22 if(c >= 0) {
23 dummy = object_read_field(message_target(msg), 0);
24 message_write_slot(message, 0, dummy);
25 for(unsigned i = 0; i < 8; i++) {
26 o = ((c >> (7 - i)) & 1) ? dummy : NULL;
27 message_write_slot(message, i + 1, o);
30 context_queue_message(ctx, message);
33 /*****************************************************************************/
34 static void capfuck_stdX_h(FILE* file, struct context* ctx,
35 struct message* msg)
37 unsigned char value = 0;
38 for(unsigned i = 0; i < 8; i++)
39 value = value * 2 + (message_read_slot(msg, i) ? 1 : 0);
41 fprintf(file, "%c", value);
45 /*****************************************************************************/
46 static void capfuck_stdout_h(struct context* ctx, struct message* msg)
48 capfuck_stdX_h(stdout, ctx, msg);
51 /*****************************************************************************/
52 static void capfuck_stderr_h(struct context* ctx, struct message* msg)
54 capfuck_stdX_h(stderr, ctx, msg);
57 /*****************************************************************************/
58 struct stdlibrary* stdlibrary_init(struct vat* vat)
60 struct object* capfuck_dummy;
61 struct object* capfuck_stdin;
62 struct object* capfuck_stdout;
63 struct object* capfuck_stderr;
65 struct stdlibrary* lib;
67 lib = malloc(sizeof(struct stdlibrary));
68 if(!lib) {
69 fprintf(stderr, "Out of memory!\n");
70 exit(1);
73 /* Create and add objects to vats. */
74 capfuck_dummy = object_create_special(NULL, 0);
75 capfuck_stdin = object_create_special(capfuck_stdin_h, 2);
76 capfuck_stdout = object_create_special(capfuck_stdout_h, 0);
77 capfuck_stderr = object_create_special(capfuck_stderr_h, 0);
78 vat_add_object(vat, capfuck_stdin);
79 vat_add_object(vat, capfuck_stdout);
80 vat_add_object(vat, capfuck_stderr);
81 vat_add_object(vat, capfuck_dummy);
82 object_write_field(capfuck_stdin, 0, capfuck_dummy);
84 lib->stdin = capfuck_stdin;
85 lib->stdout = capfuck_stdout;
86 lib->stderr = capfuck_stderr;
87 return lib;