pax_global_header00006660000000000000000000000064145162724770014531gustar00rootroot0000000000000052 comment=e7b84e0bf6695cf1dd465b90bd3d8797ec618322 dynstr-0.1.0/000077500000000000000000000000001451627247700130525ustar00rootroot00000000000000dynstr-0.1.0/.gitignore000066400000000000000000000000321451627247700150350ustar00rootroot00000000000000*.o *.obj *.a *.so *.so.* dynstr-0.1.0/CMakeLists.txt000066400000000000000000000021601451627247700156110ustar00rootroot00000000000000# Copyright 2020 Xavier Del Campo Romero # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. cmake_minimum_required(VERSION 3.0) project(dynstr C 0.1.0) add_library(${PROJECT_NAME} "dynstr.c") target_include_directories(${PROJECT_NAME} PUBLIC "include") install(TARGETS ${PROJECT_NAME}) install(DIRECTORY include/ TYPE INCLUDE) file(READ ${CMAKE_CURRENT_LIST_DIR}/dynstr.pc dynstr_pc) string(REPLACE /usr/local ${CMAKE_INSTALL_PREFIX} dynstr_repl_pc ${dynstr_pc}) file(WRITE ${CMAKE_BINARY_DIR}/dynstr.pc ${dynstr_repl_pc}) include(GNUInstallDirs) install(FILES ${CMAKE_BINARY_DIR}/dynstr.pc DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig) dynstr-0.1.0/LICENSE000066400000000000000000000260671451627247700140720ustar00rootroot00000000000000Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2020 Xavier Del Campo Romero Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. dynstr-0.1.0/Makefile000066400000000000000000000034651451627247700145220ustar00rootroot00000000000000# Copyright 2020-2023 Xavier Del Campo Romero # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. .POSIX: prefix = /usr/local exec_prefix = $(prefix) includedir = $(prefix)/include libdir = $(exec_prefix)/lib pkgcfgdir = $(libdir)/pkgconfig PROJECT = libdynstr MAJOR_VERSION = 0 MINOR_VERSION = 1 PATCH_VERSION = 0 VERSION = $(MAJOR_VERSION).$(MINOR_VERSION).$(PATCH_VERSION) PROJECT_A = $(PROJECT).a PROJECT_SO = $(PROJECT).so.$(VERSION) PROJECT_SO_FQ = $(PROJECT).so.$(MAJOR_VERSION) PROJECT_SO_NV = $(PROJECT).so CFLAGS = -Iinclude -fPIC -O1 LDFLAGS = -shared DEPS = \ dynstr.o all: $(PROJECT_A) $(PROJECT_SO) install: all $(pkgcfgdir)/dynstr.pc mkdir -p $(DESTDIR)$(includedir) cp include/dynstr.h $(DESTDIR)$(includedir) chmod 0644 $(DESTDIR)$(includedir)/dynstr.h mkdir -p $(DESTDIR)$(libdir) cp $(PROJECT_A) $(PROJECT_SO) $(DESTDIR)$(libdir) chmod 0755 $(libdir)/$(PROJECT_A) $(DESTDIR)$(libdir)/$(PROJECT_SO) ln -fs $(DESTDIR)$(libdir)/$(PROJECT_SO) $(DESTDIR)$(libdir)/$(PROJECT_SO_FQ) ln -fs $(DESTDIR)$(libdir)/$(PROJECT_SO) $(DESTDIR)$(libdir)/$(PROJECT_SO_NV) clean: rm -f $(DEPS) $(PROJECT_A): $(DEPS) $(AR) $(ARFLAGS) $@ $(DEPS) $(PROJECT_SO): $(DEPS) $(CC) $(LDFLAGS) $(DEPS) -o $@ $(pkgcfgdir)/dynstr.pc: dynstr.pc mkdir -p $(DESTDIR)$(pkgcfgdir) sed -e 's,/usr/local,$(DESTDIR)$(prefix),' $< > $@ chmod 0644 $@ dynstr-0.1.0/README.md000066400000000000000000000010321451627247700143250ustar00rootroot00000000000000dynstr ====== Minimal library that provides dynamic strings using plain C99. Convenience macros are also provided if GNU C is used. # Usage ``` #include #include "dynstr.h" int main(const int argc, const char *argv[]) { struct dynstr s; dynstr_init(&s); dynstr_append(&s, "Hello"); dynstr_append(&s, " from %s:%d\n", __func__, __LINE__); dynstr_prepend(&s, "Hey! "); printf("%s", s.str); dynstr_free(&s); return 0; } ``` Output: ``` Hey! Hello from main:10 ``` # License See LICENSE file. dynstr-0.1.0/dynstr.c000066400000000000000000000073121451627247700145440ustar00rootroot00000000000000/* Copyright 2020-2023 Xavier Del Campo Romero Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "dynstr.h" #include #include #include #include #include #if __STDC_VERSION__ < 199901L #error C99 support is mandatory for dynstr #endif /* __STDC_VERSION < 199901L */ void dynstr_init(struct dynstr *const d) { *d = (const struct dynstr){0}; } enum dynstr_err dynstr_vappend(struct dynstr *const d, const char *const format, va_list ap) { enum dynstr_err err = DYNSTR_OK; va_list apc; va_copy(apc, ap); { const size_t src_len = vsnprintf(NULL, 0, format, ap); const size_t new_len = d->len + src_len + 1; char *const s = realloc(d->str, new_len * sizeof *d->str); if (s) { vsprintf(s + d->len, format, apc); d->len += src_len; d->str = s; } else { err = DYNSTR_ERR_ALLOC; } } va_end(apc); return err; } enum dynstr_err dynstr_append(struct dynstr *const d, const char *const format, ...) { va_list ap; enum dynstr_err err; va_start(ap, format); err = dynstr_vappend(d, format, ap); va_end(ap); return err; } enum dynstr_err dynstr_vprepend(struct dynstr *const d, const char *const format, va_list ap) { enum dynstr_err err = DYNSTR_OK; va_list apc; va_copy(apc, ap); { const size_t src_len = vsnprintf(NULL, 0, format, ap); const size_t new_len = d->len + src_len + 1; char *const s = realloc(d->str, new_len * sizeof *d->str); if (s && d->len) { /* Keep byte that will be removed by later call to vsprintf. */ const char c = *s; for (size_t i = new_len - 1, j = d->len; j <= d->len; i--, j--) { s[i] = s[j]; } vsprintf(s, format, apc); s[src_len] = c; d->str = s; } else if (!d->len) { vsprintf(s + d->len, format, apc); d->str = s; } else { err = DYNSTR_ERR_ALLOC; } d->len += src_len; } va_end(apc); return err; } enum dynstr_err dynstr_prepend(struct dynstr *const d, const char *const format, ...) { va_list ap; enum dynstr_err err; va_start(ap, format); err = dynstr_vprepend(d, format, ap); return err; } enum dynstr_err dynstr_dup(struct dynstr *const dst, const struct dynstr *const src) { if (!dst->str && !dst->len) { if (src->len && src->str) { const size_t sz = (src->len + 1) * sizeof *dst->str; char *const s = realloc(dst->str, sz); if (s) { memcpy(s, src->str, sz); dst->len = src->len; dst->str = s; } else { return DYNSTR_ERR_ALLOC; } } else { return DYNSTR_ERR_SRC; } } else { return DYNSTR_ERR_INIT; } return DYNSTR_OK; } void dynstr_free(struct dynstr *const d) { if (d->str) { free(d->str); dynstr_init(d); } } dynstr-0.1.0/dynstr.pc000066400000000000000000000004511451627247700147210ustar00rootroot00000000000000prefix=/usr/local exec_prefix=${prefix} includedir=${prefix}/include libdir=${exec_prefix}/lib Name: dynstr Url: https://gitea.privatedns.org/xavi/dynstr Description: Minimal library that provides dynamic strings using plain C99. Version: 0.1.0 Cflags: -I${includedir} Libs: -L${libdir} -ldynstr dynstr-0.1.0/include/000077500000000000000000000000001451627247700144755ustar00rootroot00000000000000dynstr-0.1.0/include/dynstr.h000066400000000000000000000172621451627247700162010ustar00rootroot00000000000000/* Copyright 2020-2023 Xavier Del Campo Romero Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef DYNSTR_H #define DYNSTR_H #if __STDC_VERSION__ < 199901L #error C99 support is mandatory for dynstr #endif /* __STDC_VERSION < 199901L */ #include #include #include /** * Dynamic string type used for this library. * @note If needed, members can be safely read but should not be modified * outside this library. */ struct dynstr { char *str; /**< Null-terminated string. */ size_t len; /**< String length, null character not included. */ }; /** * List of errors that this library might return. * @note Following the tradition, success code is guaranteed to always be * zero. * @attention Error codes are guaranteed to be non-zero, but their ordering * might change, so please use descriptive error names instead of their integer * equivalents. */ enum dynstr_err { DYNSTR_OK, /**< Operation was successful. */ DYNSTR_ERR_ALLOC, /**< Alloc operation failed. */ DYNSTR_ERR_INIT, /**< Dynamic string was not initialized. */ DYNSTR_ERR_SRC /**< Source string has invalid parameters. */ }; /** * This function initializes string pointer to NULL and sets zero length. * @attention Always call this function before using an instance. * For future compatibility, please avoid initializing instances by calling * @c memset or similar and use this function instead. * @param d Dynamic string to be initialized. */ void dynstr_init(struct dynstr *d); /** * This function takes a string literal in printf format and a variable * number of arguments, calculates its size and concatenates it into the * dynamic string. * @param d Dynamic string where new string will be appended. * @param format String literal in printf format. * @return Returns one of the following error codes: * # DYNSTR_OK if successful. * # DYNSTR_ERR_ALLOC if no more memory is available. */ enum dynstr_err dynstr_append(struct dynstr *d, const char *format, ...); /** * This function takes a string literal in printf format and a variable * argument list, calculates its size and concatenates it into the * dynamic string. * @param d Dynamic string where new string will be appended. * @param format String literal in printf format. * @param ap Variable argument list. * @return Returns one of the following error codes: * # DYNSTR_OK if successful. * # DYNSTR_ERR_ALLOC if no more memory is available. */ enum dynstr_err dynstr_vappend(struct dynstr *d, const char *format, va_list ap); /** * This function takes a string literal in printf format and a variable * number of arguments, calculates its size and prepends it into the * beginning of the dynamic string. * @param d Dynamic string where new string will be prepended. * @param format String literal in printf format. * @return Returns one of the following error codes: * # DYNSTR_OK if successful. * # DYNSTR_ERR_ALLOC if no more memory is available. */ enum dynstr_err dynstr_prepend(struct dynstr *d, const char *format, ...); /** * This function takes a string literal in printf format and a variable * argument list, calculates its size and prepends it into the beginning of the * dynamic string. * @param d Dynamic string where new string will be prepended. * @param format String literal in printf format. * @param ap Variable argument list. * @return Returns one of the following error codes: * # DYNSTR_OK if successful. * # DYNSTR_ERR_ALLOC if no more memory is available. */ enum dynstr_err dynstr_vprepend(struct dynstr *d, const char *format, va_list ap); /** * This function duplicates a dynamic string to another instance. * @attention Destination instance must be initialized before calling * this function. * @attention Since this function performs a deep copy, please remember to * free the source instance if no longer used to avoid memory leaks. * @return Returns one of the following error codes: * # DYNSTR_OK if successful. * # DYNSTR_ERR_ALLOC if no more memory is available. * # DYNSTR_ERR_INIT if destination dynamic string was either not * initialized or already contains data. * # DYNSTR_ERR_SRC if source dynamic string has no length or data. * @note This function has the same effect as calling: * @code * dynstr_append(&dst, "%s", src.str); * @endcode * However, the implementation for dynstr_dup() should be faster as it * does not rely on vsnprintf(), as opposed to dynstr_append(). If in * doubt, always profile your code. */ enum dynstr_err dynstr_dup(struct dynstr *dst, const struct dynstr *src); /** * This function frees memory used by the dynamic string. * @param d Dynamic string to be freed. * @note This function does nothing on empty, initialized instances. * @attention Calling this function on an uninitialized instance leads to * undefined behaviour. * @attention Once memory is freed, @ref dynstr_init is called so it can be * used again. */ void dynstr_free(struct dynstr *d); /* Since dynstr_append() might fail (as it is based on dynamic memory * allocation), these macros can be used to avoid boilerplate code. */ /** * Convenience macro that calls dynstr_append and returns NULL if failed. */ #define dynstr_append_or_ret_null(...) \ do {if (dynstr_append(__VA_ARGS__) != DYNSTR_OK) return NULL;} while (0) /** * Convenience macro that calls dynstr_append and returns false if failed. */ #define dynstr_append_or_ret_false(...) \ do {if (dynstr_append(__VA_ARGS__) != DYNSTR_OK) return false;} while (0) /** * Convenience macro that calls dynstr_append and returns its error code if failed. */ #define dynstr_append_or_ret(...) \ do \ { \ const enum dynstr_err err = dynstr_append(__VA_ARGS__); \ if (err != DYNSTR_OK) return err; \ } while (0) /** * Convenience macro that calls dynstr_append and returns zero if failed. */ #define dynstr_append_or_ret_zero(...) \ do {if (dynstr_append(__VA_ARGS__) != DYNSTR_OK) return 0;} while (0) /** * Convenience macro that calls dynstr_append and returns one if failed. */ #define dynstr_append_or_ret_nonzero(...) \ do {if (dynstr_append(__VA_ARGS__) != DYNSTR_OK) return 1;} while (0) /** * Convenience macro that calls dynstr_prepend and returns NULL if failed. */ #define dynstr_prepend_or_ret_null(...) \ do {if (dynstr_prepend(__VA_ARGS__) != DYNSTR_OK) return NULL;} while (0) /** * Convenience macro that calls dynstr_prepend and returns false if failed. */ #define dynstr_prepend_or_ret_false(...) \ do {if (dynstr_prepend(__VA_ARGS__) != DYNSTR_OK) return false;} while (0) /** * Convenience macro that calls dynstr_prepend and returns its error code if failed. */ #define dynstr_prepend_or_ret(...) \ do \ { \ const enum dynstr_err err = dynstr_prepend(__VA_ARGS__); \ if (err != DYNSTR_OK) return err; \ } while (0) /** * Convenience macro that calls dynstr_prepend and returns zero if failed. */ #define dynstr_prepend_or_ret_zero(...) \ do {if (dynstr_prepend(__VA_ARGS__) != DYNSTR_OK) return 0;} while (0) /** * Convenience macro that calls dynstr_prepend and returns one if failed. */ #define dynstr_prepend_or_ret_nonzero(...) \ do {if (dynstr_prepend(__VA_ARGS__) != DYNSTR_OK) return 1;} while (0) #endif /* DYNSTR_H */