Run-length encoding/C: Difference between revisions

Content added Content deleted
(→‎[[Run-length encoding/C#Unbuffered - generative: The following code sample is experimental as it implements python style iterators.)
m (→‎Unbuffered - Generative: minor reformat of code and comment)
Line 29: Line 29:
#define GOTO(label) longjmp(label, TRUE)
#define GOTO(label) longjmp(label, TRUE)
#endif
#endif

/* the following line is the only time I have ever required "auto" */
/* the following line is the only time I have ever required "auto" */
#define FOR(i,iterator) auto BOOL lambda(i); yield_init = (void *)λ iterator; BOOL lambda(i)
#define FOR(i,iterator) auto BOOL lambda(i); yield_init = (void *)λ iterator; BOOL lambda(i)
Line 37: Line 37:
#define CONTINUE return TRUE
#define CONTINUE return TRUE
#define OD CONTINUE; }
#define OD CONTINUE; }
/* Warning: _Most_ FOR(,){ } loops _must_ have a CONTINUE as the last statement.
/* Warning: _Most_ FOR(,){ } loops _must_ have a CONTINUE, BREAK
* or OD as the terminating statement. Otherwise the lambda will
* Otherwise the lambda will return random value from stack, and may terminate early */
* return random value from stack, and may terminate early */

typedef BOOL ITERATOR;
typedef BOOL ITERATOR;
static volatile void *yield_init; /* not thread safe */
static volatile void *yield_init; /* not thread safe */
#define YIELDS(type) BOOL (*yield)(type) = yield_init
#define YIELDS(type) BOOL (*yield)(type) = yield_init

ITERATOR gen_char_seq (char *s){
ITERATOR gen_char_seq (char *s){
YIELDS(char);
YIELDS(char);
fflush(stdout);
fflush(stdout);
int upb_s = strlen(s);
int upb_s = strlen(s);
int i; for(i = 0; i <= upb_s; i++) YIELD(s[i]);
int i; for(i = 0; i <= upb_s; i++) YIELD(s[i]);
}
}


Line 67: Line 68:
count = 1;
count = 1;
YIELD(prev); prev = c;
YIELD(prev); prev = c;
}else{
} else {
count +=1;
count += 1;
}
}
OD;
OD;
Line 86: Line 87:
if(strchr(zero2nine, c)){
if(strchr(zero2nine, c)){
repeat = repeat*10 + c - '0';
repeat = repeat*10 + c - '0';
}else{
} else {
int i; for(i=1; i <= repeat; i++ ){ YIELD(c); }
int i; for(i = 1; i <= repeat; i++ ){ YIELD(c); }
repeat = 0;
repeat = 0;
}
}
Line 100: Line 101:
OD;
OD;
printf("\n");
printf("\n");

/* iterate through output string */
/* iterate through output string */
printf("Decode output: ");
printf("Decode output: ");
Line 113: Line 114:
Decode output: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW
Decode output: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW
</pre>
</pre>

=== Buffered ===
=== Buffered ===
These functions have no check for the size of the output buffers.
These functions have no check for the size of the output buffers.