-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuffer.c
More file actions
106 lines (93 loc) · 1.38 KB
/
buffer.c
File metadata and controls
106 lines (93 loc) · 1.38 KB
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#include "main.h"
/**
* pf_buf_init - initialize buffer
* @b: buffer
*/
void pf_buf_init(pf_buffer_t *b)
{
b->idx = 0;
b->len = 0;
b->err = 0;
}
/**
* pf_buf_flush - flush buffer to stdout
* @b: buffer
*
* Return: 0 on success, -1 on failure
*/
int pf_buf_flush(pf_buffer_t *b)
{
ssize_t w;
if (b->err)
return (-1);
if (b->idx == 0)
return (0);
w = write(1, b->buf, b->idx);
if (w == -1 || w != (ssize_t)b->idx)
{
b->err = 1;
return (-1);
}
b->idx = 0;
return (0);
}
/**
* pf_buf_putc - put a char into buffer
* @b: buffer
* @c: char
*
* Return: 0 on success, -1 on failure
*/
int pf_buf_putc(pf_buffer_t *b, char c)
{
if (b->err)
return (-1);
if (b->idx >= PF_BUF_SIZE)
{
if (pf_buf_flush(b) == -1)
return (-1);
}
b->buf[b->idx++] = c;
b->len++;
return (0);
}
/**
* pf_buf_putn - write n bytes into buffer
* @b: buffer
* @s: string
* @n: length
*
* Return: 0 on success, -1 on failure
*/
int pf_buf_putn(pf_buffer_t *b, const char *s, int n)
{
int i;
i = 0;
while (i < n)
{
if (pf_buf_putc(b, s[i]) == -1)
return (-1);
i++;
}
return (0);
}
/**
* pf_buf_pad - pad n times with char c
* @b: buffer
* @c: padding char
* @n: count
*
* Return: 0 on success, -1 on failure
*/
int pf_buf_pad(pf_buffer_t *b, char c, int n)
{
int i;
i = 0;
while (i < n)
{
if (pf_buf_putc(b, c) == -1)
return (-1);
i++;
}
return (0);
}