source: history.c @ 9b3167b

release-1.10release-1.8release-1.9
Last change on this file since 9b3167b was 25891a8, checked in by David Benjamin <davidben@mit.edu>, 13 years ago
Add a unit test for owl_history Also fix an off-by-one error in bounding the history size. May as well have those semantics be coherent and testable.
  • Property mode set to 100644
File size: 1.6 KB
RevLine 
[7d4fbcd]1#include "owl.h"
2
[70b53ec]3void owl_history_init(owl_history *h)
4{
[95b52d1]5  g_queue_init(&h->hist);
6  h->cur = h->hist.tail;        /* current position in history */
[b470451]7  h->partial = false;           /* is the 0th element is partially composed? */
[7d4fbcd]8}
9
[25891a8]10void owl_history_cleanup(owl_history *h)
11{
12  g_queue_foreach(&h->hist, (GFunc)g_free, NULL);
13  g_queue_clear(&h->hist);
14}
15
[e19eb97]16const char *owl_history_get_prev(owl_history *h)
[70b53ec]17{
[10b866d]18  if (!h) return NULL;
[7d4fbcd]19
[95b52d1]20  if (h->cur == NULL || g_list_previous(h->cur) == NULL) return NULL;
[10b866d]21
[95b52d1]22  h->cur = g_list_previous(h->cur);
23  return h->cur->data;
[7d4fbcd]24}
25
[e19eb97]26const char *owl_history_get_next(owl_history *h)
[70b53ec]27{
[10b866d]28  if (!h) return NULL;
[7d4fbcd]29
[95b52d1]30  if (h->cur == NULL || g_list_next(h->cur) == NULL) return NULL;
31
32  h->cur = g_list_next(h->cur);
33  return h->cur->data;
[7d4fbcd]34}
35
[b470451]36void owl_history_store(owl_history *h, const char *line, bool partial)
[70b53ec]37{
[10b866d]38  if (!h) return;
[12c35df]39
[83a079a]40  owl_history_reset(h);
41
[43744ce]42  /* check if the line is the same as the last */
[95b52d1]43  if (!partial && !g_queue_is_empty(&h->hist) &&
44      strcmp(line, g_queue_peek_tail(&h->hist)) == 0)
[8e515f9]45    return;
[5a9f6fe]46
[7d4fbcd]47  /* if we've reached the max history size, pop off the last element */
[25891a8]48  if (g_queue_get_length(&h->hist) >= OWL_HISTORYSIZE)
[95b52d1]49    g_free(g_queue_pop_head(&h->hist));
[7d4fbcd]50
51  /* add the new line */
[95b52d1]52  g_queue_push_tail(&h->hist, g_strdup(line));
[b470451]53  h->partial = partial;
[95b52d1]54  h->cur = h->hist.tail;
[7d4fbcd]55}
56
[70b53ec]57void owl_history_reset(owl_history *h)
58{
[10b866d]59  if (!h) return;
[ad37b39]60
61  /* if partial is set, remove the first entry first */
62  if (h->partial) {
[95b52d1]63    g_free(g_queue_pop_tail(&h->hist));
[b470451]64    h->partial = false;
[ad37b39]65  }
66
[95b52d1]67  h->cur = h->hist.tail;
[7d4fbcd]68}
69
[1e94c0b]70int owl_history_is_touched(const owl_history *h)
[70b53ec]71{
[10b866d]72  if (!h) return(0);
[95b52d1]73  return h->cur != NULL && g_list_next(h->cur) != NULL;
[7d4fbcd]74}
Note: See TracBrowser for help on using the repository browser.