VLink  2.3.0
A high-performance communication middleware
helpers.h
浏览该文件的文档.
1 /*
2  * Copyright (C) 2026 by Thun Lu. All rights reserved.
3  * Author: Thun Lu <thun.lu@zohomail.cn>
4  * Repo: https://github.com/thun-res/vlink
5  * _ __ __ _ __
6  * | | / / / / (_) ____ / /__
7  * | | / / / / / / / __ \ / //_/
8  * | |/ / / /___ / / / / / / / ,<
9  * |___/ /_____/ /_/ /_/ /_/ /_/|_|
10  *
11  * Licensed under the Apache License, Version 2.0 (the "License");
12  * you may not use this file except in compliance with the License.
13  * You may obtain a copy of the License at
14  *
15  * http://www.apache.org/licenses/LICENSE-2.0
16  *
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  */
23 
24 /**
25  * @file helpers.h
26  * @brief Stateless string, number, hash and formatting helpers used throughout VLink.
27  *
28  * @details
29  * Functions in this header are portable, allocation-free where possible, and never throw; bad
30  * input is reported via empty / default return values. Encoding conversion routines fall back
31  * to a pass-through on POSIX where the input is assumed to already be UTF-8.
32  *
33  * @par Helper categories
34  *
35  * | Category | Representative entry points |
36  * | ----------------- | -------------------------------------------------------------------------------------------- |
37  * | Number parsing | @c to_int, @c to_long, @c double_to_string |
38  * | Hashing | @c hash_combine, @c get_hash_code |
39  * | String editing | @c replace_string, @c trim_string, @c trim_string_view |
40  * | Wide / locale | @c string_to_wstring, @c wstring_to_string, @c string_local_to_utf8, @c string_utf8_to_local |
41  * | Filesystem | @c path_to_string |
42  * | Splitting | @c split, @c split_view, @c split_any, @c split_any_view |
43  * | Field encoding | @c escape_field, @c unescape_field |
44  * | Time formatting | @c format_milliseconds, @c format_date, @c format_time_diff |
45  * | Number formatting | @c format_hex_number, @c format_file_size, @c format_rate_size |
46  * | Date parsing | @c convert_date_to_timestamp |
47  * | Prefix / suffix | @c has_startwith, @c has_endwith, @c contains_substring |
48  *
49  * @par Example
50  * @code
51  * auto parts = vlink::Helpers::split("a,b,c", ','); // {"a", "b", "c"}
52  * std::string size = vlink::Helpers::format_file_size(1536); // "1.50KB"
53  * bool startsWith = vlink::Helpers::has_startwith("vlink://hello", "vlink://");
54  * @endcode
55  */
56 
57 #pragma once
58 
59 #include <cstdint>
60 #include <filesystem>
61 #include <string>
62 #include <string_view>
63 #include <vector>
64 
65 #include "./macros.h"
66 
67 namespace vlink {
68 
69 /**
70  * @namespace vlink::Helpers
71  * @brief Stateless utility functions shared across VLink subsystems.
72  */
73 namespace Helpers { // NOLINT(readability-identifier-naming)
74 
75 /**
76  * @brief Parses an integer string with auto base detection (@c 0x -> hex, leading @c 0 -> octal,
77  * otherwise decimal).
78  *
79  * @param str Source string.
80  * @param dv Default value returned on parse failure. Default: @c 0.
81  * @return Parsed @c int or @p dv on failure.
82  */
83 [[nodiscard]] VLINK_EXPORT int to_int(const std::string& str, int dv = 0) noexcept;
84 
85 /**
86  * @brief Parses a 64-bit integer string with optional trailing-character allowance.
87  *
88  * @details
89  * Calls @c std::stoll with auto base detection (@c 0x -> hex, leading @c 0 -> octal, otherwise
90  * decimal). Parsing always starts at index @c 0; @p offset is the number of trailing characters
91  * the parser may leave unconsumed (for example to skip a unit suffix such as @c "100s" with
92  * @p offset @c == @c 1). Mismatched consumption returns @p dv.
93  *
94  * @param str Source string.
95  * @param dv Default value on failure. Default: @c 0.
96  * @param offset Number of trailing characters allowed to remain unconsumed. Default: @c 0.
97  * @return Parsed @c int64_t or @p dv on failure.
98  */
99 [[nodiscard]] VLINK_EXPORT int64_t to_long(const std::string& str, int64_t dv = 0, int offset = 0) noexcept;
100 
101 /**
102  * @brief Formats a @c double with the requested decimal precision.
103  *
104  * @param value Source value.
105  * @param precision Number of digits after the decimal point. Default: @c 2.
106  * @return Decimal string representation.
107  */
108 [[nodiscard]] VLINK_EXPORT std::string double_to_string(double value, int precision = 2) noexcept;
109 
110 /**
111  * @brief Formats a @c float into a caller-provided buffer using default @c "%g" precision.
112  *
113  * @param buf Destination buffer.
114  * @param buflen Destination capacity in bytes.
115  * @param value Source value.
116  * @return Number of bytes written, or @c 0 when conversion fails.
117  */
118 [[nodiscard]] VLINK_EXPORT size_t format_floating_to(char* buf, size_t buflen, float value) noexcept;
119 
120 /**
121  * @brief Formats a @c double into a caller-provided buffer using default @c "%g" precision.
122  *
123  * @param buf Destination buffer.
124  * @param buflen Destination capacity in bytes.
125  * @param value Source value.
126  * @return Number of bytes written, or @c 0 when conversion fails.
127  */
128 [[nodiscard]] VLINK_EXPORT size_t format_floating_to(char* buf, size_t buflen, double value) noexcept;
129 
130 /**
131  * @brief Formats a @c long @c double into a caller-provided buffer using default @c "%g" precision.
132  *
133  * @param buf Destination buffer.
134  * @param buflen Destination capacity in bytes.
135  * @param value Source value.
136  * @return Number of bytes written, or @c 0 when conversion fails.
137  */
138 [[nodiscard]] VLINK_EXPORT size_t format_floating_to(char* buf, size_t buflen,
139  long double value) noexcept; // NOLINT(google-runtime-float)
140 
141 /**
142  * @brief Formats a @c double using a std::format style floating-point presentation.
143  *
144  * @param buf Destination buffer.
145  * @param buflen Destination capacity in bytes.
146  * @param value Source value.
147  * @param type Presentation type: @c e @c E @c f @c F @c g @c G @c a @c A.
148  * @param precision Digits per the presentation type, or negative for its default.
149  * @param alt Alternate form; guarantees a decimal point in the output.
150  * @return Number of bytes written, or @c 0 when conversion fails.
151  */
152 [[nodiscard]] VLINK_EXPORT size_t format_floating_spec_to(char* buf, size_t buflen, double value, char type,
153  int precision, bool alt) noexcept;
154 
155 /**
156  * @brief Formats a @c long @c double using a std::format style floating-point presentation.
157  *
158  * @param buf Destination buffer.
159  * @param buflen Destination capacity in bytes.
160  * @param value Source value.
161  * @param type Presentation type: @c e @c E @c f @c F @c g @c G @c a @c A.
162  * @param precision Digits per the presentation type, or negative for its default.
163  * @param alt Alternate form; guarantees a decimal point in the output.
164  * @return Number of bytes written, or @c 0 when conversion fails.
165  */
166 // NOLINTNEXTLINE(google-runtime-float)
167 [[nodiscard]] VLINK_EXPORT size_t format_floating_spec_to(char* buf, size_t buflen, long double value, char type,
168  int precision, bool alt) noexcept;
169 
170 /**
171  * @brief Combines two 64-bit hash values into one via a Murmur-style mix.
172  *
173  * @param a First hash value.
174  * @param b Second hash value.
175  * @return Mixed hash value.
176  */
177 [[nodiscard]] VLINK_EXPORT uint64_t hash_combine(uint64_t a, uint64_t b) noexcept;
178 
179 /**
180  * @brief Replaces all occurrences of @p from in @p str with @p to in place.
181  *
182  * @param str String mutated in place.
183  * @param from Substring to search for.
184  * @param to Replacement substring.
185  */
186 VLINK_EXPORT void replace_string(std::string& str, const std::string& from, const std::string& to) noexcept;
187 
188 /**
189  * @brief Returns @p str with leading and trailing whitespace removed.
190  *
191  * @param str Source string.
192  * @return Trimmed copy.
193  */
194 [[nodiscard]] VLINK_EXPORT std::string trim_string(const std::string& str) noexcept;
195 
196 /**
197  * @brief Trims whitespace from both sides of a @c string_view without allocating.
198  *
199  * @details
200  * The returned view references the same storage as @p str; callers must keep
201  * the original character storage alive while using the result.
202  *
203  * @param str Source view.
204  * @return Trimmed view, or an empty view when @p str is empty or all whitespace.
205  */
206 [[nodiscard]] VLINK_EXPORT std::string_view trim_string_view(std::string_view str) noexcept;
207 
208 /**
209  * @brief Converts UTF-8 to a wide-character string.
210  *
211  * @details
212  * The conversion is independent of the process locale. On POSIX a malformed, overlong or
213  * truncated sequence, a surrogate or a value above U+10FFFF yields an empty string; Windows
214  * substitutes U+FFFD instead.
215  *
216  * @param input UTF-8 source.
217  * @return Wide-character result; empty on failure.
218  */
219 [[nodiscard]] VLINK_EXPORT std::wstring string_to_wstring(const std::string& input) noexcept;
220 
221 /**
222  * @brief Converts a wide-character string to UTF-8.
223  *
224  * @details
225  * Locale-independent counterpart of @c string_to_wstring. On POSIX a surrogate or a unit
226  * above U+10FFFF yields an empty string; Windows substitutes U+FFFD instead.
227  *
228  * @param input Wide source.
229  * @return UTF-8 result; empty on failure.
230  */
231 [[nodiscard]] VLINK_EXPORT std::string wstring_to_string(const std::wstring& input) noexcept;
232 
233 /**
234  * @brief Converts a system-locale string to UTF-8.
235  *
236  * @details
237  * Performs Windows ANSI-code-page conversion; returns the input unchanged on POSIX.
238  *
239  * @param local_str Locally encoded string.
240  * @return UTF-8 string, or the input when no conversion is needed.
241  */
242 [[nodiscard]] VLINK_EXPORT std::string string_local_to_utf8(const std::string& local_str) noexcept;
243 
244 /**
245  * @brief Converts UTF-8 to the active system locale on Windows; pass-through on POSIX.
246  *
247  * @param utf8_str UTF-8 source.
248  * @return Locally encoded string.
249  */
250 [[nodiscard]] VLINK_EXPORT std::string string_utf8_to_local(const std::string& utf8_str) noexcept;
251 
252 /**
253  * @brief Converts a filesystem path to a portable UTF-8 string.
254  *
255  * @param path Source path.
256  * @return UTF-8 path string.
257  */
258 [[nodiscard]] VLINK_EXPORT std::string path_to_string(const std::filesystem::path& path) noexcept;
259 
260 /**
261  * @brief Splits a string by a single-character delimiter; empty parts are skipped.
262  *
263  * @param str Source string.
264  * @param f Delimiter character. Defaults to @c ','.
265  * @return Vector of non-empty substrings.
266  */
267 [[nodiscard]] VLINK_EXPORT std::vector<std::string> split(const std::string& str, char f = ',') noexcept;
268 
269 /**
270  * @brief Splits a @c string_view by a delimiter and returns non-owning views.
271  *
272  * @details
273  * The caller must keep @p str alive while the returned views are used.
274  *
275  * @param str Source view.
276  * @param f Delimiter character. Defaults to @c ','.
277  * @return Vector of non-empty views over the parts.
278  */
279 [[nodiscard]] VLINK_EXPORT std::vector<std::string_view> split_view(std::string_view str, char f = ',') noexcept;
280 
281 /**
282  * @brief Splits a string by any delimiter in @p delimiters; each token is trimmed and empty tokens are skipped.
283  *
284  * @param str Source string.
285  * @param delimiters Delimiter character set. Defaults to @c " ,".
286  * @return Vector of trimmed, non-empty tokens.
287  */
288 [[nodiscard]] VLINK_EXPORT std::vector<std::string> split_any(const std::string& str,
289  std::string_view delimiters = " ,") noexcept;
290 
291 /**
292  * @brief Splits a view by any delimiter in @p delimiters and returns non-owning trimmed views.
293  *
294  * @details
295  * The caller must keep @p str alive while the returned views are used.
296  *
297  * @param str Source view.
298  * @param delimiters Delimiter character set. Defaults to @c " ,".
299  * @return Vector of trimmed, non-empty views over the tokens.
300  */
301 [[nodiscard]] VLINK_EXPORT std::vector<std::string_view> split_any_view(std::string_view str,
302  std::string_view delimiters = " ,") noexcept;
303 
304 /**
305  * @brief Percent-encodes one field of a delimiter-separated text frame.
306  *
307  * @details
308  * Encodes @c %, space, @c :, LF and CR as uppercase @c %XX sequences; other bytes pass through.
309  *
310  * @param value Field to encode.
311  * @return Encoded field.
312  */
313 [[nodiscard]] VLINK_EXPORT std::string escape_field(std::string_view value) noexcept;
314 
315 /**
316  * @brief Reverses @c escape_field encoding.
317  *
318  * @details
319  * Decodes valid @c %XX sequences; preserves invalid or truncated sequences verbatim so legacy
320  * frames remain parseable.
321  *
322  * @param value Encoded field.
323  * @return Decoded field.
324  */
325 [[nodiscard]] VLINK_EXPORT std::string unescape_field(std::string_view value) noexcept;
326 
327 /**
328  * @brief Maps a string to a 32-bit code.
329  *
330  * @details
331  * If @p str parses as an integer it is returned as its numeric value; otherwise the result is
332  * @c std::hash<std::string> truncated to 32 bits. An empty string yields @c 0.
333  *
334  * @param str Source string.
335  * @return 32-bit code.
336  */
337 [[nodiscard]] VLINK_EXPORT uint32_t get_hash_code(const std::string& str) noexcept;
338 
339 /**
340  * @brief Renders a millisecond duration as a human-readable time string.
341  *
342  * @param milliseconds Source duration.
343  * @param show_millis When @c true the millisecond field is appended.
344  * @return Formatted duration string.
345  */
346 [[nodiscard]] VLINK_EXPORT std::string format_milliseconds(int64_t milliseconds, bool show_millis) noexcept;
347 
348 /**
349  * @brief Renders a nanosecond Unix timestamp as @c "YYYY-MM-DD @c HH:MM:SS.mmm" in UTC.
350  *
351  * @param nanoseconds_since_epoch Source timestamp.
352  * @return Formatted date string.
353  */
354 [[nodiscard]] VLINK_EXPORT std::string format_date(int64_t nanoseconds_since_epoch) noexcept;
355 
356 /**
357  * @brief Renders a millisecond time delta as @c "HH:MM:SS:mmm".
358  *
359  * @param milliseconds Source delta.
360  * @return Formatted delta string.
361  */
362 [[nodiscard]] VLINK_EXPORT std::string format_time_diff(int32_t milliseconds) noexcept;
363 
364 /**
365  * @brief Renders a signed 64-bit integer as a @c "0x..." hex literal.
366  *
367  * @details
368  * Uses the uppercase digits of the unsigned overload; a negative value is printed as its 64-bit
369  * two's-complement pattern. Convert a narrower type through its unsigned counterpart to keep
370  * its own width.
371  *
372  * @param hex_number Source value.
373  * @return Hex literal string.
374  */
375 [[nodiscard]] VLINK_EXPORT std::string format_hex_number(int64_t hex_number) noexcept;
376 
377 /**
378  * @brief Renders an unsigned 64-bit integer as a @c "0x..." hex literal.
379  *
380  * @param hex_number Source value.
381  * @return Hex literal string.
382  */
383 [[nodiscard]] VLINK_EXPORT std::string format_hex_number(uint64_t hex_number) noexcept;
384 
385 /**
386  * @brief Renders a byte count as a KB / MB / GB string with two decimal places.
387  *
388  * @param size Source value in bytes.
389  * @return Human-readable size string.
390  */
391 [[nodiscard]] VLINK_EXPORT std::string format_file_size(size_t size) noexcept;
392 
393 /**
394  * @brief Renders a byte-per-second rate as a B/s, KB/s, MB/s or GB/s string.
395  *
396  * @param size Source rate in bytes per second.
397  * @return Human-readable rate string.
398  */
399 [[nodiscard]] VLINK_EXPORT std::string format_rate_size(size_t size) noexcept;
400 
401 /**
402  * @brief Parses a @c "%Y/%m/%d @c %H:%M:%S" (optionally @c ":<ms>") date into a Unix nanosecond timestamp.
403  *
404  * @details
405  * Interpreted in the local timezone via @c std::mktime. ISO-8601 dashes are not accepted.
406  *
407  * @param date Source date string.
408  * @return Nanoseconds since Unix epoch, or @c -1 on parse failure.
409  */
410 [[nodiscard]] VLINK_EXPORT int64_t convert_date_to_timestamp(const std::string& date) noexcept;
411 
412 /**
413  * @brief Compile-time prefix check against a string literal.
414  *
415  * @tparam SizeT Size of @p target including the null terminator (deduced).
416  * @param str String to test.
417  * @param target Literal prefix.
418  * @return @c true when @p str starts with @p target.
419  */
420 template <uint8_t SizeT>
421 [[nodiscard]] bool has_startwith(const std::string& str, const char (&target)[SizeT]) noexcept;
422 
423 /**
424  * @brief Compile-time suffix check against a string literal.
425  *
426  * @tparam SizeT Size of @p target including the null terminator (deduced).
427  * @param str String to test.
428  * @param target Literal suffix.
429  * @return @c true when @p str ends with @p target.
430  */
431 template <uint8_t SizeT>
432 [[nodiscard]] bool has_endwith(const std::string& str, const char (&target)[SizeT]) noexcept;
433 
434 /**
435  * @brief Constexpr prefix check for two @c string_view values.
436  *
437  * @param str String to test.
438  * @param target Prefix to check for.
439  * @return @c true when @p str starts with @p target.
440  */
441 [[nodiscard]] constexpr bool has_startwith(std::string_view str, std::string_view target) noexcept;
442 
443 /**
444  * @brief Constexpr suffix check for two @c string_view values.
445  *
446  * @param str String to test.
447  * @param target Suffix to check for.
448  * @return @c true when @p str ends with @p target.
449  */
450 [[nodiscard]] constexpr bool has_endwith(std::string_view str, std::string_view target) noexcept;
451 
452 /**
453  * @brief Constexpr substring search.
454  *
455  * @param sv String to search.
456  * @param needle Substring to look for; an empty needle returns @c true.
457  * @return @c true when @p sv contains @p needle.
458  */
459 [[nodiscard]] constexpr bool contains_substring(std::string_view sv, std::string_view needle) noexcept;
460 
461 ////////////////////////////////////////////////////////////////
462 /// Details
463 ////////////////////////////////////////////////////////////////
464 
465 template <uint8_t SizeT>
466 inline bool has_startwith(const std::string& str, const char (&target)[SizeT]) noexcept {
467  if constexpr (SizeT == 0) {
468  (void)str;
469  return false;
470  }
471 
472  return str.compare(0, SizeT - 1, target) == 0;
473 }
474 
475 template <uint8_t SizeT>
476 inline bool has_endwith(const std::string& str, const char (&target)[SizeT]) noexcept {
477  if constexpr (SizeT == 0) {
478  (void)str;
479  return false;
480  }
481 
482  if VUNLIKELY (str.size() < SizeT - 1) {
483  return false;
484  }
485 
486  return str.compare(str.size() - (SizeT - 1), SizeT - 1, target) == 0;
487 }
488 
489 inline constexpr bool has_startwith(std::string_view str, std::string_view target) noexcept {
490 #if __cplusplus >= 202002L
491  return str.starts_with(target);
492 #else
493  return target.size() <= str.size() && str.substr(0, target.size()) == target;
494 #endif
495 }
496 
497 inline constexpr bool has_endwith(std::string_view str, std::string_view target) noexcept {
498 #if __cplusplus >= 202002L
499  return str.ends_with(target);
500 #else
501  return target.size() <= str.size() && str.substr(str.size() - target.size(), target.size()) == target;
502 #endif
503 }
504 
505 inline constexpr bool contains_substring(std::string_view sv, std::string_view needle) noexcept {
506  if VUNLIKELY (needle.empty()) {
507  return true;
508  }
509 
510  return sv.find(needle) != std::string_view::npos;
511 }
512 
513 } // namespace Helpers
514 
515 } // namespace vlink
Cross-platform macros for visibility, branch hints, copy prevention, singletons and string helpers.
#define VUNLIKELY(...)
Short alias for VLINK_UNLIKELY.
Definition: macros.h:292
#define VLINK_EXPORT
Definition: macros.h:81