xref: /freebsd/sys/compat/linuxkpi/common/src/linux_seq_buf.c (revision 710167623d82664ab4276776aed502ab6f91d8ff)
1 /*
2  * Copyright (c) 2025-2026 The FreeBSD Foundation
3  * Copyright (c) 2025-2026 Jean-Sébastien Pédron <dumbbell@FreeBSD.org>
4  *
5  * This software was developed by Jean-Sébastien Pédron under sponsorship
6  * from the FreeBSD Foundation.
7  *
8  * SPDX-License-Identifier: BSD-2-Clause
9  */
10 
11 #include <linux/seq_buf.h>
12 
13 void
linuxkpi_seq_buf_init(struct seq_buf * s,char * buf,unsigned int size)14 linuxkpi_seq_buf_init(struct seq_buf *s, char *buf, unsigned int size)
15 {
16 	s->buffer = buf;
17 	s->size = size;
18 
19 	seq_buf_clear(s);
20 }
21 
22 int
linuxkpi_seq_buf_printf(struct seq_buf * s,const char * fmt,...)23 linuxkpi_seq_buf_printf(struct seq_buf *s, const char *fmt, ...)
24 {
25 	int ret;
26 	va_list args;
27 
28 	va_start(args, fmt);
29 	ret = seq_buf_vprintf(s, fmt, args);
30 	va_end(args);
31 
32 	return (ret);
33 }
34 
35 int
linuxkpi_seq_buf_vprintf(struct seq_buf * s,const char * fmt,va_list args)36 linuxkpi_seq_buf_vprintf(struct seq_buf *s, const char *fmt, va_list args)
37 {
38 	int ret;
39 
40 	if (!seq_buf_has_overflowed(s)) {
41 		ret = vsnprintf(s->buffer + s->len, s->size - s->len, fmt, args);
42 		if (s->len + ret < s->size) {
43 			s->len += ret;
44 			return (0);
45 		}
46 	}
47 
48 	seq_buf_set_overflow(s);
49 	return (-1);
50 }
51 
52 const char *
linuxkpi_seq_buf_str(struct seq_buf * s)53 linuxkpi_seq_buf_str(struct seq_buf *s)
54 {
55 	if (s->size == 0)
56 		return ("");
57 
58 	if (seq_buf_buffer_left(s))
59 		s->buffer[s->len] = '\0';
60 	else
61 		s->buffer[s->size - 1] = '\0';
62 
63 	return (s->buffer);
64 }
65