a68g-inline.h
1 //! @file a68g-inline.h
2 //! @author J. Marcel van der Veer
3
4 //! @section Copyright
5 //!
6 //! This file is part of Algol68G - an Algol 68 interpreter.
7 //! Copyright 2001-2026 J. Marcel van der Veer [algol68g@algol68genie.nl].
8
9 //! @section License
10 //!
11 //! This program is free software; you can redistribute it and/or modify it
12 //! under the terms of the GNU General Public License as published by the
13 //! Free Software Foundation; either version 3 of the License, or
14 //! (at your option) any later version.
15 //!
16 //! This program is distributed in the hope that it will be useful, but
17 //! WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
18 //! or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
19 //! more details. You should have received a copy of the GNU General Public
20 //! License along with this program. If not, see [http://www.gnu.org/licenses/].
21
22 //! @section Synopsis
23 //!
24 //! Inline functions.
25
26 #if ! defined (__A68G_INLINE_H__)
27 #define __A68G_INLINE_H__
28
29 //! @brief Safely set buffer.
30
31 static inline void *a68g_bufset (void *dst, int val, size_t len)
32 {
33 // Function memset can be optimized away by a compiler.
34 // This works because sizeof (char) == 1 is true by convention.
35 ASSERT (dst != NO_TEXT);
36 char *p = (char *) dst;
37 while (len-- > 0) {
38 *(p++) = val;
39 }
40 return dst;
41 }
42
43
44 //! @brief Safely append to buffer.
45
46 static inline void a68g_bufcat (char *dst, char *src, size_t len)
47 {
48 ASSERT (dst != NO_TEXT);
49 ASSERT (src != NO_TEXT);
50 char *d = dst, *s = src;
51 int n = len;
52 // Find end of dst and left-adjust; do not go past end.
53 for (; n-- != 0 && d[0] != NULL_CHAR; d++) {
54 ;
55 }
56 int dlen = (int) (d - dst);
57 n = len - dlen;
58 if (n > 0) {
59 while (s[0] != NULL_CHAR) {
60 if (n != 1) {
61 (d++)[0] = s[0];
62 n--;
63 }
64 s++;
65 }
66 d[0] = NULL_CHAR;
67 }
68 // Better sure than sorry.
69 dst[len - 1] = NULL_CHAR;
70 }
71
72
73 //! @brief Safely copy to buffer.
74
75 static inline void a68g_bufcpy (char *dst, char *src, size_t len)
76 {
77 ASSERT (dst != NO_TEXT);
78 ASSERT (src != NO_TEXT);
79 char *d = dst, *s = src;
80 int n = len;
81 // Copy as many as fit.
82 if (n > 0 && --n > 0) {
83 do {
84 if (((d++)[0] = (s++)[0]) == NULL_CHAR) {
85 break;
86 }
87 } while (--n > 0);
88 }
89 if (n == 0 && len > 0) {
90 // Not enough room in dst, so terminate.
91 d[0] = NULL_CHAR;
92 }
93 // Better sure than sorry.
94 dst[len - 1] = NULL_CHAR;
95 }
96
97 #endif
© J.M. van der Veer • jmvdveer@algol68genie.nl