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

[C] lisp to bbcode [BBCODE] [FAGGOTRY]

Name: Anonymous 2007-12-27 22:52


#include <stdio.h>
#include <string.h>

#define MAX_NESTING 128
#define MAX_POST_SIZE 4096

typedef struct {

    int id;
    const char * name;

} Tags;

typedef struct {

    int memory[MAX_NESTING];
    int * ptr;
    size_t elements;

} Stack;

void stackinit(Stack *);
int pushid(Stack *, int);
int popid(Stack *);

#define pushid(x,y) ((x)->elements++ == MAX_NESTING ? -1 : (*(x)->ptr++ = y))
#define popid(x) ((x)->elements ? (x)->elements--,*--(x)->ptr : 0)
#define stackinit(x) (void)((x)->elements = 0, (x)->ptr = (x)->memory)

int main(void) {

    char buf[MAX_POST_SIZE] = {0};
    char * p = buf;
    int c;
    size_t n;
    Stack stack;

    Tags tags[] = {
        { 0, ")"},
        { 1, "br"},
        { 2, "b"},
        { 3, "i"},
        { 4, "u"},
        { 5, "o"},
        { 6, "code"},
        { 7, "spoiler"} /*add more tags */
    };

    stackinit(&stack);


    fread(buf, 1, sizeof buf - 1, stdin);
    while(*p != 0) {
        if(*p == '\\' && p[1]) {
            putchar(p[1]);
            p += 2;
            continue;
        } else if(*p == '(') {
            if(p[1] == ' ') {
                p++;
                continue;
            }

            if(strtok(++p, " \n") == NULL) {
                fputs(p, stdout);
                break;
            } else {
                printf("[%s]", p);
               
                for(n = 0; n < sizeof tags / sizeof tags[0]; n++)
                    if(strcmp(p, tags[n].name) == 0)
                        if(pushid(&stack, tags[n].id) == -1) {
                            fprintf(stderr, "max nesting level reached\n");
                            return -1;
                        }
                p += strlen(p);
            }
        }
        else if(*p == ')') {
            c = popid(&stack);
            for(n = 0; n < sizeof tags / sizeof tags[0]; n++)
                if(c == tags[n].id) {
                    c ? printf("[/%s]", tags[n].name) : putchar(*tags[n].name);
                    break;
                }
        }

        else putchar(*p);

        p++;
    }

    putchar('\n');


    return 0;

}


Example:

$ cc foo.c -o a
$ ./a
(i (b this is bold and italic) and this just italic)
^D
[i][b]this is bold and italic[/b] and this just italic[/i]

Name: Anonymous 2007-12-28 13:49

>>11
Hard-on for purely stack-allocated memory? I hope your fucking overly revered stack fucking overflows when you shit some nice large arrays on it because you were too fucking pussy to dynamically allocate them on the heap.

No, I have a hard-on for static arrays.  I don't care much where the data is stored.  I prefer global arrays, though.  There is really little reason to use local variables.  Multithreading, perhaps.

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