sd: remove 'ssd' driver support
[unleashed/tickless.git] / usr / src / lib / libtecla / common / history.c
blobf9169a391c618ab82bcf91d6296b076f00acc117
1 /*
2 * Copyright (c) 2000, 2001, 2002, 2003, 2004 by Martin C. Shepherd.
3 *
4 * All rights reserved.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the
8 * "Software"), to deal in the Software without restriction, including
9 * without limitation the rights to use, copy, modify, merge, publish,
10 * distribute, and/or sell copies of the Software, and to permit persons
11 * to whom the Software is furnished to do so, provided that the above
12 * copyright notice(s) and this permission notice appear in all copies of
13 * the Software and that both the above copyright notice(s) and this
14 * permission notice appear in supporting documentation.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
19 * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
20 * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
21 * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
22 * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
23 * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
24 * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
26 * Except as contained in this notice, the name of a copyright holder
27 * shall not be used in advertising or otherwise to promote the sale, use
28 * or other dealings in this Software without prior written authorization
29 * of the copyright holder.
33 * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
34 * Use is subject to license terms.
37 #include <stdlib.h>
38 #include <stdio.h>
39 #include <string.h>
40 #include <ctype.h>
41 #include <time.h>
42 #include <errno.h>
44 #include "ioutil.h"
45 #include "history.h"
46 #include "freelist.h"
47 #include "errmsg.h"
50 * History lines are split into sub-strings of GLH_SEG_SIZE
51 * characters. To avoid wasting space in the GlhLineSeg structure,
52 * this should be a multiple of the size of a pointer.
54 #define GLH_SEG_SIZE 16
57 * GlhLineSeg structures contain fixed sized segments of a larger
58 * string. These are linked into lists to record strings, with all but
59 * the last segment having GLH_SEG_SIZE characters. The last segment
60 * of a string is terminated within the GLH_SEG_SIZE characters with a
61 * '\0'.
63 typedef struct GlhLineSeg GlhLineSeg;
64 struct GlhLineSeg {
65 GlhLineSeg *next; /* The next sub-string of the history line */
66 char s[GLH_SEG_SIZE]; /* The sub-string. Beware that only the final */
67 /* substring of a line, as indicated by 'next' */
68 /* being NULL, is '\0' terminated. */
72 * History lines are recorded in a hash table, such that repeated
73 * lines are stored just once.
75 * Start by defining the size of the hash table. This should be a
76 * prime number.
78 #define GLH_HASH_SIZE 113
80 typedef struct GlhHashBucket GlhHashBucket;
83 * Each history line will be represented in the hash table by a
84 * structure of the following type.
86 typedef struct GlhHashNode GlhHashNode;
87 struct GlhHashNode {
88 GlhHashBucket *bucket; /* The parent hash-table bucket of this node */
89 GlhHashNode *next; /* The next in the list of nodes within the */
90 /* parent hash-table bucket. */
91 GlhLineSeg *head; /* The list of sub-strings which make up a line */
92 int len; /* The length of the line, excluding any '\0' */
93 int used; /* The number of times this string is pointed to by */
94 /* the time-ordered list of history lines. */
95 int reported; /* A flag that is used when searching to ensure that */
96 /* a line isn't reported redundantly. */
100 * How many new GlhHashNode elements should be allocated at a time?
102 #define GLH_HASH_INCR 50
104 static int _glh_is_line(GlhHashNode *hash, const char *line, size_t n);
105 static int _glh_line_matches_prefix(GlhHashNode *line, GlhHashNode *prefix);
106 static void _glh_return_line(GlhHashNode *hash, char *line, size_t dim);
109 * All history lines which hash to a given bucket in the hash table, are
110 * recorded in a structure of the following type.
112 struct GlhHashBucket {
113 GlhHashNode *lines; /* The list of history lines which fall in this bucket */
116 static GlhHashBucket *glh_find_bucket(GlHistory *glh, const char *line,
117 size_t n);
118 static GlhHashNode *glh_find_hash_node(GlhHashBucket *bucket, const char *line,
119 size_t n);
121 typedef struct {
122 FreeList *node_mem; /* A free-list of GlhHashNode structures */
123 GlhHashBucket bucket[GLH_HASH_SIZE]; /* The buckets of the hash table */
124 } GlhLineHash;
127 * GlhLineNode's are used to record history lines in time order.
129 typedef struct GlhLineNode GlhLineNode;
130 struct GlhLineNode {
131 long id; /* The unique identifier of this history line */
132 time_t timestamp; /* The time at which the line was archived */
133 unsigned group; /* The identifier of the history group to which the */
134 /* the line belongs. */
135 GlhLineNode *next; /* The next youngest line in the list */
136 GlhLineNode *prev; /* The next oldest line in the list */
137 GlhHashNode *line; /* The hash-table entry of the history line */
141 * The number of GlhLineNode elements per freelist block.
143 #define GLH_LINE_INCR 100
146 * Encapsulate the time-ordered list of historical lines.
148 typedef struct {
149 FreeList *node_mem; /* A freelist of GlhLineNode objects */
150 GlhLineNode *head; /* The oldest line in the list */
151 GlhLineNode *tail; /* The newest line in the list */
152 } GlhLineList;
155 * The _glh_lookup_history() returns copies of history lines in a
156 * dynamically allocated array. This array is initially allocated
157 * GLH_LOOKUP_SIZE bytes. If subsequently this size turns out to be
158 * too small, realloc() is used to increase its size to the required
159 * size plus GLH_LOOKUP_MARGIN. The idea of the later parameter is to
160 * reduce the number of realloc() operations needed.
162 #define GLH_LBUF_SIZE 300
163 #define GLH_LBUF_MARGIN 100
166 * Encapsulate all of the resources needed to store historical input lines.
168 struct GlHistory {
169 ErrMsg *err; /* The error-reporting buffer */
170 GlhLineSeg *buffer; /* An array of sub-line nodes to be partitioned */
171 /* into lists of sub-strings recording input lines. */
172 int nbuff; /* The allocated dimension of buffer[] */
173 GlhLineSeg *unused; /* The list of free nodes in buffer[] */
174 GlhLineList list; /* A time ordered list of history lines */
175 GlhLineNode *recall; /* The last line recalled, or NULL if no recall */
176 /* session is currently active. */
177 GlhLineNode *id_node;/* The node at which the last ID search terminated */
178 GlhLineHash hash; /* A hash-table of reference-counted history lines */
179 GlhHashNode *prefix; /* A pointer to a line containing the prefix that */
180 /* is being searched for. Note that if prefix==NULL */
181 /* and prefix_len>0, this means that no line in */
182 /* the buffer starts with the requested prefix. */
183 int prefix_len; /* The length of the prefix being searched for. */
184 char *lbuf; /* The array in which _glh_lookup_history() returns */
185 /* history lines */
186 int lbuf_dim; /* The allocated size of lbuf[] */
187 int nbusy; /* The number of line segments in buffer[] that are */
188 /* currently being used to record sub-lines */
189 int nfree; /* The number of line segments in buffer that are */
190 /* not currently being used to record sub-lines */
191 unsigned long seq; /* The next ID to assign to a line node */
192 unsigned group; /* The identifier of the current history group */
193 int nline; /* The number of lines currently in the history list */
194 int max_lines; /* Either -1 or a ceiling on the number of lines */
195 int enable; /* If false, ignore history additions and lookups */
198 #ifndef WITHOUT_FILE_SYSTEM
199 static int _glh_cant_load_history(GlHistory *glh, const char *filename,
200 int lineno, const char *message, FILE *fp);
201 static int _glh_cant_save_history(GlHistory *glh, const char *message,
202 const char *filename, FILE *fp);
203 static int _glh_write_timestamp(FILE *fp, time_t timestamp);
204 static int _glh_decode_timestamp(char *string, char **endp, time_t *timestamp);
205 #endif
206 static void _glh_discard_line(GlHistory *glh, GlhLineNode *node);
207 static GlhLineNode *_glh_find_id(GlHistory *glh, GlhLineID id);
208 static GlhHashNode *_glh_acquire_copy(GlHistory *glh, const char *line,
209 size_t n);
210 static GlhHashNode *_glh_discard_copy(GlHistory *glh, GlhHashNode *hnode);
211 static int _glh_prepare_for_recall(GlHistory *glh, char *line);
214 * The following structure and functions are used to iterate through
215 * the characters of a segmented history line.
217 typedef struct {
218 GlhLineSeg *seg; /* The line segment that the next character will */
219 /* be returned from. */
220 int posn; /* The index in the above line segment, containing */
221 /* the next unread character. */
222 char c; /* The current character in the input line */
223 } GlhLineStream;
224 static void glh_init_stream(GlhLineStream *str, GlhHashNode *line);
225 static void glh_step_stream(GlhLineStream *str);
228 * See if search prefix contains any globbing characters.
230 static int glh_contains_glob(GlhHashNode *prefix);
232 * Match a line against a search pattern.
234 static int glh_line_matches_glob(GlhLineStream *lstr, GlhLineStream *pstr);
235 static int glh_matches_range(char c, GlhLineStream *pstr);
237 /*.......................................................................
238 * Create a line history maintenance object.
240 * Input:
241 * buflen size_t The number of bytes to allocate to the
242 * buffer that is used to record all of the
243 * most recent lines of user input that will fit.
244 * If buflen==0, no buffer will be allocated.
245 * Output:
246 * return GlHistory * The new object, or NULL on error.
248 GlHistory *_new_GlHistory(size_t buflen)
250 GlHistory *glh; /* The object to be returned */
251 int i;
253 * Allocate the container.
255 glh = (GlHistory *) malloc(sizeof(GlHistory));
256 if(!glh) {
257 errno = ENOMEM;
258 return NULL;
261 * Before attempting any operation that might fail, initialize the
262 * container at least up to the point at which it can safely be passed
263 * to _del_GlHistory().
265 glh->err = NULL;
266 glh->buffer = NULL;
267 glh->nbuff = (buflen+GLH_SEG_SIZE-1) / GLH_SEG_SIZE;
268 glh->unused = NULL;
269 glh->list.node_mem = NULL;
270 glh->list.head = glh->list.tail = NULL;
271 glh->recall = NULL;
272 glh->id_node = NULL;
273 glh->hash.node_mem = NULL;
274 for(i=0; i<GLH_HASH_SIZE; i++)
275 glh->hash.bucket[i].lines = NULL;
276 glh->prefix = NULL;
277 glh->lbuf = NULL;
278 glh->lbuf_dim = 0;
279 glh->nbusy = 0;
280 glh->nfree = glh->nbuff;
281 glh->seq = 0;
282 glh->group = 0;
283 glh->nline = 0;
284 glh->max_lines = -1;
285 glh->enable = 1;
287 * Allocate a place to record error messages.
289 glh->err = _new_ErrMsg();
290 if(!glh->err)
291 return _del_GlHistory(glh);
293 * Allocate the buffer, if required.
295 if(glh->nbuff > 0) {
296 glh->nbuff = glh->nfree;
297 glh->buffer = (GlhLineSeg *) malloc(sizeof(GlhLineSeg) * glh->nbuff);
298 if(!glh->buffer) {
299 errno = ENOMEM;
300 return _del_GlHistory(glh);
303 * All nodes of the buffer are currently unused, so link them all into
304 * a list and make glh->unused point to the head of this list.
306 glh->unused = glh->buffer;
307 for(i=0; i<glh->nbuff-1; i++) {
308 GlhLineSeg *seg = glh->unused + i;
309 seg->next = seg + 1;
311 glh->unused[i].next = NULL;
314 * Allocate the GlhLineNode freelist.
316 glh->list.node_mem = _new_FreeList(sizeof(GlhLineNode), GLH_LINE_INCR);
317 if(!glh->list.node_mem)
318 return _del_GlHistory(glh);
320 * Allocate the GlhHashNode freelist.
322 glh->hash.node_mem = _new_FreeList(sizeof(GlhLineNode), GLH_HASH_INCR);
323 if(!glh->hash.node_mem)
324 return _del_GlHistory(glh);
326 * Allocate the array that _glh_lookup_history() uses to return a
327 * copy of a given history line. This will be resized when necessary.
329 glh->lbuf_dim = GLH_LBUF_SIZE;
330 glh->lbuf = (char *) malloc(glh->lbuf_dim);
331 if(!glh->lbuf) {
332 errno = ENOMEM;
333 return _del_GlHistory(glh);
335 return glh;
338 /*.......................................................................
339 * Delete a GlHistory object.
341 * Input:
342 * glh GlHistory * The object to be deleted.
343 * Output:
344 * return GlHistory * The deleted object (always NULL).
346 GlHistory *_del_GlHistory(GlHistory *glh)
348 if(glh) {
350 * Delete the error-message buffer.
352 glh->err = _del_ErrMsg(glh->err);
354 * Delete the buffer.
356 if(glh->buffer) {
357 free(glh->buffer);
358 glh->buffer = NULL;
359 glh->unused = NULL;
362 * Delete the freelist of GlhLineNode's.
364 glh->list.node_mem = _del_FreeList(glh->list.node_mem, 1);
366 * The contents of the list were deleted by deleting the freelist.
368 glh->list.head = NULL;
369 glh->list.tail = NULL;
371 * Delete the freelist of GlhHashNode's.
373 glh->hash.node_mem = _del_FreeList(glh->hash.node_mem, 1);
375 * Delete the lookup buffer.
377 free(glh->lbuf);
379 * Delete the container.
381 free(glh);
383 return NULL;
386 /*.......................................................................
387 * Append a new line to the history list, deleting old lines to make
388 * room, if needed.
390 * Input:
391 * glh GlHistory * The input-line history maintenance object.
392 * line char * The line to be archived.
393 * force int Unless this flag is non-zero, empty lines aren't
394 * archived. This flag requests that the line be
395 * archived regardless.
396 * Output:
397 * return int 0 - OK.
398 * 1 - Error.
400 int _glh_add_history(GlHistory *glh, const char *line, int force)
402 int slen; /* The length of the line to be recorded (minus the '\0') */
403 int empty; /* True if the string is empty */
404 const char *nlptr; /* A pointer to a newline character in line[] */
405 GlhHashNode *hnode; /* The hash-table node of the line */
406 GlhLineNode *lnode; /* A node in the time-ordered list of lines */
407 int i;
409 * Check the arguments.
411 if(!glh || !line) {
412 errno = EINVAL;
413 return 1;
416 * Is history enabled?
418 if(!glh->enable || !glh->buffer || glh->max_lines == 0)
419 return 0;
421 * Cancel any ongoing search.
423 if(_glh_cancel_search(glh))
424 return 1;
426 * How long is the string to be recorded, being careful not to include
427 * any terminating '\n' character.
429 nlptr = strchr(line, '\n');
430 if(nlptr)
431 slen = (nlptr - line);
432 else
433 slen = strlen(line);
435 * Is the line empty?
437 empty = 1;
438 for(i=0; i<slen && empty; i++)
439 empty = isspace((int)(unsigned char) line[i]);
441 * If the line is empty, don't add it to the buffer unless explicitly
442 * told to.
444 if(empty && !force)
445 return 0;
447 * Has an upper limit to the number of lines in the history list been
448 * specified?
450 if(glh->max_lines >= 0) {
452 * If necessary, remove old lines until there is room to add one new
453 * line without exceeding the specified line limit.
455 while(glh->nline > 0 && glh->nline >= glh->max_lines)
456 _glh_discard_line(glh, glh->list.head);
458 * We can't archive the line if the maximum number of lines allowed is
459 * zero.
461 if(glh->max_lines == 0)
462 return 0;
465 * Unless already stored, store a copy of the line in the history buffer,
466 * then return a reference-counted hash-node pointer to this copy.
468 hnode = _glh_acquire_copy(glh, line, slen);
469 if(!hnode) {
470 _err_record_msg(glh->err, "No room to store history line", END_ERR_MSG);
471 errno = ENOMEM;
472 return 1;
475 * Allocate a new node in the time-ordered list of lines.
477 lnode = (GlhLineNode *) _new_FreeListNode(glh->list.node_mem);
479 * If a new line-node couldn't be allocated, discard our copy of the
480 * stored line before reporting the error.
482 if(!lnode) {
483 hnode = _glh_discard_copy(glh, hnode);
484 _err_record_msg(glh->err, "No room to store history line", END_ERR_MSG);
485 errno = ENOMEM;
486 return 1;
489 * Record a pointer to the hash-table record of the line in the new
490 * list node.
492 lnode->id = glh->seq++;
493 lnode->timestamp = time(NULL);
494 lnode->group = glh->group;
495 lnode->line = hnode;
497 * Append the new node to the end of the time-ordered list.
499 if(glh->list.head)
500 glh->list.tail->next = lnode;
501 else
502 glh->list.head = lnode;
503 lnode->next = NULL;
504 lnode->prev = glh->list.tail;
505 glh->list.tail = lnode;
507 * Record the addition of a line to the list.
509 glh->nline++;
510 return 0;
513 /*.......................................................................
514 * Recall the next oldest line that has the search prefix last recorded
515 * by _glh_search_prefix().
517 * Input:
518 * glh GlHistory * The input-line history maintenance object.
519 * line char * The input line buffer. On input this should contain
520 * the current input line, and on output, if anything
521 * was found, its contents will have been replaced
522 * with the matching line.
523 * dim size_t The allocated dimension of the line buffer.
524 * Output:
525 * return char * A pointer to line[0], or NULL if not found.
527 char *_glh_find_backwards(GlHistory *glh, char *line, size_t dim)
529 GlhLineNode *node; /* The line location node being checked */
530 GlhHashNode *old_line; /* The previous recalled line */
532 * Check the arguments.
534 if(!glh || !line) {
535 if(glh)
536 _err_record_msg(glh->err, "NULL argument(s)", END_ERR_MSG);
537 errno = EINVAL;
538 return NULL;
541 * Is history enabled?
543 if(!glh->enable || !glh->buffer || glh->max_lines == 0)
544 return NULL;
546 * Check the line dimensions.
548 if(dim < strlen(line) + 1) {
549 _err_record_msg(glh->err, "'dim' argument inconsistent with strlen(line)",
550 END_ERR_MSG);
551 errno = EINVAL;
552 return NULL;
555 * Preserve the input line if needed.
557 if(_glh_prepare_for_recall(glh, line))
558 return NULL;
560 * From where should we start the search?
562 if(glh->recall) {
563 node = glh->recall->prev;
564 old_line = glh->recall->line;
565 } else {
566 node = glh->list.tail;
567 old_line = NULL;
570 * Search backwards through the list for the first match with the
571 * prefix string that differs from the last line that was recalled.
573 while(node && (node->group != glh->group || node->line == old_line ||
574 !_glh_line_matches_prefix(node->line, glh->prefix)))
575 node = node->prev;
577 * Was a matching line found?
579 if(node) {
581 * Recall the found node as the starting point for subsequent
582 * searches.
584 glh->recall = node;
586 * Copy the matching line into the provided line buffer.
588 _glh_return_line(node->line, line, dim);
590 * Return it.
592 return line;
595 * No match was found.
597 return NULL;
600 /*.......................................................................
601 * Recall the next newest line that has the search prefix last recorded
602 * by _glh_search_prefix().
604 * Input:
605 * glh GlHistory * The input-line history maintenance object.
606 * line char * The input line buffer. On input this should contain
607 * the current input line, and on output, if anything
608 * was found, its contents will have been replaced
609 * with the matching line.
610 * dim size_t The allocated dimensions of the line buffer.
611 * Output:
612 * return char * The line requested, or NULL if no matching line
613 * was found.
615 char *_glh_find_forwards(GlHistory *glh, char *line, size_t dim)
617 GlhLineNode *node; /* The line location node being checked */
618 GlhHashNode *old_line; /* The previous recalled line */
620 * Check the arguments.
622 if(!glh || !line) {
623 if(glh)
624 _err_record_msg(glh->err, "NULL argument(s)", END_ERR_MSG);
625 errno = EINVAL;
626 return NULL;
629 * Is history enabled?
631 if(!glh->enable || !glh->buffer || glh->max_lines == 0)
632 return NULL;
634 * Check the line dimensions.
636 if(dim < strlen(line) + 1) {
637 _err_record_msg(glh->err, "'dim' argument inconsistent with strlen(line)",
638 END_ERR_MSG);
639 errno = EINVAL;
640 return NULL;
643 * From where should we start the search?
645 if(glh->recall) {
646 node = glh->recall->next;
647 old_line = glh->recall->line;
648 } else {
649 return NULL;
652 * Search forwards through the list for the first match with the
653 * prefix string.
655 while(node && (node->group != glh->group || node->line == old_line ||
656 !_glh_line_matches_prefix(node->line, glh->prefix)))
657 node = node->next;
659 * Was a matching line found?
661 if(node) {
663 * Copy the matching line into the provided line buffer.
665 _glh_return_line(node->line, line, dim);
667 * Record the starting point of the next search.
669 glh->recall = node;
671 * If we just returned the line that was being entered when the search
672 * session first started, cancel the search.
674 if(node == glh->list.tail)
675 _glh_cancel_search(glh);
677 * Return the matching line to the user.
679 return line;
682 * No match was found.
684 return NULL;
687 /*.......................................................................
688 * If a search is in progress, cancel it.
690 * This involves discarding the line that was temporarily saved by
691 * _glh_find_backwards() when the search was originally started,
692 * and reseting the search iteration pointer to NULL.
694 * Input:
695 * glh GlHistory * The input-line history maintenance object.
696 * Output:
697 * return int 0 - OK.
698 * 1 - Error.
700 int _glh_cancel_search(GlHistory *glh)
703 * Check the arguments.
705 if(!glh) {
706 errno = EINVAL;
707 return 1;
710 * If there wasn't a search in progress, do nothing.
712 if(!glh->recall)
713 return 0;
715 * Reset the search pointers. Note that it is essential to set
716 * glh->recall to NULL before calling _glh_discard_line(), to avoid an
717 * infinite recursion.
719 glh->recall = NULL;
721 * Delete the node of the preserved line.
723 _glh_discard_line(glh, glh->list.tail);
724 return 0;
727 /*.......................................................................
728 * Set the prefix of subsequent history searches.
730 * Input:
731 * glh GlHistory * The input-line history maintenance object.
732 * line const char * The command line who's prefix is to be used.
733 * prefix_len int The length of the prefix.
734 * Output:
735 * return int 0 - OK.
736 * 1 - Error.
738 int _glh_search_prefix(GlHistory *glh, const char *line, int prefix_len)
741 * Check the arguments.
743 if(!glh) {
744 errno = EINVAL;
745 return 1;
748 * Is history enabled?
750 if(!glh->enable || !glh->buffer || glh->max_lines == 0)
751 return 0;
753 * Discard any existing prefix.
755 glh->prefix = _glh_discard_copy(glh, glh->prefix);
757 * Only store a copy of the prefix string if it isn't a zero-length string.
759 if(prefix_len > 0) {
761 * Get a reference-counted copy of the prefix from the history cache buffer.
763 glh->prefix = _glh_acquire_copy(glh, line, prefix_len);
765 * Was there insufficient buffer space?
767 if(!glh->prefix) {
768 _err_record_msg(glh->err, "The search prefix is too long to store",
769 END_ERR_MSG);
770 errno = ENOMEM;
771 return 1;
774 return 0;
777 /*.......................................................................
778 * Recall the oldest recorded line.
780 * Input:
781 * glh GlHistory * The input-line history maintenance object.
782 * line char * The input line buffer. On input this should contain
783 * the current input line, and on output, its contents
784 * will have been replaced with the oldest line.
785 * dim size_t The allocated dimensions of the line buffer.
786 * Output:
787 * return char * A pointer to line[0], or NULL if not found.
789 char *_glh_oldest_line(GlHistory *glh, char *line, size_t dim)
791 GlhLineNode *node; /* The line location node being checked */
793 * Check the arguments.
795 if(!glh || !line) {
796 if(glh)
797 _err_record_msg(glh->err, "NULL argument(s)", END_ERR_MSG);
798 errno = EINVAL;
799 return NULL;
802 * Is history enabled?
804 if(!glh->enable || !glh->buffer || glh->max_lines == 0)
805 return NULL;
807 * Check the line dimensions.
809 if(dim < strlen(line) + 1) {
810 _err_record_msg(glh->err, "'dim' argument inconsistent with strlen(line)",
811 END_ERR_MSG);
812 errno = EINVAL;
813 return NULL;
816 * Preserve the input line if needed.
818 if(_glh_prepare_for_recall(glh, line))
819 return NULL;
821 * Locate the oldest line that belongs to the current group.
823 for(node=glh->list.head; node && node->group != glh->group;
824 node = node->next)
827 * No line found?
829 if(!node)
830 return NULL;
832 * Record the above node as the starting point for subsequent
833 * searches.
835 glh->recall = node;
837 * Copy the recalled line into the provided line buffer.
839 _glh_return_line(node->line, line, dim);
841 * If we just returned the line that was being entered when the search
842 * session first started, cancel the search.
844 if(node == glh->list.tail)
845 _glh_cancel_search(glh);
846 return line;
849 /*.......................................................................
850 * Recall the line that was being entered when the search started.
852 * Input:
853 * glh GlHistory * The input-line history maintenance object.
854 * line char * The input line buffer. On input this should contain
855 * the current input line, and on output, its contents
856 * will have been replaced with the line that was
857 * being entered when the search was started.
858 * dim size_t The allocated dimensions of the line buffer.
859 * Output:
860 * return char * A pointer to line[0], or NULL if not found.
862 char *_glh_current_line(GlHistory *glh, char *line, size_t dim)
865 * Check the arguments.
867 if(!glh || !line) {
868 if(glh)
869 _err_record_msg(glh->err, "NULL argument(s)", END_ERR_MSG);
870 errno = EINVAL;
871 return NULL;
874 * If history isn't enabled, or no history search has yet been started,
875 * ignore the call.
877 if(!glh->enable || !glh->buffer || glh->max_lines == 0 || !glh->recall)
878 return NULL;
880 * Check the line dimensions.
882 if(dim < strlen(line) + 1) {
883 _err_record_msg(glh->err, "'dim' argument inconsistent with strlen(line)",
884 END_ERR_MSG);
885 errno = EINVAL;
886 return NULL;
889 * Copy the recalled line into the provided line buffer.
891 _glh_return_line(glh->list.tail->line, line, dim);
893 * Since we have returned to the starting point of the search, cancel it.
895 _glh_cancel_search(glh);
896 return line;
899 /*.......................................................................
900 * Query the id of a history line offset by a given number of lines from
901 * the one that is currently being recalled. If a recall session isn't
902 * in progress, or the offset points outside the history list, 0 is
903 * returned.
905 * Input:
906 * glh GlHistory * The input-line history maintenance object.
907 * offset int The line offset (0 for the current line, < 0
908 * for an older line, > 0 for a newer line.
909 * Output:
910 * return GlhLineID The identifier of the line that is currently
911 * being recalled, or 0 if no recall session is
912 * currently in progress.
914 GlhLineID _glh_line_id(GlHistory *glh, int offset)
916 GlhLineNode *node; /* The line location node being checked */
918 * Is history enabled?
920 if(!glh->enable || !glh->buffer || glh->max_lines == 0)
921 return 0;
923 * Search forward 'offset' lines to find the required line.
925 if(offset >= 0) {
926 for(node=glh->recall; node && offset != 0; node=node->next) {
927 if(node->group == glh->group)
928 offset--;
930 } else {
931 for(node=glh->recall; node && offset != 0; node=node->prev) {
932 if(node->group == glh->group)
933 offset++;
936 return node ? node->id : 0;
939 /*.......................................................................
940 * Recall a line by its history buffer ID. If the line is no longer
941 * in the buffer, or the id is zero, NULL is returned.
943 * Input:
944 * glh GlHistory * The input-line history maintenance object.
945 * id GlhLineID The ID of the line to be returned.
946 * line char * The input line buffer. On input this should contain
947 * the current input line, and on output, its contents
948 * will have been replaced with the saved line.
949 * dim size_t The allocated dimensions of the line buffer.
950 * Output:
951 * return char * A pointer to line[0], or NULL if not found.
953 char *_glh_recall_line(GlHistory *glh, GlhLineID id, char *line, size_t dim)
955 GlhLineNode *node; /* The line location node being checked */
957 * Is history enabled?
959 if(!glh->enable || !glh->buffer || glh->max_lines == 0)
960 return NULL;
962 * Preserve the input line if needed.
964 if(_glh_prepare_for_recall(glh, line))
965 return NULL;
967 * Search for the specified line.
969 node = _glh_find_id(glh, id);
971 * Not found?
973 if(!node || node->group != glh->group)
974 return NULL;
976 * Record the node of the matching line as the starting point
977 * for subsequent searches.
979 glh->recall = node;
981 * Copy the recalled line into the provided line buffer.
983 _glh_return_line(node->line, line, dim);
984 return line;
987 /*.......................................................................
988 * Save the current history in a specified file.
990 * Input:
991 * glh GlHistory * The input-line history maintenance object.
992 * filename const char * The name of the new file to record the
993 * history in.
994 * comment const char * Extra information such as timestamps will
995 * be recorded on a line started with this
996 * string, the idea being that the file can
997 * double as a command file. Specify "" if
998 * you don't care.
999 * max_lines int The maximum number of lines to save, or -1
1000 * to save all of the lines in the history
1001 * list.
1002 * Output:
1003 * return int 0 - OK.
1004 * 1 - Error.
1006 int _glh_save_history(GlHistory *glh, const char *filename, const char *comment,
1007 int max_lines)
1009 #ifdef WITHOUT_FILE_SYSTEM
1010 _err_record_msg(glh->err, "Can't save history without filesystem access",
1011 END_ERR_MSG);
1012 errno = EINVAL;
1013 return 1;
1014 #else
1015 FILE *fp; /* The output file */
1016 GlhLineNode *node; /* The line being saved */
1017 GlhLineNode *head; /* The head of the list of lines to be saved */
1018 GlhLineSeg *seg; /* One segment of a line being saved */
1020 * Check the arguments.
1022 if(!glh || !filename || !comment) {
1023 if(glh)
1024 _err_record_msg(glh->err, "NULL argument(s)", END_ERR_MSG);
1025 errno = EINVAL;
1026 return 1;
1029 * Attempt to open the specified file.
1031 fp = fopen(filename, "w");
1032 if(!fp)
1033 return _glh_cant_save_history(glh, "Can't open", filename, NULL);
1035 * If a ceiling on the number of lines to save was specified, count
1036 * that number of lines backwards, to find the first line to be saved.
1038 head = NULL;
1039 if(max_lines >= 0) {
1040 for(head=glh->list.tail; head && --max_lines > 0; head=head->prev)
1043 if(!head)
1044 head = glh->list.head;
1046 * Write the contents of the history buffer to the history file, writing
1047 * associated data such as timestamps, to a line starting with the
1048 * specified comment string.
1050 for(node=head; node; node=node->next) {
1052 * Write peripheral information associated with the line, as a comment.
1054 if(fprintf(fp, "%s ", comment) < 0 ||
1055 _glh_write_timestamp(fp, node->timestamp) ||
1056 fprintf(fp, " %u\n", node->group) < 0) {
1057 return _glh_cant_save_history(glh, "Error writing", filename, fp);
1060 * Write the history line.
1062 for(seg=node->line->head; seg; seg=seg->next) {
1063 size_t slen = seg->next ? GLH_SEG_SIZE : strlen(seg->s);
1064 if(fwrite(seg->s, sizeof(char), slen, fp) != slen)
1065 return _glh_cant_save_history(glh, "Error writing", filename, fp);
1067 fputc('\n', fp);
1070 * Close the history file.
1072 if(fclose(fp) == EOF)
1073 return _glh_cant_save_history(glh, "Error writing", filename, NULL);
1074 return 0;
1075 #endif
1078 #ifndef WITHOUT_FILE_SYSTEM
1079 /*.......................................................................
1080 * This is a private error return function of _glh_save_history(). It
1081 * composes an error report in the error buffer, composed using
1082 * sprintf("%s %s (%s)", message, filename, strerror(errno)). It then
1083 * closes fp and returns the error return code of _glh_save_history().
1085 * Input:
1086 * glh GlHistory * The input-line history maintenance object.
1087 * message const char * A message to be followed by the filename.
1088 * filename const char * The name of the offending output file.
1089 * fp FILE * The stream to be closed (send NULL if not
1090 * open).
1091 * Output:
1092 * return int Always 1.
1094 static int _glh_cant_save_history(GlHistory *glh, const char *message,
1095 const char *filename, FILE *fp)
1097 _err_record_msg(glh->err, message, filename, " (",
1098 strerror(errno), ")", END_ERR_MSG);
1099 if(fp)
1100 (void) fclose(fp);
1101 return 1;
1104 /*.......................................................................
1105 * Write a timestamp to a given stdio stream, in the format
1106 * yyyymmddhhmmss
1108 * Input:
1109 * fp FILE * The stream to write to.
1110 * timestamp time_t The timestamp to be written.
1111 * Output:
1112 * return int 0 - OK.
1113 * 1 - Error.
1115 static int _glh_write_timestamp(FILE *fp, time_t timestamp)
1117 struct tm *t; /* THe broken-down calendar time */
1119 * Get the calendar components corresponding to the given timestamp.
1121 if(timestamp < 0 || (t = localtime(&timestamp)) == NULL) {
1122 if(fprintf(fp, "?") < 0)
1123 return 1;
1124 return 0;
1127 * Write the calendar time as yyyymmddhhmmss.
1129 if(fprintf(fp, "%04d%02d%02d%02d%02d%02d", t->tm_year + 1900, t->tm_mon + 1,
1130 t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec) < 0)
1131 return 1;
1132 return 0;
1135 #endif
1137 /*.......................................................................
1138 * Restore previous history lines from a given file.
1140 * Input:
1141 * glh GlHistory * The input-line history maintenance object.
1142 * filename const char * The name of the file to read from.
1143 * comment const char * The same comment string that was passed to
1144 * _glh_save_history() when this file was
1145 * written.
1146 * line char * A buffer into which lines can be read.
1147 * dim size_t The allocated dimension of line[].
1148 * Output:
1149 * return int 0 - OK.
1150 * 1 - Error.
1152 int _glh_load_history(GlHistory *glh, const char *filename, const char *comment,
1153 char *line, size_t dim)
1155 #ifdef WITHOUT_FILE_SYSTEM
1156 _err_record_msg(glh->err, "Can't load history without filesystem access",
1157 END_ERR_MSG);
1158 errno = EINVAL;
1159 return 1;
1160 #else
1161 FILE *fp; /* The output file */
1162 size_t comment_len; /* The length of the comment string */
1163 time_t timestamp; /* The timestamp of the history line */
1164 unsigned group; /* The identifier of the history group to which */
1165 /* the line belongs. */
1166 int lineno; /* The line number being read */
1168 * Check the arguments.
1170 if(!glh || !filename || !comment || !line) {
1171 if(glh)
1172 _err_record_msg(glh->err, "NULL argument(s)", END_ERR_MSG);
1173 errno = EINVAL;
1174 return 1;
1177 * Measure the length of the comment string.
1179 comment_len = strlen(comment);
1181 * Clear the history list.
1183 _glh_clear_history(glh, 1);
1185 * Attempt to open the specified file. Don't treat it as an error
1186 * if the file doesn't exist.
1188 fp = fopen(filename, "r");
1189 if(!fp)
1190 return 0;
1192 * Attempt to read each line and preceding peripheral info, and add these
1193 * to the history list.
1195 for(lineno=1; fgets(line, dim, fp) != NULL; lineno++) {
1196 char *lptr; /* A pointer into the input line */
1198 * Check that the line starts with the comment string.
1200 if(strncmp(line, comment, comment_len) != 0) {
1201 return _glh_cant_load_history(glh, filename, lineno,
1202 "Corrupt history parameter line", fp);
1205 * Skip spaces and tabs after the comment.
1207 for(lptr=line+comment_len; *lptr && (*lptr==' ' || *lptr=='\t'); lptr++)
1210 * The next word must be a timestamp.
1212 if(_glh_decode_timestamp(lptr, &lptr, &timestamp)) {
1213 return _glh_cant_load_history(glh, filename, lineno,
1214 "Corrupt timestamp", fp);
1217 * Skip spaces and tabs.
1219 while(*lptr==' ' || *lptr=='\t')
1220 lptr++;
1222 * The next word must be an unsigned integer group number.
1224 group = (int) strtoul(lptr, &lptr, 10);
1225 if(*lptr != ' ' && *lptr != '\n') {
1226 return _glh_cant_load_history(glh, filename, lineno,
1227 "Corrupt group id", fp);
1230 * Skip spaces and tabs.
1232 while(*lptr==' ' || *lptr=='\t')
1233 lptr++;
1235 * There shouldn't be anything left on the line.
1237 if(*lptr != '\n') {
1238 return _glh_cant_load_history(glh, filename, lineno,
1239 "Corrupt parameter line", fp);
1242 * Now read the history line itself.
1244 lineno++;
1245 if(fgets(line, dim, fp) == NULL)
1246 return _glh_cant_load_history(glh, filename, lineno, "Read error", fp);
1248 * Append the line to the history buffer.
1250 if(_glh_add_history(glh, line, 1)) {
1251 return _glh_cant_load_history(glh, filename, lineno,
1252 "Insufficient memory to record line", fp);
1255 * Record the group and timestamp information along with the line.
1257 if(glh->list.tail) {
1258 glh->list.tail->timestamp = timestamp;
1259 glh->list.tail->group = group;
1263 * Close the file.
1265 (void) fclose(fp);
1266 return 0;
1267 #endif
1270 #ifndef WITHOUT_FILE_SYSTEM
1271 /*.......................................................................
1272 * This is a private error return function of _glh_load_history().
1274 static int _glh_cant_load_history(GlHistory *glh, const char *filename,
1275 int lineno, const char *message, FILE *fp)
1277 char lnum[20];
1279 * Convert the line number to a string.
1281 snprintf(lnum, sizeof(lnum), "%d", lineno);
1283 * Render an error message.
1285 _err_record_msg(glh->err, filename, ":", lnum, ":", message, END_ERR_MSG);
1287 * Close the file.
1289 if(fp)
1290 (void) fclose(fp);
1291 return 1;
1294 /*.......................................................................
1295 * Read a timestamp from a string.
1297 * Input:
1298 * string char * The string to read from.
1299 * Input/Output:
1300 * endp char ** On output *endp will point to the next unprocessed
1301 * character in string[].
1302 * timestamp time_t * The timestamp will be assigned to *t.
1303 * Output:
1304 * return int 0 - OK.
1305 * 1 - Error.
1307 static int _glh_decode_timestamp(char *string, char **endp, time_t *timestamp)
1309 unsigned year,month,day,hour,min,sec; /* Calendar time components */
1310 struct tm t;
1312 * There are 14 characters in the date format yyyymmddhhmmss.
1314 enum {TSLEN=14};
1315 char timestr[TSLEN+1]; /* The timestamp part of the string */
1317 * If the time wasn't available at the time that the line was recorded
1318 * it will have been written as "?". Check for this before trying
1319 * to read the timestamp.
1321 if(string[0] == '\?') {
1322 *endp = string+1;
1323 *timestamp = -1;
1324 return 0;
1327 * The timestamp is expected to be written in the form yyyymmddhhmmss.
1329 if(strlen(string) < TSLEN) {
1330 *endp = string;
1331 return 1;
1334 * Copy the timestamp out of the string.
1336 strncpy(timestr, string, TSLEN);
1337 timestr[TSLEN] = '\0';
1339 * Decode the timestamp.
1341 if(sscanf(timestr, "%4u%2u%2u%2u%2u%2u", &year, &month, &day, &hour, &min,
1342 &sec) != 6) {
1343 *endp = string;
1344 return 1;
1347 * Advance the string pointer over the successfully read timestamp.
1349 *endp = string + TSLEN;
1351 * Copy the read values into a struct tm.
1353 t.tm_sec = sec;
1354 t.tm_min = min;
1355 t.tm_hour = hour;
1356 t.tm_mday = day;
1357 t.tm_wday = 0;
1358 t.tm_yday = 0;
1359 t.tm_mon = month - 1;
1360 t.tm_year = year - 1900;
1361 t.tm_isdst = -1;
1363 * Convert the contents of the struct tm to a time_t.
1365 *timestamp = mktime(&t);
1366 return 0;
1368 #endif
1370 /*.......................................................................
1371 * Switch history groups.
1373 * Input:
1374 * glh GlHistory * The input-line history maintenance object.
1375 * group unsigned The new group identifier. This will be recorded
1376 * with subsequent history lines, and subsequent
1377 * history searches will only return lines with
1378 * this group identifier. This allows multiple
1379 * separate history lists to exist within
1380 * a single GlHistory object. Note that the
1381 * default group identifier is 0.
1382 * Output:
1383 * return int 0 - OK.
1384 * 1 - Error.
1386 int _glh_set_group(GlHistory *glh, unsigned group)
1389 * Check the arguments.
1391 if(!glh) {
1392 if(glh)
1393 _err_record_msg(glh->err, "NULL argument(s)", END_ERR_MSG);
1394 errno = EINVAL;
1395 return 1;
1398 * Is the group being changed?
1400 if(group != glh->group) {
1402 * Cancel any ongoing search.
1404 if(_glh_cancel_search(glh))
1405 return 1;
1407 * Record the new group.
1409 glh->group = group;
1411 return 0;
1414 /*.......................................................................
1415 * Query the current history group.
1417 * Input:
1418 * glh GlHistory * The input-line history maintenance object.
1419 * Output:
1420 * return unsigned The group identifier.
1422 int _glh_get_group(GlHistory *glh)
1424 return glh ? glh->group : 0;
1427 /*.......................................................................
1428 * Display the contents of the history list.
1430 * Input:
1431 * glh GlHistory * The input-line history maintenance object.
1432 * write_fn GlWriteFn * The function to call to write the line, or
1433 * 0 to discard the output.
1434 * data void * Anonymous data to pass to write_fn().
1435 * fmt const char * A format string. This can contain arbitrary
1436 * characters, which are written verbatim, plus
1437 * any of the following format directives:
1438 * %D - The date, like 2001-11-20
1439 * %T - The time of day, like 23:59:59
1440 * %N - The sequential entry number of the
1441 * line in the history buffer.
1442 * %G - The history group number of the line.
1443 * %% - A literal % character.
1444 * %H - The history line.
1445 * all_groups int If true, display history lines from all
1446 * history groups. Otherwise only display
1447 * those of the current history group.
1448 * max_lines int If max_lines is < 0, all available lines
1449 * are displayed. Otherwise only the most
1450 * recent max_lines lines will be displayed.
1451 * Output:
1452 * return int 0 - OK.
1453 * 1 - Error.
1455 int _glh_show_history(GlHistory *glh, GlWriteFn *write_fn, void *data,
1456 const char *fmt, int all_groups, int max_lines)
1458 GlhLineNode *node; /* The line being displayed */
1459 GlhLineNode *oldest; /* The oldest line to display */
1460 GlhLineSeg *seg; /* One segment of a line being displayed */
1461 enum {TSMAX=32}; /* The maximum length of the date and time string */
1462 char buffer[TSMAX+1]; /* The buffer in which to write the date and time */
1463 int idlen; /* The length of displayed ID strings */
1464 unsigned grpmax; /* The maximum group number in the buffer */
1465 int grplen; /* The number of characters needed to print grpmax */
1466 int len; /* The length of a string to be written */
1468 * Check the arguments.
1470 if(!glh || !write_fn || !fmt) {
1471 if(glh)
1472 _err_record_msg(glh->err, "NULL argument(s)", END_ERR_MSG);
1473 errno = EINVAL;
1474 return 1;
1477 * Is history enabled?
1479 if(!glh->enable || !glh->list.head)
1480 return 0;
1482 * Work out the length to display ID numbers, choosing the length of
1483 * the biggest number in the buffer. Smaller numbers will be padded
1484 * with leading zeroes if needed.
1486 snprintf(buffer, sizeof(buffer), "%lu", (unsigned long) glh->list.tail->id);
1487 idlen = strlen(buffer);
1489 * Find the largest group number.
1491 grpmax = 0;
1492 for(node=glh->list.head; node; node=node->next) {
1493 if(node->group > grpmax)
1494 grpmax = node->group;
1497 * Find out how many characters are needed to display the group number.
1499 snprintf(buffer, sizeof(buffer), "%u", (unsigned) grpmax);
1500 grplen = strlen(buffer);
1502 * Find the node that follows the oldest line to be displayed.
1504 if(max_lines < 0) {
1505 oldest = glh->list.head;
1506 } else if(max_lines==0) {
1507 return 0;
1508 } else {
1509 for(oldest=glh->list.tail; oldest; oldest=oldest->prev) {
1510 if((all_groups || oldest->group == glh->group) && --max_lines <= 0)
1511 break;
1514 * If the number of lines in the buffer doesn't exceed the specified
1515 * maximum, start from the oldest line in the buffer.
1517 if(!oldest)
1518 oldest = glh->list.head;
1521 * List the history lines in increasing time order.
1523 for(node=oldest; node; node=node->next) {
1525 * Only display lines from the current history group, unless
1526 * told otherwise.
1528 if(all_groups || node->group == glh->group) {
1529 const char *fptr; /* A pointer into the format string */
1530 struct tm *t = NULL; /* The broken time version of the timestamp */
1532 * Work out the calendar representation of the node timestamp.
1534 if(node->timestamp != (time_t) -1)
1535 t = localtime(&node->timestamp);
1537 * Parse the format string.
1539 fptr = fmt;
1540 while(*fptr) {
1542 * Search for the start of the next format directive or the end of the string.
1544 const char *start = fptr;
1545 while(*fptr && *fptr != '%')
1546 fptr++;
1548 * Display any literal characters that precede the located directive.
1550 if(fptr > start) {
1551 len = (int) (fptr - start);
1552 if(write_fn(data, start, len) != len)
1553 return 1;
1556 * Did we hit a new directive before the end of the line?
1558 if(*fptr) {
1560 * Obey the directive. Ignore unknown directives.
1562 switch(*++fptr) {
1563 case 'D': /* Display the date */
1564 if(t && strftime(buffer, TSMAX, "%Y-%m-%d", t) != 0) {
1565 len = strlen(buffer);
1566 if(write_fn(data, buffer, len) != len)
1567 return 1;
1569 break;
1570 case 'T': /* Display the time of day */
1571 if(t && strftime(buffer, TSMAX, "%H:%M:%S", t) != 0) {
1572 len = strlen(buffer);
1573 if(write_fn(data, buffer, len) != len)
1574 return 1;
1576 break;
1577 case 'N': /* Display the sequential entry number */
1578 snprintf(buffer, sizeof(buffer), "%*lu", idlen, (unsigned long) node->id);
1579 len = strlen(buffer);
1580 if(write_fn(data, buffer, len) != len)
1581 return 1;
1582 break;
1583 case 'G':
1584 snprintf(buffer, sizeof(buffer), "%*u", grplen, (unsigned) node->group);
1585 len = strlen(buffer);
1586 if(write_fn(data, buffer, len) != len)
1587 return 1;
1588 break;
1589 case 'H': /* Display the history line */
1590 for(seg=node->line->head; seg; seg=seg->next) {
1591 len = seg->next ? GLH_SEG_SIZE : strlen(seg->s);
1592 if(write_fn(data, seg->s, len) != len)
1593 return 1;
1595 break;
1596 case '%': /* A literal % symbol */
1597 if(write_fn(data, "%", 1) != 1)
1598 return 1;
1599 break;
1602 * Skip the directive.
1604 if(*fptr)
1605 fptr++;
1610 return 0;
1613 /*.......................................................................
1614 * Change the size of the history buffer.
1616 * Input:
1617 * glh GlHistory * The input-line history maintenance object.
1618 * bufsize size_t The number of bytes in the history buffer, or 0
1619 * to delete the buffer completely.
1620 * Output:
1621 * return int 0 - OK.
1622 * 1 - Insufficient memory (the previous buffer
1623 * will have been retained). No error message
1624 * will be displayed.
1626 int _glh_resize_history(GlHistory *glh, size_t bufsize)
1628 int nbuff; /* The number of segments in the new buffer */
1629 int i;
1631 * Check the arguments.
1633 if(!glh) {
1634 errno = EINVAL;
1635 return 1;
1638 * How many buffer segments does the requested buffer size correspond
1639 * to?
1641 nbuff = (bufsize+GLH_SEG_SIZE-1) / GLH_SEG_SIZE;
1643 * Has a different size than the current size been requested?
1645 if(glh->nbuff != nbuff) {
1647 * Cancel any ongoing search.
1649 (void) _glh_cancel_search(glh);
1651 * Create a wholly new buffer?
1653 if(glh->nbuff == 0 && nbuff>0) {
1654 glh->buffer = (GlhLineSeg *) malloc(sizeof(GlhLineSeg) * nbuff);
1655 if(!glh->buffer)
1656 return 1;
1657 glh->nbuff = nbuff;
1658 glh->nfree = glh->nbuff;
1659 glh->nbusy = 0;
1660 glh->nline = 0;
1662 * Link the currently unused nodes of the buffer into a list.
1664 glh->unused = glh->buffer;
1665 for(i=0; i<glh->nbuff-1; i++) {
1666 GlhLineSeg *seg = glh->unused + i;
1667 seg->next = seg + 1;
1669 glh->unused[i].next = NULL;
1671 * Delete an existing buffer?
1673 } else if(nbuff == 0) {
1674 _glh_clear_history(glh, 1);
1675 free(glh->buffer);
1676 glh->buffer = NULL;
1677 glh->unused = NULL;
1678 glh->nbuff = 0;
1679 glh->nfree = 0;
1680 glh->nbusy = 0;
1681 glh->nline = 0;
1683 * Change from one finite buffer size to another?
1685 } else {
1686 GlhLineSeg *buffer; /* The resized buffer */
1687 int nbusy; /* The number of used line segments in the new buffer */
1689 * Starting from the oldest line in the buffer, discard lines until
1690 * the buffer contains at most 'nbuff' used line segments.
1692 while(glh->list.head && glh->nbusy > nbuff)
1693 _glh_discard_line(glh, glh->list.head);
1695 * Attempt to allocate a new buffer.
1697 buffer = (GlhLineSeg *) malloc(nbuff * sizeof(GlhLineSeg));
1698 if(!buffer) {
1699 errno = ENOMEM;
1700 return 1;
1703 * Copy the used segments of the old buffer to the start of the new buffer.
1705 nbusy = 0;
1706 for(i=0; i<GLH_HASH_SIZE; i++) {
1707 GlhHashBucket *b = glh->hash.bucket + i;
1708 GlhHashNode *hnode;
1709 for(hnode=b->lines; hnode; hnode=hnode->next) {
1710 GlhLineSeg *seg = hnode->head;
1711 hnode->head = buffer + nbusy;
1712 for( ; seg; seg=seg->next) {
1713 buffer[nbusy] = *seg;
1714 buffer[nbusy].next = seg->next ? &buffer[nbusy+1] : NULL;
1715 nbusy++;
1720 * Make a list of the new buffer's unused segments.
1722 for(i=nbusy; i<nbuff-1; i++)
1723 buffer[i].next = &buffer[i+1];
1724 if(i < nbuff)
1725 buffer[i].next = NULL;
1727 * Discard the old buffer.
1729 free(glh->buffer);
1731 * Install the new buffer.
1733 glh->buffer = buffer;
1734 glh->nbuff = nbuff;
1735 glh->nbusy = nbusy;
1736 glh->nfree = nbuff - nbusy;
1737 glh->unused = glh->nfree > 0 ? (buffer + nbusy) : NULL;
1740 return 0;
1743 /*.......................................................................
1744 * Set an upper limit to the number of lines that can be recorded in the
1745 * history list, or remove a previously specified limit.
1747 * Input:
1748 * glh GlHistory * The input-line history maintenance object.
1749 * max_lines int The maximum number of lines to allow, or -1 to
1750 * cancel a previous limit and allow as many lines
1751 * as will fit in the current history buffer size.
1753 void _glh_limit_history(GlHistory *glh, int max_lines)
1755 if(!glh)
1756 return;
1758 * Apply a new limit?
1760 if(max_lines >= 0 && max_lines != glh->max_lines) {
1762 * Count successively older lines until we reach the start of the
1763 * list, or until we have seen max_lines lines (at which point 'node'
1764 * will be line number max_lines+1).
1766 int nline = 0;
1767 GlhLineNode *node;
1768 for(node=glh->list.tail; node && ++nline <= max_lines; node=node->prev)
1771 * Discard any lines that exceed the limit.
1773 if(node) {
1774 GlhLineNode *oldest = node->next; /* The oldest line to be kept */
1776 * Delete nodes from the head of the list until we reach the node that
1777 * is to be kept.
1779 while(glh->list.head && glh->list.head != oldest)
1780 _glh_discard_line(glh, glh->list.head);
1784 * Record the new limit.
1786 glh->max_lines = max_lines;
1787 return;
1790 /*.......................................................................
1791 * Discard either all history, or the history associated with the current
1792 * history group.
1794 * Input:
1795 * glh GlHistory * The input-line history maintenance object.
1796 * all_groups int If true, clear all of the history. If false,
1797 * clear only the stored lines associated with the
1798 * currently selected history group.
1800 void _glh_clear_history(GlHistory *glh, int all_groups)
1802 int i;
1804 * Check the arguments.
1806 if(!glh)
1807 return;
1809 * Cancel any ongoing search.
1811 (void) _glh_cancel_search(glh);
1813 * Delete all history lines regardless of group?
1815 if(all_groups) {
1817 * Claer the time-ordered list of lines.
1819 _rst_FreeList(glh->list.node_mem);
1820 glh->list.head = glh->list.tail = NULL;
1821 glh->nline = 0;
1822 glh->id_node = NULL;
1824 * Clear the hash table.
1826 for(i=0; i<GLH_HASH_SIZE; i++)
1827 glh->hash.bucket[i].lines = NULL;
1828 _rst_FreeList(glh->hash.node_mem);
1830 * Move all line segment nodes back onto the list of unused segments.
1832 if(glh->buffer) {
1833 glh->unused = glh->buffer;
1834 for(i=0; i<glh->nbuff-1; i++) {
1835 GlhLineSeg *seg = glh->unused + i;
1836 seg->next = seg + 1;
1838 glh->unused[i].next = NULL;
1839 glh->nfree = glh->nbuff;
1840 glh->nbusy = 0;
1841 } else {
1842 glh->unused = NULL;
1843 glh->nbusy = glh->nfree = 0;
1846 * Just delete lines of the current group?
1848 } else {
1849 GlhLineNode *node; /* The line node being checked */
1850 GlhLineNode *next; /* The line node that follows 'node' */
1852 * Search out and delete the line nodes of the current group.
1854 for(node=glh->list.head; node; node=next) {
1856 * Keep a record of the following node before we delete the current
1857 * node.
1859 next = node->next;
1861 * Discard this node?
1863 if(node->group == glh->group)
1864 _glh_discard_line(glh, node);
1867 return;
1870 /*.......................................................................
1871 * Temporarily enable or disable the history list.
1873 * Input:
1874 * glh GlHistory * The input-line history maintenance object.
1875 * enable int If true, turn on the history mechanism. If
1876 * false, disable it.
1878 void _glh_toggle_history(GlHistory *glh, int enable)
1880 if(glh)
1881 glh->enable = enable;
1884 /*.......................................................................
1885 * Discard a given archived input line.
1887 * Input:
1888 * glh GlHistory * The history container object.
1889 * node GlhLineNode * The line to be discarded, specified via its
1890 * entry in the time-ordered list of historical
1891 * input lines.
1893 static void _glh_discard_line(GlHistory *glh, GlhLineNode *node)
1896 * Remove the node from the linked list.
1898 if(node->prev)
1899 node->prev->next = node->next;
1900 else
1901 glh->list.head = node->next;
1902 if(node->next)
1903 node->next->prev = node->prev;
1904 else
1905 glh->list.tail = node->prev;
1907 * If we are deleting the node that is marked as the start point of the
1908 * last ID search, remove the cached starting point.
1910 if(node == glh->id_node)
1911 glh->id_node = NULL;
1913 * If we are deleting the node that is marked as the start point of the
1914 * next prefix search, cancel the search.
1916 if(node == glh->recall)
1917 _glh_cancel_search(glh);
1919 * Delete our copy of the line.
1921 node->line = _glh_discard_copy(glh, node->line);
1923 * Return the node to the freelist.
1925 (void) _del_FreeListNode(glh->list.node_mem, node);
1927 * Record the removal of a line from the list.
1929 glh->nline--;
1930 return;
1933 /*.......................................................................
1934 * Lookup the details of a given history line, given its id.
1936 * Input:
1937 * glh GlHistory * The input-line history maintenance object.
1938 * id GlLineID The sequential number of the line.
1939 * Input/Output:
1940 * line const char ** A pointer to a copy of the history line will be
1941 * assigned to *line. Beware that this pointer may
1942 * be invalidated by the next call to any public
1943 * history function.
1944 * group unsigned * The group membership of the line will be assigned
1945 * to *group.
1946 * timestamp time_t * The timestamp of the line will be assigned to
1947 * *timestamp.
1948 * Output:
1949 * return int 0 - The requested line wasn't found.
1950 * 1 - The line was found.
1952 int _glh_lookup_history(GlHistory *glh, GlhLineID id, const char **line,
1953 unsigned *group, time_t *timestamp)
1955 GlhLineNode *node; /* The located line location node */
1957 * Check the arguments.
1959 if(!glh)
1960 return 0;
1962 * Search for the line that has the specified ID.
1964 node = _glh_find_id(glh, id);
1966 * Not found?
1968 if(!node)
1969 return 0;
1971 * Has the history line been requested?
1973 if(line) {
1975 * If necessary, reallocate the lookup buffer to accomodate the size of
1976 * a copy of the located line.
1978 if(node->line->len + 1 > glh->lbuf_dim) {
1979 int lbuf_dim = node->line->len + 1;
1980 char *lbuf = realloc(glh->lbuf, lbuf_dim);
1981 if(!lbuf) {
1982 errno = ENOMEM;
1983 return 0;
1985 glh->lbuf_dim = lbuf_dim;
1986 glh->lbuf = lbuf;
1989 * Copy the history line into the lookup buffer.
1991 _glh_return_line(node->line, glh->lbuf, glh->lbuf_dim);
1993 * Assign the lookup buffer as the returned line pointer.
1995 *line = glh->lbuf;
1998 * Does the caller want to know the group of the line?
2000 if(group)
2001 *group = node->group;
2003 * Does the caller want to know the timestamp of the line?
2005 if(timestamp)
2006 *timestamp = node->timestamp;
2007 return 1;
2010 /*.......................................................................
2011 * Lookup a node in the history list by its ID.
2013 * Input:
2014 * glh GlHistory * The input-line history maintenance object.
2015 * id GlhLineID The ID of the line to be returned.
2016 * Output:
2017 * return GlhLIneNode * The located node, or NULL if not found.
2019 static GlhLineNode *_glh_find_id(GlHistory *glh, GlhLineID id)
2021 GlhLineNode *node; /* The node being checked */
2023 * Is history enabled?
2025 if(!glh->enable || !glh->list.head)
2026 return NULL;
2028 * If possible, start at the end point of the last ID search.
2029 * Otherwise start from the head of the list.
2031 node = glh->id_node;
2032 if(!node)
2033 node = glh->list.head;
2035 * Search forwards from 'node'?
2037 if(node->id < id) {
2038 while(node && node->id != id)
2039 node = node->next;
2040 glh->id_node = node ? node : glh->list.tail;
2042 * Search backwards from 'node'?
2044 } else {
2045 while(node && node->id != id)
2046 node = node->prev;
2047 glh->id_node = node ? node : glh->list.head;
2050 * Return the located node (this will be NULL if the ID wasn't found).
2052 return node;
2055 /*.......................................................................
2056 * Query the state of the history list. Note that any of the input/output
2057 * pointers can be specified as NULL.
2059 * Input:
2060 * glh GlHistory * The input-line history maintenance object.
2061 * Input/Output:
2062 * enabled int * If history is enabled, *enabled will be
2063 * set to 1. Otherwise it will be assigned 0.
2064 * group unsigned * The current history group ID will be assigned
2065 * to *group.
2066 * max_lines int * The currently requested limit on the number
2067 * of history lines in the list, or -1 if
2068 * unlimited.
2070 void _glh_state_of_history(GlHistory *glh, int *enabled, unsigned *group,
2071 int *max_lines)
2073 if(glh) {
2074 if(enabled)
2075 *enabled = glh->enable;
2076 if(group)
2077 *group = glh->group;
2078 if(max_lines)
2079 *max_lines = glh->max_lines;
2083 /*.......................................................................
2084 * Get the range of lines in the history buffer.
2086 * Input:
2087 * glh GlHistory * The input-line history maintenance object.
2088 * Input/Output:
2089 * oldest unsigned long * The sequential entry number of the oldest
2090 * line in the history list will be assigned
2091 * to *oldest, unless there are no lines, in
2092 * which case 0 will be assigned.
2093 * newest unsigned long * The sequential entry number of the newest
2094 * line in the history list will be assigned
2095 * to *newest, unless there are no lines, in
2096 * which case 0 will be assigned.
2097 * nlines int * The number of lines currently in the history
2098 * list.
2100 void _glh_range_of_history(GlHistory *glh, unsigned long *oldest,
2101 unsigned long *newest, int *nlines)
2103 if(glh) {
2104 if(oldest)
2105 *oldest = glh->list.head ? glh->list.head->id : 0;
2106 if(newest)
2107 *newest = glh->list.tail ? glh->list.tail->id : 0;
2108 if(nlines)
2109 *nlines = glh->nline;
2113 /*.......................................................................
2114 * Return the size of the history buffer and the amount of the
2115 * buffer that is currently in use.
2117 * Input:
2118 * glh GlHistory * The input-line history maintenance object.
2119 * Input/Output:
2120 * buff_size size_t * The size of the history buffer (bytes).
2121 * buff_used size_t * The amount of the history buffer that
2122 * is currently occupied (bytes).
2124 void _glh_size_of_history(GlHistory *glh, size_t *buff_size, size_t *buff_used)
2126 if(glh) {
2127 if(buff_size)
2128 *buff_size = (glh->nbusy + glh->nfree) * GLH_SEG_SIZE;
2130 * Determine the amount of buffer space that is currently occupied.
2132 if(buff_used)
2133 *buff_used = glh->nbusy * GLH_SEG_SIZE;
2137 /*.......................................................................
2138 * Return extra information (ie. in addition to that provided by errno)
2139 * about the last error to occur in any of the public functions of this
2140 * module.
2142 * Input:
2143 * glh GlHistory * The container of the history list.
2144 * Output:
2145 * return const char * A pointer to the internal buffer in which
2146 * the error message is temporarily stored.
2148 const char *_glh_last_error(GlHistory *glh)
2150 return glh ? _err_get_msg(glh->err) : "NULL GlHistory argument";
2153 /*.......................................................................
2154 * Unless already stored, store a copy of the line in the history buffer,
2155 * then return a reference-counted hash-node pointer to this copy.
2157 * Input:
2158 * glh GlHistory * The history maintenance buffer.
2159 * line const char * The history line to be recorded.
2160 * n size_t The length of the string, excluding any '\0'
2161 * terminator.
2162 * Output:
2163 * return GlhHashNode * The hash-node containing the stored line, or
2164 * NULL on error.
2166 static GlhHashNode *_glh_acquire_copy(GlHistory *glh, const char *line,
2167 size_t n)
2169 GlhHashBucket *bucket; /* The hash-table bucket of the line */
2170 GlhHashNode *hnode; /* The hash-table node of the line */
2171 int i;
2173 * In which bucket should the line be recorded?
2175 bucket = glh_find_bucket(glh, line, n);
2177 * Is the line already recorded there?
2179 hnode = glh_find_hash_node(bucket, line, n);
2181 * If the line isn't recorded in the buffer yet, make room for it.
2183 if(!hnode) {
2184 GlhLineSeg *seg; /* A line segment */
2185 int offset; /* An offset into line[] */
2187 * How many string segments will be needed to record the new line,
2188 * including space for a '\0' terminator?
2190 int nseg = ((n+1) + GLH_SEG_SIZE-1) / GLH_SEG_SIZE;
2192 * Discard the oldest history lines in the buffer until at least
2193 * 'nseg' segments have been freed up, or until we run out of buffer
2194 * space.
2196 while(glh->nfree < nseg && glh->nbusy > 0)
2197 _glh_discard_line(glh, glh->list.head);
2199 * If the buffer is smaller than the new line, don't attempt to truncate
2200 * it to fit. Simply don't archive it.
2202 if(glh->nfree < nseg)
2203 return NULL;
2205 * Record the line in the first 'nseg' segments of the list of unused segments.
2207 offset = 0;
2208 for(i=0,seg=glh->unused; i<nseg-1; i++,seg=seg->next, offset+=GLH_SEG_SIZE)
2209 memcpy(seg->s, line + offset, GLH_SEG_SIZE);
2210 memcpy(seg->s, line + offset, n-offset);
2211 seg->s[n-offset] = '\0';
2213 * Create a new hash-node for the line.
2215 hnode = (GlhHashNode *) _new_FreeListNode(glh->hash.node_mem);
2216 if(!hnode)
2217 return NULL;
2219 * Move the copy of the line from the list of unused segments to
2220 * the hash node.
2222 hnode->head = glh->unused;
2223 glh->unused = seg->next;
2224 seg->next = NULL;
2225 glh->nbusy += nseg;
2226 glh->nfree -= nseg;
2228 * Prepend the new hash node to the list within the associated bucket.
2230 hnode->next = bucket->lines;
2231 bucket->lines = hnode;
2233 * Initialize the rest of the members of the hash node.
2235 hnode->len = n;
2236 hnode->reported = 0;
2237 hnode->used = 0;
2238 hnode->bucket = bucket;
2241 * Increment the reference count of the line.
2243 hnode->used++;
2244 return hnode;
2247 /*.......................................................................
2248 * Decrement the reference count of the history line of a given hash-node,
2249 * and if the count reaches zero, delete both the hash-node and the
2250 * buffered copy of the line.
2252 * Input:
2253 * glh GlHistory * The history container object.
2254 * hnode GlhHashNode * The node to be removed.
2255 * Output:
2256 * return GlhHashNode * The deleted hash-node (ie. NULL).
2258 static GlhHashNode *_glh_discard_copy(GlHistory *glh, GlhHashNode *hnode)
2260 if(hnode) {
2261 GlhHashBucket *bucket = hnode->bucket;
2263 * If decrementing the reference count of the hash-node doesn't reduce
2264 * the reference count to zero, then the line is still in use in another
2265 * object, so don't delete it yet. Return NULL to indicate that the caller's
2266 * access to the hash-node copy has been deleted.
2268 if(--hnode->used >= 1)
2269 return NULL;
2271 * Remove the hash-node from the list in its parent bucket.
2273 if(bucket->lines == hnode) {
2274 bucket->lines = hnode->next;
2275 } else {
2276 GlhHashNode *prev; /* The node which precedes hnode in the bucket */
2277 for(prev=bucket->lines; prev && prev->next != hnode; prev=prev->next)
2279 if(prev)
2280 prev->next = hnode->next;
2282 hnode->next = NULL;
2284 * Return the line segments of the hash-node to the list of unused segments.
2286 if(hnode->head) {
2287 GlhLineSeg *tail; /* The last node in the list of line segments */
2288 int nseg; /* The number of segments being discarded */
2290 * Get the last node of the list of line segments referenced in the hash-node,
2291 * while counting the number of line segments used.
2293 for(nseg=1,tail=hnode->head; tail->next; nseg++,tail=tail->next)
2296 * Prepend the list of line segments used by the hash node to the
2297 * list of unused line segments.
2299 tail->next = glh->unused;
2300 glh->unused = hnode->head;
2301 glh->nbusy -= nseg;
2302 glh->nfree += nseg;
2305 * Return the container of the hash-node to the freelist.
2307 hnode = (GlhHashNode *) _del_FreeListNode(glh->hash.node_mem, hnode);
2309 return NULL;
2312 /*.......................................................................
2313 * Private function to locate the hash bucket associated with a given
2314 * history line.
2316 * This uses a hash-function described in the dragon-book
2317 * ("Compilers - Principles, Techniques and Tools", by Aho, Sethi and
2318 * Ullman; pub. Adison Wesley) page 435.
2320 * Input:
2321 * glh GlHistory * The history container object.
2322 * line const char * The historical line to look up.
2323 * n size_t The length of the line in line[], excluding
2324 * any '\0' terminator.
2325 * Output:
2326 * return GlhHashBucket * The located hash-bucket.
2328 static GlhHashBucket *glh_find_bucket(GlHistory *glh, const char *line,
2329 size_t n)
2331 unsigned long h = 0L;
2332 int i;
2333 for(i=0; i<n; i++) {
2334 unsigned char c = line[i];
2335 h = 65599UL * h + c; /* 65599 is a prime close to 2^16 */
2337 return glh->hash.bucket + (h % GLH_HASH_SIZE);
2340 /*.......................................................................
2341 * Find a given history line within a given hash-table bucket.
2343 * Input:
2344 * bucket GlhHashBucket * The hash-table bucket in which to search.
2345 * line const char * The historical line to lookup.
2346 * n size_t The length of the line in line[], excluding
2347 * any '\0' terminator.
2348 * Output:
2349 * return GlhHashNode * The hash-table entry of the line, or NULL
2350 * if not found.
2352 static GlhHashNode *glh_find_hash_node(GlhHashBucket *bucket, const char *line,
2353 size_t n)
2355 GlhHashNode *node; /* A node in the list of lines in the bucket */
2357 * Compare each of the lines in the list of lines, against 'line'.
2359 for(node=bucket->lines; node; node=node->next) {
2360 if(_glh_is_line(node, line, n))
2361 return node;
2363 return NULL;
2366 /*.......................................................................
2367 * Return non-zero if a given string is equal to a given segmented line
2368 * node.
2370 * Input:
2371 * hash GlhHashNode * The hash-table entry of the line.
2372 * line const char * The string to be compared to the segmented
2373 * line.
2374 * n size_t The length of the line in line[], excluding
2375 * any '\0' terminator.
2376 * Output:
2377 * return int 0 - The lines differ.
2378 * 1 - The lines are the same.
2380 static int _glh_is_line(GlhHashNode *hash, const char *line, size_t n)
2382 GlhLineSeg *seg; /* A node in the list of line segments */
2383 int i;
2385 * Do the two lines have the same length?
2387 if(n != hash->len)
2388 return 0;
2390 * Compare the characters of the segmented and unsegmented versions
2391 * of the line.
2393 for(seg=hash->head; n>0 && seg; seg=seg->next) {
2394 const char *s = seg->s;
2395 for(i=0; n>0 && i<GLH_SEG_SIZE; i++,n--) {
2396 if(*line++ != *s++)
2397 return 0;
2400 return 1;
2403 /*.......................................................................
2404 * Return non-zero if a given line has the specified segmented search
2405 * prefix.
2407 * Input:
2408 * line GlhHashNode * The line to be compared against the prefix.
2409 * prefix GlhHashNode * The search prefix, or NULL to match any string.
2410 * Output:
2411 * return int 0 - The line doesn't have the specified prefix.
2412 * 1 - The line has the specified prefix.
2414 static int _glh_line_matches_prefix(GlhHashNode *line, GlhHashNode *prefix)
2416 GlhLineStream lstr; /* The stream that is used to traverse 'line' */
2417 GlhLineStream pstr; /* The stream that is used to traverse 'prefix' */
2419 * When prefix==NULL, this means that the nul string
2420 * is to be matched, and this matches all lines.
2422 if(!prefix)
2423 return 1;
2425 * Wrap the two history lines that are to be compared in iterator
2426 * stream objects.
2428 glh_init_stream(&lstr, line);
2429 glh_init_stream(&pstr, prefix);
2431 * If the prefix contains a glob pattern, match the prefix as a glob
2432 * pattern.
2434 if(glh_contains_glob(prefix))
2435 return glh_line_matches_glob(&lstr, &pstr);
2437 * Is the prefix longer than the line being compared against it?
2439 if(prefix->len > line->len)
2440 return 0;
2442 * Compare the line to the prefix.
2444 while(pstr.c != '\0' && pstr.c == lstr.c) {
2445 glh_step_stream(&lstr);
2446 glh_step_stream(&pstr);
2449 * Did we reach the end of the prefix string before finding
2450 * any differences?
2452 return pstr.c == '\0';
2455 /*.......................................................................
2456 * Copy a given history line into a specified output string.
2458 * Input:
2459 * hash GlhHashNode The hash-table entry of the history line to
2460 * be copied.
2461 * line char * A copy of the history line.
2462 * dim size_t The allocated dimension of the line buffer.
2464 static void _glh_return_line(GlhHashNode *hash, char *line, size_t dim)
2466 GlhLineSeg *seg; /* A node in the list of line segments */
2467 int i;
2468 for(seg=hash->head; dim>0 && seg; seg=seg->next) {
2469 const char *s = seg->s;
2470 for(i=0; dim>0 && i<GLH_SEG_SIZE; i++,dim--)
2471 *line++ = *s++;
2474 * If the line wouldn't fit in the output buffer, replace the last character
2475 * with a '\0' terminator.
2477 if(dim==0)
2478 line[-1] = '\0';
2481 /*.......................................................................
2482 * This function should be called whenever a new line recall is
2483 * attempted. It preserves a copy of the current input line in the
2484 * history list while other lines in the history list are being
2485 * returned.
2487 * Input:
2488 * glh GlHistory * The input-line history maintenance object.
2489 * line char * The current contents of the input line buffer.
2490 * Output:
2491 * return int 0 - OK.
2492 * 1 - Error.
2494 static int _glh_prepare_for_recall(GlHistory *glh, char *line)
2497 * If a recall session has already been started, but we have returned
2498 * to the preserved copy of the input line, if the user has changed
2499 * this line, we should replace the preserved copy of the original
2500 * input line with the new one. To do this simply cancel the session,
2501 * so that a new session is started below.
2503 if(glh->recall && glh->recall == glh->list.tail &&
2504 !_glh_is_line(glh->recall->line, line, strlen(line))) {
2505 _glh_cancel_search(glh);
2508 * If this is the first line recall of a new recall session, save the
2509 * current line for potential recall later, and mark it as the last
2510 * line recalled.
2512 if(!glh->recall) {
2513 if(_glh_add_history(glh, line, 1))
2514 return 1;
2515 glh->recall = glh->list.tail;
2517 * The above call to _glh_add_history() will have incremented the line
2518 * sequence number, after adding the line. Since we only want this to
2519 * to be incremented for permanently entered lines, decrement it again.
2521 glh->seq--;
2523 return 0;
2526 /*.......................................................................
2527 * Return non-zero if a history search session is currently in progress.
2529 * Input:
2530 * glh GlHistory * The input-line history maintenance object.
2531 * Output:
2532 * return int 0 - No search is currently in progress.
2533 * 1 - A search is in progress.
2535 int _glh_search_active(GlHistory *glh)
2537 return glh && glh->recall;
2540 /*.......................................................................
2541 * Initialize a character iterator object to point to the start of a
2542 * given history line. The first character of the line will be placed
2543 * in str->c, and subsequent characters can be placed there by calling
2544 * glh_strep_stream().
2546 * Input:
2547 * str GlhLineStream * The iterator object to be initialized.
2548 * line GlhHashNode * The history line to be iterated over (a
2549 * NULL value here, is interpretted as an
2550 * empty string by glh_step_stream()).
2552 static void glh_init_stream(GlhLineStream *str, GlhHashNode *line)
2554 str->seg = line ? line->head : NULL;
2555 str->posn = 0;
2556 str->c = str->seg ? str->seg->s[0] : '\0';
2559 /*.......................................................................
2560 * Copy the next unread character in the line being iterated, in str->c.
2561 * Once the end of the history line has been reached, all futher calls
2562 * set str->c to '\0'.
2564 * Input:
2565 * str GlhLineStream * The history-line iterator to read from.
2567 static void glh_step_stream(GlhLineStream *str)
2570 * Get the character from the current iterator position within the line.
2572 str->c = str->seg ? str->seg->s[str->posn] : '\0';
2574 * Unless we have reached the end of the string, move the iterator
2575 * to the position of the next character in the line.
2577 if(str->c != '\0' && ++str->posn >= GLH_SEG_SIZE) {
2578 str->posn = 0;
2579 str->seg = str->seg->next;
2583 /*.......................................................................
2584 * Return non-zero if the specified search prefix contains any glob
2585 * wildcard characters.
2587 * Input:
2588 * prefix GlhHashNode * The search prefix.
2589 * Output:
2590 * return int 0 - The prefix doesn't contain any globbing
2591 * characters.
2592 * 1 - The prefix contains at least one
2593 * globbing character.
2595 static int glh_contains_glob(GlhHashNode *prefix)
2597 GlhLineStream pstr; /* The stream that is used to traverse 'prefix' */
2599 * Wrap a stream iterator around the prefix, so that we can traverse it
2600 * without worrying about line-segmentation.
2602 glh_init_stream(&pstr, prefix);
2604 * Search for unescaped wildcard characters.
2606 while(pstr.c != '\0') {
2607 switch(pstr.c) {
2608 case '\\': /* Skip escaped characters */
2609 glh_step_stream(&pstr);
2610 break;
2611 case '*': case '?': case '[': /* A wildcard character? */
2612 return 1;
2613 break;
2615 glh_step_stream(&pstr);
2618 * No wildcard characters were found.
2620 return 0;
2623 /*.......................................................................
2624 * Return non-zero if the history line matches a search prefix containing
2625 * a glob pattern.
2627 * Input:
2628 * lstr GlhLineStream * The iterator stream being used to traverse
2629 * the history line that is being matched.
2630 * pstr GlhLineStream * The iterator stream being used to traverse
2631 * the pattern.
2632 * Output:
2633 * return int 0 - Doesn't match.
2634 * 1 - The line matches the pattern.
2636 static int glh_line_matches_glob(GlhLineStream *lstr, GlhLineStream *pstr)
2639 * Match each character of the pattern until we reach the end of the
2640 * pattern.
2642 while(pstr->c != '\0') {
2644 * Handle the next character of the pattern.
2646 switch(pstr->c) {
2648 * A match zero-or-more characters wildcard operator.
2650 case '*':
2652 * Skip the '*' character in the pattern.
2654 glh_step_stream(pstr);
2656 * If the pattern ends with the '*' wildcard, then the
2657 * rest of the line matches this.
2659 if(pstr->c == '\0')
2660 return 1;
2662 * Using the wildcard to match successively longer sections of
2663 * the remaining characters of the line, attempt to match
2664 * the tail of the line against the tail of the pattern.
2666 while(lstr->c) {
2667 GlhLineStream old_lstr = *lstr;
2668 GlhLineStream old_pstr = *pstr;
2669 if(glh_line_matches_glob(lstr, pstr))
2670 return 1;
2672 * Restore the line and pattern iterators for a new try.
2674 *lstr = old_lstr;
2675 *pstr = old_pstr;
2677 * Prepare to try again, one character further into the line.
2679 glh_step_stream(lstr);
2681 return 0; /* The pattern following the '*' didn't match */
2682 break;
2684 * A match-one-character wildcard operator.
2686 case '?':
2688 * If there is a character to be matched, skip it and advance the
2689 * pattern pointer.
2691 if(lstr->c) {
2692 glh_step_stream(lstr);
2693 glh_step_stream(pstr);
2695 * If we hit the end of the line, there is no character
2696 * matching the operator, so the pattern doesn't match.
2698 } else {
2699 return 0;
2701 break;
2703 * A character range operator, with the character ranges enclosed
2704 * in matching square brackets.
2706 case '[':
2707 glh_step_stream(pstr); /* Skip the '[' character */
2708 if(!lstr->c || !glh_matches_range(lstr->c, pstr))
2709 return 0;
2710 glh_step_stream(lstr); /* Skip the character that matched */
2711 break;
2713 * A backslash in the pattern prevents the following character as
2714 * being seen as a special character.
2716 case '\\':
2717 glh_step_stream(pstr); /* Skip the backslash */
2718 /* Note fallthrough to default */
2720 * A normal character to be matched explicitly.
2722 default:
2723 if(lstr->c == pstr->c) {
2724 glh_step_stream(lstr);
2725 glh_step_stream(pstr);
2726 } else {
2727 return 0;
2729 break;
2733 * To get here, pattern must have been exhausted. The line only
2734 * matches the pattern if the line as also been exhausted.
2736 return pstr->c == '\0' && lstr->c == '\0';
2739 /*.......................................................................
2740 * Match a character range expression terminated by an unescaped close
2741 * square bracket.
2743 * Input:
2744 * c char The character to be matched with the range
2745 * pattern.
2746 * pstr GlhLineStream * The iterator stream being used to traverse
2747 * the pattern.
2748 * Output:
2749 * return int 0 - Doesn't match.
2750 * 1 - The character matched.
2752 static int glh_matches_range(char c, GlhLineStream *pstr)
2754 int invert = 0; /* True to invert the sense of the match */
2755 int matched = 0; /* True if the character matched the pattern */
2756 char lastc = '\0'; /* The previous character in the pattern */
2758 * If the first character is a caret, the sense of the match is
2759 * inverted and only if the character isn't one of those in the
2760 * range, do we say that it matches.
2762 if(pstr->c == '^') {
2763 glh_step_stream(pstr);
2764 invert = 1;
2767 * The hyphen is only a special character when it follows the first
2768 * character of the range (not including the caret).
2770 if(pstr->c == '-') {
2771 glh_step_stream(pstr);
2772 if(c == '-')
2773 matched = 1;
2775 * Skip other leading '-' characters since they make no sense.
2777 while(pstr->c == '-')
2778 glh_step_stream(pstr);
2781 * The hyphen is only a special character when it follows the first
2782 * character of the range (not including the caret or a hyphen).
2784 if(pstr->c == ']') {
2785 glh_step_stream(pstr);
2786 if(c == ']')
2787 matched = 1;
2790 * Having dealt with the characters that have special meanings at
2791 * the beginning of a character range expression, see if the
2792 * character matches any of the remaining characters of the range,
2793 * up until a terminating ']' character is seen.
2795 while(!matched && pstr->c && pstr->c != ']') {
2797 * Is this a range of characters signaled by the two end characters
2798 * separated by a hyphen?
2800 if(pstr->c == '-') {
2801 glh_step_stream(pstr); /* Skip the hyphen */
2802 if(pstr->c != ']') {
2803 if(c >= lastc && c <= pstr->c)
2804 matched = 1;
2807 * A normal character to be compared directly.
2809 } else if(pstr->c == c) {
2810 matched = 1;
2813 * Record and skip the character that we just processed.
2815 lastc = pstr->c;
2816 if(pstr->c != ']')
2817 glh_step_stream(pstr);
2820 * Find the terminating ']'.
2822 while(pstr->c && pstr->c != ']')
2823 glh_step_stream(pstr);
2825 * Did we find a terminating ']'?
2827 if(pstr->c == ']') {
2829 * Skip the terminating ']'.
2831 glh_step_stream(pstr);
2833 * If the pattern started with a caret, invert the sense of the match.
2835 if(invert)
2836 matched = !matched;
2838 * If the pattern didn't end with a ']', then it doesn't match,
2839 * regardless of the value of the required sense of the match.
2841 } else {
2842 matched = 0;
2844 return matched;