| 1 | /* |
| 2 | * Descent 3 |
| 3 | * Copyright (C) 2024 Parallax Software |
| 4 | * |
| 5 | * This program is free software: you can redistribute it and/or modify |
| 6 | * it under the terms of the GNU General Public License as published by |
| 7 | * the Free Software Foundation, either version 3 of the License, or |
| 8 | * (at your option) any later version. |
| 9 | * |
| 10 | * This program is distributed in the hope that it will be useful, |
| 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 13 | * GNU General Public License for more details. |
| 14 | * |
| 15 | * You should have received a copy of the GNU General Public License |
| 16 | * along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 17 | |
| 18 | --- HISTORICAL COMMENTS FOLLOW --- |
| 19 | |
| 20 | * $Logfile: /DescentIII/Main/misc/pstring.cpp $ |
| 21 | * $Revision: 4 $ |
| 22 | * $Date: 4/15/99 1:51a $ |
| 23 | * $Author: Jeff $ |
| 24 | * |
| 25 | * Safe string manipulation and creation functions |
| 26 | * |
| 27 | * $Log: /DescentIII/Main/misc/pstring.cpp $ |
| 28 | * |
| 29 | * 4 4/15/99 1:51a Jeff |
| 30 | * changes for linux compile |
| 31 | * |
| 32 | * 3 12/16/98 1:57p Samir |
| 33 | * Replaced CleanupString2 with CleanupStr |
| 34 | * |
| 35 | * 2 11/01/98 1:56a Jeff |
| 36 | * added pstring.cpp/.h |
| 37 | * |
| 38 | * $NoKeywords: $ |
| 39 | */ |
| 40 | |
| 41 | #include <cctype> |
| 42 | |
| 43 | #include "pstring.h" |
| 44 | #include <cstdint> |
| 45 | |
| 46 | // CleanupStr |
| 47 | // This function strips all leading and trailing spaces, keeping internal spaces. This goes for tabs too. |
| 48 | std::size_t CleanupStr(char *dest, const char *src, std::size_t destlen) { |
| 49 | if (destlen == 0) |
| 50 | return 0; |
| 51 | |
| 52 | const char *end; |
| 53 | std::size_t out_size; |
| 54 | |
| 55 | // Trim leading space |
| 56 | while (std::isspace((uint8_t)*src)) |
| 57 | src++; |
| 58 | |
| 59 | // All spaces? |
| 60 | if (*src == '\0') { |
| 61 | *dest = '\0'; |
| 62 | return 1; |
| 63 | } |
| 64 | |
| 65 | // Trim trailing space |
| 66 | end = src + std::strlen(src) - 1; |
| 67 | while (end > src && std::isspace((uint8_t)*end)) |
| 68 | end--; |
| 69 | end++; |
| 70 | |
| 71 | // Set output size to minimum of trimmed string length and buffer size minus 1 |
| 72 | out_size = (end - src) < destlen - 1 ? (end - src) : destlen - 1; |
| 73 | |
| 74 | // Copy trimmed string and add null terminator |
| 75 | std::memcpy(dest, src, out_size); |
| 76 | dest[out_size] = '\0'; |
| 77 | |
| 78 | return out_size; |
| 79 | } |