00001
00002 #include <stdio.h>
00003 #include <string.h>
00004 #include <assert.h>
00005
00006 #include "iter.h"
00007
00008
00009 char *
00010 get_next_string_in_sequence(iter *i)
00011 {
00012 static char *strings[] = { "john", "jacob", "jingleheimer", "smith", 0 };
00013 char *result;
00014
00015 result = strings[ ((int)(i->state)) ++];
00016 if (!result) i->state = 0;
00017
00018 return result;
00019 }
00020
00021 void
00022 simple_example()
00023 {
00024 iter i={0,0};
00025 char *s;
00026
00027 while (( s=get_next_string_in_sequence(&i) )) {
00028 printf("s is '%s'\n", s);
00029 }
00030
00031 }
00032
00033
00034 void
00035 medium_example()
00036 {
00037 iter i={0,0};
00038 char *s;
00039
00040 while (( s=get_next_string_in_sequence(&i) )) {
00041 if (!strcmp(s, "jingleheimer")) {
00042 iter_reset(&i);
00043 break;
00044 }
00045 printf("s is '%s'\n", s);
00046 }
00047
00048 }
00049
00050 void
00051 lookahead_1_example()
00052 {
00053 iter i={0,0};
00054 char *current=0;
00055 char *next;
00056
00057 printf("The names are: ");
00058 do {
00059 next = get_next_string_in_sequence(&i);
00060 if (current) {
00061
00062 if (next) {
00063 printf("%s, ", current);
00064 } else {
00065 printf("%s.\n", current);
00066 }
00067 }
00068 current = next;
00069 } while (current);
00070 }
00071
00072 void
00073 general_lookahead_example()
00074 {
00075 iter i={0,0};
00076 const int MAX_LOOKAHEAD = 16;
00077 char *buf[MAX_LOOKAHEAD];
00078 int current_index = 0;
00079 int buf_count = 0;
00080 int done = 0;
00081 #define peek(n,m) (buf[ (n+m) % MAX_LOOKAHEAD ])
00082
00083 for(;;) {
00084
00085 if (!done) {
00086 assert(buf_count < MAX_LOOKAHEAD);
00087 peek(current_index, buf_count) = get_next_string_in_sequence(&i);
00088 if (peek(current_index, buf_count) == 0) done = 1;
00089 buf_count++;
00090 }
00091
00092
00093 if (buf_count < 3 && !done) continue;
00094
00095 printf("%s", peek(current_index, 0));
00096
00097 if (done) switch(buf_count) {
00098 case 3:
00099 printf(", and also "); break;
00100 case 2:
00101 printf(".\n"); break;
00102 } else {
00103 printf(", ");
00104 }
00105
00106
00107 current_index = (current_index+1) % MAX_LOOKAHEAD;
00108 buf_count--;
00109 if (!peek(current_index, 0)) break;
00110 }
00111 }
00112
00113
00114 void
00115 iter_demo_driver()
00116 {
00117 printf("\n\n* simple example\n\n");
00118 simple_example();
00119
00120 printf("\n\n* medium example\n\n");
00121 medium_example();
00122
00123 printf("\n\n* lookahead_1 example\n\n");
00124 lookahead_1_example();
00125
00126 printf("\n\n* general_lookahead example\n\n");
00127 general_lookahead_example();
00128
00129 }