diff --git a/.travis.yml b/.travis.yml index 7cff9cff..f86e4449 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,63 +1,63 @@ -# Use a C++11 distro -dist: trusty -sudo: required - -# Enable C++ support -language: cpp - -# Compiler selection -compiler: gcc - -env: - global: - # coverity key - - secure: "NKZbBnMALGIIQJy/s2kc3EST/stw+gjhtrGq0jkbsWr7Wx3FH+lmLeHNsDXRnD1VbpG02c5YsLllqz9OVu+0yxWGepvKNmCz1cNITIALEHbrax8/Af9LzPRL/QZxS/Qe11sMuySp4X16mFBUyxMd/X+I9i96Xf1vKkZABklYD1Q=" - -# addons -addons: - apt: - packages: - - gcc-6 - - g++-6 - sources: - - ubuntu-toolchain-r-test - - coverity_scan: - project: - name: "mpaland/printf" - description: "Tiny printf implementation" - notification_email: marco@paland.com - build_command_prepend: "make clean" - build_command: "make" - branch_pattern: master - -before_install: - # connect coverity - - echo -n | openssl s_client -connect scan.coverity.com:443 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' | sudo tee -a /etc/ssl/certs/ca- - -# Active branches -branches: - only: - - master - -script: - # Link gcc-6 and g++-6 to their standard commands - - sudo rm /usr/bin/gcc - - sudo rm /usr/bin/g++ - - sudo ln -s /usr/bin/gcc-6 /usr/bin/gcc - - sudo ln -s /usr/bin/g++-6 /usr/bin/g++ - # Export CC and CXX - - export CC=/usr/bin/gcc-6 - - export CXX=/usr/bin/g++-6 - # Check versions of gcc, g++ - - gcc -v && g++ -v - # Run build commands - - make - # execute the text suite - - bin/test_suite -d yes - # coverall profiling - - tmp/cov/test_suite - -after_success: - ## Report to codecov - - bash <(curl -s https://codecov.io/bash) +# Use a C++11 distro +dist: trusty +sudo: required + +# Enable C++ support +language: cpp + +# Compiler selection +compiler: gcc + +env: + global: + # coverity key + - secure: "NKZbBnMALGIIQJy/s2kc3EST/stw+gjhtrGq0jkbsWr7Wx3FH+lmLeHNsDXRnD1VbpG02c5YsLllqz9OVu+0yxWGepvKNmCz1cNITIALEHbrax8/Af9LzPRL/QZxS/Qe11sMuySp4X16mFBUyxMd/X+I9i96Xf1vKkZABklYD1Q=" + +# addons +addons: + apt: + packages: + - gcc-6 + - g++-6 + sources: + - ubuntu-toolchain-r-test + + coverity_scan: + project: + name: "mpaland/printf" + description: "Tiny printf implementation" + notification_email: marco@paland.com + build_command_prepend: "make clean" + build_command: "make" + branch_pattern: master + +before_install: + # connect coverity + - echo -n | openssl s_client -connect scan.coverity.com:443 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' | sudo tee -a /etc/ssl/certs/ca- + +# Active branches +branches: + only: + - master + +script: + # Link gcc-6 and g++-6 to their standard commands + - sudo rm /usr/bin/gcc + - sudo rm /usr/bin/g++ + - sudo ln -s /usr/bin/gcc-6 /usr/bin/gcc + - sudo ln -s /usr/bin/g++-6 /usr/bin/g++ + # Export CC and CXX + - export CC=/usr/bin/gcc-6 + - export CXX=/usr/bin/g++-6 + # Check versions of gcc, g++ + - gcc -v && g++ -v + # Run build commands + - make + # execute the text suite + - bin/test_suite -d yes + # coverall profiling + - tmp/cov/test_suite + +after_success: + ## Report to codecov + - bash <(curl -s https://codecov.io/bash) diff --git a/Makefile b/Makefile index 7b28a1a1..9dba1f0b 100644 --- a/Makefile +++ b/Makefile @@ -1,271 +1,271 @@ -# ------------------------------------------------------------------------------ -# -# Generic Makefile -# -# Copyright Marco Paland 2007 - 2017 -# Distributed under the MIT License -# -# ------------------------------------------------------------------------------ - -# ------------------------------------------------------------------------------ -# Paths -# ------------------------------------------------------------------------------ -PATH_TOOLS_CC = /usr/bin/ -PATH_TOOLS_CC_LIB = /usr/lib/ -PATH_TOOLS_UTIL = - -PATH_BIN = bin -PATH_TMP = tmp -PATH_NUL = /dev/null -PATH_OBJ = $(PATH_TMP)/obj -PATH_LST = $(PATH_TMP)/lst -PATH_ERR = $(PATH_TMP)/err -PATH_PRE = $(PATH_TMP)/pre -PATH_COV = $(PATH_TMP)/cov - - -# ------------------------------------------------------------------------------ -# Application to build -# ------------------------------------------------------------------------------ - -APP = test_suite - - -# ----------------------------------------------------------------------------- -# Project file list -# Format is: -# FILES_PRJ = file1 \ -# foo/file2 \ -# bar/file3 -# ----------------------------------------------------------------------------- - -FILES_PRJ = test/test_suite - - -# ------------------------------------------------------------------------------ -# Additional include files and compiler defines -# Format is: -# C_INCLUDES = -Iinclude_path1 \ -# -Iinclude_path2 \ -# -Iinclude_path3 \ -# ------------------------------------------------------------------------------ - -C_INCLUDES = - -C_DEFINES = - - -# ------------------------------------------------------------------------------ -# The target name and location -# ------------------------------------------------------------------------------ -TRG = $(PATH_BIN)/$(APP) - - -# ------------------------------------------------------------------------------ -# object files -# ------------------------------------------------------------------------------ -FILES_TMP = $(FILES_PRJ) -FILES_O = $(addsuffix .o, $(FILES_TMP)) - - -# ------------------------------------------------------------------------------ -# VPATH definition -# -# VPATH is required for the maker to find the C-/ASM-Source files. -# Extract the directory/module names from the file list with the dir -# command and remove the duplicated directory names with the sort command. -# FILES_PRJ is listed first to make sure that the source files in the project -# directory are searched first. -# ------------------------------------------------------------------------------ -VPATH := $(sort $(dir $(FILES_TMP))) - - -# ------------------------------------------------------------------------------ -# Development tools -# ------------------------------------------------------------------------------ -AR = $(PATH_TOOLS_CC)ar -AS = $(PATH_TOOLS_CC)g++ -CC = $(PATH_TOOLS_CC)g++ -CL = $(PATH_TOOLS_CC)g++ -NM = $(PATH_TOOLS_CC)nm -GCOV = $(PATH_TOOLS_CC)gcov -OBJDUMP = $(PATH_TOOLS_CC)objdump -OBJCOPY = $(PATH_TOOLS_CC)objcopy -READELF = $(PATH_TOOLS_CC)readelf -SIZE = $(PATH_TOOLS_CC)size - -ECHO = $(PATH_TOOLS_UTIL)echo -MAKE = $(PATH_TOOLS_UTIL)make -MKDIR = $(PATH_TOOLS_UTIL)mkdir -RM = $(PATH_TOOLS_UTIL)rm -SED = $(PATH_TOOLS_UTIL)sed - - -# ------------------------------------------------------------------------------ -# Compiler flags for the target architecture -# ------------------------------------------------------------------------------ - -GCCFLAGS = $(C_INCLUDES) \ - $(C_DEFINES) \ - -std=c++11 \ - -g \ - -Wall \ - -pedantic \ - -Wmain \ - -Wundef \ - -Wsign-conversion \ - -Wuninitialized \ - -Wshadow \ - -Wunreachable-code \ - -Wswitch-default \ - -Wswitch \ - -Wcast-align \ - -Wmissing-include-dirs \ - -Winit-self \ - -Wdouble-promotion \ - -gdwarf-2 \ - -fno-exceptions \ - -O2 \ - -ffunction-sections \ - -ffat-lto-objects \ - -fdata-sections \ - -fverbose-asm \ - -Wextra \ - -Wunused-parameter \ - -Wfloat-equal - -CFLAGS = $(GCCFLAGS) \ - -Wunsuffixed-float-constants \ - -x c \ - -std=c99 - -CPPFLAGS = $(GCCFLAGS) \ - -x c++ \ - -fno-rtti \ - -fstrict-enums \ - -fno-use-cxa-atexit \ - -fno-use-cxa-get-exception-ptr \ - -fno-nonansi-builtins \ - -fno-threadsafe-statics \ - -fno-enforce-eh-specs \ - -ftemplate-depth-64 \ - -fexceptions - -AFLAGS = $(GCCFLAGS) \ - -x assembler - -LFLAGS = $(GCCFLAGS) \ - -x none \ - -Wl,--gc-sections - -# ------------------------------------------------------------------------------ -# Targets -# ------------------------------------------------------------------------------ - -# ------------------------------------------------------------------------------ -# Main-Dependencies (app: all) -# ------------------------------------------------------------------------------ -.PHONY: all -all: clean_prj $(TRG) $(TRG)_nm.txt - - -# ------------------------------------------------------------------------------ -# Main-Dependencies (app: rebuild) -# ------------------------------------------------------------------------------ -.PHONY: rebuild -rebuild: clean $(TRG) $(TRG)_nm.txt - - -# ------------------------------------------------------------------------------ -# clean project -# ------------------------------------------------------------------------------ -.PHONY: clean_prj -clean_prj: - @-$(ECHO) +++ cleaning project - @-$(RM) -rf $(PATH_BIN) 2> $(PATH_NUL) - @-$(MKDIR) -p $(PATH_BIN) - @-$(MKDIR) -p $(PATH_OBJ) - @-$(MKDIR) -p $(PATH_ERR) - @-$(MKDIR) -p $(PATH_LST) - @-$(MKDIR) -p $(PATH_PRE) - @-$(MKDIR) -p $(PATH_COV) - - -# ------------------------------------------------------------------------------ -# clean all -# ------------------------------------------------------------------------------ -.PHONY: clean -clean: - @-$(ECHO) +++ cleaning all - @-$(RM) -rf $(PATH_BIN) 2> $(PATH_NUL) - @-$(RM) -rf $(PATH_TMP) 2> $(PATH_NUL) - @-$(MKDIR) -p $(PATH_BIN) - @-$(MKDIR) -p $(PATH_OBJ) - @-$(MKDIR) -p $(PATH_ERR) - @-$(MKDIR) -p $(PATH_LST) - @-$(MKDIR) -p $(PATH_COV) - - -# ------------------------------------------------------------------------------ -# print the GNUmake version and the compiler version -# ------------------------------------------------------------------------------ -.PHONY: version -version: - # Print the GNU make version and the compiler version - @$(ECHO) GNUmake version: - @$(MAKE) --version - @$(ECHO) GCC version: - @$(CL) -v - - -# ------------------------------------------------------------------------------ -# Rules -# ------------------------------------------------------------------------------ - -# ------------------------------------------------------------------------------ -# Link/locate application -# ------------------------------------------------------------------------------ -$(TRG) : $(FILES_O) - @-$(ECHO) +++ linkink application to generate: $(TRG) - @-$(CL) $(LFLAGS) -L. -lc $(PATH_OBJ)/*.o -Wl,-Map,$(TRG).map -o $(TRG) - # profiling - @-$(CL) $(LFLAGS) -L. -lc $(PATH_COV)/*.o --coverage -o $(PATH_COV)/$(APP) - - -# ------------------------------------------------------------------------------ -# parse the object files to obtain symbol information, and create a size summary -# ------------------------------------------------------------------------------ -$(TRG)_nm.txt : $(TRG) - @-$(ECHO) +++ parsing symbols with nm to generate: $(TRG)_nm.txt - @-$(NM) --numeric-sort --print-size $(TRG) > $(TRG)_nm.txt - @-$(ECHO) +++ demangling symbols with c++filt to generate: $(TRG)_cppfilt.txt - @-$(NM) --numeric-sort --print-size $(TRG) | $(CPPFILT) > $(TRG)_cppfilt.txt - @-$(ECHO) +++ creating size summary table with size to generate: $(TRG)_size.txt - @-$(SIZE) -A -t $(TRG) > $(TRG)_size.txt - - -%.o : %.cpp - @$(ECHO) +++ compile: $< - # Compile the source file - # ...and Reformat (using sed) any possible error/warning messages for the VisualStudio(R) output window - # ...and Create an assembly listing using objdump - # ...and Generate a dependency file (using the -MM flag) - @-$(CL) $(CPPFLAGS) $< -E -o $(PATH_PRE)/$(basename $(@F)).pre - @-$(CL) $(CPPFLAGS) $< -c -o $(PATH_OBJ)/$(basename $(@F)).o 2> $(PATH_ERR)/$(basename $(@F)).err - @-$(SED) -e 's|.h:\([0-9]*\),|.h(\1) :|' -e 's|:\([0-9]*\):|(\1) :|' $(PATH_ERR)/$(basename $(@F)).err - @-$(OBJDUMP) --disassemble --line-numbers -S $(PATH_OBJ)/$(basename $(@F)).o > $(PATH_LST)/$(basename $(@F)).lst - @-$(CL) $(CPPFLAGS) $< -MM > $(PATH_OBJ)/$(basename $(@F)).d - # profiling - @-$(CL) $(CPPFLAGS) -O0 --coverage $< -c -o $(PATH_COV)/$(basename $(@F)).o 2> $(PATH_NUL) - -%.o : %.c - @$(ECHO) +++ compile: $< - # Compile the source file - # ...and Reformat (using sed) any possible error/warning messages for the VisualStudio(R) output window - # ...and Create an assembly listing using objdump - # ...and Generate a dependency file (using the -MM flag) - @-$(CL) $(CFLAGS) $< -E -o $(PATH_PRE)/$(basename $(@F)).pre - @-$(CC) $(CFLAGS) $< -c -o $(PATH_OBJ)/$(basename $(@F)).o 2> $(PATH_ERR)/$(basename $(@F)).err - @-$(SED) -e 's|.h:\([0-9]*\),|.h(\1) :|' -e 's|:\([0-9]*\):|(\1) :|' $(PATH_ERR)/$(basename $(@F)).err - @-$(OBJDUMP) -S $(PATH_OBJ)/$(basename $(@F)).o > $(PATH_LST)/$(basename $(@F)).lst - @-$(CC) $(CFLAGS) $< -MM > $(PATH_OBJ)/$(basename $(@F)).d +# ------------------------------------------------------------------------------ +# +# Generic Makefile +# +# Copyright Marco Paland 2007 - 2017 +# Distributed under the MIT License +# +# ------------------------------------------------------------------------------ + +# ------------------------------------------------------------------------------ +# Paths +# ------------------------------------------------------------------------------ +PATH_TOOLS_CC = /usr/bin/ +PATH_TOOLS_CC_LIB = /usr/lib/ +PATH_TOOLS_UTIL = + +PATH_BIN = bin +PATH_TMP = tmp +PATH_NUL = /dev/null +PATH_OBJ = $(PATH_TMP)/obj +PATH_LST = $(PATH_TMP)/lst +PATH_ERR = $(PATH_TMP)/err +PATH_PRE = $(PATH_TMP)/pre +PATH_COV = $(PATH_TMP)/cov + + +# ------------------------------------------------------------------------------ +# Application to build +# ------------------------------------------------------------------------------ + +APP = test_suite + + +# ----------------------------------------------------------------------------- +# Project file list +# Format is: +# FILES_PRJ = file1 \ +# foo/file2 \ +# bar/file3 +# ----------------------------------------------------------------------------- + +FILES_PRJ = test/test_suite + + +# ------------------------------------------------------------------------------ +# Additional include files and compiler defines +# Format is: +# C_INCLUDES = -Iinclude_path1 \ +# -Iinclude_path2 \ +# -Iinclude_path3 \ +# ------------------------------------------------------------------------------ + +C_INCLUDES = + +C_DEFINES = + + +# ------------------------------------------------------------------------------ +# The target name and location +# ------------------------------------------------------------------------------ +TRG = $(PATH_BIN)/$(APP) + + +# ------------------------------------------------------------------------------ +# object files +# ------------------------------------------------------------------------------ +FILES_TMP = $(FILES_PRJ) +FILES_O = $(addsuffix .o, $(FILES_TMP)) + + +# ------------------------------------------------------------------------------ +# VPATH definition +# +# VPATH is required for the maker to find the C-/ASM-Source files. +# Extract the directory/module names from the file list with the dir +# command and remove the duplicated directory names with the sort command. +# FILES_PRJ is listed first to make sure that the source files in the project +# directory are searched first. +# ------------------------------------------------------------------------------ +VPATH := $(sort $(dir $(FILES_TMP))) + + +# ------------------------------------------------------------------------------ +# Development tools +# ------------------------------------------------------------------------------ +AR = $(PATH_TOOLS_CC)ar +AS = $(PATH_TOOLS_CC)g++ +CC = $(PATH_TOOLS_CC)g++ +CL = $(PATH_TOOLS_CC)g++ +NM = $(PATH_TOOLS_CC)nm +GCOV = $(PATH_TOOLS_CC)gcov +OBJDUMP = $(PATH_TOOLS_CC)objdump +OBJCOPY = $(PATH_TOOLS_CC)objcopy +READELF = $(PATH_TOOLS_CC)readelf +SIZE = $(PATH_TOOLS_CC)size + +ECHO = $(PATH_TOOLS_UTIL)echo +MAKE = $(PATH_TOOLS_UTIL)make +MKDIR = $(PATH_TOOLS_UTIL)mkdir +RM = $(PATH_TOOLS_UTIL)rm +SED = $(PATH_TOOLS_UTIL)sed + + +# ------------------------------------------------------------------------------ +# Compiler flags for the target architecture +# ------------------------------------------------------------------------------ + +GCCFLAGS = $(C_INCLUDES) \ + $(C_DEFINES) \ + -std=c++11 \ + -g \ + -Wall \ + -pedantic \ + -Wmain \ + -Wundef \ + -Wsign-conversion \ + -Wuninitialized \ + -Wshadow \ + -Wunreachable-code \ + -Wswitch-default \ + -Wswitch \ + -Wcast-align \ + -Wmissing-include-dirs \ + -Winit-self \ + -Wdouble-promotion \ + -gdwarf-2 \ + -fno-exceptions \ + -O2 \ + -ffunction-sections \ + -ffat-lto-objects \ + -fdata-sections \ + -fverbose-asm \ + -Wextra \ + -Wunused-parameter \ + -Wfloat-equal + +CFLAGS = $(GCCFLAGS) \ + -Wunsuffixed-float-constants \ + -x c \ + -std=c99 + +CPPFLAGS = $(GCCFLAGS) \ + -x c++ \ + -fno-rtti \ + -fstrict-enums \ + -fno-use-cxa-atexit \ + -fno-use-cxa-get-exception-ptr \ + -fno-nonansi-builtins \ + -fno-threadsafe-statics \ + -fno-enforce-eh-specs \ + -ftemplate-depth-64 \ + -fexceptions + +AFLAGS = $(GCCFLAGS) \ + -x assembler + +LFLAGS = $(GCCFLAGS) \ + -x none \ + -Wl,--gc-sections + +# ------------------------------------------------------------------------------ +# Targets +# ------------------------------------------------------------------------------ + +# ------------------------------------------------------------------------------ +# Main-Dependencies (app: all) +# ------------------------------------------------------------------------------ +.PHONY: all +all: clean_prj $(TRG) $(TRG)_nm.txt + + +# ------------------------------------------------------------------------------ +# Main-Dependencies (app: rebuild) +# ------------------------------------------------------------------------------ +.PHONY: rebuild +rebuild: clean $(TRG) $(TRG)_nm.txt + + +# ------------------------------------------------------------------------------ +# clean project +# ------------------------------------------------------------------------------ +.PHONY: clean_prj +clean_prj: + @-$(ECHO) +++ cleaning project + @-$(RM) -rf $(PATH_BIN) 2> $(PATH_NUL) + @-$(MKDIR) -p $(PATH_BIN) + @-$(MKDIR) -p $(PATH_OBJ) + @-$(MKDIR) -p $(PATH_ERR) + @-$(MKDIR) -p $(PATH_LST) + @-$(MKDIR) -p $(PATH_PRE) + @-$(MKDIR) -p $(PATH_COV) + + +# ------------------------------------------------------------------------------ +# clean all +# ------------------------------------------------------------------------------ +.PHONY: clean +clean: + @-$(ECHO) +++ cleaning all + @-$(RM) -rf $(PATH_BIN) 2> $(PATH_NUL) + @-$(RM) -rf $(PATH_TMP) 2> $(PATH_NUL) + @-$(MKDIR) -p $(PATH_BIN) + @-$(MKDIR) -p $(PATH_OBJ) + @-$(MKDIR) -p $(PATH_ERR) + @-$(MKDIR) -p $(PATH_LST) + @-$(MKDIR) -p $(PATH_COV) + + +# ------------------------------------------------------------------------------ +# print the GNUmake version and the compiler version +# ------------------------------------------------------------------------------ +.PHONY: version +version: + # Print the GNU make version and the compiler version + @$(ECHO) GNUmake version: + @$(MAKE) --version + @$(ECHO) GCC version: + @$(CL) -v + + +# ------------------------------------------------------------------------------ +# Rules +# ------------------------------------------------------------------------------ + +# ------------------------------------------------------------------------------ +# Link/locate application +# ------------------------------------------------------------------------------ +$(TRG) : $(FILES_O) + @-$(ECHO) +++ linkink application to generate: $(TRG) + @-$(CL) $(LFLAGS) -L. -lc $(PATH_OBJ)/*.o -Wl,-Map,$(TRG).map -o $(TRG) + # profiling + @-$(CL) $(LFLAGS) -L. -lc $(PATH_COV)/*.o --coverage -o $(PATH_COV)/$(APP) + + +# ------------------------------------------------------------------------------ +# parse the object files to obtain symbol information, and create a size summary +# ------------------------------------------------------------------------------ +$(TRG)_nm.txt : $(TRG) + @-$(ECHO) +++ parsing symbols with nm to generate: $(TRG)_nm.txt + @-$(NM) --numeric-sort --print-size $(TRG) > $(TRG)_nm.txt + @-$(ECHO) +++ demangling symbols with c++filt to generate: $(TRG)_cppfilt.txt + @-$(NM) --numeric-sort --print-size $(TRG) | $(CPPFILT) > $(TRG)_cppfilt.txt + @-$(ECHO) +++ creating size summary table with size to generate: $(TRG)_size.txt + @-$(SIZE) -A -t $(TRG) > $(TRG)_size.txt + + +%.o : %.cpp + @$(ECHO) +++ compile: $< + # Compile the source file + # ...and Reformat (using sed) any possible error/warning messages for the VisualStudio(R) output window + # ...and Create an assembly listing using objdump + # ...and Generate a dependency file (using the -MM flag) + @-$(CL) $(CPPFLAGS) $< -E -o $(PATH_PRE)/$(basename $(@F)).pre + @-$(CL) $(CPPFLAGS) $< -c -o $(PATH_OBJ)/$(basename $(@F)).o 2> $(PATH_ERR)/$(basename $(@F)).err + @-$(SED) -e 's|.h:\([0-9]*\),|.h(\1) :|' -e 's|:\([0-9]*\):|(\1) :|' $(PATH_ERR)/$(basename $(@F)).err + @-$(OBJDUMP) --disassemble --line-numbers -S $(PATH_OBJ)/$(basename $(@F)).o > $(PATH_LST)/$(basename $(@F)).lst + @-$(CL) $(CPPFLAGS) $< -MM > $(PATH_OBJ)/$(basename $(@F)).d + # profiling + @-$(CL) $(CPPFLAGS) -O0 --coverage $< -c -o $(PATH_COV)/$(basename $(@F)).o 2> $(PATH_NUL) + +%.o : %.c + @$(ECHO) +++ compile: $< + # Compile the source file + # ...and Reformat (using sed) any possible error/warning messages for the VisualStudio(R) output window + # ...and Create an assembly listing using objdump + # ...and Generate a dependency file (using the -MM flag) + @-$(CL) $(CFLAGS) $< -E -o $(PATH_PRE)/$(basename $(@F)).pre + @-$(CC) $(CFLAGS) $< -c -o $(PATH_OBJ)/$(basename $(@F)).o 2> $(PATH_ERR)/$(basename $(@F)).err + @-$(SED) -e 's|.h:\([0-9]*\),|.h(\1) :|' -e 's|:\([0-9]*\):|(\1) :|' $(PATH_ERR)/$(basename $(@F)).err + @-$(OBJDUMP) -S $(PATH_OBJ)/$(basename $(@F)).o > $(PATH_LST)/$(basename $(@F)).lst + @-$(CC) $(CFLAGS) $< -MM > $(PATH_OBJ)/$(basename $(@F)).d diff --git a/README.md b/README.md index 2122653e..76537b94 100644 --- a/README.md +++ b/README.md @@ -1,212 +1,212 @@ -# A printf / sprintf Implementation for Embedded Systems - -[![Build Status](https://travis-ci.org/mpaland/printf.svg?branch=master)](https://travis-ci.org/mpaland/printf) -[![codecov](https://codecov.io/gh/mpaland/printf/branch/master/graph/badge.svg)](https://codecov.io/gh/mpaland/printf) -[![Coverity Status](https://img.shields.io/coverity/scan/14180.svg)](https://scan.coverity.com/projects/mpaland-printf) -[![Github Issues](https://img.shields.io/github/issues/mpaland/printf.svg)](http://github.com/mpaland/printf/issues) -[![Github Releases](https://img.shields.io/github/release/mpaland/printf.svg)](https://github.com/mpaland/printf/releases) -[![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/mpaland/avl_array/master/LICENSE) - -This is a tiny but **fully loaded** printf, sprintf and (v)snprintf implementation. -Primarily designed for usage in embedded systems, where printf is not available due to memory issues or in avoidance of linking against libc. -Using the standard libc printf may pull **a lot** of unwanted library stuff and can bloat code size about 20k or is not 100% thread safe. In this cases the following implementation can be used. -Absolutely **NO dependencies** are required, *printf.c* brings all necessary routines, even its own fast `ftoa` (floating point), `ntoa` (decimal) conversion. - -If memory footprint is really a critical issue, floating point, exponential and 'long long' support and can be turned off via the `PRINTF_DISABLE_SUPPORT_FLOAT`, `PRINTF_DISABLE_SUPPORT_EXPONENTIAL` and `PRINTF_DISABLE_SUPPORT_LONG_LONG` compiler switches. -When using printf (instead of sprintf/snprintf) you have to provide your own `_putchar()` low level function as console/serial output. - - -## 2020 announcement -This project is not dead! I just had no time in 2019 for sufficient support, sorry. -Within the next weeks, I will have a look to all PRs and open issues. -Thank you all for supporting this project. - - -## Highlights and Design Goals - -There is a boatload of so called 'tiny' printf implementations around. So why this one? -I've tested many implementations, but most of them have very limited flag/specifier support, a lot of other dependencies or are just not standard compliant and failing most of the test suite. -Therefore I decided to write an own, final implementation which meets the following items: - - - Very small implementation (around 600 code lines) - - NO dependencies, no libs, just one module file - - Support of all important flags, width and precision sub-specifiers (see below) - - Support of decimal/floating number representation (with an own fast itoa/ftoa) - - Reentrant and thread-safe, malloc free, no static vars/buffers - - LINT and compiler L4 warning free, mature, coverity clean, automotive ready - - Extensive test suite (> 400 test cases) passing - - Simply the best *printf* around the net - - MIT license - - -## Usage - -Add/link *printf.c* to your project and include *printf.h*. That's it. -Implement your low level output function needed for `printf()`: -```C -void _putchar(char character) -{ - // send char to console etc. -} -``` - -Usage is 1:1 like the according stdio.h library version: -```C -int printf(const char* format, ...); -int sprintf(char* buffer, const char* format, ...); -int snprintf(char* buffer, size_t count, const char* format, ...); -int vsnprintf(char* buffer, size_t count, const char* format, va_list va); - -// use output function (instead of buffer) for streamlike interface -int fctprintf(void (*out)(char character, void* arg), void* arg, const char* format, ...); -``` - -**Due to general security reasons it is highly recommended to prefer and use `snprintf` (with the max buffer size as `count` parameter) instead of `sprintf`.** -`sprintf` has no buffer limitation, so when needed - use it really with care! - -### Streamlike Usage -Besides the regular standard `printf()` functions, this module also provides `fctprintf()`, which takes an output function as first parameter to build a streamlike output like `fprintf()`: -```C -// define the output function -void my_stream_output(char character, void* arg) -{ - // opt. evaluate the argument and send the char somewhere -} - -{ - // in your code - void* arg = (void*)100; // this argument is passed to the output function - fctprintf(&my_stream_output, arg, "This is a test: %X", 0xAA); - fctprintf(&my_stream_output, nullptr, "Send to null dev"); -} -``` - -## Format Specifiers - -A format specifier follows this prototype: `%[flags][width][.precision][length]type` -The following format specifiers are supported: - - -### Supported Types - -| Type | Output | -|--------|--------| -| d or i | Signed decimal integer | -| u | Unsigned decimal integer | -| b | Unsigned binary | -| o | Unsigned octal | -| x | Unsigned hexadecimal integer (lowercase) | -| X | Unsigned hexadecimal integer (uppercase) | -| f or F | Decimal floating point | -| e or E | Scientific-notation (exponential) floating point | -| g or G | Scientific or decimal floating point | -| c | Single character | -| s | String of characters | -| p | Pointer address | -| % | A % followed by another % character will write a single % | - - -### Supported Flags - -| Flags | Description | -|-------|-------------| -| - | Left-justify within the given field width; Right justification is the default. | -| + | Forces to precede the result with a plus or minus sign (+ or -) even for positive numbers.
By default, only negative numbers are preceded with a - sign. | -| (space) | If no sign is going to be written, a blank space is inserted before the value. | -| # | Used with o, b, x or X specifiers the value is preceded with 0, 0b, 0x or 0X respectively for values different than zero.
Used with f, F it forces the written output to contain a decimal point even if no more digits follow. By default, if no digits follow, no decimal point is written. | -| 0 | Left-pads the number with zeros (0) instead of spaces when padding is specified (see width sub-specifier). | - - -### Supported Width - -| Width | Description | -|----------|-------------| -| (number) | Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger. | -| * | The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted. | - - -### Supported Precision - -| Precision | Description | -|-----------|-------------| -| .number | For integer specifiers (d, i, o, u, x, X): precision specifies the minimum number of digits to be written. If the value to be written is shorter than this number, the result is padded with leading zeros. The value is not truncated even if the result is longer. A precision of 0 means that no character is written for the value 0.
For f and F specifiers: this is the number of digits to be printed after the decimal point. **By default, this is 6, maximum is 9**.
For s: this is the maximum number of characters to be printed. By default all characters are printed until the ending null character is encountered.
If the period is specified without an explicit value for precision, 0 is assumed. | -| .* | The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted. | - - -### Supported Length - -The length sub-specifier modifies the length of the data type. - -| Length | d i | u o x X | -|--------|------|---------| -| (none) | int | unsigned int | -| hh | char | unsigned char | -| h | short int | unsigned short int | -| l | long int | unsigned long int | -| ll | long long int | unsigned long long int (if PRINTF_SUPPORT_LONG_LONG is defined) | -| j | intmax_t | uintmax_t | -| z | size_t | size_t | -| t | ptrdiff_t | ptrdiff_t (if PRINTF_SUPPORT_PTRDIFF_T is defined) | - - -### Return Value - -Upon successful return, all functions return the number of characters written, _excluding_ the terminating null character used to end the string. -Functions `snprintf()` and `vsnprintf()` don't write more than `count` bytes, _including_ the terminating null byte ('\0'). -Anyway, if the output was truncated due to this limit, the return value is the number of characters that _could_ have been written. -Notice that a value equal or larger than `count` indicates a truncation. Only when the returned value is non-negative and less than `count`, -the string has been completely written. -If any error is encountered, `-1` is returned. - -If `buffer` is set to `NULL` (`nullptr`) nothing is written and just the formatted length is returned. -```C -int length = sprintf(NULL, "Hello, world"); // length is set to 12 -``` - - -## Compiler Switches/Defines - -| Name | Default value | Description | -|------|---------------|-------------| -| PRINTF_INCLUDE_CONFIG_H | undefined | Define this as compiler switch (e.g. `gcc -DPRINTF_INCLUDE_CONFIG_H`) to include a "printf_config.h" definition file | -| PRINTF_NTOA_BUFFER_SIZE | 32 | ntoa (integer) conversion buffer size. This must be big enough to hold one converted numeric number _including_ leading zeros, normally 32 is a sufficient value. Created on the stack | -| PRINTF_FTOA_BUFFER_SIZE | 32 | ftoa (float) conversion buffer size. This must be big enough to hold one converted float number _including_ leading zeros, normally 32 is a sufficient value. Created on the stack | -| PRINTF_DEFAULT_FLOAT_PRECISION | 6 | Define the default floating point precision | -| PRINTF_MAX_FLOAT | 1e9 | Define the largest suitable value to be printed with %f, before using exponential representation | -| PRINTF_DISABLE_SUPPORT_FLOAT | undefined | Define this to disable floating point (%f) support | -| PRINTF_DISABLE_SUPPORT_EXPONENTIAL | undefined | Define this to disable exponential floating point (%e) support | -| PRINTF_DISABLE_SUPPORT_LONG_LONG | undefined | Define this to disable long long (%ll) support | -| PRINTF_DISABLE_SUPPORT_PTRDIFF_T | undefined | Define this to disable ptrdiff_t (%t) support | - - -## Caveats -None anymore (finally). - - -## Test Suite -For testing just compile, build and run the test suite located in `test/test_suite.cpp`. This uses the [catch](https://github.com/catchorg/Catch2) framework for unit-tests, which is auto-adding main(). -Running with the `--wait-for-keypress exit` option waits for the enter key after test end. - - -## Projects Using printf -- [turnkeyboard](https://github.com/mpaland/turnkeyboard) uses printf as log and generic tty (formatting) output. -- printf is part of [embeddedartistry/libc](https://github.com/embeddedartistry/libc), a libc targeted for embedded systems usage. -- The [Hatchling Platform]( https://github.com/adrian3git/HatchlingPlatform) uses printf. - -(Just send me a mail/issue/PR to get *your* project listed here) - - -## Contributing - -0. Give this project a :star: -1. Create an issue and describe your idea -2. [Fork it](https://github.com/mpaland/printf/fork) -3. Create your feature branch (`git checkout -b my-new-feature`) -4. Commit your changes (`git commit -am 'Add some feature'`) -5. Publish the branch (`git push origin my-new-feature`) -6. Create a new pull request -7. Profit! :heavy_check_mark: - - -## License -printf is written under the [MIT license](http://www.opensource.org/licenses/MIT). +# A printf / sprintf Implementation for Embedded Systems + +[![Build Status](https://travis-ci.org/mpaland/printf.svg?branch=master)](https://travis-ci.org/mpaland/printf) +[![codecov](https://codecov.io/gh/mpaland/printf/branch/master/graph/badge.svg)](https://codecov.io/gh/mpaland/printf) +[![Coverity Status](https://img.shields.io/coverity/scan/14180.svg)](https://scan.coverity.com/projects/mpaland-printf) +[![Github Issues](https://img.shields.io/github/issues/mpaland/printf.svg)](http://github.com/mpaland/printf/issues) +[![Github Releases](https://img.shields.io/github/release/mpaland/printf.svg)](https://github.com/mpaland/printf/releases) +[![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/mpaland/avl_array/master/LICENSE) + +This is a tiny but **fully loaded** printf, sprintf and (v)snprintf implementation. +Primarily designed for usage in embedded systems, where printf is not available due to memory issues or in avoidance of linking against libc. +Using the standard libc printf may pull **a lot** of unwanted library stuff and can bloat code size about 20k or is not 100% thread safe. In this cases the following implementation can be used. +Absolutely **NO dependencies** are required, *printf.c* brings all necessary routines, even its own fast `ftoa` (floating point), `ntoa` (decimal) conversion. + +If memory footprint is really a critical issue, floating point, exponential and 'long long' support and can be turned off via the `PRINTF_DISABLE_SUPPORT_FLOAT`, `PRINTF_DISABLE_SUPPORT_EXPONENTIAL` and `PRINTF_DISABLE_SUPPORT_LONG_LONG` compiler switches. +When using printf (instead of sprintf/snprintf) you have to provide your own `_putchar()` low level function as console/serial output. + + +## 2020 announcement +This project is not dead! I just had no time in 2019 for sufficient support, sorry. +Within the next weeks, I will have a look to all PRs and open issues. +Thank you all for supporting this project. + + +## Highlights and Design Goals + +There is a boatload of so called 'tiny' printf implementations around. So why this one? +I've tested many implementations, but most of them have very limited flag/specifier support, a lot of other dependencies or are just not standard compliant and failing most of the test suite. +Therefore I decided to write an own, final implementation which meets the following items: + + - Very small implementation (around 600 code lines) + - NO dependencies, no libs, just one module file + - Support of all important flags, width and precision sub-specifiers (see below) + - Support of decimal/floating number representation (with an own fast itoa/ftoa) + - Reentrant and thread-safe, malloc free, no static vars/buffers + - LINT and compiler L4 warning free, mature, coverity clean, automotive ready + - Extensive test suite (> 400 test cases) passing + - Simply the best *printf* around the net + - MIT license + + +## Usage + +Add/link *printf.c* to your project and include *printf.h*. That's it. +Implement your low level output function needed for `printf()`: +```C +void _putchar(char character) +{ + // send char to console etc. +} +``` + +Usage is 1:1 like the according stdio.h library version: +```C +int printf(const char* format, ...); +int sprintf(char* buffer, const char* format, ...); +int snprintf(char* buffer, size_t count, const char* format, ...); +int vsnprintf(char* buffer, size_t count, const char* format, va_list va); + +// use output function (instead of buffer) for streamlike interface +int fctprintf(void (*out)(char character, void* arg), void* arg, const char* format, ...); +``` + +**Due to general security reasons it is highly recommended to prefer and use `snprintf` (with the max buffer size as `count` parameter) instead of `sprintf`.** +`sprintf` has no buffer limitation, so when needed - use it really with care! + +### Streamlike Usage +Besides the regular standard `printf()` functions, this module also provides `fctprintf()`, which takes an output function as first parameter to build a streamlike output like `fprintf()`: +```C +// define the output function +void my_stream_output(char character, void* arg) +{ + // opt. evaluate the argument and send the char somewhere +} + +{ + // in your code + void* arg = (void*)100; // this argument is passed to the output function + fctprintf(&my_stream_output, arg, "This is a test: %X", 0xAA); + fctprintf(&my_stream_output, nullptr, "Send to null dev"); +} +``` + +## Format Specifiers + +A format specifier follows this prototype: `%[flags][width][.precision][length]type` +The following format specifiers are supported: + + +### Supported Types + +| Type | Output | +|--------|--------| +| d or i | Signed decimal integer | +| u | Unsigned decimal integer | +| b | Unsigned binary | +| o | Unsigned octal | +| x | Unsigned hexadecimal integer (lowercase) | +| X | Unsigned hexadecimal integer (uppercase) | +| f or F | Decimal floating point | +| e or E | Scientific-notation (exponential) floating point | +| g or G | Scientific or decimal floating point | +| c | Single character | +| s | String of characters | +| p | Pointer address | +| % | A % followed by another % character will write a single % | + + +### Supported Flags + +| Flags | Description | +|-------|-------------| +| - | Left-justify within the given field width; Right justification is the default. | +| + | Forces to precede the result with a plus or minus sign (+ or -) even for positive numbers.
By default, only negative numbers are preceded with a - sign. | +| (space) | If no sign is going to be written, a blank space is inserted before the value. | +| # | Used with o, b, x or X specifiers the value is preceded with 0, 0b, 0x or 0X respectively for values different than zero.
Used with f, F it forces the written output to contain a decimal point even if no more digits follow. By default, if no digits follow, no decimal point is written. | +| 0 | Left-pads the number with zeros (0) instead of spaces when padding is specified (see width sub-specifier). | + + +### Supported Width + +| Width | Description | +|----------|-------------| +| (number) | Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger. | +| * | The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted. | + + +### Supported Precision + +| Precision | Description | +|-----------|-------------| +| .number | For integer specifiers (d, i, o, u, x, X): precision specifies the minimum number of digits to be written. If the value to be written is shorter than this number, the result is padded with leading zeros. The value is not truncated even if the result is longer. A precision of 0 means that no character is written for the value 0.
For f and F specifiers: this is the number of digits to be printed after the decimal point. **By default, this is 6, maximum is 9**.
For s: this is the maximum number of characters to be printed. By default all characters are printed until the ending null character is encountered.
If the period is specified without an explicit value for precision, 0 is assumed. | +| .* | The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted. | + + +### Supported Length + +The length sub-specifier modifies the length of the data type. + +| Length | d i | u o x X | +|--------|------|---------| +| (none) | int | unsigned int | +| hh | char | unsigned char | +| h | short int | unsigned short int | +| l | long int | unsigned long int | +| ll | long long int | unsigned long long int (if PRINTF_SUPPORT_LONG_LONG is defined) | +| j | intmax_t | uintmax_t | +| z | size_t | size_t | +| t | ptrdiff_t | ptrdiff_t (if PRINTF_SUPPORT_PTRDIFF_T is defined) | + + +### Return Value + +Upon successful return, all functions return the number of characters written, _excluding_ the terminating null character used to end the string. +Functions `snprintf()` and `vsnprintf()` don't write more than `count` bytes, _including_ the terminating null byte ('\0'). +Anyway, if the output was truncated due to this limit, the return value is the number of characters that _could_ have been written. +Notice that a value equal or larger than `count` indicates a truncation. Only when the returned value is non-negative and less than `count`, +the string has been completely written. +If any error is encountered, `-1` is returned. + +If `buffer` is set to `NULL` (`nullptr`) nothing is written and just the formatted length is returned. +```C +int length = sprintf(NULL, "Hello, world"); // length is set to 12 +``` + + +## Compiler Switches/Defines + +| Name | Default value | Description | +|------|---------------|-------------| +| PRINTF_INCLUDE_CONFIG_H | undefined | Define this as compiler switch (e.g. `gcc -DPRINTF_INCLUDE_CONFIG_H`) to include a "printf_config.h" definition file | +| PRINTF_NTOA_BUFFER_SIZE | 32 | ntoa (integer) conversion buffer size. This must be big enough to hold one converted numeric number _including_ leading zeros, normally 32 is a sufficient value. Created on the stack | +| PRINTF_FTOA_BUFFER_SIZE | 32 | ftoa (float) conversion buffer size. This must be big enough to hold one converted float number _including_ leading zeros, normally 32 is a sufficient value. Created on the stack | +| PRINTF_DEFAULT_FLOAT_PRECISION | 6 | Define the default floating point precision | +| PRINTF_MAX_FLOAT | 1e9 | Define the largest suitable value to be printed with %f, before using exponential representation | +| PRINTF_DISABLE_SUPPORT_FLOAT | undefined | Define this to disable floating point (%f) support | +| PRINTF_DISABLE_SUPPORT_EXPONENTIAL | undefined | Define this to disable exponential floating point (%e) support | +| PRINTF_DISABLE_SUPPORT_LONG_LONG | undefined | Define this to disable long long (%ll) support | +| PRINTF_DISABLE_SUPPORT_PTRDIFF_T | undefined | Define this to disable ptrdiff_t (%t) support | + + +## Caveats +None anymore (finally). + + +## Test Suite +For testing just compile, build and run the test suite located in `test/test_suite.cpp`. This uses the [catch](https://github.com/catchorg/Catch2) framework for unit-tests, which is auto-adding main(). +Running with the `--wait-for-keypress exit` option waits for the enter key after test end. + + +## Projects Using printf +- [turnkeyboard](https://github.com/mpaland/turnkeyboard) uses printf as log and generic tty (formatting) output. +- printf is part of [embeddedartistry/libc](https://github.com/embeddedartistry/libc), a libc targeted for embedded systems usage. +- The [Hatchling Platform]( https://github.com/adrian3git/HatchlingPlatform) uses printf. + +(Just send me a mail/issue/PR to get *your* project listed here) + + +## Contributing + +0. Give this project a :star: +1. Create an issue and describe your idea +2. [Fork it](https://github.com/mpaland/printf/fork) +3. Create your feature branch (`git checkout -b my-new-feature`) +4. Commit your changes (`git commit -am 'Add some feature'`) +5. Publish the branch (`git push origin my-new-feature`) +6. Create a new pull request +7. Profit! :heavy_check_mark: + + +## License +printf is written under the [MIT license](http://www.opensource.org/licenses/MIT). diff --git a/codecov.yml b/codecov.yml index 523c6850..cece49d2 100644 --- a/codecov.yml +++ b/codecov.yml @@ -1,2 +1,2 @@ -ignore: - - "test" # ignore the test folder +ignore: + - "test" # ignore the test folder diff --git a/printf.c b/printf.c index 8a700add..93029741 100644 --- a/printf.c +++ b/printf.c @@ -1,914 +1,914 @@ -/////////////////////////////////////////////////////////////////////////////// -// \author (c) Marco Paland (info@paland.com) -// 2014-2019, PALANDesign Hannover, Germany -// -// \license The MIT License (MIT) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// -// \brief Tiny printf, sprintf and (v)snprintf implementation, optimized for speed on -// embedded systems with a very limited resources. These routines are thread -// safe and reentrant! -// Use this instead of the bloated standard/newlib printf cause these use -// malloc for printf (and may not be thread safe). -// -/////////////////////////////////////////////////////////////////////////////// - -#include -#include - -#include "printf.h" - - -// define this globally (e.g. gcc -DPRINTF_INCLUDE_CONFIG_H ...) to include the -// printf_config.h header file -// default: undefined -#ifdef PRINTF_INCLUDE_CONFIG_H -#include "printf_config.h" -#endif - - -// 'ntoa' conversion buffer size, this must be big enough to hold one converted -// numeric number including padded zeros (dynamically created on stack) -// default: 32 byte -#ifndef PRINTF_NTOA_BUFFER_SIZE -#define PRINTF_NTOA_BUFFER_SIZE 32U -#endif - -// 'ftoa' conversion buffer size, this must be big enough to hold one converted -// float number including padded zeros (dynamically created on stack) -// default: 32 byte -#ifndef PRINTF_FTOA_BUFFER_SIZE -#define PRINTF_FTOA_BUFFER_SIZE 32U -#endif - -// support for the floating point type (%f) -// default: activated -#ifndef PRINTF_DISABLE_SUPPORT_FLOAT -#define PRINTF_SUPPORT_FLOAT -#endif - -// support for exponential floating point notation (%e/%g) -// default: activated -#ifndef PRINTF_DISABLE_SUPPORT_EXPONENTIAL -#define PRINTF_SUPPORT_EXPONENTIAL -#endif - -// define the default floating point precision -// default: 6 digits -#ifndef PRINTF_DEFAULT_FLOAT_PRECISION -#define PRINTF_DEFAULT_FLOAT_PRECISION 6U -#endif - -// define the largest float suitable to print with %f -// default: 1e9 -#ifndef PRINTF_MAX_FLOAT -#define PRINTF_MAX_FLOAT 1e9 -#endif - -// support for the long long types (%llu or %p) -// default: activated -#ifndef PRINTF_DISABLE_SUPPORT_LONG_LONG -#define PRINTF_SUPPORT_LONG_LONG -#endif - -// support for the ptrdiff_t type (%t) -// ptrdiff_t is normally defined in as long or long long type -// default: activated -#ifndef PRINTF_DISABLE_SUPPORT_PTRDIFF_T -#define PRINTF_SUPPORT_PTRDIFF_T -#endif - -/////////////////////////////////////////////////////////////////////////////// - -// internal flag definitions -#define FLAGS_ZEROPAD (1U << 0U) -#define FLAGS_LEFT (1U << 1U) -#define FLAGS_PLUS (1U << 2U) -#define FLAGS_SPACE (1U << 3U) -#define FLAGS_HASH (1U << 4U) -#define FLAGS_UPPERCASE (1U << 5U) -#define FLAGS_CHAR (1U << 6U) -#define FLAGS_SHORT (1U << 7U) -#define FLAGS_LONG (1U << 8U) -#define FLAGS_LONG_LONG (1U << 9U) -#define FLAGS_PRECISION (1U << 10U) -#define FLAGS_ADAPT_EXP (1U << 11U) - - -// import float.h for DBL_MAX -#if defined(PRINTF_SUPPORT_FLOAT) -#include -#endif - - -// output function type -typedef void (*out_fct_type)(char character, void* buffer, size_t idx, size_t maxlen); - - -// wrapper (used as buffer) for output function type -typedef struct { - void (*fct)(char character, void* arg); - void* arg; -} out_fct_wrap_type; - - -// internal buffer output -static inline void _out_buffer(char character, void* buffer, size_t idx, size_t maxlen) -{ - if (idx < maxlen) { - ((char*)buffer)[idx] = character; - } -} - - -// internal null output -static inline void _out_null(char character, void* buffer, size_t idx, size_t maxlen) -{ - (void)character; (void)buffer; (void)idx; (void)maxlen; -} - - -// internal _putchar wrapper -static inline void _out_char(char character, void* buffer, size_t idx, size_t maxlen) -{ - (void)buffer; (void)idx; (void)maxlen; - if (character) { - _putchar(character); - } -} - - -// internal output function wrapper -static inline void _out_fct(char character, void* buffer, size_t idx, size_t maxlen) -{ - (void)idx; (void)maxlen; - if (character) { - // buffer is the output fct pointer - ((out_fct_wrap_type*)buffer)->fct(character, ((out_fct_wrap_type*)buffer)->arg); - } -} - - -// internal secure strlen -// \return The length of the string (excluding the terminating 0) limited by 'maxsize' -static inline unsigned int _strnlen_s(const char* str, size_t maxsize) -{ - const char* s; - for (s = str; *s && maxsize--; ++s); - return (unsigned int)(s - str); -} - - -// internal test if char is a digit (0-9) -// \return true if char is a digit -static inline bool _is_digit(char ch) -{ - return (ch >= '0') && (ch <= '9'); -} - - -// internal ASCII string to unsigned int conversion -static unsigned int _atoi(const char** str) -{ - unsigned int i = 0U; - while (_is_digit(**str)) { - i = i * 10U + (unsigned int)(*((*str)++) - '0'); - } - return i; -} - - -// output the specified string in reverse, taking care of any zero-padding -static size_t _out_rev(out_fct_type out, char* buffer, size_t idx, size_t maxlen, const char* buf, size_t len, unsigned int width, unsigned int flags) -{ - const size_t start_idx = idx; - - // pad spaces up to given width - if (!(flags & FLAGS_LEFT) && !(flags & FLAGS_ZEROPAD)) { - for (size_t i = len; i < width; i++) { - out(' ', buffer, idx++, maxlen); - } - } - - // reverse string - while (len) { - out(buf[--len], buffer, idx++, maxlen); - } - - // append pad spaces up to given width - if (flags & FLAGS_LEFT) { - while (idx - start_idx < width) { - out(' ', buffer, idx++, maxlen); - } - } - - return idx; -} - - -// internal itoa format -static size_t _ntoa_format(out_fct_type out, char* buffer, size_t idx, size_t maxlen, char* buf, size_t len, bool negative, unsigned int base, unsigned int prec, unsigned int width, unsigned int flags) -{ - // pad leading zeros - if (!(flags & FLAGS_LEFT)) { - if (width && (flags & FLAGS_ZEROPAD) && (negative || (flags & (FLAGS_PLUS | FLAGS_SPACE)))) { - width--; - } - while ((len < prec) && (len < PRINTF_NTOA_BUFFER_SIZE)) { - buf[len++] = '0'; - } - while ((flags & FLAGS_ZEROPAD) && (len < width) && (len < PRINTF_NTOA_BUFFER_SIZE)) { - buf[len++] = '0'; - } - } - - // handle hash - if (flags & FLAGS_HASH) { - if (!(flags & FLAGS_PRECISION) && len && ((len == prec) || (len == width))) { - len--; - if (len && (base == 16U)) { - len--; - } - } - if ((base == 16U) && !(flags & FLAGS_UPPERCASE) && (len < PRINTF_NTOA_BUFFER_SIZE)) { - buf[len++] = 'x'; - } - else if ((base == 16U) && (flags & FLAGS_UPPERCASE) && (len < PRINTF_NTOA_BUFFER_SIZE)) { - buf[len++] = 'X'; - } - else if ((base == 2U) && (len < PRINTF_NTOA_BUFFER_SIZE)) { - buf[len++] = 'b'; - } - if (len < PRINTF_NTOA_BUFFER_SIZE) { - buf[len++] = '0'; - } - } - - if (len < PRINTF_NTOA_BUFFER_SIZE) { - if (negative) { - buf[len++] = '-'; - } - else if (flags & FLAGS_PLUS) { - buf[len++] = '+'; // ignore the space if the '+' exists - } - else if (flags & FLAGS_SPACE) { - buf[len++] = ' '; - } - } - - return _out_rev(out, buffer, idx, maxlen, buf, len, width, flags); -} - - -// internal itoa for 'long' type -static size_t _ntoa_long(out_fct_type out, char* buffer, size_t idx, size_t maxlen, unsigned long value, bool negative, unsigned long base, unsigned int prec, unsigned int width, unsigned int flags) -{ - char buf[PRINTF_NTOA_BUFFER_SIZE]; - size_t len = 0U; - - // no hash for 0 values - if (!value) { - flags &= ~FLAGS_HASH; - } - - // write if precision != 0 and value is != 0 - if (!(flags & FLAGS_PRECISION) || value) { - do { - const char digit = (char)(value % base); - buf[len++] = digit < 10 ? '0' + digit : (flags & FLAGS_UPPERCASE ? 'A' : 'a') + digit - 10; - value /= base; - } while (value && (len < PRINTF_NTOA_BUFFER_SIZE)); - } - - return _ntoa_format(out, buffer, idx, maxlen, buf, len, negative, (unsigned int)base, prec, width, flags); -} - - -// internal itoa for 'long long' type -#if defined(PRINTF_SUPPORT_LONG_LONG) -static size_t _ntoa_long_long(out_fct_type out, char* buffer, size_t idx, size_t maxlen, unsigned long long value, bool negative, unsigned long long base, unsigned int prec, unsigned int width, unsigned int flags) -{ - char buf[PRINTF_NTOA_BUFFER_SIZE]; - size_t len = 0U; - - // no hash for 0 values - if (!value) { - flags &= ~FLAGS_HASH; - } - - // write if precision != 0 and value is != 0 - if (!(flags & FLAGS_PRECISION) || value) { - do { - const char digit = (char)(value % base); - buf[len++] = digit < 10 ? '0' + digit : (flags & FLAGS_UPPERCASE ? 'A' : 'a') + digit - 10; - value /= base; - } while (value && (len < PRINTF_NTOA_BUFFER_SIZE)); - } - - return _ntoa_format(out, buffer, idx, maxlen, buf, len, negative, (unsigned int)base, prec, width, flags); -} -#endif // PRINTF_SUPPORT_LONG_LONG - - -#if defined(PRINTF_SUPPORT_FLOAT) - -#if defined(PRINTF_SUPPORT_EXPONENTIAL) -// forward declaration so that _ftoa can switch to exp notation for values > PRINTF_MAX_FLOAT -static size_t _etoa(out_fct_type out, char* buffer, size_t idx, size_t maxlen, double value, unsigned int prec, unsigned int width, unsigned int flags); -#endif - - -// internal ftoa for fixed decimal floating point -static size_t _ftoa(out_fct_type out, char* buffer, size_t idx, size_t maxlen, double value, unsigned int prec, unsigned int width, unsigned int flags) -{ - char buf[PRINTF_FTOA_BUFFER_SIZE]; - size_t len = 0U; - double diff = 0.0; - - // powers of 10 - static const double pow10[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 }; - - // test for special values - if (value != value) - return _out_rev(out, buffer, idx, maxlen, "nan", 3, width, flags); - if (value < -DBL_MAX) - return _out_rev(out, buffer, idx, maxlen, "fni-", 4, width, flags); - if (value > DBL_MAX) - return _out_rev(out, buffer, idx, maxlen, (flags & FLAGS_PLUS) ? "fni+" : "fni", (flags & FLAGS_PLUS) ? 4U : 3U, width, flags); - - // test for very large values - // standard printf behavior is to print EVERY whole number digit -- which could be 100s of characters overflowing your buffers == bad - if ((value > PRINTF_MAX_FLOAT) || (value < -PRINTF_MAX_FLOAT)) { -#if defined(PRINTF_SUPPORT_EXPONENTIAL) - return _etoa(out, buffer, idx, maxlen, value, prec, width, flags); -#else - return 0U; -#endif - } - - // test for negative - bool negative = false; - if (value < 0) { - negative = true; - value = 0 - value; - } - - // set default precision, if not set explicitly - if (!(flags & FLAGS_PRECISION)) { - prec = PRINTF_DEFAULT_FLOAT_PRECISION; - } - // limit precision to 9, cause a prec >= 10 can lead to overflow errors - while ((len < PRINTF_FTOA_BUFFER_SIZE) && (prec > 9U)) { - buf[len++] = '0'; - prec--; - } - - int whole = (int)value; - double tmp = (value - whole) * pow10[prec]; - unsigned long frac = (unsigned long)tmp; - diff = tmp - frac; - - if (diff > 0.5) { - ++frac; - // handle rollover, e.g. case 0.99 with prec 1 is 1.0 - if (frac >= pow10[prec]) { - frac = 0; - ++whole; - } - } - else if (diff < 0.5) { - } - else if ((frac == 0U) || (frac & 1U)) { - // if halfway, round up if odd OR if last digit is 0 - ++frac; - } - - if (prec == 0U) { - diff = value - (double)whole; - if ((!(diff < 0.5) || (diff > 0.5)) && (whole & 1)) { - // exactly 0.5 and ODD, then round up - // 1.5 -> 2, but 2.5 -> 2 - ++whole; - } - } - else { - unsigned int count = prec; - // now do fractional part, as an unsigned number - while (len < PRINTF_FTOA_BUFFER_SIZE) { - --count; - buf[len++] = (char)(48U + (frac % 10U)); - if (!(frac /= 10U)) { - break; - } - } - // add extra 0s - while ((len < PRINTF_FTOA_BUFFER_SIZE) && (count-- > 0U)) { - buf[len++] = '0'; - } - if (len < PRINTF_FTOA_BUFFER_SIZE) { - // add decimal - buf[len++] = '.'; - } - } - - // do whole part, number is reversed - while (len < PRINTF_FTOA_BUFFER_SIZE) { - buf[len++] = (char)(48 + (whole % 10)); - if (!(whole /= 10)) { - break; - } - } - - // pad leading zeros - if (!(flags & FLAGS_LEFT) && (flags & FLAGS_ZEROPAD)) { - if (width && (negative || (flags & (FLAGS_PLUS | FLAGS_SPACE)))) { - width--; - } - while ((len < width) && (len < PRINTF_FTOA_BUFFER_SIZE)) { - buf[len++] = '0'; - } - } - - if (len < PRINTF_FTOA_BUFFER_SIZE) { - if (negative) { - buf[len++] = '-'; - } - else if (flags & FLAGS_PLUS) { - buf[len++] = '+'; // ignore the space if the '+' exists - } - else if (flags & FLAGS_SPACE) { - buf[len++] = ' '; - } - } - - return _out_rev(out, buffer, idx, maxlen, buf, len, width, flags); -} - - -#if defined(PRINTF_SUPPORT_EXPONENTIAL) -// internal ftoa variant for exponential floating-point type, contributed by Martijn Jasperse -static size_t _etoa(out_fct_type out, char* buffer, size_t idx, size_t maxlen, double value, unsigned int prec, unsigned int width, unsigned int flags) -{ - // check for NaN and special values - if ((value != value) || (value > DBL_MAX) || (value < -DBL_MAX)) { - return _ftoa(out, buffer, idx, maxlen, value, prec, width, flags); - } - - // determine the sign - const bool negative = value < 0; - if (negative) { - value = -value; - } - - // default precision - if (!(flags & FLAGS_PRECISION)) { - prec = PRINTF_DEFAULT_FLOAT_PRECISION; - } - - // determine the decimal exponent - // based on the algorithm by David Gay (https://www.ampl.com/netlib/fp/dtoa.c) - union { - uint64_t U; - double F; - } conv; - - conv.F = value; - int exp2 = (int)((conv.U >> 52U) & 0x07FFU) - 1023; // effectively log2 - conv.U = (conv.U & ((1ULL << 52U) - 1U)) | (1023ULL << 52U); // drop the exponent so conv.F is now in [1,2) - // now approximate log10 from the log2 integer part and an expansion of ln around 1.5 - int expval = (int)(0.1760912590558 + exp2 * 0.301029995663981 + (conv.F - 1.5) * 0.289529654602168); - // now we want to compute 10^expval but we want to be sure it won't overflow - exp2 = (int)(expval * 3.321928094887362 + 0.5); - const double z = expval * 2.302585092994046 - exp2 * 0.6931471805599453; - const double z2 = z * z; - conv.U = (uint64_t)(exp2 + 1023) << 52U; - // compute exp(z) using continued fractions, see https://en.wikipedia.org/wiki/Exponential_function#Continued_fractions_for_ex - conv.F *= 1 + 2 * z / (2 - z + (z2 / (6 + (z2 / (10 + z2 / 14))))); - // correct for rounding errors - if (value < conv.F) { - expval--; - conv.F /= 10; - } - - // the exponent format is "%+03d" and largest value is "307", so set aside 4-5 characters - unsigned int minwidth = ((expval < 100) && (expval > -100)) ? 4U : 5U; - - // in "%g" mode, "prec" is the number of *significant figures* not decimals - if (flags & FLAGS_ADAPT_EXP) { - // do we want to fall-back to "%f" mode? - if ((value >= 1e-4) && (value < 1e6)) { - if ((int)prec > expval) { - prec = (unsigned)((int)prec - expval - 1); - } - else { - prec = 0; - } - flags |= FLAGS_PRECISION; // make sure _ftoa respects precision - // no characters in exponent - minwidth = 0U; - expval = 0; - } - else { - // we use one sigfig for the whole part - if ((prec > 0) && (flags & FLAGS_PRECISION)) { - --prec; - } - } - } - - // will everything fit? - unsigned int fwidth = width; - if (width > minwidth) { - // we didn't fall-back so subtract the characters required for the exponent - fwidth -= minwidth; - } else { - // not enough characters, so go back to default sizing - fwidth = 0U; - } - if ((flags & FLAGS_LEFT) && minwidth) { - // if we're padding on the right, DON'T pad the floating part - fwidth = 0U; - } - - // rescale the float value - if (expval) { - value /= conv.F; - } - - // output the floating part - const size_t start_idx = idx; - idx = _ftoa(out, buffer, idx, maxlen, negative ? -value : value, prec, fwidth, flags & ~FLAGS_ADAPT_EXP); - - // output the exponent part - if (minwidth) { - // output the exponential symbol - out((flags & FLAGS_UPPERCASE) ? 'E' : 'e', buffer, idx++, maxlen); - // output the exponent value - idx = _ntoa_long(out, buffer, idx, maxlen, (expval < 0) ? -expval : expval, expval < 0, 10, 0, minwidth-1, FLAGS_ZEROPAD | FLAGS_PLUS); - // might need to right-pad spaces - if (flags & FLAGS_LEFT) { - while (idx - start_idx < width) out(' ', buffer, idx++, maxlen); - } - } - return idx; -} -#endif // PRINTF_SUPPORT_EXPONENTIAL -#endif // PRINTF_SUPPORT_FLOAT - - -// internal vsnprintf -static int _vsnprintf(out_fct_type out, char* buffer, const size_t maxlen, const char* format, va_list va) -{ - unsigned int flags, width, precision, n; - size_t idx = 0U; - - if (!buffer) { - // use null output function - out = _out_null; - } - - while (*format) - { - // format specifier? %[flags][width][.precision][length] - if (*format != '%') { - // no - out(*format, buffer, idx++, maxlen); - format++; - continue; - } - else { - // yes, evaluate it - format++; - } - - // evaluate flags - flags = 0U; - do { - switch (*format) { - case '0': flags |= FLAGS_ZEROPAD; format++; n = 1U; break; - case '-': flags |= FLAGS_LEFT; format++; n = 1U; break; - case '+': flags |= FLAGS_PLUS; format++; n = 1U; break; - case ' ': flags |= FLAGS_SPACE; format++; n = 1U; break; - case '#': flags |= FLAGS_HASH; format++; n = 1U; break; - default : n = 0U; break; - } - } while (n); - - // evaluate width field - width = 0U; - if (_is_digit(*format)) { - width = _atoi(&format); - } - else if (*format == '*') { - const int w = va_arg(va, int); - if (w < 0) { - flags |= FLAGS_LEFT; // reverse padding - width = (unsigned int)-w; - } - else { - width = (unsigned int)w; - } - format++; - } - - // evaluate precision field - precision = 0U; - if (*format == '.') { - flags |= FLAGS_PRECISION; - format++; - if (_is_digit(*format)) { - precision = _atoi(&format); - } - else if (*format == '*') { - const int prec = (int)va_arg(va, int); - precision = prec > 0 ? (unsigned int)prec : 0U; - format++; - } - } - - // evaluate length field - switch (*format) { - case 'l' : - flags |= FLAGS_LONG; - format++; - if (*format == 'l') { - flags |= FLAGS_LONG_LONG; - format++; - } - break; - case 'h' : - flags |= FLAGS_SHORT; - format++; - if (*format == 'h') { - flags |= FLAGS_CHAR; - format++; - } - break; -#if defined(PRINTF_SUPPORT_PTRDIFF_T) - case 't' : - flags |= (sizeof(ptrdiff_t) == sizeof(long) ? FLAGS_LONG : FLAGS_LONG_LONG); - format++; - break; -#endif - case 'j' : - flags |= (sizeof(intmax_t) == sizeof(long) ? FLAGS_LONG : FLAGS_LONG_LONG); - format++; - break; - case 'z' : - flags |= (sizeof(size_t) == sizeof(long) ? FLAGS_LONG : FLAGS_LONG_LONG); - format++; - break; - default : - break; - } - - // evaluate specifier - switch (*format) { - case 'd' : - case 'i' : - case 'u' : - case 'x' : - case 'X' : - case 'o' : - case 'b' : { - // set the base - unsigned int base; - if (*format == 'x' || *format == 'X') { - base = 16U; - } - else if (*format == 'o') { - base = 8U; - } - else if (*format == 'b') { - base = 2U; - } - else { - base = 10U; - flags &= ~FLAGS_HASH; // no hash for dec format - } - // uppercase - if (*format == 'X') { - flags |= FLAGS_UPPERCASE; - } - - // no plus or space flag for u, x, X, o, b - if ((*format != 'i') && (*format != 'd')) { - flags &= ~(FLAGS_PLUS | FLAGS_SPACE); - } - - // ignore '0' flag when precision is given - if (flags & FLAGS_PRECISION) { - flags &= ~FLAGS_ZEROPAD; - } - - // convert the integer - if ((*format == 'i') || (*format == 'd')) { - // signed - if (flags & FLAGS_LONG_LONG) { -#if defined(PRINTF_SUPPORT_LONG_LONG) - const long long value = va_arg(va, long long); - idx = _ntoa_long_long(out, buffer, idx, maxlen, (unsigned long long)(value > 0 ? value : 0 - value), value < 0, base, precision, width, flags); -#endif - } - else if (flags & FLAGS_LONG) { - const long value = va_arg(va, long); - idx = _ntoa_long(out, buffer, idx, maxlen, (unsigned long)(value > 0 ? value : 0 - value), value < 0, base, precision, width, flags); - } - else { - const int value = (flags & FLAGS_CHAR) ? (char)va_arg(va, int) : (flags & FLAGS_SHORT) ? (short int)va_arg(va, int) : va_arg(va, int); - idx = _ntoa_long(out, buffer, idx, maxlen, (unsigned int)(value > 0 ? value : 0 - value), value < 0, base, precision, width, flags); - } - } - else { - // unsigned - if (flags & FLAGS_LONG_LONG) { -#if defined(PRINTF_SUPPORT_LONG_LONG) - idx = _ntoa_long_long(out, buffer, idx, maxlen, va_arg(va, unsigned long long), false, base, precision, width, flags); -#endif - } - else if (flags & FLAGS_LONG) { - idx = _ntoa_long(out, buffer, idx, maxlen, va_arg(va, unsigned long), false, base, precision, width, flags); - } - else { - const unsigned int value = (flags & FLAGS_CHAR) ? (unsigned char)va_arg(va, unsigned int) : (flags & FLAGS_SHORT) ? (unsigned short int)va_arg(va, unsigned int) : va_arg(va, unsigned int); - idx = _ntoa_long(out, buffer, idx, maxlen, value, false, base, precision, width, flags); - } - } - format++; - break; - } -#if defined(PRINTF_SUPPORT_FLOAT) - case 'f' : - case 'F' : - if (*format == 'F') flags |= FLAGS_UPPERCASE; - idx = _ftoa(out, buffer, idx, maxlen, va_arg(va, double), precision, width, flags); - format++; - break; -#if defined(PRINTF_SUPPORT_EXPONENTIAL) - case 'e': - case 'E': - case 'g': - case 'G': - if ((*format == 'g')||(*format == 'G')) flags |= FLAGS_ADAPT_EXP; - if ((*format == 'E')||(*format == 'G')) flags |= FLAGS_UPPERCASE; - idx = _etoa(out, buffer, idx, maxlen, va_arg(va, double), precision, width, flags); - format++; - break; -#endif // PRINTF_SUPPORT_EXPONENTIAL -#endif // PRINTF_SUPPORT_FLOAT - case 'c' : { - unsigned int l = 1U; - // pre padding - if (!(flags & FLAGS_LEFT)) { - while (l++ < width) { - out(' ', buffer, idx++, maxlen); - } - } - // char output - out((char)va_arg(va, int), buffer, idx++, maxlen); - // post padding - if (flags & FLAGS_LEFT) { - while (l++ < width) { - out(' ', buffer, idx++, maxlen); - } - } - format++; - break; - } - - case 's' : { - const char* p = va_arg(va, char*); - unsigned int l = _strnlen_s(p, precision ? precision : (size_t)-1); - // pre padding - if (flags & FLAGS_PRECISION) { - l = (l < precision ? l : precision); - } - if (!(flags & FLAGS_LEFT)) { - while (l++ < width) { - out(' ', buffer, idx++, maxlen); - } - } - // string output - while ((*p != 0) && (!(flags & FLAGS_PRECISION) || precision--)) { - out(*(p++), buffer, idx++, maxlen); - } - // post padding - if (flags & FLAGS_LEFT) { - while (l++ < width) { - out(' ', buffer, idx++, maxlen); - } - } - format++; - break; - } - - case 'p' : { - width = sizeof(void*) * 2U; - flags |= FLAGS_ZEROPAD | FLAGS_UPPERCASE; -#if defined(PRINTF_SUPPORT_LONG_LONG) - const bool is_ll = sizeof(uintptr_t) == sizeof(long long); - if (is_ll) { - idx = _ntoa_long_long(out, buffer, idx, maxlen, (uintptr_t)va_arg(va, void*), false, 16U, precision, width, flags); - } - else { -#endif - idx = _ntoa_long(out, buffer, idx, maxlen, (unsigned long)((uintptr_t)va_arg(va, void*)), false, 16U, precision, width, flags); -#if defined(PRINTF_SUPPORT_LONG_LONG) - } -#endif - format++; - break; - } - - case '%' : - out('%', buffer, idx++, maxlen); - format++; - break; - - default : - out(*format, buffer, idx++, maxlen); - format++; - break; - } - } - - // termination - out((char)0, buffer, idx < maxlen ? idx : maxlen - 1U, maxlen); - - // return written chars without terminating \0 - return (int)idx; -} - - -/////////////////////////////////////////////////////////////////////////////// - -int printf_(const char* format, ...) -{ - va_list va; - va_start(va, format); - char buffer[1]; - const int ret = _vsnprintf(_out_char, buffer, (size_t)-1, format, va); - va_end(va); - return ret; -} - - -int sprintf_(char* buffer, const char* format, ...) -{ - va_list va; - va_start(va, format); - const int ret = _vsnprintf(_out_buffer, buffer, (size_t)-1, format, va); - va_end(va); - return ret; -} - - -int snprintf_(char* buffer, size_t count, const char* format, ...) -{ - va_list va; - va_start(va, format); - const int ret = _vsnprintf(_out_buffer, buffer, count, format, va); - va_end(va); - return ret; -} - - -int vprintf_(const char* format, va_list va) -{ - char buffer[1]; - return _vsnprintf(_out_char, buffer, (size_t)-1, format, va); -} - - -int vsnprintf_(char* buffer, size_t count, const char* format, va_list va) -{ - return _vsnprintf(_out_buffer, buffer, count, format, va); -} - - -int fctprintf(void (*out)(char character, void* arg), void* arg, const char* format, ...) -{ - va_list va; - va_start(va, format); - const out_fct_wrap_type out_fct_wrap = { out, arg }; - const int ret = _vsnprintf(_out_fct, (char*)(uintptr_t)&out_fct_wrap, (size_t)-1, format, va); - va_end(va); - return ret; -} +/////////////////////////////////////////////////////////////////////////////// +// \author (c) Marco Paland (info@paland.com) +// 2014-2019, PALANDesign Hannover, Germany +// +// \license The MIT License (MIT) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// +// \brief Tiny printf, sprintf and (v)snprintf implementation, optimized for speed on +// embedded systems with a very limited resources. These routines are thread +// safe and reentrant! +// Use this instead of the bloated standard/newlib printf cause these use +// malloc for printf (and may not be thread safe). +// +/////////////////////////////////////////////////////////////////////////////// + +#include +#include + +#include "printf.h" + + +// define this globally (e.g. gcc -DPRINTF_INCLUDE_CONFIG_H ...) to include the +// printf_config.h header file +// default: undefined +#ifdef PRINTF_INCLUDE_CONFIG_H +#include "printf_config.h" +#endif + + +// 'ntoa' conversion buffer size, this must be big enough to hold one converted +// numeric number including padded zeros (dynamically created on stack) +// default: 32 byte +#ifndef PRINTF_NTOA_BUFFER_SIZE +#define PRINTF_NTOA_BUFFER_SIZE 32U +#endif + +// 'ftoa' conversion buffer size, this must be big enough to hold one converted +// float number including padded zeros (dynamically created on stack) +// default: 32 byte +#ifndef PRINTF_FTOA_BUFFER_SIZE +#define PRINTF_FTOA_BUFFER_SIZE 32U +#endif + +// support for the floating point type (%f) +// default: activated +#ifndef PRINTF_DISABLE_SUPPORT_FLOAT +#define PRINTF_SUPPORT_FLOAT +#endif + +// support for exponential floating point notation (%e/%g) +// default: activated +#ifndef PRINTF_DISABLE_SUPPORT_EXPONENTIAL +#define PRINTF_SUPPORT_EXPONENTIAL +#endif + +// define the default floating point precision +// default: 6 digits +#ifndef PRINTF_DEFAULT_FLOAT_PRECISION +#define PRINTF_DEFAULT_FLOAT_PRECISION 6U +#endif + +// define the largest float suitable to print with %f +// default: 1e9 +#ifndef PRINTF_MAX_FLOAT +#define PRINTF_MAX_FLOAT 1e9 +#endif + +// support for the long long types (%llu or %p) +// default: activated +#ifndef PRINTF_DISABLE_SUPPORT_LONG_LONG +#define PRINTF_SUPPORT_LONG_LONG +#endif + +// support for the ptrdiff_t type (%t) +// ptrdiff_t is normally defined in as long or long long type +// default: activated +#ifndef PRINTF_DISABLE_SUPPORT_PTRDIFF_T +#define PRINTF_SUPPORT_PTRDIFF_T +#endif + +/////////////////////////////////////////////////////////////////////////////// + +// internal flag definitions +#define FLAGS_ZEROPAD (1U << 0U) +#define FLAGS_LEFT (1U << 1U) +#define FLAGS_PLUS (1U << 2U) +#define FLAGS_SPACE (1U << 3U) +#define FLAGS_HASH (1U << 4U) +#define FLAGS_UPPERCASE (1U << 5U) +#define FLAGS_CHAR (1U << 6U) +#define FLAGS_SHORT (1U << 7U) +#define FLAGS_LONG (1U << 8U) +#define FLAGS_LONG_LONG (1U << 9U) +#define FLAGS_PRECISION (1U << 10U) +#define FLAGS_ADAPT_EXP (1U << 11U) + + +// import float.h for DBL_MAX +#if defined(PRINTF_SUPPORT_FLOAT) +#include +#endif + + +// output function type +typedef void (*out_fct_type)(char character, void* buffer, size_t idx, size_t maxlen); + + +// wrapper (used as buffer) for output function type +typedef struct { + void (*fct)(char character, void* arg); + void* arg; +} out_fct_wrap_type; + + +// internal buffer output +static inline void _out_buffer(char character, void* buffer, size_t idx, size_t maxlen) +{ + if (idx < maxlen) { + ((char*)buffer)[idx] = character; + } +} + + +// internal null output +static inline void _out_null(char character, void* buffer, size_t idx, size_t maxlen) +{ + (void)character; (void)buffer; (void)idx; (void)maxlen; +} + + +// internal _putchar wrapper +static inline void _out_char(char character, void* buffer, size_t idx, size_t maxlen) +{ + (void)buffer; (void)idx; (void)maxlen; + if (character) { + _putchar(character); + } +} + + +// internal output function wrapper +static inline void _out_fct(char character, void* buffer, size_t idx, size_t maxlen) +{ + (void)idx; (void)maxlen; + if (character) { + // buffer is the output fct pointer + ((out_fct_wrap_type*)buffer)->fct(character, ((out_fct_wrap_type*)buffer)->arg); + } +} + + +// internal secure strlen +// \return The length of the string (excluding the terminating 0) limited by 'maxsize' +static inline unsigned int _strnlen_s(const char* str, size_t maxsize) +{ + const char* s; + for (s = str; *s && maxsize--; ++s); + return (unsigned int)(s - str); +} + + +// internal test if char is a digit (0-9) +// \return true if char is a digit +static inline bool _is_digit(char ch) +{ + return (ch >= '0') && (ch <= '9'); +} + + +// internal ASCII string to unsigned int conversion +static unsigned int _atoi(const char** str) +{ + unsigned int i = 0U; + while (_is_digit(**str)) { + i = i * 10U + (unsigned int)(*((*str)++) - '0'); + } + return i; +} + + +// output the specified string in reverse, taking care of any zero-padding +static size_t _out_rev(out_fct_type out, char* buffer, size_t idx, size_t maxlen, const char* buf, size_t len, unsigned int width, unsigned int flags) +{ + const size_t start_idx = idx; + + // pad spaces up to given width + if (!(flags & FLAGS_LEFT) && !(flags & FLAGS_ZEROPAD)) { + for (size_t i = len; i < width; i++) { + out(' ', buffer, idx++, maxlen); + } + } + + // reverse string + while (len) { + out(buf[--len], buffer, idx++, maxlen); + } + + // append pad spaces up to given width + if (flags & FLAGS_LEFT) { + while (idx - start_idx < width) { + out(' ', buffer, idx++, maxlen); + } + } + + return idx; +} + + +// internal itoa format +static size_t _ntoa_format(out_fct_type out, char* buffer, size_t idx, size_t maxlen, char* buf, size_t len, bool negative, unsigned int base, unsigned int prec, unsigned int width, unsigned int flags) +{ + // pad leading zeros + if (!(flags & FLAGS_LEFT)) { + if (width && (flags & FLAGS_ZEROPAD) && (negative || (flags & (FLAGS_PLUS | FLAGS_SPACE)))) { + width--; + } + while ((len < prec) && (len < PRINTF_NTOA_BUFFER_SIZE)) { + buf[len++] = '0'; + } + while ((flags & FLAGS_ZEROPAD) && (len < width) && (len < PRINTF_NTOA_BUFFER_SIZE)) { + buf[len++] = '0'; + } + } + + // handle hash + if (flags & FLAGS_HASH) { + if (!(flags & FLAGS_PRECISION) && len && ((len == prec) || (len == width))) { + len--; + if (len && (base == 16U)) { + len--; + } + } + if ((base == 16U) && !(flags & FLAGS_UPPERCASE) && (len < PRINTF_NTOA_BUFFER_SIZE)) { + buf[len++] = 'x'; + } + else if ((base == 16U) && (flags & FLAGS_UPPERCASE) && (len < PRINTF_NTOA_BUFFER_SIZE)) { + buf[len++] = 'X'; + } + else if ((base == 2U) && (len < PRINTF_NTOA_BUFFER_SIZE)) { + buf[len++] = 'b'; + } + if (len < PRINTF_NTOA_BUFFER_SIZE) { + buf[len++] = '0'; + } + } + + if (len < PRINTF_NTOA_BUFFER_SIZE) { + if (negative) { + buf[len++] = '-'; + } + else if (flags & FLAGS_PLUS) { + buf[len++] = '+'; // ignore the space if the '+' exists + } + else if (flags & FLAGS_SPACE) { + buf[len++] = ' '; + } + } + + return _out_rev(out, buffer, idx, maxlen, buf, len, width, flags); +} + + +// internal itoa for 'long' type +static size_t _ntoa_long(out_fct_type out, char* buffer, size_t idx, size_t maxlen, unsigned long value, bool negative, unsigned long base, unsigned int prec, unsigned int width, unsigned int flags) +{ + char buf[PRINTF_NTOA_BUFFER_SIZE]; + size_t len = 0U; + + // no hash for 0 values + if (!value) { + flags &= ~FLAGS_HASH; + } + + // write if precision != 0 and value is != 0 + if (!(flags & FLAGS_PRECISION) || value) { + do { + const char digit = (char)(value % base); + buf[len++] = digit < 10 ? '0' + digit : (flags & FLAGS_UPPERCASE ? 'A' : 'a') + digit - 10; + value /= base; + } while (value && (len < PRINTF_NTOA_BUFFER_SIZE)); + } + + return _ntoa_format(out, buffer, idx, maxlen, buf, len, negative, (unsigned int)base, prec, width, flags); +} + + +// internal itoa for 'long long' type +#if defined(PRINTF_SUPPORT_LONG_LONG) +static size_t _ntoa_long_long(out_fct_type out, char* buffer, size_t idx, size_t maxlen, unsigned long long value, bool negative, unsigned long long base, unsigned int prec, unsigned int width, unsigned int flags) +{ + char buf[PRINTF_NTOA_BUFFER_SIZE]; + size_t len = 0U; + + // no hash for 0 values + if (!value) { + flags &= ~FLAGS_HASH; + } + + // write if precision != 0 and value is != 0 + if (!(flags & FLAGS_PRECISION) || value) { + do { + const char digit = (char)(value % base); + buf[len++] = digit < 10 ? '0' + digit : (flags & FLAGS_UPPERCASE ? 'A' : 'a') + digit - 10; + value /= base; + } while (value && (len < PRINTF_NTOA_BUFFER_SIZE)); + } + + return _ntoa_format(out, buffer, idx, maxlen, buf, len, negative, (unsigned int)base, prec, width, flags); +} +#endif // PRINTF_SUPPORT_LONG_LONG + + +#if defined(PRINTF_SUPPORT_FLOAT) + +#if defined(PRINTF_SUPPORT_EXPONENTIAL) +// forward declaration so that _ftoa can switch to exp notation for values > PRINTF_MAX_FLOAT +static size_t _etoa(out_fct_type out, char* buffer, size_t idx, size_t maxlen, double value, unsigned int prec, unsigned int width, unsigned int flags); +#endif + + +// internal ftoa for fixed decimal floating point +static size_t _ftoa(out_fct_type out, char* buffer, size_t idx, size_t maxlen, double value, unsigned int prec, unsigned int width, unsigned int flags) +{ + char buf[PRINTF_FTOA_BUFFER_SIZE]; + size_t len = 0U; + double diff = 0.0; + + // powers of 10 + static const double pow10[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 }; + + // test for special values + if (value != value) + return _out_rev(out, buffer, idx, maxlen, "nan", 3, width, flags); + if (value < -DBL_MAX) + return _out_rev(out, buffer, idx, maxlen, "fni-", 4, width, flags); + if (value > DBL_MAX) + return _out_rev(out, buffer, idx, maxlen, (flags & FLAGS_PLUS) ? "fni+" : "fni", (flags & FLAGS_PLUS) ? 4U : 3U, width, flags); + + // test for very large values + // standard printf behavior is to print EVERY whole number digit -- which could be 100s of characters overflowing your buffers == bad + if ((value > PRINTF_MAX_FLOAT) || (value < -PRINTF_MAX_FLOAT)) { +#if defined(PRINTF_SUPPORT_EXPONENTIAL) + return _etoa(out, buffer, idx, maxlen, value, prec, width, flags); +#else + return 0U; +#endif + } + + // test for negative + bool negative = false; + if (value < 0) { + negative = true; + value = 0 - value; + } + + // set default precision, if not set explicitly + if (!(flags & FLAGS_PRECISION)) { + prec = PRINTF_DEFAULT_FLOAT_PRECISION; + } + // limit precision to 9, cause a prec >= 10 can lead to overflow errors + while ((len < PRINTF_FTOA_BUFFER_SIZE) && (prec > 9U)) { + buf[len++] = '0'; + prec--; + } + + int whole = (int)value; + double tmp = (value - whole) * pow10[prec]; + unsigned long frac = (unsigned long)tmp; + diff = tmp - frac; + + if (diff > 0.5) { + ++frac; + // handle rollover, e.g. case 0.99 with prec 1 is 1.0 + if (frac >= pow10[prec]) { + frac = 0; + ++whole; + } + } + else if (diff < 0.5) { + } + else if ((frac == 0U) || (frac & 1U)) { + // if halfway, round up if odd OR if last digit is 0 + ++frac; + } + + if (prec == 0U) { + diff = value - (double)whole; + if ((!(diff < 0.5) || (diff > 0.5)) && (whole & 1)) { + // exactly 0.5 and ODD, then round up + // 1.5 -> 2, but 2.5 -> 2 + ++whole; + } + } + else { + unsigned int count = prec; + // now do fractional part, as an unsigned number + while (len < PRINTF_FTOA_BUFFER_SIZE) { + --count; + buf[len++] = (char)(48U + (frac % 10U)); + if (!(frac /= 10U)) { + break; + } + } + // add extra 0s + while ((len < PRINTF_FTOA_BUFFER_SIZE) && (count-- > 0U)) { + buf[len++] = '0'; + } + if (len < PRINTF_FTOA_BUFFER_SIZE) { + // add decimal + buf[len++] = '.'; + } + } + + // do whole part, number is reversed + while (len < PRINTF_FTOA_BUFFER_SIZE) { + buf[len++] = (char)(48 + (whole % 10)); + if (!(whole /= 10)) { + break; + } + } + + // pad leading zeros + if (!(flags & FLAGS_LEFT) && (flags & FLAGS_ZEROPAD)) { + if (width && (negative || (flags & (FLAGS_PLUS | FLAGS_SPACE)))) { + width--; + } + while ((len < width) && (len < PRINTF_FTOA_BUFFER_SIZE)) { + buf[len++] = '0'; + } + } + + if (len < PRINTF_FTOA_BUFFER_SIZE) { + if (negative) { + buf[len++] = '-'; + } + else if (flags & FLAGS_PLUS) { + buf[len++] = '+'; // ignore the space if the '+' exists + } + else if (flags & FLAGS_SPACE) { + buf[len++] = ' '; + } + } + + return _out_rev(out, buffer, idx, maxlen, buf, len, width, flags); +} + + +#if defined(PRINTF_SUPPORT_EXPONENTIAL) +// internal ftoa variant for exponential floating-point type, contributed by Martijn Jasperse +static size_t _etoa(out_fct_type out, char* buffer, size_t idx, size_t maxlen, double value, unsigned int prec, unsigned int width, unsigned int flags) +{ + // check for NaN and special values + if ((value != value) || (value > DBL_MAX) || (value < -DBL_MAX)) { + return _ftoa(out, buffer, idx, maxlen, value, prec, width, flags); + } + + // determine the sign + const bool negative = value < 0; + if (negative) { + value = -value; + } + + // default precision + if (!(flags & FLAGS_PRECISION)) { + prec = PRINTF_DEFAULT_FLOAT_PRECISION; + } + + // determine the decimal exponent + // based on the algorithm by David Gay (https://www.ampl.com/netlib/fp/dtoa.c) + union { + uint64_t U; + double F; + } conv; + + conv.F = value; + int exp2 = (int)((conv.U >> 52U) & 0x07FFU) - 1023; // effectively log2 + conv.U = (conv.U & ((1ULL << 52U) - 1U)) | (1023ULL << 52U); // drop the exponent so conv.F is now in [1,2) + // now approximate log10 from the log2 integer part and an expansion of ln around 1.5 + int expval = (int)(0.1760912590558 + exp2 * 0.301029995663981 + (conv.F - 1.5) * 0.289529654602168); + // now we want to compute 10^expval but we want to be sure it won't overflow + exp2 = (int)(expval * 3.321928094887362 + 0.5); + const double z = expval * 2.302585092994046 - exp2 * 0.6931471805599453; + const double z2 = z * z; + conv.U = (uint64_t)(exp2 + 1023) << 52U; + // compute exp(z) using continued fractions, see https://en.wikipedia.org/wiki/Exponential_function#Continued_fractions_for_ex + conv.F *= 1 + 2 * z / (2 - z + (z2 / (6 + (z2 / (10 + z2 / 14))))); + // correct for rounding errors + if (value < conv.F) { + expval--; + conv.F /= 10; + } + + // the exponent format is "%+03d" and largest value is "307", so set aside 4-5 characters + unsigned int minwidth = ((expval < 100) && (expval > -100)) ? 4U : 5U; + + // in "%g" mode, "prec" is the number of *significant figures* not decimals + if (flags & FLAGS_ADAPT_EXP) { + // do we want to fall-back to "%f" mode? + if ((value >= 1e-4) && (value < 1e6)) { + if ((int)prec > expval) { + prec = (unsigned)((int)prec - expval - 1); + } + else { + prec = 0; + } + flags |= FLAGS_PRECISION; // make sure _ftoa respects precision + // no characters in exponent + minwidth = 0U; + expval = 0; + } + else { + // we use one sigfig for the whole part + if ((prec > 0) && (flags & FLAGS_PRECISION)) { + --prec; + } + } + } + + // will everything fit? + unsigned int fwidth = width; + if (width > minwidth) { + // we didn't fall-back so subtract the characters required for the exponent + fwidth -= minwidth; + } else { + // not enough characters, so go back to default sizing + fwidth = 0U; + } + if ((flags & FLAGS_LEFT) && minwidth) { + // if we're padding on the right, DON'T pad the floating part + fwidth = 0U; + } + + // rescale the float value + if (expval) { + value /= conv.F; + } + + // output the floating part + const size_t start_idx = idx; + idx = _ftoa(out, buffer, idx, maxlen, negative ? -value : value, prec, fwidth, flags & ~FLAGS_ADAPT_EXP); + + // output the exponent part + if (minwidth) { + // output the exponential symbol + out((flags & FLAGS_UPPERCASE) ? 'E' : 'e', buffer, idx++, maxlen); + // output the exponent value + idx = _ntoa_long(out, buffer, idx, maxlen, (expval < 0) ? -expval : expval, expval < 0, 10, 0, minwidth-1, FLAGS_ZEROPAD | FLAGS_PLUS); + // might need to right-pad spaces + if (flags & FLAGS_LEFT) { + while (idx - start_idx < width) out(' ', buffer, idx++, maxlen); + } + } + return idx; +} +#endif // PRINTF_SUPPORT_EXPONENTIAL +#endif // PRINTF_SUPPORT_FLOAT + + +// internal vsnprintf +static int _vsnprintf(out_fct_type out, char* buffer, const size_t maxlen, const char* format, va_list va) +{ + unsigned int flags, width, precision, n; + size_t idx = 0U; + + if (!buffer) { + // use null output function + out = _out_null; + } + + while (*format) + { + // format specifier? %[flags][width][.precision][length] + if (*format != '%') { + // no + out(*format, buffer, idx++, maxlen); + format++; + continue; + } + else { + // yes, evaluate it + format++; + } + + // evaluate flags + flags = 0U; + do { + switch (*format) { + case '0': flags |= FLAGS_ZEROPAD; format++; n = 1U; break; + case '-': flags |= FLAGS_LEFT; format++; n = 1U; break; + case '+': flags |= FLAGS_PLUS; format++; n = 1U; break; + case ' ': flags |= FLAGS_SPACE; format++; n = 1U; break; + case '#': flags |= FLAGS_HASH; format++; n = 1U; break; + default : n = 0U; break; + } + } while (n); + + // evaluate width field + width = 0U; + if (_is_digit(*format)) { + width = _atoi(&format); + } + else if (*format == '*') { + const int w = va_arg(va, int); + if (w < 0) { + flags |= FLAGS_LEFT; // reverse padding + width = (unsigned int)-w; + } + else { + width = (unsigned int)w; + } + format++; + } + + // evaluate precision field + precision = 0U; + if (*format == '.') { + flags |= FLAGS_PRECISION; + format++; + if (_is_digit(*format)) { + precision = _atoi(&format); + } + else if (*format == '*') { + const int prec = (int)va_arg(va, int); + precision = prec > 0 ? (unsigned int)prec : 0U; + format++; + } + } + + // evaluate length field + switch (*format) { + case 'l' : + flags |= FLAGS_LONG; + format++; + if (*format == 'l') { + flags |= FLAGS_LONG_LONG; + format++; + } + break; + case 'h' : + flags |= FLAGS_SHORT; + format++; + if (*format == 'h') { + flags |= FLAGS_CHAR; + format++; + } + break; +#if defined(PRINTF_SUPPORT_PTRDIFF_T) + case 't' : + flags |= (sizeof(ptrdiff_t) == sizeof(long) ? FLAGS_LONG : FLAGS_LONG_LONG); + format++; + break; +#endif + case 'j' : + flags |= (sizeof(intmax_t) == sizeof(long) ? FLAGS_LONG : FLAGS_LONG_LONG); + format++; + break; + case 'z' : + flags |= (sizeof(size_t) == sizeof(long) ? FLAGS_LONG : FLAGS_LONG_LONG); + format++; + break; + default : + break; + } + + // evaluate specifier + switch (*format) { + case 'd' : + case 'i' : + case 'u' : + case 'x' : + case 'X' : + case 'o' : + case 'b' : { + // set the base + unsigned int base; + if (*format == 'x' || *format == 'X') { + base = 16U; + } + else if (*format == 'o') { + base = 8U; + } + else if (*format == 'b') { + base = 2U; + } + else { + base = 10U; + flags &= ~FLAGS_HASH; // no hash for dec format + } + // uppercase + if (*format == 'X') { + flags |= FLAGS_UPPERCASE; + } + + // no plus or space flag for u, x, X, o, b + if ((*format != 'i') && (*format != 'd')) { + flags &= ~(FLAGS_PLUS | FLAGS_SPACE); + } + + // ignore '0' flag when precision is given + if (flags & FLAGS_PRECISION) { + flags &= ~FLAGS_ZEROPAD; + } + + // convert the integer + if ((*format == 'i') || (*format == 'd')) { + // signed + if (flags & FLAGS_LONG_LONG) { +#if defined(PRINTF_SUPPORT_LONG_LONG) + const long long value = va_arg(va, long long); + idx = _ntoa_long_long(out, buffer, idx, maxlen, (unsigned long long)(value > 0 ? value : 0 - value), value < 0, base, precision, width, flags); +#endif + } + else if (flags & FLAGS_LONG) { + const long value = va_arg(va, long); + idx = _ntoa_long(out, buffer, idx, maxlen, (unsigned long)(value > 0 ? value : 0 - value), value < 0, base, precision, width, flags); + } + else { + const int value = (flags & FLAGS_CHAR) ? (char)va_arg(va, int) : (flags & FLAGS_SHORT) ? (short int)va_arg(va, int) : va_arg(va, int); + idx = _ntoa_long(out, buffer, idx, maxlen, (unsigned int)(value > 0 ? value : 0 - value), value < 0, base, precision, width, flags); + } + } + else { + // unsigned + if (flags & FLAGS_LONG_LONG) { +#if defined(PRINTF_SUPPORT_LONG_LONG) + idx = _ntoa_long_long(out, buffer, idx, maxlen, va_arg(va, unsigned long long), false, base, precision, width, flags); +#endif + } + else if (flags & FLAGS_LONG) { + idx = _ntoa_long(out, buffer, idx, maxlen, va_arg(va, unsigned long), false, base, precision, width, flags); + } + else { + const unsigned int value = (flags & FLAGS_CHAR) ? (unsigned char)va_arg(va, unsigned int) : (flags & FLAGS_SHORT) ? (unsigned short int)va_arg(va, unsigned int) : va_arg(va, unsigned int); + idx = _ntoa_long(out, buffer, idx, maxlen, value, false, base, precision, width, flags); + } + } + format++; + break; + } +#if defined(PRINTF_SUPPORT_FLOAT) + case 'f' : + case 'F' : + if (*format == 'F') flags |= FLAGS_UPPERCASE; + idx = _ftoa(out, buffer, idx, maxlen, va_arg(va, double), precision, width, flags); + format++; + break; +#if defined(PRINTF_SUPPORT_EXPONENTIAL) + case 'e': + case 'E': + case 'g': + case 'G': + if ((*format == 'g')||(*format == 'G')) flags |= FLAGS_ADAPT_EXP; + if ((*format == 'E')||(*format == 'G')) flags |= FLAGS_UPPERCASE; + idx = _etoa(out, buffer, idx, maxlen, va_arg(va, double), precision, width, flags); + format++; + break; +#endif // PRINTF_SUPPORT_EXPONENTIAL +#endif // PRINTF_SUPPORT_FLOAT + case 'c' : { + unsigned int l = 1U; + // pre padding + if (!(flags & FLAGS_LEFT)) { + while (l++ < width) { + out(' ', buffer, idx++, maxlen); + } + } + // char output + out((char)va_arg(va, int), buffer, idx++, maxlen); + // post padding + if (flags & FLAGS_LEFT) { + while (l++ < width) { + out(' ', buffer, idx++, maxlen); + } + } + format++; + break; + } + + case 's' : { + const char* p = va_arg(va, char*); + unsigned int l = _strnlen_s(p, precision ? precision : (size_t)-1); + // pre padding + if (flags & FLAGS_PRECISION) { + l = (l < precision ? l : precision); + } + if (!(flags & FLAGS_LEFT)) { + while (l++ < width) { + out(' ', buffer, idx++, maxlen); + } + } + // string output + while ((*p != 0) && (!(flags & FLAGS_PRECISION) || precision--)) { + out(*(p++), buffer, idx++, maxlen); + } + // post padding + if (flags & FLAGS_LEFT) { + while (l++ < width) { + out(' ', buffer, idx++, maxlen); + } + } + format++; + break; + } + + case 'p' : { + width = sizeof(void*) * 2U; + flags |= FLAGS_ZEROPAD | FLAGS_UPPERCASE; +#if defined(PRINTF_SUPPORT_LONG_LONG) + const bool is_ll = sizeof(uintptr_t) == sizeof(long long); + if (is_ll) { + idx = _ntoa_long_long(out, buffer, idx, maxlen, (uintptr_t)va_arg(va, void*), false, 16U, precision, width, flags); + } + else { +#endif + idx = _ntoa_long(out, buffer, idx, maxlen, (unsigned long)((uintptr_t)va_arg(va, void*)), false, 16U, precision, width, flags); +#if defined(PRINTF_SUPPORT_LONG_LONG) + } +#endif + format++; + break; + } + + case '%' : + out('%', buffer, idx++, maxlen); + format++; + break; + + default : + out(*format, buffer, idx++, maxlen); + format++; + break; + } + } + + // termination + out((char)0, buffer, idx < maxlen ? idx : maxlen - 1U, maxlen); + + // return written chars without terminating \0 + return (int)idx; +} + + +/////////////////////////////////////////////////////////////////////////////// + +int printf_(const char* format, ...) +{ + va_list va; + va_start(va, format); + char buffer[1]; + const int ret = _vsnprintf(_out_char, buffer, (size_t)-1, format, va); + va_end(va); + return ret; +} + + +int sprintf_(char* buffer, const char* format, ...) +{ + va_list va; + va_start(va, format); + const int ret = _vsnprintf(_out_buffer, buffer, (size_t)-1, format, va); + va_end(va); + return ret; +} + + +int snprintf_(char* buffer, size_t count, const char* format, ...) +{ + va_list va; + va_start(va, format); + const int ret = _vsnprintf(_out_buffer, buffer, count, format, va); + va_end(va); + return ret; +} + + +int vprintf_(const char* format, va_list va) +{ + char buffer[1]; + return _vsnprintf(_out_char, buffer, (size_t)-1, format, va); +} + + +int vsnprintf_(char* buffer, size_t count, const char* format, va_list va) +{ + return _vsnprintf(_out_buffer, buffer, count, format, va); +} + + +int fctprintf(void (*out)(char character, void* arg), void* arg, const char* format, ...) +{ + va_list va; + va_start(va, format); + const out_fct_wrap_type out_fct_wrap = { out, arg }; + const int ret = _vsnprintf(_out_fct, (char*)(uintptr_t)&out_fct_wrap, (size_t)-1, format, va); + va_end(va); + return ret; +} diff --git a/printf.h b/printf.h index 6104ccfb..8f7a4c8f 100644 --- a/printf.h +++ b/printf.h @@ -1,117 +1,117 @@ -/////////////////////////////////////////////////////////////////////////////// -// \author (c) Marco Paland (info@paland.com) -// 2014-2019, PALANDesign Hannover, Germany -// -// \license The MIT License (MIT) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// -// \brief Tiny printf, sprintf and snprintf implementation, optimized for speed on -// embedded systems with a very limited resources. -// Use this instead of bloated standard/newlib printf. -// These routines are thread safe and reentrant. -// -/////////////////////////////////////////////////////////////////////////////// - -#ifndef _PRINTF_H_ -#define _PRINTF_H_ - -#include -#include - - -#ifdef __cplusplus -extern "C" { -#endif - - -/** - * Output a character to a custom device like UART, used by the printf() function - * This function is declared here only. You have to write your custom implementation somewhere - * \param character Character to output - */ -void _putchar(char character); - - -/** - * Tiny printf implementation - * You have to implement _putchar if you use printf() - * To avoid conflicts with the regular printf() API it is overridden by macro defines - * and internal underscore-appended functions like printf_() are used - * \param format A string that specifies the format of the output - * \return The number of characters that are written into the array, not counting the terminating null character - */ -#define printf printf_ -int printf_(const char* format, ...); - - -/** - * Tiny sprintf implementation - * Due to security reasons (buffer overflow) YOU SHOULD CONSIDER USING (V)SNPRINTF INSTEAD! - * \param buffer A pointer to the buffer where to store the formatted string. MUST be big enough to store the output! - * \param format A string that specifies the format of the output - * \return The number of characters that are WRITTEN into the buffer, not counting the terminating null character - */ -#define sprintf sprintf_ -int sprintf_(char* buffer, const char* format, ...); - - -/** - * Tiny snprintf/vsnprintf implementation - * \param buffer A pointer to the buffer where to store the formatted string - * \param count The maximum number of characters to store in the buffer, including a terminating null character - * \param format A string that specifies the format of the output - * \param va A value identifying a variable arguments list - * \return The number of characters that COULD have been written into the buffer, not counting the terminating - * null character. A value equal or larger than count indicates truncation. Only when the returned value - * is non-negative and less than count, the string has been completely written. - */ -#define snprintf snprintf_ -#define vsnprintf vsnprintf_ -int snprintf_(char* buffer, size_t count, const char* format, ...); -int vsnprintf_(char* buffer, size_t count, const char* format, va_list va); - - -/** - * Tiny vprintf implementation - * \param format A string that specifies the format of the output - * \param va A value identifying a variable arguments list - * \return The number of characters that are WRITTEN into the buffer, not counting the terminating null character - */ -#define vprintf vprintf_ -int vprintf_(const char* format, va_list va); - - -/** - * printf with output function - * You may use this as dynamic alternative to printf() with its fixed _putchar() output - * \param out An output function which takes one character and an argument pointer - * \param arg An argument pointer for user data passed to output function - * \param format A string that specifies the format of the output - * \return The number of characters that are sent to the output function, not counting the terminating null character - */ -int fctprintf(void (*out)(char character, void* arg), void* arg, const char* format, ...); - - -#ifdef __cplusplus -} -#endif - - -#endif // _PRINTF_H_ +/////////////////////////////////////////////////////////////////////////////// +// \author (c) Marco Paland (info@paland.com) +// 2014-2019, PALANDesign Hannover, Germany +// +// \license The MIT License (MIT) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// +// \brief Tiny printf, sprintf and snprintf implementation, optimized for speed on +// embedded systems with a very limited resources. +// Use this instead of bloated standard/newlib printf. +// These routines are thread safe and reentrant. +// +/////////////////////////////////////////////////////////////////////////////// + +#ifndef _PRINTF_H_ +#define _PRINTF_H_ + +#include +#include + + +#ifdef __cplusplus +extern "C" { +#endif + + +/** + * Output a character to a custom device like UART, used by the printf() function + * This function is declared here only. You have to write your custom implementation somewhere + * \param character Character to output + */ +void _putchar(char character); + + +/** + * Tiny printf implementation + * You have to implement _putchar if you use printf() + * To avoid conflicts with the regular printf() API it is overridden by macro defines + * and internal underscore-appended functions like printf_() are used + * \param format A string that specifies the format of the output + * \return The number of characters that are written into the array, not counting the terminating null character + */ +#define printf printf_ +int printf_(const char* format, ...); + + +/** + * Tiny sprintf implementation + * Due to security reasons (buffer overflow) YOU SHOULD CONSIDER USING (V)SNPRINTF INSTEAD! + * \param buffer A pointer to the buffer where to store the formatted string. MUST be big enough to store the output! + * \param format A string that specifies the format of the output + * \return The number of characters that are WRITTEN into the buffer, not counting the terminating null character + */ +#define sprintf sprintf_ +int sprintf_(char* buffer, const char* format, ...); + + +/** + * Tiny snprintf/vsnprintf implementation + * \param buffer A pointer to the buffer where to store the formatted string + * \param count The maximum number of characters to store in the buffer, including a terminating null character + * \param format A string that specifies the format of the output + * \param va A value identifying a variable arguments list + * \return The number of characters that COULD have been written into the buffer, not counting the terminating + * null character. A value equal or larger than count indicates truncation. Only when the returned value + * is non-negative and less than count, the string has been completely written. + */ +#define snprintf snprintf_ +#define vsnprintf vsnprintf_ +int snprintf_(char* buffer, size_t count, const char* format, ...); +int vsnprintf_(char* buffer, size_t count, const char* format, va_list va); + + +/** + * Tiny vprintf implementation + * \param format A string that specifies the format of the output + * \param va A value identifying a variable arguments list + * \return The number of characters that are WRITTEN into the buffer, not counting the terminating null character + */ +#define vprintf vprintf_ +int vprintf_(const char* format, va_list va); + + +/** + * printf with output function + * You may use this as dynamic alternative to printf() with its fixed _putchar() output + * \param out An output function which takes one character and an argument pointer + * \param arg An argument pointer for user data passed to output function + * \param format A string that specifies the format of the output + * \return The number of characters that are sent to the output function, not counting the terminating null character + */ +int fctprintf(void (*out)(char character, void* arg), void* arg, const char* format, ...); + + +#ifdef __cplusplus +} +#endif + + +#endif // _PRINTF_H_ diff --git a/test/test_suite.cpp b/test/test_suite.cpp index 5507c3bd..c26dc769 100644 --- a/test/test_suite.cpp +++ b/test/test_suite.cpp @@ -1,1513 +1,1513 @@ -/////////////////////////////////////////////////////////////////////////////// -// \author (c) Marco Paland (info@paland.com) -// 2017-2019, PALANDesign Hannover, Germany -// -// \license The MIT License (MIT) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// -// \brief printf unit tests -// -/////////////////////////////////////////////////////////////////////////////// - -// use the 'catch' test framework -#define CATCH_CONFIG_MAIN -#include "catch.hpp" - -#include -#include -#include - - -namespace test { - // use functions in own test namespace to avoid stdio conflicts - #include "../printf.h" - #include "../printf.c" -} // namespace test - - -// dummy putchar -static char printf_buffer[100]; -static size_t printf_idx = 0U; - -void test::_putchar(char character) -{ - printf_buffer[printf_idx++] = character; -} - -void _out_fct(char character, void* arg) -{ - (void)arg; - printf_buffer[printf_idx++] = character; -} - - -TEST_CASE("printf", "[]" ) { - printf_idx = 0U; - memset(printf_buffer, 0xCC, 100U); - REQUIRE(test::printf("% d", 4232) == 5); - REQUIRE(printf_buffer[5] == (char)0xCC); - printf_buffer[5] = 0; - REQUIRE(!strcmp(printf_buffer, " 4232")); -} - - -TEST_CASE("fctprintf", "[]" ) { - printf_idx = 0U; - memset(printf_buffer, 0xCC, 100U); - test::fctprintf(&_out_fct, nullptr, "This is a test of %X", 0x12EFU); - REQUIRE(!strncmp(printf_buffer, "This is a test of 12EF", 22U)); - REQUIRE(printf_buffer[22] == (char)0xCC); -} - - -TEST_CASE("snprintf", "[]" ) { - char buffer[100]; - - test::snprintf(buffer, 100U, "%d", -1000); - REQUIRE(!strcmp(buffer, "-1000")); - - test::snprintf(buffer, 3U, "%d", -1000); - REQUIRE(!strcmp(buffer, "-1")); -} - -static void vprintf_builder_1(char* buffer, ...) -{ - va_list args; - va_start(args, buffer); - test::vprintf("%d", args); - va_end(args); -} - -static void vsnprintf_builder_1(char* buffer, ...) -{ - va_list args; - va_start(args, buffer); - test::vsnprintf(buffer, 100U, "%d", args); - va_end(args); -} - -static void vsnprintf_builder_3(char* buffer, ...) -{ - va_list args; - va_start(args, buffer); - test::vsnprintf(buffer, 100U, "%d %d %s", args); - va_end(args); -} - - -TEST_CASE("vprintf", "[]" ) { - char buffer[100]; - printf_idx = 0U; - memset(printf_buffer, 0xCC, 100U); - vprintf_builder_1(buffer, 2345); - REQUIRE(printf_buffer[4] == (char)0xCC); - printf_buffer[4] = 0; - REQUIRE(!strcmp(printf_buffer, "2345")); -} - - -TEST_CASE("vsnprintf", "[]" ) { - char buffer[100]; - - vsnprintf_builder_1(buffer, -1); - REQUIRE(!strcmp(buffer, "-1")); - - vsnprintf_builder_3(buffer, 3, -1000, "test"); - REQUIRE(!strcmp(buffer, "3 -1000 test")); -} - - -TEST_CASE("space flag", "[]" ) { - char buffer[100]; - - test::sprintf(buffer, "% d", 42); - REQUIRE(!strcmp(buffer, " 42")); - - test::sprintf(buffer, "% d", -42); - REQUIRE(!strcmp(buffer, "-42")); - - test::sprintf(buffer, "% 5d", 42); - REQUIRE(!strcmp(buffer, " 42")); - - test::sprintf(buffer, "% 5d", -42); - REQUIRE(!strcmp(buffer, " -42")); - - test::sprintf(buffer, "% 15d", 42); - REQUIRE(!strcmp(buffer, " 42")); - - test::sprintf(buffer, "% 15d", -42); - REQUIRE(!strcmp(buffer, " -42")); - - test::sprintf(buffer, "% 15d", -42); - REQUIRE(!strcmp(buffer, " -42")); - - test::sprintf(buffer, "% 15.3f", -42.987); - REQUIRE(!strcmp(buffer, " -42.987")); - - test::sprintf(buffer, "% 15.3f", 42.987); - REQUIRE(!strcmp(buffer, " 42.987")); - - test::sprintf(buffer, "% s", "Hello testing"); - REQUIRE(!strcmp(buffer, "Hello testing")); - - test::sprintf(buffer, "% d", 1024); - REQUIRE(!strcmp(buffer, " 1024")); - - test::sprintf(buffer, "% d", -1024); - REQUIRE(!strcmp(buffer, "-1024")); - - test::sprintf(buffer, "% i", 1024); - REQUIRE(!strcmp(buffer, " 1024")); - - test::sprintf(buffer, "% i", -1024); - REQUIRE(!strcmp(buffer, "-1024")); - - test::sprintf(buffer, "% u", 1024); - REQUIRE(!strcmp(buffer, "1024")); - - test::sprintf(buffer, "% u", 4294966272U); - REQUIRE(!strcmp(buffer, "4294966272")); - - test::sprintf(buffer, "% o", 511); - REQUIRE(!strcmp(buffer, "777")); - - test::sprintf(buffer, "% o", 4294966785U); - REQUIRE(!strcmp(buffer, "37777777001")); - - test::sprintf(buffer, "% x", 305441741); - REQUIRE(!strcmp(buffer, "1234abcd")); - - test::sprintf(buffer, "% x", 3989525555U); - REQUIRE(!strcmp(buffer, "edcb5433")); - - test::sprintf(buffer, "% X", 305441741); - REQUIRE(!strcmp(buffer, "1234ABCD")); - - test::sprintf(buffer, "% X", 3989525555U); - REQUIRE(!strcmp(buffer, "EDCB5433")); - - test::sprintf(buffer, "% c", 'x'); - REQUIRE(!strcmp(buffer, "x")); -} - - -TEST_CASE("+ flag", "[]" ) { - char buffer[100]; - - test::sprintf(buffer, "%+d", 42); - REQUIRE(!strcmp(buffer, "+42")); - - test::sprintf(buffer, "%+d", -42); - REQUIRE(!strcmp(buffer, "-42")); - - test::sprintf(buffer, "%+5d", 42); - REQUIRE(!strcmp(buffer, " +42")); - - test::sprintf(buffer, "%+5d", -42); - REQUIRE(!strcmp(buffer, " -42")); - - test::sprintf(buffer, "%+15d", 42); - REQUIRE(!strcmp(buffer, " +42")); - - test::sprintf(buffer, "%+15d", -42); - REQUIRE(!strcmp(buffer, " -42")); - - test::sprintf(buffer, "%+s", "Hello testing"); - REQUIRE(!strcmp(buffer, "Hello testing")); - - test::sprintf(buffer, "%+d", 1024); - REQUIRE(!strcmp(buffer, "+1024")); - - test::sprintf(buffer, "%+d", -1024); - REQUIRE(!strcmp(buffer, "-1024")); - - test::sprintf(buffer, "%+i", 1024); - REQUIRE(!strcmp(buffer, "+1024")); - - test::sprintf(buffer, "%+i", -1024); - REQUIRE(!strcmp(buffer, "-1024")); - - test::sprintf(buffer, "%+u", 1024); - REQUIRE(!strcmp(buffer, "1024")); - - test::sprintf(buffer, "%+u", 4294966272U); - REQUIRE(!strcmp(buffer, "4294966272")); - - test::sprintf(buffer, "%+o", 511); - REQUIRE(!strcmp(buffer, "777")); - - test::sprintf(buffer, "%+o", 4294966785U); - REQUIRE(!strcmp(buffer, "37777777001")); - - test::sprintf(buffer, "%+x", 305441741); - REQUIRE(!strcmp(buffer, "1234abcd")); - - test::sprintf(buffer, "%+x", 3989525555U); - REQUIRE(!strcmp(buffer, "edcb5433")); - - test::sprintf(buffer, "%+X", 305441741); - REQUIRE(!strcmp(buffer, "1234ABCD")); - - test::sprintf(buffer, "%+X", 3989525555U); - REQUIRE(!strcmp(buffer, "EDCB5433")); - - test::sprintf(buffer, "%+c", 'x'); - REQUIRE(!strcmp(buffer, "x")); - - test::sprintf(buffer, "%+.0d", 0); - REQUIRE(!strcmp(buffer, "+")); -} - - -TEST_CASE("0 flag", "[]" ) { - char buffer[100]; - - test::sprintf(buffer, "%0d", 42); - REQUIRE(!strcmp(buffer, "42")); - - test::sprintf(buffer, "%0ld", 42L); - REQUIRE(!strcmp(buffer, "42")); - - test::sprintf(buffer, "%0d", -42); - REQUIRE(!strcmp(buffer, "-42")); - - test::sprintf(buffer, "%05d", 42); - REQUIRE(!strcmp(buffer, "00042")); - - test::sprintf(buffer, "%05d", -42); - REQUIRE(!strcmp(buffer, "-0042")); - - test::sprintf(buffer, "%015d", 42); - REQUIRE(!strcmp(buffer, "000000000000042")); - - test::sprintf(buffer, "%015d", -42); - REQUIRE(!strcmp(buffer, "-00000000000042")); - - test::sprintf(buffer, "%015.2f", 42.1234); - REQUIRE(!strcmp(buffer, "000000000042.12")); - - test::sprintf(buffer, "%015.3f", 42.9876); - REQUIRE(!strcmp(buffer, "00000000042.988")); - - test::sprintf(buffer, "%015.5f", -42.9876); - REQUIRE(!strcmp(buffer, "-00000042.98760")); -} - - -TEST_CASE("- flag", "[]" ) { - char buffer[100]; - - test::sprintf(buffer, "%-d", 42); - REQUIRE(!strcmp(buffer, "42")); - - test::sprintf(buffer, "%-d", -42); - REQUIRE(!strcmp(buffer, "-42")); - - test::sprintf(buffer, "%-5d", 42); - REQUIRE(!strcmp(buffer, "42 ")); - - test::sprintf(buffer, "%-5d", -42); - REQUIRE(!strcmp(buffer, "-42 ")); - - test::sprintf(buffer, "%-15d", 42); - REQUIRE(!strcmp(buffer, "42 ")); - - test::sprintf(buffer, "%-15d", -42); - REQUIRE(!strcmp(buffer, "-42 ")); - - test::sprintf(buffer, "%-0d", 42); - REQUIRE(!strcmp(buffer, "42")); - - test::sprintf(buffer, "%-0d", -42); - REQUIRE(!strcmp(buffer, "-42")); - - test::sprintf(buffer, "%-05d", 42); - REQUIRE(!strcmp(buffer, "42 ")); - - test::sprintf(buffer, "%-05d", -42); - REQUIRE(!strcmp(buffer, "-42 ")); - - test::sprintf(buffer, "%-015d", 42); - REQUIRE(!strcmp(buffer, "42 ")); - - test::sprintf(buffer, "%-015d", -42); - REQUIRE(!strcmp(buffer, "-42 ")); - - test::sprintf(buffer, "%0-d", 42); - REQUIRE(!strcmp(buffer, "42")); - - test::sprintf(buffer, "%0-d", -42); - REQUIRE(!strcmp(buffer, "-42")); - - test::sprintf(buffer, "%0-5d", 42); - REQUIRE(!strcmp(buffer, "42 ")); - - test::sprintf(buffer, "%0-5d", -42); - REQUIRE(!strcmp(buffer, "-42 ")); - - test::sprintf(buffer, "%0-15d", 42); - REQUIRE(!strcmp(buffer, "42 ")); - - test::sprintf(buffer, "%0-15d", -42); - REQUIRE(!strcmp(buffer, "-42 ")); - - test::sprintf(buffer, "%0-15.3e", -42.); -#ifndef PRINTF_DISABLE_SUPPORT_EXPONENTIAL - REQUIRE(!strcmp(buffer, "-4.200e+01 ")); -#else - REQUIRE(!strcmp(buffer, "e")); -#endif - - test::sprintf(buffer, "%0-15.3g", -42.); -#ifndef PRINTF_DISABLE_SUPPORT_EXPONENTIAL - REQUIRE(!strcmp(buffer, "-42.0 ")); -#else - REQUIRE(!strcmp(buffer, "g")); -#endif -} - - -TEST_CASE("# flag", "[]" ) { - char buffer[100]; - - test::sprintf(buffer, "%#.0x", 0); - REQUIRE(!strcmp(buffer, "")); - test::sprintf(buffer, "%#.1x", 0); - REQUIRE(!strcmp(buffer, "0")); - test::sprintf(buffer, "%#.0llx", (long long)0); - REQUIRE(!strcmp(buffer, "")); - test::sprintf(buffer, "%#.8x", 0x614e); - REQUIRE(!strcmp(buffer, "0x0000614e")); - test::sprintf(buffer,"%#b", 6); - REQUIRE(!strcmp(buffer, "0b110")); -} - - -TEST_CASE("specifier", "[]" ) { - char buffer[100]; - - test::sprintf(buffer, "Hello testing"); - REQUIRE(!strcmp(buffer, "Hello testing")); - - test::sprintf(buffer, "%s", "Hello testing"); - REQUIRE(!strcmp(buffer, "Hello testing")); - - test::sprintf(buffer, "%d", 1024); - REQUIRE(!strcmp(buffer, "1024")); - - test::sprintf(buffer, "%d", -1024); - REQUIRE(!strcmp(buffer, "-1024")); - - test::sprintf(buffer, "%i", 1024); - REQUIRE(!strcmp(buffer, "1024")); - - test::sprintf(buffer, "%i", -1024); - REQUIRE(!strcmp(buffer, "-1024")); - - test::sprintf(buffer, "%u", 1024); - REQUIRE(!strcmp(buffer, "1024")); - - test::sprintf(buffer, "%u", 4294966272U); - REQUIRE(!strcmp(buffer, "4294966272")); - - test::sprintf(buffer, "%o", 511); - REQUIRE(!strcmp(buffer, "777")); - - test::sprintf(buffer, "%o", 4294966785U); - REQUIRE(!strcmp(buffer, "37777777001")); - - test::sprintf(buffer, "%x", 305441741); - REQUIRE(!strcmp(buffer, "1234abcd")); - - test::sprintf(buffer, "%x", 3989525555U); - REQUIRE(!strcmp(buffer, "edcb5433")); - - test::sprintf(buffer, "%X", 305441741); - REQUIRE(!strcmp(buffer, "1234ABCD")); - - test::sprintf(buffer, "%X", 3989525555U); - REQUIRE(!strcmp(buffer, "EDCB5433")); - - test::sprintf(buffer, "%%"); - REQUIRE(!strcmp(buffer, "%")); -} - - -TEST_CASE("width", "[]" ) { - char buffer[100]; - - test::sprintf(buffer, "%1s", "Hello testing"); - REQUIRE(!strcmp(buffer, "Hello testing")); - - test::sprintf(buffer, "%1d", 1024); - REQUIRE(!strcmp(buffer, "1024")); - - test::sprintf(buffer, "%1d", -1024); - REQUIRE(!strcmp(buffer, "-1024")); - - test::sprintf(buffer, "%1i", 1024); - REQUIRE(!strcmp(buffer, "1024")); - - test::sprintf(buffer, "%1i", -1024); - REQUIRE(!strcmp(buffer, "-1024")); - - test::sprintf(buffer, "%1u", 1024); - REQUIRE(!strcmp(buffer, "1024")); - - test::sprintf(buffer, "%1u", 4294966272U); - REQUIRE(!strcmp(buffer, "4294966272")); - - test::sprintf(buffer, "%1o", 511); - REQUIRE(!strcmp(buffer, "777")); - - test::sprintf(buffer, "%1o", 4294966785U); - REQUIRE(!strcmp(buffer, "37777777001")); - - test::sprintf(buffer, "%1x", 305441741); - REQUIRE(!strcmp(buffer, "1234abcd")); - - test::sprintf(buffer, "%1x", 3989525555U); - REQUIRE(!strcmp(buffer, "edcb5433")); - - test::sprintf(buffer, "%1X", 305441741); - REQUIRE(!strcmp(buffer, "1234ABCD")); - - test::sprintf(buffer, "%1X", 3989525555U); - REQUIRE(!strcmp(buffer, "EDCB5433")); - - test::sprintf(buffer, "%1c", 'x'); - REQUIRE(!strcmp(buffer, "x")); -} - - -TEST_CASE("width 20", "[]" ) { - char buffer[100]; - - test::sprintf(buffer, "%20s", "Hello"); - REQUIRE(!strcmp(buffer, " Hello")); - - test::sprintf(buffer, "%20d", 1024); - REQUIRE(!strcmp(buffer, " 1024")); - - test::sprintf(buffer, "%20d", -1024); - REQUIRE(!strcmp(buffer, " -1024")); - - test::sprintf(buffer, "%20i", 1024); - REQUIRE(!strcmp(buffer, " 1024")); - - test::sprintf(buffer, "%20i", -1024); - REQUIRE(!strcmp(buffer, " -1024")); - - test::sprintf(buffer, "%20u", 1024); - REQUIRE(!strcmp(buffer, " 1024")); - - test::sprintf(buffer, "%20u", 4294966272U); - REQUIRE(!strcmp(buffer, " 4294966272")); - - test::sprintf(buffer, "%20o", 511); - REQUIRE(!strcmp(buffer, " 777")); - - test::sprintf(buffer, "%20o", 4294966785U); - REQUIRE(!strcmp(buffer, " 37777777001")); - - test::sprintf(buffer, "%20x", 305441741); - REQUIRE(!strcmp(buffer, " 1234abcd")); - - test::sprintf(buffer, "%20x", 3989525555U); - REQUIRE(!strcmp(buffer, " edcb5433")); - - test::sprintf(buffer, "%20X", 305441741); - REQUIRE(!strcmp(buffer, " 1234ABCD")); - - test::sprintf(buffer, "%20X", 3989525555U); - REQUIRE(!strcmp(buffer, " EDCB5433")); - - test::sprintf(buffer, "%20c", 'x'); - REQUIRE(!strcmp(buffer, " x")); -} - - -TEST_CASE("width *20", "[]" ) { - char buffer[100]; - - test::sprintf(buffer, "%*s", 20, "Hello"); - REQUIRE(!strcmp(buffer, " Hello")); - - test::sprintf(buffer, "%*d", 20, 1024); - REQUIRE(!strcmp(buffer, " 1024")); - - test::sprintf(buffer, "%*d", 20, -1024); - REQUIRE(!strcmp(buffer, " -1024")); - - test::sprintf(buffer, "%*i", 20, 1024); - REQUIRE(!strcmp(buffer, " 1024")); - - test::sprintf(buffer, "%*i", 20, -1024); - REQUIRE(!strcmp(buffer, " -1024")); - - test::sprintf(buffer, "%*u", 20, 1024); - REQUIRE(!strcmp(buffer, " 1024")); - - test::sprintf(buffer, "%*u", 20, 4294966272U); - REQUIRE(!strcmp(buffer, " 4294966272")); - - test::sprintf(buffer, "%*o", 20, 511); - REQUIRE(!strcmp(buffer, " 777")); - - test::sprintf(buffer, "%*o", 20, 4294966785U); - REQUIRE(!strcmp(buffer, " 37777777001")); - - test::sprintf(buffer, "%*x", 20, 305441741); - REQUIRE(!strcmp(buffer, " 1234abcd")); - - test::sprintf(buffer, "%*x", 20, 3989525555U); - REQUIRE(!strcmp(buffer, " edcb5433")); - - test::sprintf(buffer, "%*X", 20, 305441741); - REQUIRE(!strcmp(buffer, " 1234ABCD")); - - test::sprintf(buffer, "%*X", 20, 3989525555U); - REQUIRE(!strcmp(buffer, " EDCB5433")); - - test::sprintf(buffer, "%*c", 20,'x'); - REQUIRE(!strcmp(buffer, " x")); -} - - -TEST_CASE("width -20", "[]" ) { - char buffer[100]; - - test::sprintf(buffer, "%-20s", "Hello"); - REQUIRE(!strcmp(buffer, "Hello ")); - - test::sprintf(buffer, "%-20d", 1024); - REQUIRE(!strcmp(buffer, "1024 ")); - - test::sprintf(buffer, "%-20d", -1024); - REQUIRE(!strcmp(buffer, "-1024 ")); - - test::sprintf(buffer, "%-20i", 1024); - REQUIRE(!strcmp(buffer, "1024 ")); - - test::sprintf(buffer, "%-20i", -1024); - REQUIRE(!strcmp(buffer, "-1024 ")); - - test::sprintf(buffer, "%-20u", 1024); - REQUIRE(!strcmp(buffer, "1024 ")); - - test::sprintf(buffer, "%-20.4f", 1024.1234); - REQUIRE(!strcmp(buffer, "1024.1234 ")); - - test::sprintf(buffer, "%-20u", 4294966272U); - REQUIRE(!strcmp(buffer, "4294966272 ")); - - test::sprintf(buffer, "%-20o", 511); - REQUIRE(!strcmp(buffer, "777 ")); - - test::sprintf(buffer, "%-20o", 4294966785U); - REQUIRE(!strcmp(buffer, "37777777001 ")); - - test::sprintf(buffer, "%-20x", 305441741); - REQUIRE(!strcmp(buffer, "1234abcd ")); - - test::sprintf(buffer, "%-20x", 3989525555U); - REQUIRE(!strcmp(buffer, "edcb5433 ")); - - test::sprintf(buffer, "%-20X", 305441741); - REQUIRE(!strcmp(buffer, "1234ABCD ")); - - test::sprintf(buffer, "%-20X", 3989525555U); - REQUIRE(!strcmp(buffer, "EDCB5433 ")); - - test::sprintf(buffer, "%-20c", 'x'); - REQUIRE(!strcmp(buffer, "x ")); - - test::sprintf(buffer, "|%5d| |%-2d| |%5d|", 9, 9, 9); - REQUIRE(!strcmp(buffer, "| 9| |9 | | 9|")); - - test::sprintf(buffer, "|%5d| |%-2d| |%5d|", 10, 10, 10); - REQUIRE(!strcmp(buffer, "| 10| |10| | 10|")); - - test::sprintf(buffer, "|%5d| |%-12d| |%5d|", 9, 9, 9); - REQUIRE(!strcmp(buffer, "| 9| |9 | | 9|")); - - test::sprintf(buffer, "|%5d| |%-12d| |%5d|", 10, 10, 10); - REQUIRE(!strcmp(buffer, "| 10| |10 | | 10|")); -} - - -TEST_CASE("width 0-20", "[]" ) { - char buffer[100]; - - test::sprintf(buffer, "%0-20s", "Hello"); - REQUIRE(!strcmp(buffer, "Hello ")); - - test::sprintf(buffer, "%0-20d", 1024); - REQUIRE(!strcmp(buffer, "1024 ")); - - test::sprintf(buffer, "%0-20d", -1024); - REQUIRE(!strcmp(buffer, "-1024 ")); - - test::sprintf(buffer, "%0-20i", 1024); - REQUIRE(!strcmp(buffer, "1024 ")); - - test::sprintf(buffer, "%0-20i", -1024); - REQUIRE(!strcmp(buffer, "-1024 ")); - - test::sprintf(buffer, "%0-20u", 1024); - REQUIRE(!strcmp(buffer, "1024 ")); - - test::sprintf(buffer, "%0-20u", 4294966272U); - REQUIRE(!strcmp(buffer, "4294966272 ")); - - test::sprintf(buffer, "%0-20o", 511); - REQUIRE(!strcmp(buffer, "777 ")); - - test::sprintf(buffer, "%0-20o", 4294966785U); - REQUIRE(!strcmp(buffer, "37777777001 ")); - - test::sprintf(buffer, "%0-20x", 305441741); - REQUIRE(!strcmp(buffer, "1234abcd ")); - - test::sprintf(buffer, "%0-20x", 3989525555U); - REQUIRE(!strcmp(buffer, "edcb5433 ")); - - test::sprintf(buffer, "%0-20X", 305441741); - REQUIRE(!strcmp(buffer, "1234ABCD ")); - - test::sprintf(buffer, "%0-20X", 3989525555U); - REQUIRE(!strcmp(buffer, "EDCB5433 ")); - - test::sprintf(buffer, "%0-20c", 'x'); - REQUIRE(!strcmp(buffer, "x ")); -} - - -TEST_CASE("padding 20", "[]" ) { - char buffer[100]; - - test::sprintf(buffer, "%020d", 1024); - REQUIRE(!strcmp(buffer, "00000000000000001024")); - - test::sprintf(buffer, "%020d", -1024); - REQUIRE(!strcmp(buffer, "-0000000000000001024")); - - test::sprintf(buffer, "%020i", 1024); - REQUIRE(!strcmp(buffer, "00000000000000001024")); - - test::sprintf(buffer, "%020i", -1024); - REQUIRE(!strcmp(buffer, "-0000000000000001024")); - - test::sprintf(buffer, "%020u", 1024); - REQUIRE(!strcmp(buffer, "00000000000000001024")); - - test::sprintf(buffer, "%020u", 4294966272U); - REQUIRE(!strcmp(buffer, "00000000004294966272")); - - test::sprintf(buffer, "%020o", 511); - REQUIRE(!strcmp(buffer, "00000000000000000777")); - - test::sprintf(buffer, "%020o", 4294966785U); - REQUIRE(!strcmp(buffer, "00000000037777777001")); - - test::sprintf(buffer, "%020x", 305441741); - REQUIRE(!strcmp(buffer, "0000000000001234abcd")); - - test::sprintf(buffer, "%020x", 3989525555U); - REQUIRE(!strcmp(buffer, "000000000000edcb5433")); - - test::sprintf(buffer, "%020X", 305441741); - REQUIRE(!strcmp(buffer, "0000000000001234ABCD")); - - test::sprintf(buffer, "%020X", 3989525555U); - REQUIRE(!strcmp(buffer, "000000000000EDCB5433")); -} - - -TEST_CASE("padding .20", "[]" ) { - char buffer[100]; - - test::sprintf(buffer, "%.20d", 1024); - REQUIRE(!strcmp(buffer, "00000000000000001024")); - - test::sprintf(buffer, "%.20d", -1024); - REQUIRE(!strcmp(buffer, "-00000000000000001024")); - - test::sprintf(buffer, "%.20i", 1024); - REQUIRE(!strcmp(buffer, "00000000000000001024")); - - test::sprintf(buffer, "%.20i", -1024); - REQUIRE(!strcmp(buffer, "-00000000000000001024")); - - test::sprintf(buffer, "%.20u", 1024); - REQUIRE(!strcmp(buffer, "00000000000000001024")); - - test::sprintf(buffer, "%.20u", 4294966272U); - REQUIRE(!strcmp(buffer, "00000000004294966272")); - - test::sprintf(buffer, "%.20o", 511); - REQUIRE(!strcmp(buffer, "00000000000000000777")); - - test::sprintf(buffer, "%.20o", 4294966785U); - REQUIRE(!strcmp(buffer, "00000000037777777001")); - - test::sprintf(buffer, "%.20x", 305441741); - REQUIRE(!strcmp(buffer, "0000000000001234abcd")); - - test::sprintf(buffer, "%.20x", 3989525555U); - REQUIRE(!strcmp(buffer, "000000000000edcb5433")); - - test::sprintf(buffer, "%.20X", 305441741); - REQUIRE(!strcmp(buffer, "0000000000001234ABCD")); - - test::sprintf(buffer, "%.20X", 3989525555U); - REQUIRE(!strcmp(buffer, "000000000000EDCB5433")); -} - - -TEST_CASE("padding #020", "[]" ) { - char buffer[100]; - - test::sprintf(buffer, "%#020d", 1024); - REQUIRE(!strcmp(buffer, "00000000000000001024")); - - test::sprintf(buffer, "%#020d", -1024); - REQUIRE(!strcmp(buffer, "-0000000000000001024")); - - test::sprintf(buffer, "%#020i", 1024); - REQUIRE(!strcmp(buffer, "00000000000000001024")); - - test::sprintf(buffer, "%#020i", -1024); - REQUIRE(!strcmp(buffer, "-0000000000000001024")); - - test::sprintf(buffer, "%#020u", 1024); - REQUIRE(!strcmp(buffer, "00000000000000001024")); - - test::sprintf(buffer, "%#020u", 4294966272U); - REQUIRE(!strcmp(buffer, "00000000004294966272")); - - test::sprintf(buffer, "%#020o", 511); - REQUIRE(!strcmp(buffer, "00000000000000000777")); - - test::sprintf(buffer, "%#020o", 4294966785U); - REQUIRE(!strcmp(buffer, "00000000037777777001")); - - test::sprintf(buffer, "%#020x", 305441741); - REQUIRE(!strcmp(buffer, "0x00000000001234abcd")); - - test::sprintf(buffer, "%#020x", 3989525555U); - REQUIRE(!strcmp(buffer, "0x0000000000edcb5433")); - - test::sprintf(buffer, "%#020X", 305441741); - REQUIRE(!strcmp(buffer, "0X00000000001234ABCD")); - - test::sprintf(buffer, "%#020X", 3989525555U); - REQUIRE(!strcmp(buffer, "0X0000000000EDCB5433")); -} - - -TEST_CASE("padding #20", "[]" ) { - char buffer[100]; - - test::sprintf(buffer, "%#20d", 1024); - REQUIRE(!strcmp(buffer, " 1024")); - - test::sprintf(buffer, "%#20d", -1024); - REQUIRE(!strcmp(buffer, " -1024")); - - test::sprintf(buffer, "%#20i", 1024); - REQUIRE(!strcmp(buffer, " 1024")); - - test::sprintf(buffer, "%#20i", -1024); - REQUIRE(!strcmp(buffer, " -1024")); - - test::sprintf(buffer, "%#20u", 1024); - REQUIRE(!strcmp(buffer, " 1024")); - - test::sprintf(buffer, "%#20u", 4294966272U); - REQUIRE(!strcmp(buffer, " 4294966272")); - - test::sprintf(buffer, "%#20o", 511); - REQUIRE(!strcmp(buffer, " 0777")); - - test::sprintf(buffer, "%#20o", 4294966785U); - REQUIRE(!strcmp(buffer, " 037777777001")); - - test::sprintf(buffer, "%#20x", 305441741); - REQUIRE(!strcmp(buffer, " 0x1234abcd")); - - test::sprintf(buffer, "%#20x", 3989525555U); - REQUIRE(!strcmp(buffer, " 0xedcb5433")); - - test::sprintf(buffer, "%#20X", 305441741); - REQUIRE(!strcmp(buffer, " 0X1234ABCD")); - - test::sprintf(buffer, "%#20X", 3989525555U); - REQUIRE(!strcmp(buffer, " 0XEDCB5433")); -} - - -TEST_CASE("padding 20.5", "[]" ) { - char buffer[100]; - - test::sprintf(buffer, "%20.5d", 1024); - REQUIRE(!strcmp(buffer, " 01024")); - - test::sprintf(buffer, "%20.5d", -1024); - REQUIRE(!strcmp(buffer, " -01024")); - - test::sprintf(buffer, "%20.5i", 1024); - REQUIRE(!strcmp(buffer, " 01024")); - - test::sprintf(buffer, "%20.5i", -1024); - REQUIRE(!strcmp(buffer, " -01024")); - - test::sprintf(buffer, "%20.5u", 1024); - REQUIRE(!strcmp(buffer, " 01024")); - - test::sprintf(buffer, "%20.5u", 4294966272U); - REQUIRE(!strcmp(buffer, " 4294966272")); - - test::sprintf(buffer, "%20.5o", 511); - REQUIRE(!strcmp(buffer, " 00777")); - - test::sprintf(buffer, "%20.5o", 4294966785U); - REQUIRE(!strcmp(buffer, " 37777777001")); - - test::sprintf(buffer, "%20.5x", 305441741); - REQUIRE(!strcmp(buffer, " 1234abcd")); - - test::sprintf(buffer, "%20.10x", 3989525555U); - REQUIRE(!strcmp(buffer, " 00edcb5433")); - - test::sprintf(buffer, "%20.5X", 305441741); - REQUIRE(!strcmp(buffer, " 1234ABCD")); - - test::sprintf(buffer, "%20.10X", 3989525555U); - REQUIRE(!strcmp(buffer, " 00EDCB5433")); -} - - -TEST_CASE("padding neg numbers", "[]" ) { - char buffer[100]; - - // space padding - test::sprintf(buffer, "% 1d", -5); - REQUIRE(!strcmp(buffer, "-5")); - - test::sprintf(buffer, "% 2d", -5); - REQUIRE(!strcmp(buffer, "-5")); - - test::sprintf(buffer, "% 3d", -5); - REQUIRE(!strcmp(buffer, " -5")); - - test::sprintf(buffer, "% 4d", -5); - REQUIRE(!strcmp(buffer, " -5")); - - // zero padding - test::sprintf(buffer, "%01d", -5); - REQUIRE(!strcmp(buffer, "-5")); - - test::sprintf(buffer, "%02d", -5); - REQUIRE(!strcmp(buffer, "-5")); - - test::sprintf(buffer, "%03d", -5); - REQUIRE(!strcmp(buffer, "-05")); - - test::sprintf(buffer, "%04d", -5); - REQUIRE(!strcmp(buffer, "-005")); -} - - -TEST_CASE("float padding neg numbers", "[]" ) { - char buffer[100]; - - // space padding - test::sprintf(buffer, "% 3.1f", -5.); - REQUIRE(!strcmp(buffer, "-5.0")); - - test::sprintf(buffer, "% 4.1f", -5.); - REQUIRE(!strcmp(buffer, "-5.0")); - - test::sprintf(buffer, "% 5.1f", -5.); - REQUIRE(!strcmp(buffer, " -5.0")); - -#ifndef PRINTF_DISABLE_SUPPORT_EXPONENTIAL - test::sprintf(buffer, "% 6.1g", -5.); - REQUIRE(!strcmp(buffer, " -5")); - - test::sprintf(buffer, "% 6.1e", -5.); - REQUIRE(!strcmp(buffer, "-5.0e+00")); - - test::sprintf(buffer, "% 10.1e", -5.); - REQUIRE(!strcmp(buffer, " -5.0e+00")); -#endif - - // zero padding - test::sprintf(buffer, "%03.1f", -5.); - REQUIRE(!strcmp(buffer, "-5.0")); - - test::sprintf(buffer, "%04.1f", -5.); - REQUIRE(!strcmp(buffer, "-5.0")); - - test::sprintf(buffer, "%05.1f", -5.); - REQUIRE(!strcmp(buffer, "-05.0")); - - // zero padding no decimal point - test::sprintf(buffer, "%01.0f", -5.); - REQUIRE(!strcmp(buffer, "-5")); - - test::sprintf(buffer, "%02.0f", -5.); - REQUIRE(!strcmp(buffer, "-5")); - - test::sprintf(buffer, "%03.0f", -5.); - REQUIRE(!strcmp(buffer, "-05")); - -#ifndef PRINTF_DISABLE_SUPPORT_EXPONENTIAL - test::sprintf(buffer, "%010.1e", -5.); - REQUIRE(!strcmp(buffer, "-005.0e+00")); - - test::sprintf(buffer, "%07.0E", -5.); - REQUIRE(!strcmp(buffer, "-05E+00")); - - test::sprintf(buffer, "%03.0g", -5.); - REQUIRE(!strcmp(buffer, "-05")); -#endif -} - -TEST_CASE("length", "[]" ) { - char buffer[100]; - - test::sprintf(buffer, "%.0s", "Hello testing"); - REQUIRE(!strcmp(buffer, "")); - - test::sprintf(buffer, "%20.0s", "Hello testing"); - REQUIRE(!strcmp(buffer, " ")); - - test::sprintf(buffer, "%.s", "Hello testing"); - REQUIRE(!strcmp(buffer, "")); - - test::sprintf(buffer, "%20.s", "Hello testing"); - REQUIRE(!strcmp(buffer, " ")); - - test::sprintf(buffer, "%20.0d", 1024); - REQUIRE(!strcmp(buffer, " 1024")); - - test::sprintf(buffer, "%20.0d", -1024); - REQUIRE(!strcmp(buffer, " -1024")); - - test::sprintf(buffer, "%20.d", 0); - REQUIRE(!strcmp(buffer, " ")); - - test::sprintf(buffer, "%20.0i", 1024); - REQUIRE(!strcmp(buffer, " 1024")); - - test::sprintf(buffer, "%20.i", -1024); - REQUIRE(!strcmp(buffer, " -1024")); - - test::sprintf(buffer, "%20.i", 0); - REQUIRE(!strcmp(buffer, " ")); - - test::sprintf(buffer, "%20.u", 1024); - REQUIRE(!strcmp(buffer, " 1024")); - - test::sprintf(buffer, "%20.0u", 4294966272U); - REQUIRE(!strcmp(buffer, " 4294966272")); - - test::sprintf(buffer, "%20.u", 0U); - REQUIRE(!strcmp(buffer, " ")); - - test::sprintf(buffer, "%20.o", 511); - REQUIRE(!strcmp(buffer, " 777")); - - test::sprintf(buffer, "%20.0o", 4294966785U); - REQUIRE(!strcmp(buffer, " 37777777001")); - - test::sprintf(buffer, "%20.o", 0U); - REQUIRE(!strcmp(buffer, " ")); - - test::sprintf(buffer, "%20.x", 305441741); - REQUIRE(!strcmp(buffer, " 1234abcd")); - - test::sprintf(buffer, "%50.x", 305441741); - REQUIRE(!strcmp(buffer, " 1234abcd")); - - test::sprintf(buffer, "%50.x%10.u", 305441741, 12345); - REQUIRE(!strcmp(buffer, " 1234abcd 12345")); - - test::sprintf(buffer, "%20.0x", 3989525555U); - REQUIRE(!strcmp(buffer, " edcb5433")); - - test::sprintf(buffer, "%20.x", 0U); - REQUIRE(!strcmp(buffer, " ")); - - test::sprintf(buffer, "%20.X", 305441741); - REQUIRE(!strcmp(buffer, " 1234ABCD")); - - test::sprintf(buffer, "%20.0X", 3989525555U); - REQUIRE(!strcmp(buffer, " EDCB5433")); - - test::sprintf(buffer, "%20.X", 0U); - REQUIRE(!strcmp(buffer, " ")); - - test::sprintf(buffer, "%02.0u", 0U); - REQUIRE(!strcmp(buffer, " ")); - - test::sprintf(buffer, "%02.0d", 0); - REQUIRE(!strcmp(buffer, " ")); -} - - -TEST_CASE("float", "[]" ) { - char buffer[100]; - - // test special-case floats using math.h macros - test::sprintf(buffer, "%8f", NAN); - REQUIRE(!strcmp(buffer, " nan")); - - test::sprintf(buffer, "%8f", INFINITY); - REQUIRE(!strcmp(buffer, " inf")); - - test::sprintf(buffer, "%-8f", -INFINITY); - REQUIRE(!strcmp(buffer, "-inf ")); - -#ifndef PRINTF_DISABLE_SUPPORT_EXPONENTIAL - test::sprintf(buffer, "%+8e", INFINITY); - REQUIRE(!strcmp(buffer, " +inf")); -#endif - - test::sprintf(buffer, "%.4f", 3.1415354); - REQUIRE(!strcmp(buffer, "3.1415")); - - test::sprintf(buffer, "%.3f", 30343.1415354); - REQUIRE(!strcmp(buffer, "30343.142")); - - test::sprintf(buffer, "%.0f", 34.1415354); - REQUIRE(!strcmp(buffer, "34")); - - test::sprintf(buffer, "%.0f", 1.3); - REQUIRE(!strcmp(buffer, "1")); - - test::sprintf(buffer, "%.0f", 1.55); - REQUIRE(!strcmp(buffer, "2")); - - test::sprintf(buffer, "%.1f", 1.64); - REQUIRE(!strcmp(buffer, "1.6")); - - test::sprintf(buffer, "%.2f", 42.8952); - REQUIRE(!strcmp(buffer, "42.90")); - - test::sprintf(buffer, "%.9f", 42.8952); - REQUIRE(!strcmp(buffer, "42.895200000")); - - test::sprintf(buffer, "%.10f", 42.895223); - REQUIRE(!strcmp(buffer, "42.8952230000")); - - // this testcase checks, that the precision is truncated to 9 digits. - // a perfect working float should return the whole number - test::sprintf(buffer, "%.12f", 42.89522312345678); - REQUIRE(!strcmp(buffer, "42.895223123000")); - - // this testcase checks, that the precision is truncated AND rounded to 9 digits. - // a perfect working float should return the whole number - test::sprintf(buffer, "%.12f", 42.89522387654321); - REQUIRE(!strcmp(buffer, "42.895223877000")); - - test::sprintf(buffer, "%6.2f", 42.8952); - REQUIRE(!strcmp(buffer, " 42.90")); - - test::sprintf(buffer, "%+6.2f", 42.8952); - REQUIRE(!strcmp(buffer, "+42.90")); - - test::sprintf(buffer, "%+5.1f", 42.9252); - REQUIRE(!strcmp(buffer, "+42.9")); - - test::sprintf(buffer, "%f", 42.5); - REQUIRE(!strcmp(buffer, "42.500000")); - - test::sprintf(buffer, "%.1f", 42.5); - REQUIRE(!strcmp(buffer, "42.5")); - - test::sprintf(buffer, "%f", 42167.0); - REQUIRE(!strcmp(buffer, "42167.000000")); - - test::sprintf(buffer, "%.9f", -12345.987654321); - REQUIRE(!strcmp(buffer, "-12345.987654321")); - - test::sprintf(buffer, "%.1f", 3.999); - REQUIRE(!strcmp(buffer, "4.0")); - - test::sprintf(buffer, "%.0f", 3.5); - REQUIRE(!strcmp(buffer, "4")); - - test::sprintf(buffer, "%.0f", 4.5); - REQUIRE(!strcmp(buffer, "4")); - - test::sprintf(buffer, "%.0f", 3.49); - REQUIRE(!strcmp(buffer, "3")); - - test::sprintf(buffer, "%.1f", 3.49); - REQUIRE(!strcmp(buffer, "3.5")); - - test::sprintf(buffer, "a%-5.1f", 0.5); - REQUIRE(!strcmp(buffer, "a0.5 ")); - - test::sprintf(buffer, "a%-5.1fend", 0.5); - REQUIRE(!strcmp(buffer, "a0.5 end")); - -#ifndef PRINTF_DISABLE_SUPPORT_EXPONENTIAL - test::sprintf(buffer, "%G", 12345.678); - REQUIRE(!strcmp(buffer, "12345.7")); - - test::sprintf(buffer, "%.7G", 12345.678); - REQUIRE(!strcmp(buffer, "12345.68")); - - test::sprintf(buffer, "%.5G", 123456789.); - REQUIRE(!strcmp(buffer, "1.2346E+08")); - - test::sprintf(buffer, "%.6G", 12345.); - REQUIRE(!strcmp(buffer, "12345.0")); - - test::sprintf(buffer, "%+12.4g", 123456789.); - REQUIRE(!strcmp(buffer, " +1.235e+08")); - - test::sprintf(buffer, "%.2G", 0.001234); - REQUIRE(!strcmp(buffer, "0.0012")); - - test::sprintf(buffer, "%+10.4G", 0.001234); - REQUIRE(!strcmp(buffer, " +0.001234")); - - test::sprintf(buffer, "%+012.4g", 0.00001234); - REQUIRE(!strcmp(buffer, "+001.234e-05")); - - test::sprintf(buffer, "%.3g", -1.2345e-308); - REQUIRE(!strcmp(buffer, "-1.23e-308")); - - test::sprintf(buffer, "%+.3E", 1.23e+308); - REQUIRE(!strcmp(buffer, "+1.230E+308")); -#endif - - // out of range for float: should switch to exp notation if supported, else empty - test::sprintf(buffer, "%.1f", 1E20); -#ifndef PRINTF_DISABLE_SUPPORT_EXPONENTIAL - REQUIRE(!strcmp(buffer, "1.0e+20")); -#else - REQUIRE(!strcmp(buffer, "")); -#endif - - // brute force float - bool fail = false; - std::stringstream str; - str.precision(5); - for (float i = -100000; i < 100000; i += 1) { - test::sprintf(buffer, "%.5f", i / 10000); - str.str(""); - str << std::fixed << i / 10000; - fail = fail || !!strcmp(buffer, str.str().c_str()); - } - REQUIRE(!fail); - - -#ifndef PRINTF_DISABLE_SUPPORT_EXPONENTIAL - // brute force exp - str.setf(std::ios::scientific, std::ios::floatfield); - for (float i = -1e20; i < 1e20; i += 1e15) { - test::sprintf(buffer, "%.5f", i); - str.str(""); - str << i; - fail = fail || !!strcmp(buffer, str.str().c_str()); - } - REQUIRE(!fail); -#endif -} - - -TEST_CASE("types", "[]" ) { - char buffer[100]; - - test::sprintf(buffer, "%i", 0); - REQUIRE(!strcmp(buffer, "0")); - - test::sprintf(buffer, "%i", 1234); - REQUIRE(!strcmp(buffer, "1234")); - - test::sprintf(buffer, "%i", 32767); - REQUIRE(!strcmp(buffer, "32767")); - - test::sprintf(buffer, "%i", -32767); - REQUIRE(!strcmp(buffer, "-32767")); - - test::sprintf(buffer, "%li", 30L); - REQUIRE(!strcmp(buffer, "30")); - - test::sprintf(buffer, "%li", -2147483647L); - REQUIRE(!strcmp(buffer, "-2147483647")); - - test::sprintf(buffer, "%li", 2147483647L); - REQUIRE(!strcmp(buffer, "2147483647")); - - test::sprintf(buffer, "%lli", 30LL); - REQUIRE(!strcmp(buffer, "30")); - - test::sprintf(buffer, "%lli", -9223372036854775807LL); - REQUIRE(!strcmp(buffer, "-9223372036854775807")); - - test::sprintf(buffer, "%lli", 9223372036854775807LL); - REQUIRE(!strcmp(buffer, "9223372036854775807")); - - test::sprintf(buffer, "%lu", 100000L); - REQUIRE(!strcmp(buffer, "100000")); - - test::sprintf(buffer, "%lu", 0xFFFFFFFFL); - REQUIRE(!strcmp(buffer, "4294967295")); - - test::sprintf(buffer, "%llu", 281474976710656LLU); - REQUIRE(!strcmp(buffer, "281474976710656")); - - test::sprintf(buffer, "%llu", 18446744073709551615LLU); - REQUIRE(!strcmp(buffer, "18446744073709551615")); - - test::sprintf(buffer, "%zu", 2147483647UL); - REQUIRE(!strcmp(buffer, "2147483647")); - - test::sprintf(buffer, "%zd", 2147483647UL); - REQUIRE(!strcmp(buffer, "2147483647")); - - if (sizeof(size_t) == sizeof(long)) { - test::sprintf(buffer, "%zi", -2147483647L); - REQUIRE(!strcmp(buffer, "-2147483647")); - } - else { - test::sprintf(buffer, "%zi", -2147483647LL); - REQUIRE(!strcmp(buffer, "-2147483647")); - } - - test::sprintf(buffer, "%b", 60000); - REQUIRE(!strcmp(buffer, "1110101001100000")); - - test::sprintf(buffer, "%lb", 12345678L); - REQUIRE(!strcmp(buffer, "101111000110000101001110")); - - test::sprintf(buffer, "%o", 60000); - REQUIRE(!strcmp(buffer, "165140")); - - test::sprintf(buffer, "%lo", 12345678L); - REQUIRE(!strcmp(buffer, "57060516")); - - test::sprintf(buffer, "%lx", 0x12345678L); - REQUIRE(!strcmp(buffer, "12345678")); - - test::sprintf(buffer, "%llx", 0x1234567891234567LLU); - REQUIRE(!strcmp(buffer, "1234567891234567")); - - test::sprintf(buffer, "%lx", 0xabcdefabL); - REQUIRE(!strcmp(buffer, "abcdefab")); - - test::sprintf(buffer, "%lX", 0xabcdefabL); - REQUIRE(!strcmp(buffer, "ABCDEFAB")); - - test::sprintf(buffer, "%c", 'v'); - REQUIRE(!strcmp(buffer, "v")); - - test::sprintf(buffer, "%cv", 'w'); - REQUIRE(!strcmp(buffer, "wv")); - - test::sprintf(buffer, "%s", "A Test"); - REQUIRE(!strcmp(buffer, "A Test")); - - test::sprintf(buffer, "%hhu", 0xFFFFUL); - REQUIRE(!strcmp(buffer, "255")); - - test::sprintf(buffer, "%hu", 0x123456UL); - REQUIRE(!strcmp(buffer, "13398")); - - test::sprintf(buffer, "%s%hhi %hu", "Test", 10000, 0xFFFFFFFF); - REQUIRE(!strcmp(buffer, "Test16 65535")); - - test::sprintf(buffer, "%tx", &buffer[10] - &buffer[0]); - REQUIRE(!strcmp(buffer, "a")); - -// TBD - if (sizeof(intmax_t) == sizeof(long)) { - test::sprintf(buffer, "%ji", -2147483647L); - REQUIRE(!strcmp(buffer, "-2147483647")); - } - else { - test::sprintf(buffer, "%ji", -2147483647LL); - REQUIRE(!strcmp(buffer, "-2147483647")); - } -} - - -TEST_CASE("pointer", "[]" ) { - char buffer[100]; - - test::sprintf(buffer, "%p", (void*)0x1234U); - if (sizeof(void*) == 4U) { - REQUIRE(!strcmp(buffer, "00001234")); - } - else { - REQUIRE(!strcmp(buffer, "0000000000001234")); - } - - test::sprintf(buffer, "%p", (void*)0x12345678U); - if (sizeof(void*) == 4U) { - REQUIRE(!strcmp(buffer, "12345678")); - } - else { - REQUIRE(!strcmp(buffer, "0000000012345678")); - } - - test::sprintf(buffer, "%p-%p", (void*)0x12345678U, (void*)0x7EDCBA98U); - if (sizeof(void*) == 4U) { - REQUIRE(!strcmp(buffer, "12345678-7EDCBA98")); - } - else { - REQUIRE(!strcmp(buffer, "0000000012345678-000000007EDCBA98")); - } - - if (sizeof(uintptr_t) == sizeof(uint64_t)) { - test::sprintf(buffer, "%p", (void*)(uintptr_t)0xFFFFFFFFU); - REQUIRE(!strcmp(buffer, "00000000FFFFFFFF")); - } - else { - test::sprintf(buffer, "%p", (void*)(uintptr_t)0xFFFFFFFFU); - REQUIRE(!strcmp(buffer, "FFFFFFFF")); - } -} - - -TEST_CASE("unknown flag", "[]" ) { - char buffer[100]; - - test::sprintf(buffer, "%kmarco", 42, 37); - REQUIRE(!strcmp(buffer, "kmarco")); -} - - -TEST_CASE("string length", "[]" ) { - char buffer[100]; - - test::sprintf(buffer, "%.4s", "This is a test"); - REQUIRE(!strcmp(buffer, "This")); - - test::sprintf(buffer, "%.4s", "test"); - REQUIRE(!strcmp(buffer, "test")); - - test::sprintf(buffer, "%.7s", "123"); - REQUIRE(!strcmp(buffer, "123")); - - test::sprintf(buffer, "%.7s", ""); - REQUIRE(!strcmp(buffer, "")); - - test::sprintf(buffer, "%.4s%.2s", "123456", "abcdef"); - REQUIRE(!strcmp(buffer, "1234ab")); - - test::sprintf(buffer, "%.4.2s", "123456"); - REQUIRE(!strcmp(buffer, ".2s")); - - test::sprintf(buffer, "%.*s", 3, "123456"); - REQUIRE(!strcmp(buffer, "123")); -} - - -TEST_CASE("buffer length", "[]" ) { - char buffer[100]; - int ret; - - ret = test::snprintf(nullptr, 10, "%s", "Test"); - REQUIRE(ret == 4); - ret = test::snprintf(nullptr, 0, "%s", "Test"); - REQUIRE(ret == 4); - - buffer[0] = (char)0xA5; - ret = test::snprintf(buffer, 0, "%s", "Test"); - REQUIRE(buffer[0] == (char)0xA5); - REQUIRE(ret == 4); - - buffer[0] = (char)0xCC; - test::snprintf(buffer, 1, "%s", "Test"); - REQUIRE(buffer[0] == '\0'); - - test::snprintf(buffer, 2, "%s", "Hello"); - REQUIRE(!strcmp(buffer, "H")); -} - - -TEST_CASE("ret value", "[]" ) { - char buffer[100] ; - int ret; - - ret = test::snprintf(buffer, 6, "0%s", "1234"); - REQUIRE(!strcmp(buffer, "01234")); - REQUIRE(ret == 5); - - ret = test::snprintf(buffer, 6, "0%s", "12345"); - REQUIRE(!strcmp(buffer, "01234")); - REQUIRE(ret == 6); // '5' is truncated - - ret = test::snprintf(buffer, 6, "0%s", "1234567"); - REQUIRE(!strcmp(buffer, "01234")); - REQUIRE(ret == 8); // '567' are truncated - - ret = test::snprintf(buffer, 10, "hello, world"); - REQUIRE(ret == 12); - - ret = test::snprintf(buffer, 3, "%d", 10000); - REQUIRE(ret == 5); - REQUIRE(strlen(buffer) == 2U); - REQUIRE(buffer[0] == '1'); - REQUIRE(buffer[1] == '0'); - REQUIRE(buffer[2] == '\0'); -} - - -TEST_CASE("misc", "[]" ) { - char buffer[100]; - - test::sprintf(buffer, "%u%u%ctest%d %s", 5, 3000, 'a', -20, "bit"); - REQUIRE(!strcmp(buffer, "53000atest-20 bit")); - - test::sprintf(buffer, "%.*f", 2, 0.33333333); - REQUIRE(!strcmp(buffer, "0.33")); - - test::sprintf(buffer, "%.*d", -1, 1); - REQUIRE(!strcmp(buffer, "1")); - - test::sprintf(buffer, "%.3s", "foobar"); - REQUIRE(!strcmp(buffer, "foo")); - - test::sprintf(buffer, "% .0d", 0); - REQUIRE(!strcmp(buffer, " ")); - - test::sprintf(buffer, "%10.5d", 4); - REQUIRE(!strcmp(buffer, " 00004")); - - test::sprintf(buffer, "%*sx", -3, "hi"); - REQUIRE(!strcmp(buffer, "hi x")); - -#ifndef PRINTF_DISABLE_SUPPORT_EXPONENTIAL - test::sprintf(buffer, "%.*g", 2, 0.33333333); - REQUIRE(!strcmp(buffer, "0.33")); - - test::sprintf(buffer, "%.*e", 2, 0.33333333); - REQUIRE(!strcmp(buffer, "3.33e-01")); -#endif -} +/////////////////////////////////////////////////////////////////////////////// +// \author (c) Marco Paland (info@paland.com) +// 2017-2019, PALANDesign Hannover, Germany +// +// \license The MIT License (MIT) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// +// \brief printf unit tests +// +/////////////////////////////////////////////////////////////////////////////// + +// use the 'catch' test framework +#define CATCH_CONFIG_MAIN +#include "catch.hpp" + +#include +#include +#include + + +namespace test { + // use functions in own test namespace to avoid stdio conflicts + #include "../printf.h" + #include "../printf.c" +} // namespace test + + +// dummy putchar +static char printf_buffer[100]; +static size_t printf_idx = 0U; + +void test::_putchar(char character) +{ + printf_buffer[printf_idx++] = character; +} + +void _out_fct(char character, void* arg) +{ + (void)arg; + printf_buffer[printf_idx++] = character; +} + + +TEST_CASE("printf", "[]" ) { + printf_idx = 0U; + memset(printf_buffer, 0xCC, 100U); + REQUIRE(test::printf("% d", 4232) == 5); + REQUIRE(printf_buffer[5] == (char)0xCC); + printf_buffer[5] = 0; + REQUIRE(!strcmp(printf_buffer, " 4232")); +} + + +TEST_CASE("fctprintf", "[]" ) { + printf_idx = 0U; + memset(printf_buffer, 0xCC, 100U); + test::fctprintf(&_out_fct, nullptr, "This is a test of %X", 0x12EFU); + REQUIRE(!strncmp(printf_buffer, "This is a test of 12EF", 22U)); + REQUIRE(printf_buffer[22] == (char)0xCC); +} + + +TEST_CASE("snprintf", "[]" ) { + char buffer[100]; + + test::snprintf(buffer, 100U, "%d", -1000); + REQUIRE(!strcmp(buffer, "-1000")); + + test::snprintf(buffer, 3U, "%d", -1000); + REQUIRE(!strcmp(buffer, "-1")); +} + +static void vprintf_builder_1(char* buffer, ...) +{ + va_list args; + va_start(args, buffer); + test::vprintf("%d", args); + va_end(args); +} + +static void vsnprintf_builder_1(char* buffer, ...) +{ + va_list args; + va_start(args, buffer); + test::vsnprintf(buffer, 100U, "%d", args); + va_end(args); +} + +static void vsnprintf_builder_3(char* buffer, ...) +{ + va_list args; + va_start(args, buffer); + test::vsnprintf(buffer, 100U, "%d %d %s", args); + va_end(args); +} + + +TEST_CASE("vprintf", "[]" ) { + char buffer[100]; + printf_idx = 0U; + memset(printf_buffer, 0xCC, 100U); + vprintf_builder_1(buffer, 2345); + REQUIRE(printf_buffer[4] == (char)0xCC); + printf_buffer[4] = 0; + REQUIRE(!strcmp(printf_buffer, "2345")); +} + + +TEST_CASE("vsnprintf", "[]" ) { + char buffer[100]; + + vsnprintf_builder_1(buffer, -1); + REQUIRE(!strcmp(buffer, "-1")); + + vsnprintf_builder_3(buffer, 3, -1000, "test"); + REQUIRE(!strcmp(buffer, "3 -1000 test")); +} + + +TEST_CASE("space flag", "[]" ) { + char buffer[100]; + + test::sprintf(buffer, "% d", 42); + REQUIRE(!strcmp(buffer, " 42")); + + test::sprintf(buffer, "% d", -42); + REQUIRE(!strcmp(buffer, "-42")); + + test::sprintf(buffer, "% 5d", 42); + REQUIRE(!strcmp(buffer, " 42")); + + test::sprintf(buffer, "% 5d", -42); + REQUIRE(!strcmp(buffer, " -42")); + + test::sprintf(buffer, "% 15d", 42); + REQUIRE(!strcmp(buffer, " 42")); + + test::sprintf(buffer, "% 15d", -42); + REQUIRE(!strcmp(buffer, " -42")); + + test::sprintf(buffer, "% 15d", -42); + REQUIRE(!strcmp(buffer, " -42")); + + test::sprintf(buffer, "% 15.3f", -42.987); + REQUIRE(!strcmp(buffer, " -42.987")); + + test::sprintf(buffer, "% 15.3f", 42.987); + REQUIRE(!strcmp(buffer, " 42.987")); + + test::sprintf(buffer, "% s", "Hello testing"); + REQUIRE(!strcmp(buffer, "Hello testing")); + + test::sprintf(buffer, "% d", 1024); + REQUIRE(!strcmp(buffer, " 1024")); + + test::sprintf(buffer, "% d", -1024); + REQUIRE(!strcmp(buffer, "-1024")); + + test::sprintf(buffer, "% i", 1024); + REQUIRE(!strcmp(buffer, " 1024")); + + test::sprintf(buffer, "% i", -1024); + REQUIRE(!strcmp(buffer, "-1024")); + + test::sprintf(buffer, "% u", 1024); + REQUIRE(!strcmp(buffer, "1024")); + + test::sprintf(buffer, "% u", 4294966272U); + REQUIRE(!strcmp(buffer, "4294966272")); + + test::sprintf(buffer, "% o", 511); + REQUIRE(!strcmp(buffer, "777")); + + test::sprintf(buffer, "% o", 4294966785U); + REQUIRE(!strcmp(buffer, "37777777001")); + + test::sprintf(buffer, "% x", 305441741); + REQUIRE(!strcmp(buffer, "1234abcd")); + + test::sprintf(buffer, "% x", 3989525555U); + REQUIRE(!strcmp(buffer, "edcb5433")); + + test::sprintf(buffer, "% X", 305441741); + REQUIRE(!strcmp(buffer, "1234ABCD")); + + test::sprintf(buffer, "% X", 3989525555U); + REQUIRE(!strcmp(buffer, "EDCB5433")); + + test::sprintf(buffer, "% c", 'x'); + REQUIRE(!strcmp(buffer, "x")); +} + + +TEST_CASE("+ flag", "[]" ) { + char buffer[100]; + + test::sprintf(buffer, "%+d", 42); + REQUIRE(!strcmp(buffer, "+42")); + + test::sprintf(buffer, "%+d", -42); + REQUIRE(!strcmp(buffer, "-42")); + + test::sprintf(buffer, "%+5d", 42); + REQUIRE(!strcmp(buffer, " +42")); + + test::sprintf(buffer, "%+5d", -42); + REQUIRE(!strcmp(buffer, " -42")); + + test::sprintf(buffer, "%+15d", 42); + REQUIRE(!strcmp(buffer, " +42")); + + test::sprintf(buffer, "%+15d", -42); + REQUIRE(!strcmp(buffer, " -42")); + + test::sprintf(buffer, "%+s", "Hello testing"); + REQUIRE(!strcmp(buffer, "Hello testing")); + + test::sprintf(buffer, "%+d", 1024); + REQUIRE(!strcmp(buffer, "+1024")); + + test::sprintf(buffer, "%+d", -1024); + REQUIRE(!strcmp(buffer, "-1024")); + + test::sprintf(buffer, "%+i", 1024); + REQUIRE(!strcmp(buffer, "+1024")); + + test::sprintf(buffer, "%+i", -1024); + REQUIRE(!strcmp(buffer, "-1024")); + + test::sprintf(buffer, "%+u", 1024); + REQUIRE(!strcmp(buffer, "1024")); + + test::sprintf(buffer, "%+u", 4294966272U); + REQUIRE(!strcmp(buffer, "4294966272")); + + test::sprintf(buffer, "%+o", 511); + REQUIRE(!strcmp(buffer, "777")); + + test::sprintf(buffer, "%+o", 4294966785U); + REQUIRE(!strcmp(buffer, "37777777001")); + + test::sprintf(buffer, "%+x", 305441741); + REQUIRE(!strcmp(buffer, "1234abcd")); + + test::sprintf(buffer, "%+x", 3989525555U); + REQUIRE(!strcmp(buffer, "edcb5433")); + + test::sprintf(buffer, "%+X", 305441741); + REQUIRE(!strcmp(buffer, "1234ABCD")); + + test::sprintf(buffer, "%+X", 3989525555U); + REQUIRE(!strcmp(buffer, "EDCB5433")); + + test::sprintf(buffer, "%+c", 'x'); + REQUIRE(!strcmp(buffer, "x")); + + test::sprintf(buffer, "%+.0d", 0); + REQUIRE(!strcmp(buffer, "+")); +} + + +TEST_CASE("0 flag", "[]" ) { + char buffer[100]; + + test::sprintf(buffer, "%0d", 42); + REQUIRE(!strcmp(buffer, "42")); + + test::sprintf(buffer, "%0ld", 42L); + REQUIRE(!strcmp(buffer, "42")); + + test::sprintf(buffer, "%0d", -42); + REQUIRE(!strcmp(buffer, "-42")); + + test::sprintf(buffer, "%05d", 42); + REQUIRE(!strcmp(buffer, "00042")); + + test::sprintf(buffer, "%05d", -42); + REQUIRE(!strcmp(buffer, "-0042")); + + test::sprintf(buffer, "%015d", 42); + REQUIRE(!strcmp(buffer, "000000000000042")); + + test::sprintf(buffer, "%015d", -42); + REQUIRE(!strcmp(buffer, "-00000000000042")); + + test::sprintf(buffer, "%015.2f", 42.1234); + REQUIRE(!strcmp(buffer, "000000000042.12")); + + test::sprintf(buffer, "%015.3f", 42.9876); + REQUIRE(!strcmp(buffer, "00000000042.988")); + + test::sprintf(buffer, "%015.5f", -42.9876); + REQUIRE(!strcmp(buffer, "-00000042.98760")); +} + + +TEST_CASE("- flag", "[]" ) { + char buffer[100]; + + test::sprintf(buffer, "%-d", 42); + REQUIRE(!strcmp(buffer, "42")); + + test::sprintf(buffer, "%-d", -42); + REQUIRE(!strcmp(buffer, "-42")); + + test::sprintf(buffer, "%-5d", 42); + REQUIRE(!strcmp(buffer, "42 ")); + + test::sprintf(buffer, "%-5d", -42); + REQUIRE(!strcmp(buffer, "-42 ")); + + test::sprintf(buffer, "%-15d", 42); + REQUIRE(!strcmp(buffer, "42 ")); + + test::sprintf(buffer, "%-15d", -42); + REQUIRE(!strcmp(buffer, "-42 ")); + + test::sprintf(buffer, "%-0d", 42); + REQUIRE(!strcmp(buffer, "42")); + + test::sprintf(buffer, "%-0d", -42); + REQUIRE(!strcmp(buffer, "-42")); + + test::sprintf(buffer, "%-05d", 42); + REQUIRE(!strcmp(buffer, "42 ")); + + test::sprintf(buffer, "%-05d", -42); + REQUIRE(!strcmp(buffer, "-42 ")); + + test::sprintf(buffer, "%-015d", 42); + REQUIRE(!strcmp(buffer, "42 ")); + + test::sprintf(buffer, "%-015d", -42); + REQUIRE(!strcmp(buffer, "-42 ")); + + test::sprintf(buffer, "%0-d", 42); + REQUIRE(!strcmp(buffer, "42")); + + test::sprintf(buffer, "%0-d", -42); + REQUIRE(!strcmp(buffer, "-42")); + + test::sprintf(buffer, "%0-5d", 42); + REQUIRE(!strcmp(buffer, "42 ")); + + test::sprintf(buffer, "%0-5d", -42); + REQUIRE(!strcmp(buffer, "-42 ")); + + test::sprintf(buffer, "%0-15d", 42); + REQUIRE(!strcmp(buffer, "42 ")); + + test::sprintf(buffer, "%0-15d", -42); + REQUIRE(!strcmp(buffer, "-42 ")); + + test::sprintf(buffer, "%0-15.3e", -42.); +#ifndef PRINTF_DISABLE_SUPPORT_EXPONENTIAL + REQUIRE(!strcmp(buffer, "-4.200e+01 ")); +#else + REQUIRE(!strcmp(buffer, "e")); +#endif + + test::sprintf(buffer, "%0-15.3g", -42.); +#ifndef PRINTF_DISABLE_SUPPORT_EXPONENTIAL + REQUIRE(!strcmp(buffer, "-42.0 ")); +#else + REQUIRE(!strcmp(buffer, "g")); +#endif +} + + +TEST_CASE("# flag", "[]" ) { + char buffer[100]; + + test::sprintf(buffer, "%#.0x", 0); + REQUIRE(!strcmp(buffer, "")); + test::sprintf(buffer, "%#.1x", 0); + REQUIRE(!strcmp(buffer, "0")); + test::sprintf(buffer, "%#.0llx", (long long)0); + REQUIRE(!strcmp(buffer, "")); + test::sprintf(buffer, "%#.8x", 0x614e); + REQUIRE(!strcmp(buffer, "0x0000614e")); + test::sprintf(buffer,"%#b", 6); + REQUIRE(!strcmp(buffer, "0b110")); +} + + +TEST_CASE("specifier", "[]" ) { + char buffer[100]; + + test::sprintf(buffer, "Hello testing"); + REQUIRE(!strcmp(buffer, "Hello testing")); + + test::sprintf(buffer, "%s", "Hello testing"); + REQUIRE(!strcmp(buffer, "Hello testing")); + + test::sprintf(buffer, "%d", 1024); + REQUIRE(!strcmp(buffer, "1024")); + + test::sprintf(buffer, "%d", -1024); + REQUIRE(!strcmp(buffer, "-1024")); + + test::sprintf(buffer, "%i", 1024); + REQUIRE(!strcmp(buffer, "1024")); + + test::sprintf(buffer, "%i", -1024); + REQUIRE(!strcmp(buffer, "-1024")); + + test::sprintf(buffer, "%u", 1024); + REQUIRE(!strcmp(buffer, "1024")); + + test::sprintf(buffer, "%u", 4294966272U); + REQUIRE(!strcmp(buffer, "4294966272")); + + test::sprintf(buffer, "%o", 511); + REQUIRE(!strcmp(buffer, "777")); + + test::sprintf(buffer, "%o", 4294966785U); + REQUIRE(!strcmp(buffer, "37777777001")); + + test::sprintf(buffer, "%x", 305441741); + REQUIRE(!strcmp(buffer, "1234abcd")); + + test::sprintf(buffer, "%x", 3989525555U); + REQUIRE(!strcmp(buffer, "edcb5433")); + + test::sprintf(buffer, "%X", 305441741); + REQUIRE(!strcmp(buffer, "1234ABCD")); + + test::sprintf(buffer, "%X", 3989525555U); + REQUIRE(!strcmp(buffer, "EDCB5433")); + + test::sprintf(buffer, "%%"); + REQUIRE(!strcmp(buffer, "%")); +} + + +TEST_CASE("width", "[]" ) { + char buffer[100]; + + test::sprintf(buffer, "%1s", "Hello testing"); + REQUIRE(!strcmp(buffer, "Hello testing")); + + test::sprintf(buffer, "%1d", 1024); + REQUIRE(!strcmp(buffer, "1024")); + + test::sprintf(buffer, "%1d", -1024); + REQUIRE(!strcmp(buffer, "-1024")); + + test::sprintf(buffer, "%1i", 1024); + REQUIRE(!strcmp(buffer, "1024")); + + test::sprintf(buffer, "%1i", -1024); + REQUIRE(!strcmp(buffer, "-1024")); + + test::sprintf(buffer, "%1u", 1024); + REQUIRE(!strcmp(buffer, "1024")); + + test::sprintf(buffer, "%1u", 4294966272U); + REQUIRE(!strcmp(buffer, "4294966272")); + + test::sprintf(buffer, "%1o", 511); + REQUIRE(!strcmp(buffer, "777")); + + test::sprintf(buffer, "%1o", 4294966785U); + REQUIRE(!strcmp(buffer, "37777777001")); + + test::sprintf(buffer, "%1x", 305441741); + REQUIRE(!strcmp(buffer, "1234abcd")); + + test::sprintf(buffer, "%1x", 3989525555U); + REQUIRE(!strcmp(buffer, "edcb5433")); + + test::sprintf(buffer, "%1X", 305441741); + REQUIRE(!strcmp(buffer, "1234ABCD")); + + test::sprintf(buffer, "%1X", 3989525555U); + REQUIRE(!strcmp(buffer, "EDCB5433")); + + test::sprintf(buffer, "%1c", 'x'); + REQUIRE(!strcmp(buffer, "x")); +} + + +TEST_CASE("width 20", "[]" ) { + char buffer[100]; + + test::sprintf(buffer, "%20s", "Hello"); + REQUIRE(!strcmp(buffer, " Hello")); + + test::sprintf(buffer, "%20d", 1024); + REQUIRE(!strcmp(buffer, " 1024")); + + test::sprintf(buffer, "%20d", -1024); + REQUIRE(!strcmp(buffer, " -1024")); + + test::sprintf(buffer, "%20i", 1024); + REQUIRE(!strcmp(buffer, " 1024")); + + test::sprintf(buffer, "%20i", -1024); + REQUIRE(!strcmp(buffer, " -1024")); + + test::sprintf(buffer, "%20u", 1024); + REQUIRE(!strcmp(buffer, " 1024")); + + test::sprintf(buffer, "%20u", 4294966272U); + REQUIRE(!strcmp(buffer, " 4294966272")); + + test::sprintf(buffer, "%20o", 511); + REQUIRE(!strcmp(buffer, " 777")); + + test::sprintf(buffer, "%20o", 4294966785U); + REQUIRE(!strcmp(buffer, " 37777777001")); + + test::sprintf(buffer, "%20x", 305441741); + REQUIRE(!strcmp(buffer, " 1234abcd")); + + test::sprintf(buffer, "%20x", 3989525555U); + REQUIRE(!strcmp(buffer, " edcb5433")); + + test::sprintf(buffer, "%20X", 305441741); + REQUIRE(!strcmp(buffer, " 1234ABCD")); + + test::sprintf(buffer, "%20X", 3989525555U); + REQUIRE(!strcmp(buffer, " EDCB5433")); + + test::sprintf(buffer, "%20c", 'x'); + REQUIRE(!strcmp(buffer, " x")); +} + + +TEST_CASE("width *20", "[]" ) { + char buffer[100]; + + test::sprintf(buffer, "%*s", 20, "Hello"); + REQUIRE(!strcmp(buffer, " Hello")); + + test::sprintf(buffer, "%*d", 20, 1024); + REQUIRE(!strcmp(buffer, " 1024")); + + test::sprintf(buffer, "%*d", 20, -1024); + REQUIRE(!strcmp(buffer, " -1024")); + + test::sprintf(buffer, "%*i", 20, 1024); + REQUIRE(!strcmp(buffer, " 1024")); + + test::sprintf(buffer, "%*i", 20, -1024); + REQUIRE(!strcmp(buffer, " -1024")); + + test::sprintf(buffer, "%*u", 20, 1024); + REQUIRE(!strcmp(buffer, " 1024")); + + test::sprintf(buffer, "%*u", 20, 4294966272U); + REQUIRE(!strcmp(buffer, " 4294966272")); + + test::sprintf(buffer, "%*o", 20, 511); + REQUIRE(!strcmp(buffer, " 777")); + + test::sprintf(buffer, "%*o", 20, 4294966785U); + REQUIRE(!strcmp(buffer, " 37777777001")); + + test::sprintf(buffer, "%*x", 20, 305441741); + REQUIRE(!strcmp(buffer, " 1234abcd")); + + test::sprintf(buffer, "%*x", 20, 3989525555U); + REQUIRE(!strcmp(buffer, " edcb5433")); + + test::sprintf(buffer, "%*X", 20, 305441741); + REQUIRE(!strcmp(buffer, " 1234ABCD")); + + test::sprintf(buffer, "%*X", 20, 3989525555U); + REQUIRE(!strcmp(buffer, " EDCB5433")); + + test::sprintf(buffer, "%*c", 20,'x'); + REQUIRE(!strcmp(buffer, " x")); +} + + +TEST_CASE("width -20", "[]" ) { + char buffer[100]; + + test::sprintf(buffer, "%-20s", "Hello"); + REQUIRE(!strcmp(buffer, "Hello ")); + + test::sprintf(buffer, "%-20d", 1024); + REQUIRE(!strcmp(buffer, "1024 ")); + + test::sprintf(buffer, "%-20d", -1024); + REQUIRE(!strcmp(buffer, "-1024 ")); + + test::sprintf(buffer, "%-20i", 1024); + REQUIRE(!strcmp(buffer, "1024 ")); + + test::sprintf(buffer, "%-20i", -1024); + REQUIRE(!strcmp(buffer, "-1024 ")); + + test::sprintf(buffer, "%-20u", 1024); + REQUIRE(!strcmp(buffer, "1024 ")); + + test::sprintf(buffer, "%-20.4f", 1024.1234); + REQUIRE(!strcmp(buffer, "1024.1234 ")); + + test::sprintf(buffer, "%-20u", 4294966272U); + REQUIRE(!strcmp(buffer, "4294966272 ")); + + test::sprintf(buffer, "%-20o", 511); + REQUIRE(!strcmp(buffer, "777 ")); + + test::sprintf(buffer, "%-20o", 4294966785U); + REQUIRE(!strcmp(buffer, "37777777001 ")); + + test::sprintf(buffer, "%-20x", 305441741); + REQUIRE(!strcmp(buffer, "1234abcd ")); + + test::sprintf(buffer, "%-20x", 3989525555U); + REQUIRE(!strcmp(buffer, "edcb5433 ")); + + test::sprintf(buffer, "%-20X", 305441741); + REQUIRE(!strcmp(buffer, "1234ABCD ")); + + test::sprintf(buffer, "%-20X", 3989525555U); + REQUIRE(!strcmp(buffer, "EDCB5433 ")); + + test::sprintf(buffer, "%-20c", 'x'); + REQUIRE(!strcmp(buffer, "x ")); + + test::sprintf(buffer, "|%5d| |%-2d| |%5d|", 9, 9, 9); + REQUIRE(!strcmp(buffer, "| 9| |9 | | 9|")); + + test::sprintf(buffer, "|%5d| |%-2d| |%5d|", 10, 10, 10); + REQUIRE(!strcmp(buffer, "| 10| |10| | 10|")); + + test::sprintf(buffer, "|%5d| |%-12d| |%5d|", 9, 9, 9); + REQUIRE(!strcmp(buffer, "| 9| |9 | | 9|")); + + test::sprintf(buffer, "|%5d| |%-12d| |%5d|", 10, 10, 10); + REQUIRE(!strcmp(buffer, "| 10| |10 | | 10|")); +} + + +TEST_CASE("width 0-20", "[]" ) { + char buffer[100]; + + test::sprintf(buffer, "%0-20s", "Hello"); + REQUIRE(!strcmp(buffer, "Hello ")); + + test::sprintf(buffer, "%0-20d", 1024); + REQUIRE(!strcmp(buffer, "1024 ")); + + test::sprintf(buffer, "%0-20d", -1024); + REQUIRE(!strcmp(buffer, "-1024 ")); + + test::sprintf(buffer, "%0-20i", 1024); + REQUIRE(!strcmp(buffer, "1024 ")); + + test::sprintf(buffer, "%0-20i", -1024); + REQUIRE(!strcmp(buffer, "-1024 ")); + + test::sprintf(buffer, "%0-20u", 1024); + REQUIRE(!strcmp(buffer, "1024 ")); + + test::sprintf(buffer, "%0-20u", 4294966272U); + REQUIRE(!strcmp(buffer, "4294966272 ")); + + test::sprintf(buffer, "%0-20o", 511); + REQUIRE(!strcmp(buffer, "777 ")); + + test::sprintf(buffer, "%0-20o", 4294966785U); + REQUIRE(!strcmp(buffer, "37777777001 ")); + + test::sprintf(buffer, "%0-20x", 305441741); + REQUIRE(!strcmp(buffer, "1234abcd ")); + + test::sprintf(buffer, "%0-20x", 3989525555U); + REQUIRE(!strcmp(buffer, "edcb5433 ")); + + test::sprintf(buffer, "%0-20X", 305441741); + REQUIRE(!strcmp(buffer, "1234ABCD ")); + + test::sprintf(buffer, "%0-20X", 3989525555U); + REQUIRE(!strcmp(buffer, "EDCB5433 ")); + + test::sprintf(buffer, "%0-20c", 'x'); + REQUIRE(!strcmp(buffer, "x ")); +} + + +TEST_CASE("padding 20", "[]" ) { + char buffer[100]; + + test::sprintf(buffer, "%020d", 1024); + REQUIRE(!strcmp(buffer, "00000000000000001024")); + + test::sprintf(buffer, "%020d", -1024); + REQUIRE(!strcmp(buffer, "-0000000000000001024")); + + test::sprintf(buffer, "%020i", 1024); + REQUIRE(!strcmp(buffer, "00000000000000001024")); + + test::sprintf(buffer, "%020i", -1024); + REQUIRE(!strcmp(buffer, "-0000000000000001024")); + + test::sprintf(buffer, "%020u", 1024); + REQUIRE(!strcmp(buffer, "00000000000000001024")); + + test::sprintf(buffer, "%020u", 4294966272U); + REQUIRE(!strcmp(buffer, "00000000004294966272")); + + test::sprintf(buffer, "%020o", 511); + REQUIRE(!strcmp(buffer, "00000000000000000777")); + + test::sprintf(buffer, "%020o", 4294966785U); + REQUIRE(!strcmp(buffer, "00000000037777777001")); + + test::sprintf(buffer, "%020x", 305441741); + REQUIRE(!strcmp(buffer, "0000000000001234abcd")); + + test::sprintf(buffer, "%020x", 3989525555U); + REQUIRE(!strcmp(buffer, "000000000000edcb5433")); + + test::sprintf(buffer, "%020X", 305441741); + REQUIRE(!strcmp(buffer, "0000000000001234ABCD")); + + test::sprintf(buffer, "%020X", 3989525555U); + REQUIRE(!strcmp(buffer, "000000000000EDCB5433")); +} + + +TEST_CASE("padding .20", "[]" ) { + char buffer[100]; + + test::sprintf(buffer, "%.20d", 1024); + REQUIRE(!strcmp(buffer, "00000000000000001024")); + + test::sprintf(buffer, "%.20d", -1024); + REQUIRE(!strcmp(buffer, "-00000000000000001024")); + + test::sprintf(buffer, "%.20i", 1024); + REQUIRE(!strcmp(buffer, "00000000000000001024")); + + test::sprintf(buffer, "%.20i", -1024); + REQUIRE(!strcmp(buffer, "-00000000000000001024")); + + test::sprintf(buffer, "%.20u", 1024); + REQUIRE(!strcmp(buffer, "00000000000000001024")); + + test::sprintf(buffer, "%.20u", 4294966272U); + REQUIRE(!strcmp(buffer, "00000000004294966272")); + + test::sprintf(buffer, "%.20o", 511); + REQUIRE(!strcmp(buffer, "00000000000000000777")); + + test::sprintf(buffer, "%.20o", 4294966785U); + REQUIRE(!strcmp(buffer, "00000000037777777001")); + + test::sprintf(buffer, "%.20x", 305441741); + REQUIRE(!strcmp(buffer, "0000000000001234abcd")); + + test::sprintf(buffer, "%.20x", 3989525555U); + REQUIRE(!strcmp(buffer, "000000000000edcb5433")); + + test::sprintf(buffer, "%.20X", 305441741); + REQUIRE(!strcmp(buffer, "0000000000001234ABCD")); + + test::sprintf(buffer, "%.20X", 3989525555U); + REQUIRE(!strcmp(buffer, "000000000000EDCB5433")); +} + + +TEST_CASE("padding #020", "[]" ) { + char buffer[100]; + + test::sprintf(buffer, "%#020d", 1024); + REQUIRE(!strcmp(buffer, "00000000000000001024")); + + test::sprintf(buffer, "%#020d", -1024); + REQUIRE(!strcmp(buffer, "-0000000000000001024")); + + test::sprintf(buffer, "%#020i", 1024); + REQUIRE(!strcmp(buffer, "00000000000000001024")); + + test::sprintf(buffer, "%#020i", -1024); + REQUIRE(!strcmp(buffer, "-0000000000000001024")); + + test::sprintf(buffer, "%#020u", 1024); + REQUIRE(!strcmp(buffer, "00000000000000001024")); + + test::sprintf(buffer, "%#020u", 4294966272U); + REQUIRE(!strcmp(buffer, "00000000004294966272")); + + test::sprintf(buffer, "%#020o", 511); + REQUIRE(!strcmp(buffer, "00000000000000000777")); + + test::sprintf(buffer, "%#020o", 4294966785U); + REQUIRE(!strcmp(buffer, "00000000037777777001")); + + test::sprintf(buffer, "%#020x", 305441741); + REQUIRE(!strcmp(buffer, "0x00000000001234abcd")); + + test::sprintf(buffer, "%#020x", 3989525555U); + REQUIRE(!strcmp(buffer, "0x0000000000edcb5433")); + + test::sprintf(buffer, "%#020X", 305441741); + REQUIRE(!strcmp(buffer, "0X00000000001234ABCD")); + + test::sprintf(buffer, "%#020X", 3989525555U); + REQUIRE(!strcmp(buffer, "0X0000000000EDCB5433")); +} + + +TEST_CASE("padding #20", "[]" ) { + char buffer[100]; + + test::sprintf(buffer, "%#20d", 1024); + REQUIRE(!strcmp(buffer, " 1024")); + + test::sprintf(buffer, "%#20d", -1024); + REQUIRE(!strcmp(buffer, " -1024")); + + test::sprintf(buffer, "%#20i", 1024); + REQUIRE(!strcmp(buffer, " 1024")); + + test::sprintf(buffer, "%#20i", -1024); + REQUIRE(!strcmp(buffer, " -1024")); + + test::sprintf(buffer, "%#20u", 1024); + REQUIRE(!strcmp(buffer, " 1024")); + + test::sprintf(buffer, "%#20u", 4294966272U); + REQUIRE(!strcmp(buffer, " 4294966272")); + + test::sprintf(buffer, "%#20o", 511); + REQUIRE(!strcmp(buffer, " 0777")); + + test::sprintf(buffer, "%#20o", 4294966785U); + REQUIRE(!strcmp(buffer, " 037777777001")); + + test::sprintf(buffer, "%#20x", 305441741); + REQUIRE(!strcmp(buffer, " 0x1234abcd")); + + test::sprintf(buffer, "%#20x", 3989525555U); + REQUIRE(!strcmp(buffer, " 0xedcb5433")); + + test::sprintf(buffer, "%#20X", 305441741); + REQUIRE(!strcmp(buffer, " 0X1234ABCD")); + + test::sprintf(buffer, "%#20X", 3989525555U); + REQUIRE(!strcmp(buffer, " 0XEDCB5433")); +} + + +TEST_CASE("padding 20.5", "[]" ) { + char buffer[100]; + + test::sprintf(buffer, "%20.5d", 1024); + REQUIRE(!strcmp(buffer, " 01024")); + + test::sprintf(buffer, "%20.5d", -1024); + REQUIRE(!strcmp(buffer, " -01024")); + + test::sprintf(buffer, "%20.5i", 1024); + REQUIRE(!strcmp(buffer, " 01024")); + + test::sprintf(buffer, "%20.5i", -1024); + REQUIRE(!strcmp(buffer, " -01024")); + + test::sprintf(buffer, "%20.5u", 1024); + REQUIRE(!strcmp(buffer, " 01024")); + + test::sprintf(buffer, "%20.5u", 4294966272U); + REQUIRE(!strcmp(buffer, " 4294966272")); + + test::sprintf(buffer, "%20.5o", 511); + REQUIRE(!strcmp(buffer, " 00777")); + + test::sprintf(buffer, "%20.5o", 4294966785U); + REQUIRE(!strcmp(buffer, " 37777777001")); + + test::sprintf(buffer, "%20.5x", 305441741); + REQUIRE(!strcmp(buffer, " 1234abcd")); + + test::sprintf(buffer, "%20.10x", 3989525555U); + REQUIRE(!strcmp(buffer, " 00edcb5433")); + + test::sprintf(buffer, "%20.5X", 305441741); + REQUIRE(!strcmp(buffer, " 1234ABCD")); + + test::sprintf(buffer, "%20.10X", 3989525555U); + REQUIRE(!strcmp(buffer, " 00EDCB5433")); +} + + +TEST_CASE("padding neg numbers", "[]" ) { + char buffer[100]; + + // space padding + test::sprintf(buffer, "% 1d", -5); + REQUIRE(!strcmp(buffer, "-5")); + + test::sprintf(buffer, "% 2d", -5); + REQUIRE(!strcmp(buffer, "-5")); + + test::sprintf(buffer, "% 3d", -5); + REQUIRE(!strcmp(buffer, " -5")); + + test::sprintf(buffer, "% 4d", -5); + REQUIRE(!strcmp(buffer, " -5")); + + // zero padding + test::sprintf(buffer, "%01d", -5); + REQUIRE(!strcmp(buffer, "-5")); + + test::sprintf(buffer, "%02d", -5); + REQUIRE(!strcmp(buffer, "-5")); + + test::sprintf(buffer, "%03d", -5); + REQUIRE(!strcmp(buffer, "-05")); + + test::sprintf(buffer, "%04d", -5); + REQUIRE(!strcmp(buffer, "-005")); +} + + +TEST_CASE("float padding neg numbers", "[]" ) { + char buffer[100]; + + // space padding + test::sprintf(buffer, "% 3.1f", -5.); + REQUIRE(!strcmp(buffer, "-5.0")); + + test::sprintf(buffer, "% 4.1f", -5.); + REQUIRE(!strcmp(buffer, "-5.0")); + + test::sprintf(buffer, "% 5.1f", -5.); + REQUIRE(!strcmp(buffer, " -5.0")); + +#ifndef PRINTF_DISABLE_SUPPORT_EXPONENTIAL + test::sprintf(buffer, "% 6.1g", -5.); + REQUIRE(!strcmp(buffer, " -5")); + + test::sprintf(buffer, "% 6.1e", -5.); + REQUIRE(!strcmp(buffer, "-5.0e+00")); + + test::sprintf(buffer, "% 10.1e", -5.); + REQUIRE(!strcmp(buffer, " -5.0e+00")); +#endif + + // zero padding + test::sprintf(buffer, "%03.1f", -5.); + REQUIRE(!strcmp(buffer, "-5.0")); + + test::sprintf(buffer, "%04.1f", -5.); + REQUIRE(!strcmp(buffer, "-5.0")); + + test::sprintf(buffer, "%05.1f", -5.); + REQUIRE(!strcmp(buffer, "-05.0")); + + // zero padding no decimal point + test::sprintf(buffer, "%01.0f", -5.); + REQUIRE(!strcmp(buffer, "-5")); + + test::sprintf(buffer, "%02.0f", -5.); + REQUIRE(!strcmp(buffer, "-5")); + + test::sprintf(buffer, "%03.0f", -5.); + REQUIRE(!strcmp(buffer, "-05")); + +#ifndef PRINTF_DISABLE_SUPPORT_EXPONENTIAL + test::sprintf(buffer, "%010.1e", -5.); + REQUIRE(!strcmp(buffer, "-005.0e+00")); + + test::sprintf(buffer, "%07.0E", -5.); + REQUIRE(!strcmp(buffer, "-05E+00")); + + test::sprintf(buffer, "%03.0g", -5.); + REQUIRE(!strcmp(buffer, "-05")); +#endif +} + +TEST_CASE("length", "[]" ) { + char buffer[100]; + + test::sprintf(buffer, "%.0s", "Hello testing"); + REQUIRE(!strcmp(buffer, "")); + + test::sprintf(buffer, "%20.0s", "Hello testing"); + REQUIRE(!strcmp(buffer, " ")); + + test::sprintf(buffer, "%.s", "Hello testing"); + REQUIRE(!strcmp(buffer, "")); + + test::sprintf(buffer, "%20.s", "Hello testing"); + REQUIRE(!strcmp(buffer, " ")); + + test::sprintf(buffer, "%20.0d", 1024); + REQUIRE(!strcmp(buffer, " 1024")); + + test::sprintf(buffer, "%20.0d", -1024); + REQUIRE(!strcmp(buffer, " -1024")); + + test::sprintf(buffer, "%20.d", 0); + REQUIRE(!strcmp(buffer, " ")); + + test::sprintf(buffer, "%20.0i", 1024); + REQUIRE(!strcmp(buffer, " 1024")); + + test::sprintf(buffer, "%20.i", -1024); + REQUIRE(!strcmp(buffer, " -1024")); + + test::sprintf(buffer, "%20.i", 0); + REQUIRE(!strcmp(buffer, " ")); + + test::sprintf(buffer, "%20.u", 1024); + REQUIRE(!strcmp(buffer, " 1024")); + + test::sprintf(buffer, "%20.0u", 4294966272U); + REQUIRE(!strcmp(buffer, " 4294966272")); + + test::sprintf(buffer, "%20.u", 0U); + REQUIRE(!strcmp(buffer, " ")); + + test::sprintf(buffer, "%20.o", 511); + REQUIRE(!strcmp(buffer, " 777")); + + test::sprintf(buffer, "%20.0o", 4294966785U); + REQUIRE(!strcmp(buffer, " 37777777001")); + + test::sprintf(buffer, "%20.o", 0U); + REQUIRE(!strcmp(buffer, " ")); + + test::sprintf(buffer, "%20.x", 305441741); + REQUIRE(!strcmp(buffer, " 1234abcd")); + + test::sprintf(buffer, "%50.x", 305441741); + REQUIRE(!strcmp(buffer, " 1234abcd")); + + test::sprintf(buffer, "%50.x%10.u", 305441741, 12345); + REQUIRE(!strcmp(buffer, " 1234abcd 12345")); + + test::sprintf(buffer, "%20.0x", 3989525555U); + REQUIRE(!strcmp(buffer, " edcb5433")); + + test::sprintf(buffer, "%20.x", 0U); + REQUIRE(!strcmp(buffer, " ")); + + test::sprintf(buffer, "%20.X", 305441741); + REQUIRE(!strcmp(buffer, " 1234ABCD")); + + test::sprintf(buffer, "%20.0X", 3989525555U); + REQUIRE(!strcmp(buffer, " EDCB5433")); + + test::sprintf(buffer, "%20.X", 0U); + REQUIRE(!strcmp(buffer, " ")); + + test::sprintf(buffer, "%02.0u", 0U); + REQUIRE(!strcmp(buffer, " ")); + + test::sprintf(buffer, "%02.0d", 0); + REQUIRE(!strcmp(buffer, " ")); +} + + +TEST_CASE("float", "[]" ) { + char buffer[100]; + + // test special-case floats using math.h macros + test::sprintf(buffer, "%8f", NAN); + REQUIRE(!strcmp(buffer, " nan")); + + test::sprintf(buffer, "%8f", INFINITY); + REQUIRE(!strcmp(buffer, " inf")); + + test::sprintf(buffer, "%-8f", -INFINITY); + REQUIRE(!strcmp(buffer, "-inf ")); + +#ifndef PRINTF_DISABLE_SUPPORT_EXPONENTIAL + test::sprintf(buffer, "%+8e", INFINITY); + REQUIRE(!strcmp(buffer, " +inf")); +#endif + + test::sprintf(buffer, "%.4f", 3.1415354); + REQUIRE(!strcmp(buffer, "3.1415")); + + test::sprintf(buffer, "%.3f", 30343.1415354); + REQUIRE(!strcmp(buffer, "30343.142")); + + test::sprintf(buffer, "%.0f", 34.1415354); + REQUIRE(!strcmp(buffer, "34")); + + test::sprintf(buffer, "%.0f", 1.3); + REQUIRE(!strcmp(buffer, "1")); + + test::sprintf(buffer, "%.0f", 1.55); + REQUIRE(!strcmp(buffer, "2")); + + test::sprintf(buffer, "%.1f", 1.64); + REQUIRE(!strcmp(buffer, "1.6")); + + test::sprintf(buffer, "%.2f", 42.8952); + REQUIRE(!strcmp(buffer, "42.90")); + + test::sprintf(buffer, "%.9f", 42.8952); + REQUIRE(!strcmp(buffer, "42.895200000")); + + test::sprintf(buffer, "%.10f", 42.895223); + REQUIRE(!strcmp(buffer, "42.8952230000")); + + // this testcase checks, that the precision is truncated to 9 digits. + // a perfect working float should return the whole number + test::sprintf(buffer, "%.12f", 42.89522312345678); + REQUIRE(!strcmp(buffer, "42.895223123000")); + + // this testcase checks, that the precision is truncated AND rounded to 9 digits. + // a perfect working float should return the whole number + test::sprintf(buffer, "%.12f", 42.89522387654321); + REQUIRE(!strcmp(buffer, "42.895223877000")); + + test::sprintf(buffer, "%6.2f", 42.8952); + REQUIRE(!strcmp(buffer, " 42.90")); + + test::sprintf(buffer, "%+6.2f", 42.8952); + REQUIRE(!strcmp(buffer, "+42.90")); + + test::sprintf(buffer, "%+5.1f", 42.9252); + REQUIRE(!strcmp(buffer, "+42.9")); + + test::sprintf(buffer, "%f", 42.5); + REQUIRE(!strcmp(buffer, "42.500000")); + + test::sprintf(buffer, "%.1f", 42.5); + REQUIRE(!strcmp(buffer, "42.5")); + + test::sprintf(buffer, "%f", 42167.0); + REQUIRE(!strcmp(buffer, "42167.000000")); + + test::sprintf(buffer, "%.9f", -12345.987654321); + REQUIRE(!strcmp(buffer, "-12345.987654321")); + + test::sprintf(buffer, "%.1f", 3.999); + REQUIRE(!strcmp(buffer, "4.0")); + + test::sprintf(buffer, "%.0f", 3.5); + REQUIRE(!strcmp(buffer, "4")); + + test::sprintf(buffer, "%.0f", 4.5); + REQUIRE(!strcmp(buffer, "4")); + + test::sprintf(buffer, "%.0f", 3.49); + REQUIRE(!strcmp(buffer, "3")); + + test::sprintf(buffer, "%.1f", 3.49); + REQUIRE(!strcmp(buffer, "3.5")); + + test::sprintf(buffer, "a%-5.1f", 0.5); + REQUIRE(!strcmp(buffer, "a0.5 ")); + + test::sprintf(buffer, "a%-5.1fend", 0.5); + REQUIRE(!strcmp(buffer, "a0.5 end")); + +#ifndef PRINTF_DISABLE_SUPPORT_EXPONENTIAL + test::sprintf(buffer, "%G", 12345.678); + REQUIRE(!strcmp(buffer, "12345.7")); + + test::sprintf(buffer, "%.7G", 12345.678); + REQUIRE(!strcmp(buffer, "12345.68")); + + test::sprintf(buffer, "%.5G", 123456789.); + REQUIRE(!strcmp(buffer, "1.2346E+08")); + + test::sprintf(buffer, "%.6G", 12345.); + REQUIRE(!strcmp(buffer, "12345.0")); + + test::sprintf(buffer, "%+12.4g", 123456789.); + REQUIRE(!strcmp(buffer, " +1.235e+08")); + + test::sprintf(buffer, "%.2G", 0.001234); + REQUIRE(!strcmp(buffer, "0.0012")); + + test::sprintf(buffer, "%+10.4G", 0.001234); + REQUIRE(!strcmp(buffer, " +0.001234")); + + test::sprintf(buffer, "%+012.4g", 0.00001234); + REQUIRE(!strcmp(buffer, "+001.234e-05")); + + test::sprintf(buffer, "%.3g", -1.2345e-308); + REQUIRE(!strcmp(buffer, "-1.23e-308")); + + test::sprintf(buffer, "%+.3E", 1.23e+308); + REQUIRE(!strcmp(buffer, "+1.230E+308")); +#endif + + // out of range for float: should switch to exp notation if supported, else empty + test::sprintf(buffer, "%.1f", 1E20); +#ifndef PRINTF_DISABLE_SUPPORT_EXPONENTIAL + REQUIRE(!strcmp(buffer, "1.0e+20")); +#else + REQUIRE(!strcmp(buffer, "")); +#endif + + // brute force float + bool fail = false; + std::stringstream str; + str.precision(5); + for (float i = -100000; i < 100000; i += 1) { + test::sprintf(buffer, "%.5f", i / 10000); + str.str(""); + str << std::fixed << i / 10000; + fail = fail || !!strcmp(buffer, str.str().c_str()); + } + REQUIRE(!fail); + + +#ifndef PRINTF_DISABLE_SUPPORT_EXPONENTIAL + // brute force exp + str.setf(std::ios::scientific, std::ios::floatfield); + for (float i = -1e20; i < 1e20; i += 1e15) { + test::sprintf(buffer, "%.5f", i); + str.str(""); + str << i; + fail = fail || !!strcmp(buffer, str.str().c_str()); + } + REQUIRE(!fail); +#endif +} + + +TEST_CASE("types", "[]" ) { + char buffer[100]; + + test::sprintf(buffer, "%i", 0); + REQUIRE(!strcmp(buffer, "0")); + + test::sprintf(buffer, "%i", 1234); + REQUIRE(!strcmp(buffer, "1234")); + + test::sprintf(buffer, "%i", 32767); + REQUIRE(!strcmp(buffer, "32767")); + + test::sprintf(buffer, "%i", -32767); + REQUIRE(!strcmp(buffer, "-32767")); + + test::sprintf(buffer, "%li", 30L); + REQUIRE(!strcmp(buffer, "30")); + + test::sprintf(buffer, "%li", -2147483647L); + REQUIRE(!strcmp(buffer, "-2147483647")); + + test::sprintf(buffer, "%li", 2147483647L); + REQUIRE(!strcmp(buffer, "2147483647")); + + test::sprintf(buffer, "%lli", 30LL); + REQUIRE(!strcmp(buffer, "30")); + + test::sprintf(buffer, "%lli", -9223372036854775807LL); + REQUIRE(!strcmp(buffer, "-9223372036854775807")); + + test::sprintf(buffer, "%lli", 9223372036854775807LL); + REQUIRE(!strcmp(buffer, "9223372036854775807")); + + test::sprintf(buffer, "%lu", 100000L); + REQUIRE(!strcmp(buffer, "100000")); + + test::sprintf(buffer, "%lu", 0xFFFFFFFFL); + REQUIRE(!strcmp(buffer, "4294967295")); + + test::sprintf(buffer, "%llu", 281474976710656LLU); + REQUIRE(!strcmp(buffer, "281474976710656")); + + test::sprintf(buffer, "%llu", 18446744073709551615LLU); + REQUIRE(!strcmp(buffer, "18446744073709551615")); + + test::sprintf(buffer, "%zu", 2147483647UL); + REQUIRE(!strcmp(buffer, "2147483647")); + + test::sprintf(buffer, "%zd", 2147483647UL); + REQUIRE(!strcmp(buffer, "2147483647")); + + if (sizeof(size_t) == sizeof(long)) { + test::sprintf(buffer, "%zi", -2147483647L); + REQUIRE(!strcmp(buffer, "-2147483647")); + } + else { + test::sprintf(buffer, "%zi", -2147483647LL); + REQUIRE(!strcmp(buffer, "-2147483647")); + } + + test::sprintf(buffer, "%b", 60000); + REQUIRE(!strcmp(buffer, "1110101001100000")); + + test::sprintf(buffer, "%lb", 12345678L); + REQUIRE(!strcmp(buffer, "101111000110000101001110")); + + test::sprintf(buffer, "%o", 60000); + REQUIRE(!strcmp(buffer, "165140")); + + test::sprintf(buffer, "%lo", 12345678L); + REQUIRE(!strcmp(buffer, "57060516")); + + test::sprintf(buffer, "%lx", 0x12345678L); + REQUIRE(!strcmp(buffer, "12345678")); + + test::sprintf(buffer, "%llx", 0x1234567891234567LLU); + REQUIRE(!strcmp(buffer, "1234567891234567")); + + test::sprintf(buffer, "%lx", 0xabcdefabL); + REQUIRE(!strcmp(buffer, "abcdefab")); + + test::sprintf(buffer, "%lX", 0xabcdefabL); + REQUIRE(!strcmp(buffer, "ABCDEFAB")); + + test::sprintf(buffer, "%c", 'v'); + REQUIRE(!strcmp(buffer, "v")); + + test::sprintf(buffer, "%cv", 'w'); + REQUIRE(!strcmp(buffer, "wv")); + + test::sprintf(buffer, "%s", "A Test"); + REQUIRE(!strcmp(buffer, "A Test")); + + test::sprintf(buffer, "%hhu", 0xFFFFUL); + REQUIRE(!strcmp(buffer, "255")); + + test::sprintf(buffer, "%hu", 0x123456UL); + REQUIRE(!strcmp(buffer, "13398")); + + test::sprintf(buffer, "%s%hhi %hu", "Test", 10000, 0xFFFFFFFF); + REQUIRE(!strcmp(buffer, "Test16 65535")); + + test::sprintf(buffer, "%tx", &buffer[10] - &buffer[0]); + REQUIRE(!strcmp(buffer, "a")); + +// TBD + if (sizeof(intmax_t) == sizeof(long)) { + test::sprintf(buffer, "%ji", -2147483647L); + REQUIRE(!strcmp(buffer, "-2147483647")); + } + else { + test::sprintf(buffer, "%ji", -2147483647LL); + REQUIRE(!strcmp(buffer, "-2147483647")); + } +} + + +TEST_CASE("pointer", "[]" ) { + char buffer[100]; + + test::sprintf(buffer, "%p", (void*)0x1234U); + if (sizeof(void*) == 4U) { + REQUIRE(!strcmp(buffer, "00001234")); + } + else { + REQUIRE(!strcmp(buffer, "0000000000001234")); + } + + test::sprintf(buffer, "%p", (void*)0x12345678U); + if (sizeof(void*) == 4U) { + REQUIRE(!strcmp(buffer, "12345678")); + } + else { + REQUIRE(!strcmp(buffer, "0000000012345678")); + } + + test::sprintf(buffer, "%p-%p", (void*)0x12345678U, (void*)0x7EDCBA98U); + if (sizeof(void*) == 4U) { + REQUIRE(!strcmp(buffer, "12345678-7EDCBA98")); + } + else { + REQUIRE(!strcmp(buffer, "0000000012345678-000000007EDCBA98")); + } + + if (sizeof(uintptr_t) == sizeof(uint64_t)) { + test::sprintf(buffer, "%p", (void*)(uintptr_t)0xFFFFFFFFU); + REQUIRE(!strcmp(buffer, "00000000FFFFFFFF")); + } + else { + test::sprintf(buffer, "%p", (void*)(uintptr_t)0xFFFFFFFFU); + REQUIRE(!strcmp(buffer, "FFFFFFFF")); + } +} + + +TEST_CASE("unknown flag", "[]" ) { + char buffer[100]; + + test::sprintf(buffer, "%kmarco", 42, 37); + REQUIRE(!strcmp(buffer, "kmarco")); +} + + +TEST_CASE("string length", "[]" ) { + char buffer[100]; + + test::sprintf(buffer, "%.4s", "This is a test"); + REQUIRE(!strcmp(buffer, "This")); + + test::sprintf(buffer, "%.4s", "test"); + REQUIRE(!strcmp(buffer, "test")); + + test::sprintf(buffer, "%.7s", "123"); + REQUIRE(!strcmp(buffer, "123")); + + test::sprintf(buffer, "%.7s", ""); + REQUIRE(!strcmp(buffer, "")); + + test::sprintf(buffer, "%.4s%.2s", "123456", "abcdef"); + REQUIRE(!strcmp(buffer, "1234ab")); + + test::sprintf(buffer, "%.4.2s", "123456"); + REQUIRE(!strcmp(buffer, ".2s")); + + test::sprintf(buffer, "%.*s", 3, "123456"); + REQUIRE(!strcmp(buffer, "123")); +} + + +TEST_CASE("buffer length", "[]" ) { + char buffer[100]; + int ret; + + ret = test::snprintf(nullptr, 10, "%s", "Test"); + REQUIRE(ret == 4); + ret = test::snprintf(nullptr, 0, "%s", "Test"); + REQUIRE(ret == 4); + + buffer[0] = (char)0xA5; + ret = test::snprintf(buffer, 0, "%s", "Test"); + REQUIRE(buffer[0] == (char)0xA5); + REQUIRE(ret == 4); + + buffer[0] = (char)0xCC; + test::snprintf(buffer, 1, "%s", "Test"); + REQUIRE(buffer[0] == '\0'); + + test::snprintf(buffer, 2, "%s", "Hello"); + REQUIRE(!strcmp(buffer, "H")); +} + + +TEST_CASE("ret value", "[]" ) { + char buffer[100] ; + int ret; + + ret = test::snprintf(buffer, 6, "0%s", "1234"); + REQUIRE(!strcmp(buffer, "01234")); + REQUIRE(ret == 5); + + ret = test::snprintf(buffer, 6, "0%s", "12345"); + REQUIRE(!strcmp(buffer, "01234")); + REQUIRE(ret == 6); // '5' is truncated + + ret = test::snprintf(buffer, 6, "0%s", "1234567"); + REQUIRE(!strcmp(buffer, "01234")); + REQUIRE(ret == 8); // '567' are truncated + + ret = test::snprintf(buffer, 10, "hello, world"); + REQUIRE(ret == 12); + + ret = test::snprintf(buffer, 3, "%d", 10000); + REQUIRE(ret == 5); + REQUIRE(strlen(buffer) == 2U); + REQUIRE(buffer[0] == '1'); + REQUIRE(buffer[1] == '0'); + REQUIRE(buffer[2] == '\0'); +} + + +TEST_CASE("misc", "[]" ) { + char buffer[100]; + + test::sprintf(buffer, "%u%u%ctest%d %s", 5, 3000, 'a', -20, "bit"); + REQUIRE(!strcmp(buffer, "53000atest-20 bit")); + + test::sprintf(buffer, "%.*f", 2, 0.33333333); + REQUIRE(!strcmp(buffer, "0.33")); + + test::sprintf(buffer, "%.*d", -1, 1); + REQUIRE(!strcmp(buffer, "1")); + + test::sprintf(buffer, "%.3s", "foobar"); + REQUIRE(!strcmp(buffer, "foo")); + + test::sprintf(buffer, "% .0d", 0); + REQUIRE(!strcmp(buffer, " ")); + + test::sprintf(buffer, "%10.5d", 4); + REQUIRE(!strcmp(buffer, " 00004")); + + test::sprintf(buffer, "%*sx", -3, "hi"); + REQUIRE(!strcmp(buffer, "hi x")); + +#ifndef PRINTF_DISABLE_SUPPORT_EXPONENTIAL + test::sprintf(buffer, "%.*g", 2, 0.33333333); + REQUIRE(!strcmp(buffer, "0.33")); + + test::sprintf(buffer, "%.*e", 2, 0.33333333); + REQUIRE(!strcmp(buffer, "3.33e-01")); +#endif +}