summaryrefslogtreecommitdiffstats
path: root/runtime/scbuf.c
blob: 15458beedb43bf3cb86884f23d0ac3e1fcf37a70 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#ifndef _SCBUF_C_
#define _SCBUF_C_

/* -*- linux-c -*- */
/** @file scbuf.c
 * @addtogroup scbuf Scratch Buffer
 * Scratch Buffer Functions.
 * The scratch buffer is for collecting output before storing in a map,
 * printing, etc. This is a per-cpu static buffer.  It is necessary because 
 * of the limited stack space available in the kernel.
 * @{
 */

/** Maximum size of buffer, not including terminating NULL */
#define STP_BUF_LEN 8191

/** Scratch buffer for printing, building strings, etc */
char _stp_scbuf[STP_BUF_LEN+1];
static int _stp_scbuf_len = STP_BUF_LEN;

/** Sprint into the scratch buffer.
 * Like printf, except output goes into  #_stp_scbuf,
 * which will contain the null-terminated output.
 * Safe because overflowing #_stp_scbuf is not allowed.
 * Size is limited by length of scratch buffer, STP_BUF_LEN.
 *
 * @param fmt A printf-style format string followed by a 
 * variable number of args.
 * @sa _stp_scbuf_clear
 */

void _stp_sprint (const char *fmt, ...)
{
  int num;
  va_list args;
  char *buf = _stp_scbuf + STP_BUF_LEN - _stp_scbuf_len;
  va_start(args, fmt);
  num = vscnprintf(buf, _stp_scbuf_len, fmt, args);
  va_end(args);
  if (num > 0)
    _stp_scbuf_len -= num;
}

void _stp_sprint_str (const char *str)
{
  char *buf = _stp_scbuf + STP_BUF_LEN - _stp_scbuf_len;
  int num = strlen (str);
  if (num > _stp_scbuf_len)
    num = _stp_scbuf_len;
  strncpy (buf, str, num);
  _stp_scbuf_len -= num;
}

/** Clear the scratch buffer.
 * Output from _stp_sprint() will accumulate in the buffer
 * until this is called.
 */

void _stp_scbuf_clear (void)
{
  _stp_scbuf_len = STP_BUF_LEN;
  _stp_scbuf[0] = 0;
}

static char *_stp_scbuf_cur (void)
{
  return _stp_scbuf + STP_BUF_LEN - _stp_scbuf_len;
}

/** @} */
#endif /* _SCBUF_C_ */