aboutsummaryrefslogtreecommitdiff
path: root/main/sockbuf.c
blob: 8ae413c442cd082df7bf7a16a2a433d526eba1b2 (plain) (blame)
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
72
#include "sockbuf.h"

#include <ctype.h>
#include <string.h>
#include <unistd.h>

void sockbuf_write(sockbuf_t* sockbuf, const char* value)
{
  write(sockbuf->socket, value, strlen(value));
}

sockbuf_t* init_sockbuf(sockbuf_t* sockbuf, int socket)
{
  memset(sockbuf, 0, sizeof(sockbuf_t));
  sockbuf->socket = socket;

  return sockbuf;
}

int peek_char(sockbuf_t* sockbuf)
{
  if (sockbuf->next == sockbuf->last) {
    sockbuf->next = 0;
    int size = read(sockbuf->socket, sockbuf->buf, sizeof(sockbuf->buf));
    sockbuf->last = (uint8_t)size;

    if (size <= 0) {
      return size - 1;
    }
  }

  return sockbuf->buf[sockbuf->next];
}

int get_char(sockbuf_t* sockbuf)
{
  int ret = peek_char(sockbuf);

  if (ret >= 0) {
    sockbuf->next++;
  }

  return ret;
}

char* read_token(sockbuf_t* sockbuf, char* into, size_t sz)
{
  int cur = 0;

  int ch = get_char(sockbuf);

  while (ch >= 0 && isspace(ch)) {
    ch = get_char(sockbuf);
  }

  while (ch >= 0 && !isspace(ch)) {
    if (sz > 1) {
      into[cur++] = (char)ch;
      sz--;
    }
    ch = get_char(sockbuf);
  }

  if (ch < 0) {
    return NULL;
  }

  if (sz >= 1) {
    into[cur] = 0;
  }
  return into;
}