Index: Makefile.in ================================================================== --- Makefile.in +++ Makefile.in @@ -4,54 +4,27 @@ # build is for Unix platforms with GNU Make 3.81+. all: .NOTPARALLEL: # stop subdir makes and reconfigure from launching # multiple times concurrently. include config.make -ShakeNMake.CISH_SOURCES := $(wildcard *.c) $(wildcard $(SRC.DIR)/*.c) +ShakeNMake.CISH_SOURCES := $(wildcard *.c) # Subdir cleanup rules and deps list must come before shakenmake.make is included # or they must be set up manually afterwards... -clean-.: clean-doc clean-fnc clean-bindings -distclean-.: distclean-doc distclean-fnc distclean-bindings +clean-.: clean-fnc clean-src +distclean-.: distclean-fnc distclean-src include shakenmake.make MAIN_MAKEFILES := $(PACKAGE.MAKEFILE) $(ShakeNMake.MAKEFILE) @AUTODEPS@ -AUTOCONFIG_H := @srcdir@/include/fossil-scm/autoconfig.h -#SRCDIR := @top_srcdir@/src -SRCDIR := @srcdir@/src define CALL.SUBDIR endef SUBDIRS := src fnc $(eval $(call ShakeNMake.CALL.SUBDIRS,$(SUBDIRS))) #$(eval $(call ShakeNMake.CALL.SUBDIR,src)) subdir-fnc: subdir-src all: subdir-src subdir-fnc - -ifeq (1,@LIBFOSSIL_STATIC@) - THELIB.LIB := libfossil$(ShakeNMake.EXTENSIONS.LIB) -else - THELIB.LIB := -endif -ifeq (1,@LIBFOSSIL_SHARED@) - THELIB.DLL := libfossil$(ShakeNMake.EXTENSIONS.DLL) -else - THELIB.DLL := -endif - -ifneq (,$(THELIB.DLL)$(THELIB.LIB)) -src/$(THELIB.DLL): - $(MAKE) -C src -src/$(THELIB.LIB): - $(MAKE) -C src -$(THELIB.DLL): src/$(THELIB.DLL) - ln -sf src/$(THELIB.DLL) . -$(THELIB.LIB): src/$(THELIB.LIB) - ln -sf src/$(THELIB.LIB) . -all: $(THELIB.DLL) $(THELIB.LIB) -CLEAN_FILES += $(wildcard libfossil.so libfossil.dll libfossil.a) -endif DISTCLEAN_FILES += config.make ######################################################################## # Other stuff... @@ -64,22 +37,13 @@ endif install: all @echo 'No installation rules yet.' -DISTCLEAN_FILES += $(AUTOCONFIG_H) Makefile config.log autosetup/jimsh0 \ +DISTCLEAN_FILES += Makefile config.log autosetup/jimsh0 \ $(wildcard compile_commands/*) compile_commands.json+ -# automake compatibility. do nothing for all these targets -#EMPTY_AUTOMAKE_TARGETS := dvi pdf ps info html tags ctags mostlyclean maintainer-clean check installcheck installdirs \ -# install-pdf install-ps install-info install-html -install-dvi uninstall install-exec install-data distdir -#.PHONY: $(EMPTY_AUTOMAKE_TARGETS) -#$(EMPTY_AUTOMAKE_TARGETS): - -## @top_srcdir@/Makefile.in: # b/c AUTODEPS contains this name (it probably shouldn't) -#$(FSL.OBJ): @AUTODEPS@ @top_srcdir@/Makefile @top_srcdir@/config.make - # Reconfigure if needed ifeq ($(findstring clean,$(MAKECMDGOALS)),) @top_srcdir@/config.make: @AUTODEPS@ @top_srcdir@/config.make.in @@AUTOREMAKE@ @top_srcdir@/Makefile: @AUTODEPS@ @top_srcdir@/Makefile.in Index: auto.def ================================================================== --- auto.def +++ auto.def @@ -1,256 +1,27 @@ # vim:se syn=tcl: # use cc cc-shared cc-lib options { - shared=1 => "Disable build of a shared library." no-debug=0 => "Disable debug build options." - amal => "Generates a conservative config file for the amalgamation build." - static=1 => "Disable build of a static library." loud=0 => "Enables 'loud' build mode." } # autosetup interceps 'debug' and 'enable-debug' flags :/ # prefix:=[get-env HOME /usr/local] -> "Installation prefix." -define FSL_PACKAGE_NAME "libfossil" -define FSL_LIBRARY_VERSION 0.0.1-alphabeta - -######################################################################## -# See if we can get the fossil schema version from the current -# checkout. If so, use that one, otherwise fall back to some hard-coded -# default. -set auxSchema {} -set contentSchema {} - -set fossilBin [find-an-executable fossil] -if {[string length $fossilBin] > 0} { - puts "Found fossil binary: $fossilBin" - catch { - set auxSchema [string trimright \ - [exec echo \ - {SELECT value FROM config WHERE name='aux-schema';} \ - "|" $fossilBin sqlite3] ] - set contentSchema [string trimright \ - [exec echo \ - {SELECT value FROM config WHERE name='content-schema';} \ - "|" $fossilBin sqlite3] ] - } ex -# puts "exception=$ex" -} - -#set uname [exec $fossilBin version -v "|" grep "Schema version"] -#puts "uname=$uname" -#return - -if {[string length $auxSchema] == 16} { - puts "Got aux-schema value from current repo: $auxSchema" - puts "Got content-schema value from current repo: $contentSchema" -} else { - set auxSchema "2015-01-24" - # "2011-04-25 19:50" - set contentSchema 2 - puts "Using hard-coded aux-schema: $auxSchema" - puts "Using hard-coded content-schema: $contentSchema" -} -define FSL_AUX_SCHEMA $auxSchema -define FSL_CONTENT_SCHEMA $contentSchema - -######################################################################## -# Grab the code version and timestamp from manifest.uuid and manifest -# files... -# -# This requires that the repo is NOT generating delta manifests. As -# of 2020-03, the libfossil server uses the forbid-delta-manifest -# setting. -set timestamp [clock format [clock seconds] \ - -gmt 1 -format "%Y-%m-%d %H:%M"] -set fp [open "manifest.uuid" r] -set libVersionHash [string trimright [read $fp]] -close $fp -set fp [open "manifest"] -# Get C-card: -gets $fp -# Get D-card: -gets $fp line -close $fp -unset fp -set manifestTimestamp [string map {"D " "" T " "} $line] -unset line -puts "libVersionHash = $libVersionHash" -puts "manifestTimestamp = $manifestTimestamp" - -set FSL_PLATFORM_CONFIG_H " -\#define FSL_LIB_VERSION_HASH \"$libVersionHash\" -\#define FSL_LIB_VERSION_TIMESTAMP \"$manifestTimestamp UTC\" -\#define FSL_LIB_CONFIG_TIME \"$timestamp GMT\" -\#if defined(_MSC_VER) -\#define FSL_PLATFORM_OS \"windows\" -\#define FSL_PLATFORM_IS_WINDOWS 1 -\#define FSL_PLATFORM_IS_UNIX 0 -\#define FSL_PLATFORM_PLATFORM \"windows\" -\#define FSL_PLATFORM_PATH_SEPARATOR \";\" -\#define FSL_CHECKOUTDB_NAME \"./_FOSSIL_\" -\/* define a __func__ compatibility macro *\/ -\#if _MSC_VER < 1500 /* (vc9.0; dev studio 2008) */ -/* sorry; cant do much better than nothing at all on those earlier ones */ -\#define __func__ \"(func)\" -\#else -\#define __func__ __FUNCTION__ -\#endif -/* for the time being at least, don't complain about there being secure crt alternatives: */ -\#ifndef _CRT_SECURE_NO_WARNINGS -\#define _CRT_SECURE_NO_WARNINGS -\#endif -/* for the time being at least, don't complain about using POSIX names instead of ISO C++: */ -\#pragma warning ( disable : 4996 ) -/* for the time being at least, suppresss some int conversion warnings */ -\#pragma warning ( disable : 4244 ) /*'fsl_size_t' to 'int'; this masks other problems that should be fixed*/ -\#pragma warning ( disable : 4761 ) /*'integral size mismatch in argument'; more size_t problems*/ -\#pragma warning ( disable : 4267 ) /*'size_t' to 'int'; crops up especially in 64-bit builds*/ -/* these were extracted from fossil's unistd.h */ -\#define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR) -\#include -\#elif defined(__MINGW32__) -\#define FSL_PLATFORM_OS \"mingw\" -\#define FSL_PLATFORM_IS_WINDOWS 1 -\#define FSL_PLATFORM_IS_UNIX 0 -\#define FSL_PLATFORM_PLATFORM \"windows\" -\#define FSL_PLATFORM_PATH_SEPARATOR \";\" -\#define FSL_CHECKOUTDB_NAME \"./.fslckout\" -\#elif defined(__CYGWIN__) -\#define FSL_PLATFORM_OS \"cygwin\" -\#define FSL_PLATFORM_IS_WINDOWS 0 -\#define FSL_PLATFORM_IS_UNIX 1 -\#define FSL_PLATFORM_PLATFORM \"unix\" -\#define FSL_PLATFORM_PATH_SEPARATOR \":\" -\#define FSL_CHECKOUTDB_NAME \"./_FOSSIL_\" -\#else -\#define FSL_PLATFORM_OS \"unknown\" -\#define FSL_PLATFORM_IS_WINDOWS 0 -\#define FSL_PLATFORM_IS_UNIX 1 -\#define FSL_PLATFORM_PLATFORM \"unix\" -\#define FSL_PLATFORM_PATH_SEPARATOR \":\" -\#define FSL_CHECKOUTDB_NAME \"./.fslckout\" -\#endif -" - -if {[opt-bool amal]} { - puts "Generating conservative config for the amalgamation build..." - set incGuard _NET_FOSSIL_SCM_FSL_AMALGAMATION_CONFIG_H_INCLUDED_ - set ofile libfossil-config.h - set out [open $ofile w] - puts $out "\#if !defined($incGuard) -\#define $incGuard 1 -\#define FSL_AUX_SCHEMA \"$auxSchema\" -\#define FSL_CONTENT_SCHEMA \"$contentSchema\" -\#define FSL_PACKAGE_NAME \"[get-define FSL_PACKAGE_NAME]\" -\#define FSL_LIBRARY_VERSION \"[get-define FSL_LIBRARY_VERSION]\" -/* Tweak the following for your system... */ -\#if !defined(HAVE_COMPRESS) -\# define HAVE_COMPRESS 1 -\#endif -\#if !defined(HAVE_DLFCN_H) -\# define HAVE_DLFCN_H 0 -\#endif -\#if !defined(HAVE_DLOPEN) -\# define HAVE_DLOPEN 0 -\#endif -\#if !defined(HAVE_GETADDRINFO) -\# define HAVE_GETADDRINFO 0 -\#endif -\#if !defined(HAVE_INET_NTOP) -\# define HAVE_INET_NTOP 0 -\#endif -\#if !defined(HAVE_INTTYPES_H) -\# define HAVE_INTTYPES_H 0 -\#endif -\#if !defined(HAVE_LIBDL) -\# define HAVE_LIBDL 0 -\#endif -\#if !defined(HAVE_LIBLTDL) -\# define HAVE_LIBLTDL 0 -\#endif -\#if !defined(_WIN32) -\#if !defined(HAVE_LSTAT) -\# define HAVE_LSTAT 1 -\#endif -\#if !defined(HAVE_LTDL_H) -\# define HAVE_LTDL_H 0 -\#endif -\#if !defined(HAVE_LT_DLOPEN) -\# define HAVE_LT_DLOPEN 0 -\#endif -\#if !defined(HAVE_OPENDIR) -\# define HAVE_OPENDIR 1 -\#endif -\#if !defined(HAVE_PIPE) -\# define HAVE_PIPE 1 -\#endif -\#if !defined(HAVE_STAT) -\# define HAVE_STAT 1 -\#endif -\#if !defined(HAVE_STDINT_H) -\# define HAVE_STDINT_H 0 -\#endif -\#if !defined(_DEFAULT_SOURCE) -\# define _DEFAULT_SOURCE 1 -\#endif -\#if !defined(_XOPEN_SOURCE) -\# define _XOPEN_SOURCE 500 -\#endif -\#else -\#if !defined(HAVE_LSTAT) -\# define HAVE_LSTAT 0 -\#endif -\#if !defined(HAVE_LTDL_H) -\# define HAVE_LTDL_H 0 -\#endif -\#if !defined(HAVE_LT_DLOPEN) -\# define HAVE_LT_DLOPEN 0 -\#endif -\#if !defined(HAVE_OPENDIR) -\# define HAVE_OPENDIR 1 -\#endif -\#if !defined(HAVE_PIPE) -\# define HAVE_PIPE 0 -\#endif -\#if !defined(HAVE_STAT) -\# define HAVE_STAT 0 -\#endif -\#if !defined(HAVE_STDINT_H) -\# define HAVE_STDINT_H 0 -\#endif -\#endif -/* _WIN32 */ - -$FSL_PLATFORM_CONFIG_H - -\#endif -/* $incGuard */ -" - close $out - puts "Generated $ofile." - return -} -# end of --amal bootstrap config generation - -cc-check-c11 +#cc-check-c11 cc-check-sizeof "void *" if {![cc-check-includes zlib.h] || ![cc-check-function-in-lib compress z]} { user-error "Missing functional zlib" } cc-check-function-in-lib iconv iconv -#if {![cc-check-functions iconv] && -# ![cc-check-function-in-lib iconv iconv]} { -# user-error "Cannot find iconv(3) in libc or libiconv" -#} ######################################################################## # Checks for C99 via (__STDC_VERSION__ >= 199901L). Returns 1 if so, 0 # 0 if not. proc cc-check-c99 {} { @@ -277,44 +48,10 @@ if {![cc-check-c99]} { user-error "As of 2021-02-21, libfossil requires C99." } define CC_FLAG_C99 $CC_FLAG_C99 -######################################################################## -# Module loader is currently used only by the s2 binding. -define HAVE_LIBLTDL 0 -define HAVE_LIBDL 0 -define LDFLAGS_MODULE_LOADER "" -define FSL_ENABLE_MODULE_LOADER 0 -if {[cc-check-includes ltdl.h] && [cc-check-function-in-lib lt_dlopen ltdl]} { - define HAVE_LIBLTDL 1 - define LDFLAGS_MODULE_LOADER "-lltdl" - define FSL_ENABLE_MODULE_LOADER 1 -} elseif {[cc-with {-includes dlfcn.h} { - cctest -link 1 -declare "extern char* dlerror(void);" -code "dlerror();"}]} { - msg-result "This system can use dlopen() w/o -ldl" - define HAVE_LIBDL 1 - define LDFLAGS_MODULE_LOADER "" - define FSL_ENABLE_MODULE_LOADER 1 -} elseif {[cc-check-includes dlfcn.h]} { - msg-result "Found dlfcn.h." - define HAVE_LIBDL 1 - if {[cc-check-function-in-lib dlopen dl]} { - msg-result "Found libdl." - define LDFLAGS_MODULE_LOADER "-ldl" - } else { - msg-result "No libdl found. Assuming dlopen is built-in." - define LDFLAGS_MODULE_LOADER "" - } - define FSL_ENABLE_MODULE_LOADER 1 -} - -if {![get-define FSL_ENABLE_MODULE_LOADER]} { - msg-result {No usable module loading library found. No worries, because we won't have a module system yet. :-D} -} else { - msg-result {Found a module loader. Now we just need something to do with it.} -} ######################################################################## # A proxy for cc-check-function-in-lib which "undoes" any changes that # routine makes to the LIBS define. proc my-check-function-in-lib {function libs {otherlibs {}}} { @@ -322,26 +59,10 @@ set found [cc-check-function-in-lib $function $libs $otherlibs] define LIBS $_LIBS return $found } -######################################################################## -# readline is only used (if at all) by s2sh. If it's not available, we -# fall back to a tree-local copy of the BSD-licensed linenoise editing -# library. -if {[cc-check-includes readline/readline.h] && - [my-check-function-in-lib readline readline]} { - define FSL_ENABLE_READLINE 1 - define FSL_ENABLE_LINENOISE 0 - msg-result "Enabling libreadline for f-s2sh line editing." -} else { - msg-result "libreadline not found. f-s2sh will use the linenoise line editor." - define FSL_ENABLE_READLINE 0 - define FSL_ENABLE_LINENOISE 1 - define lib_readline "" -} - # cc-check-functions getcwd fopen cc-check-functions opendir stat pipe inet_ntop getaddrinfo #msg-result [cc-check-functions lstat] if {[cc-check-functions lstat]} { @@ -371,10 +92,102 @@ set cFlags "$cFlags -O2" } else { msg-result "Debug build enabled. Use --no-debug to build in non-debug mode." set cFlags "$cFlags -g -DDEBUG -O0" } + + +set pcBin [find-an-executable pkg-config] +if {"" eq $pcBin} { + puts {pkg-config not found, so making some guesses about +available packages.} +} +######################################################################## +# Curses! +set LIB_CURSES "" +set CFLAGS_CURSES "" +puts "Looking for \[n]curses..." +if {"" ne $pcBin && $::tcl_platform(os)!="Darwin"} { +# Some macOS pkg-config configurations alter library search paths, which make +# the compiler unable to find lib iconv, so don't use pkg-config on macOS. + set np "" + foreach p {ncursesw ncurses} { + if {[catch {exec $pcBin --exists $p}]} { + continue + } + set np $p + puts "Using pkg-config curses package \[$p]" + break + } + if {"" ne $np} { + set ppanel "" + if {"ncursesw" eq $np} { + if {![catch {exec $pcBin --exists panelw}]} { + set ppanel panelw + } + } + if {"" eq $ppanel && ![catch {exec $pcBin --exists panel}]} { + set ppanel panel + } + set CFLAGS_CURSES [exec $pcBin --cflags $np] + set LIB_CURSES [exec $pcBin --libs $np] + if {"" eq $ppanel} { + # Apparently Mac brew has pkg-config for ncursesw but not + # panel/panelw, but hard-coding -lpanel seems to work on + # that platform. + append LIB_CURSES " -lpanel" + } else { + append LIB_CURSES " " [exec $pcBin --libs $ppanel] + # append CFLAGS_CURSES " " [exec $pcBin --cflags $ppanel] + # ^^^^ appending the panel cflags will end up duplicating + # at least one -D flag from $np's cflags, leading to + # "already defined" errors at compile-time. Sigh. Note, however, + # that $ppanel's cflags have flags which $np's do not, so we + # may need to include those flags anyway and manually perform + # surgery on the list to remove dupes. Sigh. + } + } +} + +if {"" eq $LIB_CURSES} { + puts "Guessing curses location (will fail for exotic locations)..." + define HAVE_CURSES_H [cc-check-includes curses.h] + if {[get-define HAVE_CURSES_H]} { + # Linux has -lncurses, BSD -lcurses. Both have + msg-result "Found curses.h" + if {[my-check-function-in-lib waddnwstr ncursesw]} { + msg-result "Found -lncursesw" + set LIB_CURSES "-lncursesw -lpanelw" + } elseif {[my-check-function-in-lib initscr ncurses]} { + msg-result "Found -lncurses" + set LIB_CURSES "-lncurses -lpanel" + } elseif {[my-check-function-in-lib initscr curses]} { + msg-result "Found -lcurses" + set LIB_CURSES "-lcurses -lpanel" + } + } +} +if {"" eq $LIB_CURSES} { + user-error "!Curses! Foiled again!" +} else { + puts { + ************************************************************ + If your build fails due to missing functions such as + waddwstr(), make sure you have the ncursesW development + package installed. Some platforms combine the "w" and non-w + curses builds and some don't. + + The package may have a name such as libncursesw5-dev or + some such. + ************************************************************ + } +} +define LIB_CURSES $LIB_CURSES +define CFLAGS_CURSES $CFLAGS_CURSES +unset LIB_CURSES +unset CFLAGS_CURSES + puts "Checking for compile_commands.json support..." if {[cctest -lang c -cflags {/dev/null -MJ} -source {}]} { msg-result "Compiler supports compile_commands.json." define MAKE_COMPILATION_DB yes @@ -382,44 +195,18 @@ msg-result "Compiler does not support compile_commands.json." define MAKE_COMPILATION_DB no } define CFLAGS $cFlags - -if {[opt-bool shared]} { - msg-result "Enabling build of shared library." - define LIBFOSSIL_SHARED 1 -} else { - define LIBFOSSIL_SHARED 0 - msg-result "Disabling build of shared library." -} - -if {[opt-bool static]} { - msg-result "Enabling build of static library." - define LIBFOSSIL_STATIC 1 -} else { - define LIBFOSSIL_STATIC 0 - msg-result "Disabling build of static library." -} - if {[opt-bool loud]} { define BUILD_QUIETLY 0 puts "Using 'loud' build mode." } else { define BUILD_QUIETLY 1 puts "Enabling quiet build mode. Use --loud to enable loud mode." } - -set dotBin [find-an-executable dot] -if {[string length $dotBin]} { - define DOXYGEN_HAVE_DOT YES - msg-result "Adding HAVE_DOT=YES to doxyfile." -} else { - define DOXYGEN_HAVE_DOT NO -} - # Creates mkefile(-like) file $name from $name.in but explicitly makes # the output read-only, to avoid inadvertent editing (who, me?). proc makeFromDotIn {name} { catch { exec chmod u+w $name } @@ -428,15 +215,12 @@ } # Each generated Makefile requires an input file with a .in extension: set makefiles { config.make Makefile - doc/Doxyfile src/Makefile fnc/Makefile - bindings/Makefile - bindings/cpp/Makefile } foreach {f} $makefiles { makeFromDotIn $f } @@ -446,112 +230,5 @@ make-config-header include/fossil-scm/autoconfig.h \ -none {DOXYGEN_*} \ -bare {HAVE_* FSL_ENABLE_* _DEFAULT_SOURCE _XOPEN_SOURCE} \ -str {FSL_* PACKAGE_*} } - -######################################################################## -# Generate our autconf header by hand to allow finer control -# over the structure.... -set confH include/fossil-scm/autoconfig.h -set incGuard _NET_FOSSIL_SCM_FSL_AUTO_CONFIG_H_INCLUDED_ -if {[opt-bool amal]} { - set confH libfossil-config.h - set incGuard _NET_FOSSIL_SCM_FSL_AMALGAMATION_CONFIG_H_INCLUDED_ -} -puts "Generating config header $confH" - set out [open $confH w] - puts $out "\#if !defined($incGuard) -\#define $incGuard 1 -\#define FSL_AUX_SCHEMA \"$auxSchema\" -\#define FSL_CONTENT_SCHEMA \"$contentSchema\" -\#define FSL_PACKAGE_NAME \"[get-define FSL_PACKAGE_NAME]\" -\#define FSL_LIBRARY_VERSION \"[get-define FSL_LIBRARY_VERSION]\" -\#define FSL_SHA1_HARDENED 1 -/* Tweak the following for your system... */ -\#if !defined(HAVE_GETADDRINFO) -\# define HAVE_GETADDRINFO [get-define HAVE_GETADDRINFO 0] -\#endif -\#if !defined(HAVE_INET_NTOP) -\# define HAVE_INET_NTOP [get-define HAVE_INET_NTOP 0] -\#endif -\#if !defined(_WIN32) -\#if !defined(HAVE_DLFCN_H) -\# define HAVE_DLFCN_H [get-define HAVE_DLFCN_H 0] -\#endif -\#if !defined(HAVE_DLOPEN) -\# define HAVE_DLOPEN [get-define HAVE_DLOPEN 0] -\#endif -\#if !defined(HAVE_LIBDL) -\# define HAVE_LIBDL [get-define HAVE_LIBDL 0] -\#endif -\#if !defined(HAVE_LIBLTDL) -\# define HAVE_LIBLTDL [get-define HAVE_LIBLTDL 0] -\#endif -\#if !defined(HAVE_LSTAT) -\# define HAVE_LSTAT [get-define HAVE_LSTAT 1] -\#endif -\#if !defined(HAVE_LTDL_H) -\# define HAVE_LTDL_H [get-define HAVE_LTDL_H 0] -\#endif -\#if !defined(HAVE_LT_DLOPEN) -\# define HAVE_LT_DLOPEN [get-define HAVE_LT_DLOPEN 0] -\#endif -\#if !defined(HAVE_OPENDIR) -\# define HAVE_OPENDIR [get-define HAVE_OPENDIR 1] -\#endif -\#if !defined(HAVE_PIPE) -\# define HAVE_PIPE [get-define HAVE_PIPE 1] -\#endif -\#if !defined(HAVE_STAT) -\# define HAVE_STAT [get-define HAVE_STAT 1] -\#endif -\#if !defined(_DEFAULT_SOURCE) -\# define _DEFAULT_SOURCE [get-define _DEFAULT_SOURCE 1] -\#endif -\#if !defined(_XOPEN_SOURCE) -\# define _XOPEN_SOURCE [get-define _XOPEN_SOURCE 500] -\#endif -\#else -/* _WIN32: */ -\#if !defined(HAVE_DLFCN_H) -\# define HAVE_DLFCN_H 0 -\#endif -\#if !defined(HAVE_DLOPEN) -\# define HAVE_DLOPEN 0 -\#endif -\#if !defined(HAVE_LIBDL) -\# define HAVE_LIBDL 0 -\#endif -\#if !defined(HAVE_LIBLTDL) -\# define HAVE_LIBLTDL 0 -\#endif -\#if !defined(HAVE_LSTAT) -\# define HAVE_LSTAT 0 -\#endif -\#if !defined(HAVE_LTDL_H) -\# define HAVE_LTDL_H 0 -\#endif -\#if !defined(HAVE_LT_DLOPEN) -\# define HAVE_LT_DLOPEN 0 -\#endif -\#if !defined(HAVE_OPENDIR) -\# define HAVE_OPENDIR 1 -\#endif -\#if !defined(HAVE_PIPE) -\# define HAVE_PIPE 0 -\#endif -\#if !defined(HAVE_STAT) -\# define HAVE_STAT 0 -\#endif -\#endif -/*_WIN32*/ - -$FSL_PLATFORM_CONFIG_H - -\#endif -/* $incGuard */ -" - close $out - puts "Generated $confH." - return -} DELETED bindings/Makefile Index: bindings/Makefile ================================================================== --- bindings/Makefile +++ bindings/Makefile @@ -1,18 +0,0 @@ -#!/usr/bin/make # help out emacs -all: -SUBDIRS := -# Subdir cleanup rules and deps list must come before shakenmake.make is included -# or they must be set up manually afterwards... -ifneq (,$(CXX)) -clean-.: clean-cpp -distclean-.: distclean-cpp -SUBDIRS += cpp -all: subdir-cpp -endif - -clean-.: clean-s2 -distclean-.: distclean-s2 -include ../subdir-inc.make -SUBDIRS += s2 -$(eval $(call ShakeNMake.CALL.SUBDIRS,$(SUBDIRS))) -all: subdir-s2 DELETED bindings/Makefile.in Index: bindings/Makefile.in ================================================================== --- bindings/Makefile.in +++ bindings/Makefile.in @@ -1,18 +0,0 @@ -#!/usr/bin/make # help out emacs -all: -SUBDIRS := -# Subdir cleanup rules and deps list must come before shakenmake.make is included -# or they must be set up manually afterwards... -ifneq (,$(CXX)) -clean-.: clean-cpp -distclean-.: distclean-cpp -SUBDIRS += cpp -all: subdir-cpp -endif - -clean-.: clean-s2 -distclean-.: distclean-s2 -include ../subdir-inc.make -SUBDIRS += s2 -$(eval $(call ShakeNMake.CALL.SUBDIRS,$(SUBDIRS))) -all: subdir-s2 DELETED bindings/cpp/Context.cpp Index: bindings/cpp/Context.cpp ================================================================== --- bindings/cpp/Context.cpp +++ bindings/cpp/Context.cpp @@ -1,291 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=2 et sw=2 tw=80: */ -#include "fossil-scm/fossil.hpp" -#include - -/* only for debugging */ -#include -#define CERR std::cerr << __FILE__ << ":" << std::dec << __LINE__ << " : " - -namespace fsl { - - Context::~Context(){ - if(this->ownsCx){ - fsl_cx_finalize(this->f); - } - } - - void Context::setup(fsl_cx_init_opt const * opt){ - //this->f = fsl_cx_malloc(); - //if(!this->f) throw OOMException(); - assert(!this->f); - int const rc = fsl_cx_init(&this->f, opt); - if(rc){ - fsl_error err = fsl_error_empty; - if(this->f){ - fsl_error_move( &this->f->error, &err ); - fsl_cx_finalize(this->f); - this->f = NULL; - }else{ - fsl_error_set( &err, rc, - "fsl_cx_init() failed with code %s", - fsl_rc_cstr(rc) ); - } - throw Exception(err); - } - } - - Context::Context() - : f(NULL), - ownsCx(true), - dbCkout(), - dbRe(), - dbMain() - { - this->setup(NULL); - } - - Context::Context(fsl_cx_init_opt const & opt) - : f(NULL), - ownsCx(true), - dbCkout(), - dbRe(), - dbMain() - { - this->setup(&opt); - } - - Context::Context(fsl_cx * f, bool ownsHandle) - : f(f), - ownsCx(ownsHandle), - dbCkout(), - dbRe(), - dbMain() - { - - } - - Context::operator fsl_cx * () throw(){ - return this->f; - } - - Context::operator fsl_cx const * () const throw() { - return this->f; - } - - void Context::propagateError() const{ - if(this->f){ - fsl_error const * err = fsl_cx_err_get_e(this->f); - if(err->code) throw Exception(err); - } - } - - void Context::assertRC(char const * context, int rc) const{ - if(rc){ - this->propagateError(); - throw Exception(rc, "%s: %s", context, fsl_rc_cstr(rc)); - } - } - - void Context::assertHasRepo(){ - assert(this->f); - if(!fsl_needs_repo(this->f)){ - fsl_error const * err = fsl_cx_err_get_e(this->f); - assert(err->code); - throw Exception(err); - } - } - - void Context::assertHasCheckout(){ - assert(this->f); - if(!fsl_needs_ckout(this->f)){ - fsl_error const * err = fsl_cx_err_get_e(this->f); - assert(err->code); - throw Exception(err); - } - } - - fsl_cx * Context::handle() throw(){ - return this->f; - } - - fsl_cx const * Context::handle() const throw(){ - return this->f; - } - - Db & Context::db() throw() { - if(!this->dbMain.handle()){ - fsl_db * db = fsl_cx_db(*this); - if(db) this->dbMain.handle(db, false); - } - return this->dbMain; - } - - - Db & Context::dbRepo() throw() { - if(!this->dbRe.handle()){ - fsl_db * db = fsl_cx_db_repo(*this); - if(db) this->dbRe.handle(db, false); - } - return this->dbRe; - } - - Db & Context::dbCheckout() throw() { - if(!this->dbCkout.handle()){ - fsl_db * db = fsl_cx_db_ckout(*this); - if(db) this->dbCkout.handle(db, false); - } - return this->dbCkout; - } - - Context & Context::openCheckout( char const * dirName ){ - this->assertRC( "openCheckout()", - fsl_ckout_open_dir(this->f, dirName, true) ); - return *this; - } - - Context & Context::openRepo( char const * dbName ){ - this->assertRC( "openRepo()", - fsl_repo_open(this->f, dbName) ); - return *this; - } - - Context & Context::closeDbs() throw(){ - fsl_cx_close_dbs(this->f) - /* - Reminder to self: the 3 fsl_cx db handles are stored as - complete fsl_db instances (not pointers) in fsl_cx, with the - exception of the "main" db, which is just a pointer to one of - the other 3. What does that mean? It means that when we use - fsl_cx_close_dbs(), this->dbRe and friends will (if - initialized) still be pointing to those pointers... which are - (due to internal details) actually still valid, they just - refer to closed fsl_db handles. - - That's actually good for us here, except that certain - combinations of C-level ops "might" get our checkout/repo db - pointers cross a bit. - */ - ; - assert(!this->dbRe.ownsHandle()); - assert(!this->dbMain.ownsHandle()); - assert(!this->dbCkout.ownsHandle()); - this->dbRe.close(); - this->dbCkout.close(); - this->dbMain.close(); - if(this->dbRe.handle()){ - assert(!this->dbRe.handle()->dbh); - } - return *this; - } - - bool Context::ownsHandle() const throw(){ - return this->ownsCx; - } - - std::string Context::ridToArtifactUuid(fsl_id_t rid, - fsl_satype_e type){ - this->assertHasRepo(); - fsl_uuid_str uuid = fsl_rid_to_artifact_uuid(*this, rid, type); - if(!uuid){ - this->propagateError(); - throw Exception(FSL_RC_NOT_FOUND, - "Could not resolve RID %" FSL_ID_T_PFMT - " as artifact type %s.", - (fsl_id_t)rid, fsl_satype_cstr(type)); - } - std::string const & rc = uuid; - fsl_free(uuid); - return rc; - } - - std::string Context::ridToUuid(fsl_id_t rid){ - this->assertHasRepo(); - fsl_uuid_str uuid = fsl_rid_to_uuid(*this, rid); - if(!uuid){ - this->propagateError(); - throw Exception(FSL_RC_NOT_FOUND, "Could not resolve RID %" FSL_ID_T_PFMT ".", - (fsl_id_t)rid); - } - std::string const & rc = uuid; - fsl_free(uuid); - return rc; - } - - std::string Context::symToUuid(char const * symbolicName, - fsl_id_t * rid, - fsl_satype_e type){ - this->assertHasRepo(); - fsl_uuid_str uuid = NULL; - int const rc = fsl_sym_to_uuid(*this, symbolicName, type, &uuid, rid); - if(rc){ - this->propagateError(); - throw Exception(rc); - } - std::string const & rv = uuid; - fsl_free(uuid); - return rv; - } - - - fsl_id_t Context::symToRid(char const * symbolicName, fsl_satype_e type){ - this->assertHasRepo(); - fsl_id_t rv = 0; - int const rc = fsl_sym_to_rid(*this, symbolicName, type, &rv); - if(rc){ - this->propagateError(); - throw Exception(rc); - } - assert(rv>0); - return rv; - } - - fsl_id_t Context::symToRid(std::string const & symbolicName, - fsl_satype_e type){ - return this->symToRid( symbolicName.c_str(), type ); - } - - Context::Transaction::Transaction(Context &cx) - : tr( cx.db() ), - level(tr.level()){ - } - - Context::Transaction::~Transaction() throw(){ - if(this->level) this->tr.rollback(); - } - - void Context::Transaction::commit(){ - if(this->level){ - this->level = 0; - this->tr.commit(); - }else{ - throw Exception(FSL_RC_MISUSE, - "commit() called multiple times."); - } - } - - Context & Context::getContent( fsl_id_t rid, Buffer & dest ){ - int const rc = fsl_content_get( *this, rid, dest ); - if(rc){ - this->propagateError(); - throw Exception(rc); - } - return *this; - } - - Context & Context::getContent( char const * sym, Buffer & dest ){ - int const rc = fsl_content_get_sym( *this, sym, dest ); - if(rc){ - this->propagateError(); - throw Exception(rc); - } - return *this; - } - - Context & Context::getContent( std::string const & sym, Buffer & dest ){ - return this->getContent( sym.c_str(), dest ); - } - -} // namespace fsl - -#undef CERR DELETED bindings/cpp/Db.cpp Index: bindings/cpp/Db.cpp ================================================================== --- bindings/cpp/Db.cpp +++ bindings/cpp/Db.cpp @@ -1,564 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=2 et sw=2 tw=80: */ -#include "fossil-scm/fossil.hpp" -#include - -/* only for debugging */ -#include -#define CERR std::cerr << __FILE__ << ":" << std::dec << __LINE__ << " : " - -namespace fsl { - Stmt::~Stmt() throw(){ - fsl_stmt_finalize(*this); - } - - Stmt::Stmt(Db & db) throw() : - db(db), - stmt(fsl_stmt_empty){ - } - - Stmt::operator fsl_stmt * () throw(){ - return &this->stmt; - } - - Stmt::operator fsl_stmt const * () const throw() { - return &this->stmt; - } - - - void Stmt::assertPrepared() const{ - if(!this->stmt.stmt){ - throw Exception(FSL_RC_MISUSE, - "Statement is not prepared."); - } - assert(this->stmt.db); - } - - void Stmt::assertRange(short col, short base) const{ - this->assertPrepared(); - char const * errMsg = NULL; - if(col<0){ - errMsg = "column/parameter index %d is invalid"; - }else if(base){ - assert(1==base); - if(!col || col > fsl_stmt_param_count(*this)){ - errMsg = "parameter index %d is out of range"; - } - }else{ - assert(0==base); - if(col >= fsl_stmt_col_count(*this)){ - errMsg = "column index %d is out of range"; - } - } - if(errMsg) throw Exception(FSL_RC_RANGE, errMsg, col+base); - } - - void Stmt::propagateError() const{ - this->db.propagateError(); - } - - void Stmt::assertRC(char const * context, int rc) const{ - if(rc){ - this->propagateError(); - throw Exception(rc, "%s: %s", context, fsl_rc_cstr(rc)); - } - } - - Stmt & Stmt::prepare(std::string const & sql){ - return this->prepare("%s", sql.c_str()); - } - - Stmt & Stmt::prepare(Buffer const & sql){ - return this->prepare("%s", sql.c_str()); - } - - Stmt & Stmt::prepare(char const * sql, ... ){ - va_list vargs; - if(this->stmt.stmt) throw Exception(FSL_RC_MISUSE, - "Statement is prepared and not " - "yet finalized. Cowardly refusing " - "to re-prepare() non-finalized statement: %s", - this->sql()); - int rc = 0; - va_start(vargs,sql); - rc = fsl_db_preparev( this->db.handle(), *this, - sql, vargs ); - va_end(vargs); - if(rc){ - this->propagateError(); - throw Exception(rc,"SQL preparation failed for: %s", sql); - }else{ - assert(this->stmt.db == this->db.handle()); - return *this; - } - } - - int Stmt::stepCount() const throw(){ - return this->stmt.rowCount; - } - - int Stmt::paramCount() const throw(){ - return this->stmt.paramCount; - } - - int Stmt::columnCount() const throw(){ - return this->stmt.colCount; - } - - char const * Stmt::sql() const throw() { - return stmt.stmt - ? fsl_buffer_cstr(&stmt.sql) - : NULL; - } - - fsl_stmt * Stmt::handle() throw(){ - return &this->stmt; - } - - fsl_stmt const * Stmt::handle() const throw() { - return &this->stmt; - } - - Stmt & Stmt::reset(bool resetStepCounterToo){ - this->assertRC("reset()", - fsl_stmt_reset2(*this, - resetStepCounterToo)); - return *this; - } - - Stmt & Stmt::finalize() throw(){ - fsl_stmt_finalize(*this); - return *this; - } - - bool Stmt::step(){ - this->assertPrepared(); - int const rc = fsl_stmt_step(*this); - switch(rc){ - case FSL_RC_STEP_ROW: return true; - case FSL_RC_STEP_DONE: return false; - default: - this->propagateError(); - throw Exception(rc,"No idea what went wrong."); - } - } - - Stmt & Stmt::stepExpectDone(){ - if(this->step()){ - throw Exception(FSL_RC_ERROR, - "Expecting statement to return no rows: %s", - this->sql()); - } - return *this; - } - - int32_t Stmt::getInt32(short col){ - this->assertRange(col, 0); - return fsl_stmt_g_int32( *this, col ); - } - - int64_t Stmt::getInt64(short col){ - this->assertRange(col, 0); - return fsl_stmt_g_int64( *this, col ); - } - - double Stmt::getDouble(short col){ - this->assertRange(col, 0); - return fsl_stmt_g_double( *this, col ); - } - - fsl_id_t Stmt::getId(short col){ - this->assertRange(col, 0); - return fsl_stmt_g_id( *this, col ); - } - - char const * Stmt::columnName(short col){ - this->assertRange(col, 0); - return fsl_stmt_col_name(*this, col); - } - - char const * Stmt::getText(short col, fsl_size_t * length){ - this->assertRange(col, 0); - return fsl_stmt_g_text(*this, col, length); - } - - void const * Stmt::getBlob(short col, fsl_size_t * length){ - void const * v = NULL; - this->assertRange(col, 0); - fsl_stmt_get_blob(*this, col, &v, length); - return v; - } - - Stmt & Stmt::bind(short col){ - this->assertRange(col, 1); - this->assertRC("bind NULL", - fsl_stmt_bind_null(*this, col)); - return *this; - } - - Stmt & Stmt::bind(short col, int32_t v){ - this->assertRange(col, 1); - this->assertRC("bind int32", - fsl_stmt_bind_int32(*this, col, v)); - return *this; - } - - Stmt & Stmt::bind(short col, int64_t v){ - this->assertRange(col, 1); - this->assertRC("bind int64", - fsl_stmt_bind_int64(*this, col, v)); - return *this; - } - - Stmt & Stmt::bind(short col, double v){ - this->assertRange(col, 1); - this->assertRC("bind double", - fsl_stmt_bind_double(*this, col, v)); - return *this; - } - - Stmt & Stmt::bind(short col, char const * str, - fsl_int_t len, bool copyBytes){ - this->assertRange(col, 1); - this->assertRC("bind text", - fsl_stmt_bind_text(*this, col, str, len, copyBytes)); - return *this; - } - - Stmt & Stmt::bind(short col, std::string const & str){ - return this->bind(col, str.c_str(), (fsl_int_t)str.size(), 1); - } - - Stmt & Stmt::bind(short col, void const * v, - fsl_size_t len, bool copyBytes){ - this->assertRange(col, 1); - this->assertRC("bind blob", - fsl_stmt_bind_blob(*this, col, v, len, copyBytes)); - return *this; - } - - int Stmt::paramIndex(char const * name){ - this->assertPrepared(); - return fsl_stmt_param_index(*this, name); - } - - Stmt & Stmt::bind(char const * col){ - this->assertRC("bind NULL", - fsl_stmt_bind_null_name(*this, col)); - return *this; - } - - Stmt & Stmt::bind(char const * col, int32_t v){ - this->assertRC("bind int32", - fsl_stmt_bind_int32_name(*this, col, v)); - return *this; - } - - Stmt & Stmt::bind(char const * col, int64_t v){ - this->assertRC("bind int64", - fsl_stmt_bind_int64_name(*this, col, v)); - return *this; - } - - Stmt & Stmt::bind(char const * col, double v){ - this->assertRC("bind double", - fsl_stmt_bind_double_name(*this, col, v)); - return *this; - } - - Stmt & Stmt::bind(char const * col, char const * str, - fsl_int_t len, bool copyBytes){ - this->assertRC("bind text", - fsl_stmt_bind_text_name(*this, col, str, len, copyBytes)); - return *this; - } - - Stmt & Stmt::bind(char const * col, std::string const & str){ - return this->bind(col, str.c_str(), (fsl_int_t)str.size(), 1); - } - - Stmt & Stmt::bind(char const * col, void const * v, - fsl_size_t len, bool copyBytes){ - this->assertRC("bind blob", - fsl_stmt_bind_blob_name(*this, col, v, len, copyBytes)); - return *this; - } - - StmtBinder::~StmtBinder(){} - - StmtBinder::StmtBinder(Stmt &s) : st(s), col(0) - {} - - Stmt & StmtBinder::stmt(){ - return this->st; - } - - StmtBinder & StmtBinder::operator()(){ - st.bind(++this->col); - return *this; - } - - StmtBinder & StmtBinder::operator()(char const * v, fsl_int_t len, - bool copyBytes){ - st.bind(++this->col, v, len, copyBytes); - return *this; - } - - StmtBinder & StmtBinder::operator()(void const * v, fsl_size_t len, - bool copyBytes){ - st.bind(++this->col, v, len, copyBytes); - return *this; - } - - StmtBinder & StmtBinder::reset(bool alsoStatement) { - this->col = 0; - if(alsoStatement) this->st.reset(); - return *this; - } - - bool StmtBinder::step(){ - return this->st.step(); - } - - StmtBinder & StmtBinder::once(){ - this->st.stepExpectDone(); - return this->reset(); - } - - Db::~Db() throw(){ - this->close(); - } - - void Db::setup(){ - assert(!this->db); - this->db = fsl_db_malloc(); - if(!this->db) throw OOMException(); - this->ownsDb = true; - } - - Db::Db(): db(NULL), - ownsDb(true){ - } - - Db::Db(char const * filename, int openFlags) - : db(NULL), - ownsDb(true){ - try{ - this->open(filename, openFlags); - }catch(...){ - if(this->db) fsl_db_close(this->db); - throw; - } - } - - void Db::propagateError() const{ - if(this->db && this->db->error.code){ - throw Exception(this->db->error); - } - } - - void Db::assertRC(char const * context, int rc) const{ - if(rc){ - this->propagateError(); - throw Exception(rc, "%s: %s", context, fsl_rc_cstr(rc)); - } - } - - void Db::assertOpened() const{ - if(!this->db || !this->db->dbh){ - throw Exception(FSL_RC_MISUSE, - "Db is not opened."); - } - } - - Db::operator fsl_db * () throw(){ - return this->db; - } - - Db::operator fsl_db const * () const throw() { - return this->db; - } - - Db & Db::handle( fsl_db * db, bool ownsHandle )throw(){ - if(this->db != db){ - this->close(); - this->db = db; - this->ownsDb = ownsHandle; - } - return *this; - } - - Db & Db::close() throw(){ - if(this->db){ - if(this->ownsDb){ - fsl_db_close(*this); - } - this->db = NULL; - } - return *this; - } - - char const * Db::filename() throw(){ - return this->db - ? fsl_db_filename(*this, NULL) - : NULL; - } - - Db & Db::open(char const * filename, int openFlags){ - if(!this->db) this->setup(); - else if(this->db->dbh){ - throw Exception(FSL_RC_MISUSE, - "Db is already opened: %s", - this->filename()); - } - int const rc = fsl_db_open(*this, filename, openFlags); - if(rc){ - /* - The problem here is that open() can be called from the ctor, - and if the ctor throws then the dtor is not called, so we - have to free up this->db. Oh, wait... the open() ctor does - that for us, so this gets easier. - - But... if it throws from outside the ctor then we DO have to - clean up. - */ - Exception const & ex = this->db->error.code - ? Exception(this->db->error) - : Exception(rc,"fsl_db_open(%s) failed: %s", - filename, fsl_rc_cstr(rc)); - this->close(); - throw ex; - } - return *this; - } - - bool Db::isOpened() const throw(){ - return (this->db && this->db->dbh) ? true : false; - } - - bool Db::ownsHandle() const throw(){ - return this->ownsDb; - } - - fsl_db * Db::handle() throw(){ - return this->db; - } - - fsl_db const * Db::handle() const throw() { - return this->db; - } - - Db & Db::begin(){ - this->assertOpened(); - this->assertRC( - "begin()", - fsl_db_transaction_begin(*this) ); - return *this; - } - - Db & Db::commit(){ - this->assertOpened(); - this->assertRC( "commit()", - fsl_db_transaction_end(*this, 0) ); - return *this; - } - - Db & Db::rollback() throw() { - this->assertOpened(); - fsl_db_transaction_end(*this, 1); - return *this; - } - - Db & Db::exec(std::string const & sql){ - return this->exec("%s", sql.c_str()); - } - - Db & Db::exec(char const * sql, ...){ - this->assertOpened(); - va_list vargs; - int rc = 0; - va_start(vargs,sql); - rc = fsl_db_execv( *this, sql, vargs ); - va_end(vargs); - if(rc){ - this->propagateError(); - throw Exception(rc,"SQL execution failed for: %s", sql); - } - else return *this; - } - - Db & Db::execMulti(char const * sql, ...){ - this->assertOpened(); - va_list vargs; - int rc = 0; - va_start(vargs,sql); - rc = fsl_db_exec_multiv( *this, sql, vargs ); - va_end(vargs); - if(rc){ - this->propagateError(); - throw Exception(rc,"SQL multi-exec failed for: %s", sql); - } - else return *this; - } - - Db & Db::execMulti(std::string const & sql){ - return this->execMulti("%s", sql.c_str()); - } - - - Db & Db::attach(char const * filename, char const * label){ - this->assertRC( "attach()", fsl_db_attach(*this, filename, label) ); - return *this; - } - - Db & Db::detach(char const * label){ - this->assertRC( "detach()", fsl_db_detach(*this, label) ); - return *this; - } - - int Db::transactionLevel() const throw(){ - return this->db - ? this->db->beginCount - : 0; - } - - Db::Transaction::Transaction(Db & db) - : db(db), inTrans(false){ - db.begin(); - inTrans = db.transactionLevel(); - } - - Db::Transaction::~Transaction() throw(){ - if(inTrans) this->rollback(); - } - - void Db::Transaction::commit(){ - assert(inTrans); - if(inTrans>0){ - inTrans = 0; - db.commit(); - } - } - - void Db::Transaction::rollback() throw(){ - assert(inTrans); - if(inTrans){ -#if 1 - inTrans = 0; - db.rollback(); -#else - /* sane? */ - while(inTrans < db.transactionLevel()){ - db.rollback(); - } -#endif - } - } - - int Db::Transaction::level() const throw(){ - return db.transactionLevel(); - } - -}// namespace fsl - -#undef CERR DELETED bindings/cpp/Deck.cpp Index: bindings/cpp/Deck.cpp ================================================================== --- bindings/cpp/Deck.cpp +++ bindings/cpp/Deck.cpp @@ -1,414 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=2 et sw=2 tw=80: */ -#include "fossil-scm/fossil.hpp" -#include - -/* only for debugging */ -#include -#define CERR std::cerr << __FILE__ << ":" << std::dec << __LINE__ << " : " - -namespace fsl { - - Deck::~Deck() throw(){ - delete this->deltaBase; - if(this->ownsDeck){ - assert(this->d->allocStamp); - fsl_deck_finalize(this->d); - } - } - - void Deck::setup(fsl_deck * mf, fsl_satype_e type){ - if(!mf){ - assert(!this->d); - assert(this->ownsDeck); - this->d = fsl_deck_malloc(); - if(!this->d) throw OOMException(); - }else{ - assert(this->d == mf); - if(d && d->f && (d->f != this->cx.handle())){ - throw Exception(FSL_RC_MISUSE, - "Mis-matched fsl_cx contexts for deck."); - } - } - if(ownsDeck){ - fsl_deck_init( this->cx, d, type ); - } - } - - Deck::Deck(Context & cx, fsl_satype_e type) - : cx(cx), - d(NULL), - deltaBase(NULL), - ownsDeck(true){ - this->setup( NULL, type ); - } - - Deck::Deck(Context & cx, fsl_deck * d, bool ownsDeck) - : cx(cx), - d(d), - deltaBase(NULL), - ownsDeck(ownsDeck){ - if(!d){ - throw Exception(FSL_RC_MISUSE, - "A proxied Deck may not be NULL."); - } - this->setup( d, d->type ); - } - - void Deck::propagateError() const{ - fsl_error const * err = fsl_cx_err_get_e(this->cx); - if(err->code){ - throw Exception(err); - } - } - - void Deck::assertRC(char const * context, int rc) const{ - if(rc){ - this->propagateError(); - throw Exception(rc, "%s: %s", context, fsl_rc_cstr(rc)); - } - } - - Deck & Deck::cleanup() throw(){ - fsl_deck_clean(*this); - return *this; - } - - fsl_satype_e Deck::type() const throw(){ - return this->d->type; - } - - fsl_id_t Deck::rid() const throw(){ - return this->d->rid; - } - - fsl_uuid_cstr Deck::uuid() const throw(){ - return this->d->uuid; - } - - Deck::operator fsl_deck *() throw(){ - return this->d; - } - - Deck::operator fsl_deck const *() const throw(){ - return this->d; - } - - Context & Deck::context() throw() { return this->cx; } - Context const & Deck::context() const throw() { return this->cx; } - - fsl_deck * Deck::handle() throw(){ - return this->d; - } - - fsl_deck const * Deck::handle() const throw(){ - return this->d; - } - - bool Deck::hasAllRequiredCards() const throw(){ - return fsl_deck_has_required_cards(*this); - } - - Deck const & Deck::assertHasRequiredCards() const{ - if(!fsl_deck_has_required_cards(*this)){ - throw Exception(fsl_cx_err_get_e(this->cx)); - } - else return *this; - } - - bool Deck::cardIsLegal(char cardLetter) const throw(){ - return fsl_card_is_legal( this->d->type, cardLetter ); - } - - Deck & Deck::unshuffle(bool calcRCard){ - int const rc = fsl_deck_unshuffle(*this, calcRCard); - if(rc){ - this->propagateError(); - throw Exception(rc); - }else return *this; - } - - Deck const & Deck::output( fsl_output_f f, void * outState ) const{ - int const rc = fsl_deck_output( this->d, f, outState ); - if(rc) throw Exception(this->d->f->error); - else return *this; - } - - Deck const & Deck::output( std::ostream & os ) const{ - return this->output( fsl_output_f_std_ostream, &os ); - } - - Deck & Deck::save(bool isPrivate){ - int const rc = fsl_deck_save( *this, isPrivate ); - if(rc){ - this->propagateError(); - throw Exception(rc,"fsl_deck_save() failed: %s", - fsl_rc_cstr(rc)); - } - else return *this; - } - - Deck & Deck::load( fsl_id_t rid, fsl_satype_e type ){ - this->cleanup(); - int const rc = fsl_deck_load_rid( this->cx, *this, - rid, type ); - if(rc){ - this->propagateError(); - throw Exception(rc, "fsl_deck_load_rid() failed " - "with %s for symbol: %" FSL_ID_T_PFMT, - fsl_rc_cstr(rc), (fsl_id_t)rid); - }else return *this; - } - - Deck & Deck::load( char const * symbolicName, fsl_satype_e type){ - this->cleanup(); - int const rc = fsl_deck_load_sym( this->cx, *this, - symbolicName, type ); - if(rc){ - this->propagateError(); - throw Exception(rc, "fsl_deck_load_sym() failed " - "with %s for symbol: %s", - fsl_rc_cstr(rc), symbolicName); - }else return *this; - } - - Deck & Deck::load( std::string const & symbolicName, fsl_satype_e type){ - return this->load( symbolicName.c_str(), type ); - } - - Deck & Deck::setCardA( char const * name, - char const * tgt, - fsl_uuid_cstr uuid ){ - int const rc = fsl_deck_A_set(*this, name, tgt, uuid); - this->assertRC("fsl_deck_A_set()", rc); - return *this; - } - - Deck & Deck::setCardB(fsl_uuid_cstr uuid){ - if(this->deltaBase){ - delete this->deltaBase; - this->deltaBase = NULL; - } - int const rc = fsl_deck_B_set(*this, uuid); - this->assertRC("fsl_deck_B_add()", rc); - return *this; - } - - - Deck & Deck::setCardC( char const * comment ){ - int const rc = fsl_deck_C_set(*this, comment, -1); - this->assertRC("fsl_deck_C_set()", rc); - return *this; - } - - Deck & Deck::setCardD(double julianDay){ - int const rc = fsl_deck_D_set(*this, - julianDay<0 - ? fsl_julian_now() - : julianDay); - this->assertRC("fsl_deck_D_set()", rc); - return *this; - } - - Deck & Deck::setCardE( fsl_uuid_cstr uuid, double julian ){ - int const rc = fsl_deck_E_set(*this, - julian<0 - ? fsl_julian_now() - : julian, - uuid ); - this->assertRC("fsl_deck_E_set()", rc); - return *this; - } - - - Deck & Deck::addCardF(char const * name, - fsl_uuid_cstr uuid, - fsl_fileperm_e perm, - char const * oldName ){ - int const rc = fsl_deck_F_add(*this, name, uuid, perm, oldName); - this->assertRC("fsl_deck_F_add()", rc); - return *this; - } - - Deck & Deck::addCardJ( char isAppend, char const * key, char const * value ){ - int const rc = fsl_deck_J_add(*this, isAppend, key, value); - this->assertRC("fsl_deck_J_add()", rc); - return *this; - } - - - Deck & Deck::setCardK(fsl_uuid_cstr uuid){ - int const rc = fsl_deck_K_set(*this, uuid); - this->assertRC("fsl_deck_K_set()", rc); - return *this; - } - - Deck & Deck::setCardL( char const * title ){ - int const rc = fsl_deck_L_set(*this, title, -1); - this->assertRC("fsl_deck_L_set()", rc); - return *this; - } - - Deck & Deck::addCardM(fsl_uuid_cstr uuid){ - int const rc = fsl_deck_M_add(*this, uuid); - this->assertRC("fsl_deck_M_add()", rc); - return *this; - } - - - Deck & Deck::setCardN(char const * name){ - int const rc = fsl_deck_N_set(*this, name, -1); - this->assertRC("fsl_deck_N_set()", rc); - return *this; - } - - Deck & Deck::addCardP(fsl_uuid_cstr uuid){ - int const rc = fsl_deck_P_add(*this, uuid); - this->assertRC("fsl_deck_P_add()", rc); - return *this; - } - - Deck & Deck::addCardQ(char type, fsl_uuid_cstr target, - fsl_uuid_cstr baseline){ - int const rc = fsl_deck_Q_add(*this, type, target, baseline); - this->assertRC("fsl_deck_Q_add()", rc); - return *this; - } - - Deck & Deck::addCardT(fsl_tagtype_e tagType, - char const * name, - fsl_uuid_cstr uuid, - char const * value){ - int const rc = fsl_deck_T_add( *this, tagType, uuid, name, value ); - this->assertRC("fsl_deck_T_add()", rc); - return *this; - } - - - Deck & Deck::setCardU(char const * user){ - if(!user || !*user){ - user = fsl_cx_user_get(this->cx); - } - if(!user || !*user){ - throw Exception(FSL_RC_MISUSE, - "setCardU(): NULL/empty user name is not legal."); - } - int const rc = fsl_deck_U_set(*this, user); - this->assertRC("fsl_deck_U_set()", rc); - return *this; - } - - Deck & Deck::setCardW(char const * content, fsl_int_t len){ - int const rc = fsl_deck_W_set(*this, content, len); - this->assertRC("fsl_deck_W_set()", rc); - return *this; - } - - Deck::FCardIterator::~FCardIterator() throw() - {} - - Deck::FCardIterator::FCardIterator(Deck & d, bool skipDeletedFiles) - : d(&d), - fc(NULL), - skipDeleted(skipDeletedFiles) - { - int const rc = fsl_deck_F_rewind(d); - if(rc) throw Exception(rc, "fsl_deck_F_rewind() failed: %s", - fsl_rc_cstr(rc)); - fsl_deck_F_next(d, &this->fc); - } - - Deck::FCardIterator::FCardIterator() throw() - : d(NULL), - fc(NULL), - skipDeleted(false) - {} - - void Deck::FCardIterator::assertHasDeck(){ - if(!this->d) throw Exception(FSL_RC_MISUSE, - "Iterator requires a deck object."); - } - - Deck::FCardIterator & Deck::FCardIterator::operator++(){ - if(this->fc){ - do{ - int const rc = fsl_deck_F_next(*this->d, &this->fc); - if(rc) throw Exception(rc); - }while(skipDeleted && (this->fc && !this->fc->uuid)); - } - return *this; - } - - fsl_card_F const * Deck::FCardIterator::operator*(){ - return this->fc; - } - - fsl_card_F const * Deck::FCardIterator::operator->(){ - if(!this->fc) throw Exception(FSL_RC_MISUSE, - "Throwing to avoid " - "dereferencing a NULL fsl_card_F."); - return this->fc; - } - - - bool Deck::FCardIterator::operator==(FCardIterator const &rhs) const throw(){ - if(this->fc==rhs.fc) return true; - else if(!this->fc || !rhs.fc) return false; - return 0==fsl_strcmp(this->fc->name, rhs.fc->name); - } - - bool Deck::FCardIterator::operator!=(FCardIterator const &rhs) const throw(){ - if(this->fc==rhs.fc) return false; - else if(!this->fc || !rhs.fc) return true; - return 0!=fsl_strcmp(this->fc->name, rhs.fc->name); - } - - bool Deck::FCardIterator::operator<(FCardIterator const &rhs) const throw(){ - if(!this->fc) return rhs.fc ? true : false; - else if(!rhs.fc) return false; - return 0 > fsl_strcmp(this->fc->name, rhs.fc->name); - } - - Deck * Deck::baseline(){ - if(FSL_SATYPE_CHECKIN==this->d->type){ - if(this->deltaBase) return this->deltaBase; - else if(!this->d->B.uuid) return NULL; - else if(!this->d->B.baseline){ - int const rc = fsl_deck_F_rewind(*this); - this->assertRC("fsl_deck_rewind()", rc); - assert(this->d->B.baseline); - } - return this->deltaBase = new Deck(this->cx, - this->d->B.baseline, - false); - }else{ - return NULL; - } - } - - Deck::TCardIterator::TCardIterator(Deck & d) - : ParentType(d.handle()->T) - {} - - Deck::TCardIterator::TCardIterator() - : ParentType() - {} - - Deck::TCardIterator::~TCardIterator() throw() - {} - - fsl_card_T const * Deck::TCardIterator::operator->() const{ - fsl_card_T const * rv = this->currentValue(); - if( !rv ) throw Exception(FSL_RC_MISUSE, - "Throwing to avoid dereferencing a NULL " - "fsl_card_T."); - else return rv; - } - std::ostream & operator<<( std::ostream & os, Deck const & d ){ - d.output(os); - return os; - } - -} // namespace fsl - -#undef CERR DELETED bindings/cpp/Exception.cpp Index: bindings/cpp/Exception.cpp ================================================================== --- bindings/cpp/Exception.cpp +++ bindings/cpp/Exception.cpp @@ -1,121 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=2 et sw=2 tw=80: */ -#include "fossil-scm/fossil.hpp" -#include - -/* only for debugging */ -#include -#define CERR std::cerr << __FILE__ << ":" << std::dec << __LINE__ << " : " - -namespace fsl { - - Exception::~Exception() throw() { - fsl_error_clear(*this); - } - - Exception::Exception(Exception const &other) throw() - : err(fsl_error_empty){ - fsl_error_copy(&other.err, *this); - //CERR << "Exception("<code){ - fsl_error_copy( err, *this ); - }else{ - fsl_error_set( *this, FSL_RC_MISUSE, - "Exception(fsl_error const *) ctor passed a %s!", - err ? "fsl_error with code==0" : "NULL"); - } - } - - void Exception::error(int code, char const * fmt, va_list vargs) throw(){ - fsl_error_setv(*this, code, fmt, vargs); - //CERR << "Exception("<error(code, fmt, vargs); - va_end(vargs); - } - - Exception::Exception(int code, char const * fmt, va_list vargs) throw() - : err(fsl_error_empty){ - this->error(code, fmt, vargs); - } - - Exception::operator fsl_error * () throw(){ - return &this->err; - } - - Exception::operator fsl_error const * () const throw(){ - return &this->err; - } - - char const * Exception::messsage() const throw(){ - return this->what(); - } - - char const * Exception::what() const throw() { - return (FSL_RC_OOM==this->err.code) - ? fsl_rc_cstr(this->err.code) - : fsl_buffer_cstr(&this->err.msg); - } - - char const * Exception::codeString() const throw(){ - return fsl_rc_cstr(this->err.code); - } - - int Exception::code() const throw(){ - return this->err.code; - } - - OOMException::OOMException() throw() - : Exception(FSL_RC_OOM) - { - } - -} // namespace fsl - -#undef CERR DELETED bindings/cpp/Fossil.cpp Index: bindings/cpp/Fossil.cpp ================================================================== --- bindings/cpp/Fossil.cpp +++ bindings/cpp/Fossil.cpp @@ -1,193 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=2 et sw=2 tw=80: */ -#include "fossil-scm/fossil.hpp" - -/** - - */ -namespace fsl { - - - Buffer::~Buffer() throw(){ - this->clear(); - } - - Buffer::Buffer(fsl_size_t startingSize) - : buf(fsl_buffer_empty) - { - if(startingSize){ - if(fsl_buffer_reserve(&this->buf, startingSize)){ - throw OOMException(); - } - } - } - - Buffer::Buffer() - : buf(fsl_buffer_empty) - {} - - Buffer & Buffer::operator=(Buffer const & other){ - fsl_size_t const oldSize = this->buf.capacity; - this->reset(); - if((&other != this) - && !other.empty() - && fsl_buffer_append(*this, other.mem(), other.used()) - ){ - throw OOMException(); - } - /* A rather arbitrary heuristic to determine whether or not - we should free up some spce by to resizing buf() - after re-using it... */ - if((this->buf.capacity == oldSize) - && (this->buf.capacity > 20) - && (this->buf.used < (this->buf.capacity/2))){ - fsl_buffer_resize( *this, this->buf.used ); - } - return *this; - } - - Buffer::Buffer(Buffer const & other) - : buf() { - if(!other.empty() - && fsl_buffer_append(*this, other.mem(), other.used()) - ){ - throw OOMException(); - } - } - - Buffer::operator fsl_buffer *() throw(){ - return &this->buf; - } - - Buffer::operator fsl_buffer const *() const throw(){ - return &this->buf; - } - - fsl_buffer * Buffer::handle() throw(){ - return &this->buf; - } - - fsl_buffer const * Buffer::handle() const throw(){ - return &this->buf; - } - - bool Buffer::empty() const throw() { return 0==this->buf.used; } - - fsl_size_t Buffer::used() const throw() { return this->buf.used; } - - fsl_size_t Buffer::capacity() const throw() { return this->buf.capacity; } - - unsigned char const * Buffer::mem() const throw() { - return this->buf.used - ? this->buf.mem - : NULL; - } - - unsigned char * Buffer::mem() throw() { - return this->buf.used - ? this->buf.mem - : NULL; - } - - Buffer & Buffer::clear() throw() { - fsl_buffer_clear(*this); - return *this; - } - - Buffer & Buffer::reset() throw() { - fsl_buffer_reuse(*this); - return *this; - } - - Buffer & Buffer::reserve(fsl_size_t n){ - int const rc = fsl_buffer_reserve(*this, n); - if(rc) throw Exception(rc, "Buffer::reserve() failed"); - return *this; - } - - Buffer & Buffer::resize(fsl_size_t n){ - int const rc = fsl_buffer_resize(*this, n); - if(rc) throw Exception(rc, "Buffer::resize() failed"); - return *this; - } - - Buffer::iterator Buffer::begin() throw() { - return this->buf.used - ? this->buf.mem - : NULL; - } - - Buffer::iterator Buffer::end() throw() { - return this->buf.used - ? this->buf.mem + this->buf.used - : NULL; - } - - Buffer::const_iterator Buffer::begin() const throw() { - return this->buf.mem; - } - - Buffer::const_iterator Buffer::end() const throw() { - return this->buf.used - ? this->buf.mem + this->buf.used - : NULL; - } - - std::ostream & operator<<( std::ostream & os, Buffer const & b ){ - fsl_size_t n = 0; - char const * s = fsl_buffer_cstr2(b, &n); - if(n) os.write(s, n); - return os; - } - - Buffer & Buffer::appendf(char const * fmt, ...){ - va_list vargs; - int rc = 0; - va_start(vargs,fmt); - rc = fsl_buffer_appendfv(*this, fmt, vargs); - va_end(vargs); - if(rc){ - throw Exception(rc, "fsl_appendfv() failed: %s", - fsl_rc_cstr(rc)); - } - return *this; - } - - char const * Buffer::c_str() const throw(){ - return fsl_buffer_cstr(*this); - } - - void Buffer::toss(int errorCode) const{ - throw Exception(errorCode, "%s", fsl_buffer_cstr(*this)); - } - - int fsl_input_f_std_istream( void * state, void * dest, fsl_size_t * n ){ - std::istream * is = static_cast(state); - try{ - /** - We have to read byte-by-byte to fullfil the requirement that - we write the number of read bytes to *n. std::istream::read() - does not give us a (direct) way to know exactly how many - bytes were read before EOF. - */ - int rc; - fsl_size_t i; - unsigned char * out = (unsigned char *) dest; - for( i = 0; i < *n; ++i ){ - rc = is->get(); - if(is->eof()){ - *n = i; - return 0; - }else if(!is->good()){ - return FSL_RC_IO; - }else{ - *out++ = rc & 0xFF; - } - } - return 0; - }catch(...){ - return FSL_RC_IO; - } - } - -} // namespace fsl DELETED bindings/cpp/Makefile.in Index: bindings/cpp/Makefile.in ================================================================== --- bindings/cpp/Makefile.in +++ bindings/cpp/Makefile.in @@ -1,129 +0,0 @@ -all: -include ../../subdir-inc.make -#$(error $(TOP_SRCDIR)) -#CPPFLAGS += -I$(TOP_INCDIR) -#CPPFLAGS += -I$(TOP_SRCDIR)/include -CPPFLAGS += -I$(TOP_SRCDIR)/src# workaround for in-tree sqlite3.h -CXXFLAGS += -fPIC -Wall -Werror - -#INCLUDES_PATH ?= $(HOME)/include /usr/local/include /usr/include - -LIBFOSSIL.LDFLAGS := -L$(TOP_SRCDIR) -lfossil -lz - -#ifeq (,$(strip $(filter distclean clean,$(MAKECMDGOALS)))) -#$(LIBFOSSIL.LDFLAGS): -# $(MAKE) -C .. -#endif - -CPP.SRC := \ - Context.cpp \ - Db.cpp \ - Deck.cpp \ - Exception.cpp \ - Fossil.cpp \ - OStream.cpp - -OBJECTS := $(patsubst %.cpp,%.o,$(CPP.SRC)) - -libfossil++.DLL.OBJECTS := $(OBJECTS) -libfossil++.BIN.LDFLAGS := -lstdc++ -fPIC $(LIBFOSSIL.LDFLAGS)# -lsqlite3 -lz -libfossil++.LIB.OBJECTS := $(libfossil++.DLL.OBJECTS) -Makefile: Makefile.in -$(libfossil++.DLL.OBJECTS): Makefile -######################################################################## -# Shared lib -$(eval $(call ShakeNMake.CALL.RULES.DLLS,libfossil++)) -all: $(libfossil++.DLL) -$(libfossil++.DLL): $(libfossil++.DLL.OBJECTS) -#Static lib (don't work well with _some_ C++ template uses) -#$(eval $(call ShakeNMake.CALL.RULES.LIBS,libfossil++)) -#all: $(libfossil++.LIB) -#$(libfossil++.LIB): $(libfossil++.LIB.OBJECTS) - -test.BIN.OBJECTS := test.o -ifeq (0,1) -test.BIN.LDFLAGS := $(LIBFOSSIL.LDFLAGS) $(EXTRA_LIBS) -lstdc++ -L. -lfossil++ @SH_LINKFLAGS@ -else -test.BIN.OBJECTS += $(libfossil++.DLL.OBJECTS) -test.BIN.LDFLAGS := $(LIBFOSSIL.LDFLAGS) $(EXTRA_LIBS) -lstdc++ @SH_LINKFLAGS@ -endif -$(eval $(call ShakeNMake.CALL.RULES.BINS,test)) -all: $(test.BIN) - - -######################################################################## -# A quick-n-dirty amalgamation build... -INCD := $(TOP_INCDIR)/fossil-scm -AMAL_D := $(TOP_SRCDIR_REL) -AMAL_C := $(AMAL_D)/libfossil.c -AMAL_H := $(AMAL_D)/libfossil.h -AMAL_CPP := $(AMAL_D)/libfossil++.cpp -AMAL_HPP := $(AMAL_D)/libfossil++.hpp -AMAL_CONF.H := $(AMAL_D)/libfossil-config.h -CLEAN_FILES += $(AMAL_HPP) $(AMAL_CPP) - -$(AMAL_C) $(AMAL_H): - $(MAKE) -C $(TOP_SRCDIR_REL)/src amal - -AMAL_CPP.SRC := \ - $(CPP.SRC) - -# ACHTUNG: in AMAL_H.SRC, $(AMAL_CONF.H) MUST be included first. -AMAL_HPP.SRC := \ - $(INCD)/fossil.hpp - -$(AMAL_HPP.SRC): -$(AMAL_CPP.SRC): -$(AMAL_HPP): Makefile $(AMAL_HPP.SRC) -$(AMAL_CPP): Makefile $(AMAL_HPP) $(AMAL_CPP.SRC) -$(AMAL_CONF.H): $(MAIN_MAKEFILES) - @echo "Generating $@ ..." - cd $(TOP_SRCDIR_REL) && sh configure --amal - -$(AMAL_HPP): - @echo "Creating $@..." - @{ \ - echo '#if !defined(FSLPP_AMALGAMATION_BUILD)'; \ - echo '#define FSLPP_AMALGAMATION_BUILD 1'; \ - echo '#endif'; \ - echo '#include "$(notdir $(AMAL_H))"'; \ - } > $@ - @{ \ - for i in $(AMAL_HPP.SRC); do \ - echo "/* start of file $$i */"; \ - cat $$i; \ - echo "/* end of file $$i */"; \ - done; \ - } | sed \ - -e '/[ ]*#[ ]*include[ ]*.*fossil.*\.h[>"]/d' \ - -e '/[ ]*#[ ]*include[ ]*.*".*config\.h[>"]/d' \ - >> $@ - -$(AMAL_CPP): $(AMAL_HPP) - @echo "Creating $@..." - @echo '#include "$(notdir $(AMAL_HPP))"' > $@ - @{ \ - for i in $(AMAL_CPP.SRC); do \ - echo "/* start of file $$i */"; \ - cat $$i; \ - echo "/* end of file $$i */"; \ - done; \ - } | sed \ - -e '/[ ]*#[ ]*include[ ]*.*fossil.*\.h.*[>"]/d' \ - >> $@ - -AMAL_CPP_FLAGS := -I$(TOP_INCDIR) -I$(TOP_SRCDIR_REL) -I. -I$(TOP_SRCDIR_REL)/src# for sqlite3.h :/ -.PHONY: amal -amal: $(AMAL_CPP) - @ls -ls $(AMAL_CPP) $(AMAL_HPP) - @if which g++ >/dev/null; then \ - echo "Trying GCC..."; \ - g++ -c $(AMAL_CPP) -pedantic -Wstrict-aliasing -Wall -Werror -Wno-long-long $(AMAL_CPP_FLAGS); \ - fi; true - @if which clang >/dev/null; then \ - echo "Trying clang..."; \ - clang -c $(AMAL_CPP) -pedantic -Wstrict-aliasing -Wall -Werror -Wno-long-long $(AMAL_CPP_FLAGS); \ - fi; true - -# /amalgamation -######################################################################## DELETED bindings/cpp/OStream.cpp Index: bindings/cpp/OStream.cpp ================================================================== --- bindings/cpp/OStream.cpp +++ bindings/cpp/OStream.cpp @@ -1,206 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=2 et sw=2 tw=80: */ -#include "fossil-scm/fossil.hpp" - -/** - - */ -namespace fsl { - - - fsl_int_t fsl_appendf_f_std_ostream( void * state, - char const * data, - fsl_int_t n ){ - std::ostream * os = static_cast(state); - try{ - os->write( data, (std::streamsize)n ); - return (*os) ? 0 : FSL_RC_IO; - }catch(...){ - return FSL_RC_IO; - } - } - - int fsl_output_f_std_ostream( void * state, - void const * data, - fsl_size_t n ){ - std::ostream * os = static_cast(state); - try{ - os->write( (char const *)data, (std::streamsize)n ); - return (*os) ? 0 : FSL_RC_IO; - }catch(...){ - return FSL_RC_IO; - } - } - - - ContextOStreamBuf::~ContextOStreamBuf() throw(){ - this->sync(); - if( this->m_os ){ - this->m_os->rdbuf( this->m_old ); - } - } - - void ContextOStreamBuf::setup( fsl_cx * fx ){ - if(!fx) throw Exception(FSL_RC_MISUSE, - "ContextOStreamBuf requires " - "a non-NULL fsl_cx."); - this->f = fx; - this->setp( 0, 0 ); - this->setg( 0, 0, 0 ); - if(m_os) m_os->rdbuf( this ); - } - - ContextOStreamBuf::ContextOStreamBuf( fsl_cx * f, std::ostream & os ) - : f(NULL), - m_os(&os), - m_old(os.rdbuf()){ - this->setup(f); - } - - ContextOStreamBuf::ContextOStreamBuf( fsl_cx * f ) - : f(NULL), - m_os(NULL), - m_old(NULL){ - this->setup(f); - } - - ContextOStreamBuf::ContextOStreamBuf( Context & cx, std::ostream & os ) - : f(NULL), - m_os(&os), - m_old(os.rdbuf()){ - this->setup(cx.handle()); - } - - ContextOStreamBuf::ContextOStreamBuf( Context & cx ) - : f(NULL), - m_os(NULL), - m_old(NULL){ - this->setup(cx.handle()); - } - - - int ContextOStreamBuf::overflow( int c ){ - char const ch = c & 0xFF; - int const rc = fsl_output(this->f, &ch, 1); - if(rc) throw Exception(FSL_RC_IO, - "fsl_output() failed with code %d (%s)", - rc, fsl_rc_cstr(rc)); - else return 0; - } - - int ContextOStreamBuf::sync(){ - return this->f - ? fsl_flush(this->f) - : FSL_RC_IO; - } - - ContextOStream::~ContextOStream() throw(){ - delete this->sb; - } - - ContextOStream::ContextOStream( fsl_cx * f ) - :f(f), - sb(new ContextOStreamBuf(f, *this)){ - } - - ContextOStream::ContextOStream( Context & cx ) - :f(cx.handle()), - sb(new ContextOStreamBuf(f, *this)){ - } - - ContextOStream & ContextOStream::appendf(char const * fmt, ...){ - va_list vargs; - int rc = 0; - va_start(vargs,fmt); - rc = fsl_outputfv(this->f, fmt, vargs); - va_end(vargs); - if(rc){ - throw Exception(rc, "fsl_outputfv() failed: %s", - fsl_rc_cstr(rc)); - } - return *this; - } - - FslOutputFStreamBuf::~FslOutputFStreamBuf() throw(){ - if( this->m_os ){ - this->m_os->rdbuf( this->m_old ); - } - } - - void FslOutputFStreamBuf::setup( fsl_output_f f, void * state ){ - if(!f) throw Exception(FSL_RC_MISUSE, - "FslOutputFStream output function may " - "not be NULL."); - this->out = f; - this->outState = state; - this->setp( 0, 0 ); - this->setg( 0, 0, 0 ); - if(m_os) m_os->rdbuf( this ); - } - - FslOutputFStreamBuf::FslOutputFStreamBuf( fsl_output_f f, void * state ) - : out(NULL), outState(NULL), - m_os(NULL), m_old(NULL) - { - this->setup(f, state); - } - - FslOutputFStreamBuf::FslOutputFStreamBuf( fsl_output_f f, void * state, - std::ostream & os) - : out(NULL), outState(NULL), - m_os(&os), m_old(os.rdbuf()) - { - this->setup(f, state); - } - - int FslOutputFStreamBuf::overflow( int c ){ - char const ch = c & 0xFF; - int const rc = this->out( this->outState, &ch, 1); - if(rc) throw Exception(FSL_RC_IO, - "fsl_output_f() proxy failed with code " - "%d (%s)", rc, fsl_rc_cstr(rc)); - else return 0; - } - - int FslOutputFStreamBuf::sync(){ - return 0; - } - - FslOutputFStream::~FslOutputFStream() throw(){ - delete this->sb; - } - - FslOutputFStream::FslOutputFStream( fsl_output_f out, void * outState ) - : sb(new FslOutputFStreamBuf(out, outState, *this)){ - } - - fsl_int_t FslOutputFStream::fslAppendfF( void * state, - char const * s, fsl_int_t n ){ - FslOutputFStream * out = static_cast(state); - if(out->good()){ - out->write( s, (std::streamsize)n ); - return out->good() ? 0 : -1; - }else return -1; - } - - FslOutputFStream & FslOutputFStream::appendf(char const * fmt, ...){ - va_list vargs; - fsl_int_t rc = 0; - va_start(vargs,fmt); - rc = fsl_appendfv(FslOutputFStream::fslAppendfF, this, fmt, vargs); - va_end(vargs); - if(rc<0) throw Exception(FSL_RC_IO, - "fsl_appendfv() failed mysteriously."); - return *this; - } - - BufferOStream::BufferOStream(fsl_buffer * b) : - FslOutputFStream(fsl_output_f_buffer, b){ - if(!b) throw Exception(FSL_RC_MISUSE, - "fsl_buffer argument may not be NULL."); - } - - BufferOStream::~BufferOStream() throw(){ - } - -} // namespace fsl DELETED bindings/cpp/test.cpp Index: bindings/cpp/test.cpp ================================================================== --- bindings/cpp/test.cpp +++ bindings/cpp/test.cpp @@ -1,271 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=2 et sw=2 tw=80: */ -#include "fossil-scm/fossil.hpp" /* MUST come first b/c of config bits. */ -#include -#include -#include -#include -#include /* EXIT_SUCCESS, EXIT_FAILURE */ - -#define CERR std::cerr << __FILE__ << ":" << std::dec << __LINE__ << " : " -#define COUT std::cout << __FILE__ << ":" << std::dec << __LINE__ << " : " - -#define RCStr(C) fsl_rc_cstr(C) - -/** - A functor for use with fsl::Stmt::eachRow(). -*/ -struct RowDumper { - std::ostream & os; - char const * separator; - bool showHeader; - explicit RowDumper(std::ostream & os = std::cout) - : os(os), - separator("\t"), - showHeader(true) - {} - void operator()(fsl::Stmt &s) const{ - int i; - int const n = s.columnCount(); - if(this->showHeader && (1==s.stepCount())){ - for(i = 0; i < n; ++i ){ - this->os << (i ? this->separator : "") << s.columnName(i); - } - this->os << '\n'; - } - for(i = 0; i < n; ++i ){ - this->os << (i ? this->separator : "") << s.getText(i); - } - this->os << '\n'; - } -}; - -static void test_db_1(){ - namespace f = fsl; - char const * dbName = 0 - ? "/fail" - : ":memory:" - ; - //using fsl::Exception; - //throw Exception(FSL_RC_NYI, "Just %s", "testing"); - f::Db db; - f::Stmt st(db); - db.open(dbName, FSL_OPEN_F_RWC); - COUT << "Opened db: "< LI; - LI li; - li.push_back("4"); - li.push_back("fource. Or fice."); - b.bindList(li).insert(); - - st.finalize() - .prepare("SELECT rowid, a, b FROM t ORDER BY a") - .eachRow( RowDumper() ) - .finalize(); - - f::Buffer sb; - (sb << "SELECT ").appendf("%Q", "percent 'Q'"); - st.prepare(sb) - .eachRow( RowDumper() ); - -} - -static void test_stream_1(fsl::Context & cx){ - namespace f = fsl; - - f::ContextOStream fout(cx); - { - char const * sym = "rid:1"; - fout << "UUID of ["< "<type) - << tag->name; - } - fout << '\n'; - } - - fout << "Re-read artifact via Deck::load():\n"; - fout << f::Deck(cx).load( d.rid() ); - - f::Buffer content; - cx.getContent( d.rid(), content ); - fout << "And again via Context::getContent():\n" << content; - } - - if(0){ - fsl_id_t rid = 1; - fout << "Loading checkin #"<name); - assert(fit->name == fc->name); - } - fout << "Traversed " - < $@ -$(UNIT_MEGA2.S2): $(UNIT_SCRIPT_LIST) Makefile - @echo "Generating $@..." - @{ \ - false && echo "const INTERN_THESE=['object','array','integer','double','string','function','bool'];"; \ - for i in $(UNIT_SCRIPT_LIST); do \ - echo "import(false,'$$i');"; \ - done; \ - } > $@ - -.PHONY: unit unit-proxy unit2 -unit-proxy: $(f-s2sh.BIN) $(UNIT_GENERATED) - @for i in $(UNIT_SCRIPTS_ALL); do \ - cmd="$(UNIT_RUN_CMD) -f $$i"; \ - echo "****************************** Script [$$i]"; \ - echo $$cmd; $$cmd || exit $$?; \ - echo "****************************** Done [$$i]"; \ - done - @echo "Done running through unit test scripts." - -unit: UNIT_SCRIPTS_ALL:=$(UNIT_SCRIPT_LIST) $(UNIT_GENERATED) -unit: unit-proxy -unit2: UNIT_SCRIPTS_ALL:=$(filter unit2/%,$(UNIT_SCRIPT_LIST)) -unit2: unit-proxy -.PHONY: unit-r -.PHONY: unit-rc -unit-r: S2SH.SHELL.FLAGS:=--no-init-script -norv -norc -unit-r: unit -unit-s: S2SH.SHELL.FLAGS:=--no-init-script -rc -rc -nosi -unit-s: unit -unit-rc: S2SH.SHELL.FLAGS:=--no-init-script -norv -norc -unit-rc: unit -unit-rsc: S2SH.SHELL.FLAGS:=--no-init-script -norv -norc -nosi -unit-rsc: unit -units: - @for i in unit unit-r unit-rc unit-s unit-rsc; do \ - echo "Making $$i ..."; \ - $(MAKE) $$i || exit $$?; \ - done -include vg.make DELETED bindings/s2/cliapp.c Index: bindings/s2/cliapp.c ================================================================== --- bindings/s2/cliapp.c +++ bindings/s2/cliapp.c @@ -1,548 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=2 et sw=2 tw=80: */ - -#ifdef HAVE_CONFIG_H -# include "config.h" -#endif -#include "cliapp.h" -#include -#include -#include /* vsprintf() */ -#include /* abort() */ - -#ifndef CLIAPP_ENABLE_READLINE -# define CLIAPP_ENABLE_READLINE 0 -#endif - -#ifndef CLIAPP_ENABLE_LINENOISE -# define CLIAPP_ENABLE_LINENOISE 0 -#endif - -#if CLIAPP_ENABLE_READLINE && CLIAPP_ENABLE_LINENOISE -# error "Use *one* of CLIAPP_ENABLE_READLINE or CLIAPP_ENABLE_LINENOISE, not both." -#endif - -#if CLIAPP_ENABLE_LINENOISE -# include "linenoise/linenoise.h" -#elif CLIAPP_ENABLE_READLINE -# include "readline/readline.h" -# include "readline/history.h" -#endif - - -#if 1 -#define MARKER(pfexp) if(1) printf("%s:%d:\t",__FILE__,__LINE__); \ - if(1) printf pfexp -#else -static void noop_printf(char const * fmt, ...) {} -#define MARKER(pfexp) if(0) noop_printf pfexp -#endif -#define MESSAGE(pfexp) printf pfexp - -struct CliApp cliApp = { -0/*argc*/, 0/*argv*/, -0/*cursorNonflag*/, -0/*errMsg*/, -0/*flags*/, -vprintf/*print*/, -0/*argCallback*/, -{/*doubleDash*/ - 0/*argc*/, - 0/*argv*/ -}, -{/*lineread*/ - CLIAPP_ENABLE_LINENOISE ? 1 : (CLIAPP_ENABLE_READLINE ? 2 : 0) /*enabled*/, - 0 /* historyFile */, 0 /*needsSave*/ -} -}; - -enum { -/** Buffer size for cliapp_errmsg() */ -CLIAPP_MSGBUF_SIZE = 1024 * 4, -/** Buffer size for cliapp_process_argv() argument keys. */ -CLIAPP_ARGV_KBUF_SIZE = 1024 * 2, -/** Maximum cliapp_process_argv() arg count. */ -CLIAPP_ARGV_COUNT = (int)(1024 * 2 / sizeof(CliAppArg)) -}; - -static char cliAppErrBuf[CLIAPP_MSGBUF_SIZE] = {0}; - -static char const * cliapp_verrmsg(char const * fmt, va_list args){ - int rc; - char * buf = cliAppErrBuf; - rc = vsprintf(buf, fmt, args) - /* Noting that vsnprintf() requires C99 and s2 aims to compile in - strict C89 mode. */; - if(rc >= CLIAPP_MSGBUF_SIZE){ - fprintf(stderr,"%s:%d: Internal misuse of error message buffer. " - "Dangerous buffer overrun!\n", - __FILE__, __LINE__); - abort(); - } - return cliApp.errMsg = buf; -} -static char const * cliapp_errmsg(char const * fmt, ...){ - /** Stores error messages, at least until it's overwritten. */ - char const * rc; - va_list args; - va_start(args,fmt); - rc = cliapp_verrmsg(fmt, args); - va_end(args); - return rc; -} - -void cliapp_err_clear(){ - cliApp.errMsg = 0; - cliAppErrBuf[0] = 0; -} - -char const * cliapp_err_get(){ - return cliApp.errMsg; -} - -static const CliAppSwitch CliAppSwitch_end = CliAppSwitch_sentinel; -#define cliapp__switch_is_end(S) \ - (0==memcmp(S, &CliAppSwitch_end, sizeof(CliAppSwitch))) -int cliapp_switch_is_end(CliAppSwitch const *s){ - return cliapp__switch_is_end(s); -} - -CliAppSwitch const * cliapp_switch_for_arg(CliAppArg const * arg, - int alsoFlag){ - CliAppSwitch const * a = cliApp.switches; - for(; !cliapp__switch_is_end(a); ++a){ - if((alsoFlag==0 || arg->dash==a->dash) - && 0==strcmp(a->key, arg->key)){ - return a; - } - } - return 0; -} - -CliAppArg const * cliapp_arg_next_same(CliAppArg const * arg){ - CliAppArg const * a = arg; - CliAppArg const * tail = cliApp.argv + cliApp.argc; - if(arg < cliApp.argv || arg >= tail){ - return 0; - } - for( ++a; a < tail; ++a ){ - if(a->key && 0==strcmp(a->key, arg->key)) return a; - } - return 0; -} - -CliAppArg const * cliapp_arg_nonflag(){ - CliAppArg const * p = 0; - for(; cliApp.cursorNonflag < cliApp.argc;){ - p = cliApp.argv + cliApp.cursorNonflag; - ++cliApp.cursorNonflag; - if(p->key && 0==p->dash){ - return p; - } - } - return 0; -} - -void cliapp_arg_nonflag_rewind(){ - cliApp.cursorNonflag = 1; -} - -CliAppArg const * cliapp_arg_flag(char const * key1, - char const * key2, - int *atPos){ - int i = atPos ? *atPos : 1; - assert(key1 || key2); - if(!key1 & !key2) return 0; - for( ; i < cliApp.argc; ++i ){ - CliAppArg const * p = cliApp.argv + i; - if(!p->key) continue; - else if((key1 && 0==strcmp(key1,p->key)) - || - (key2 && 0==strcmp(key2,p->key))){ - if(atPos) *atPos = i; - return p; - } - } - return 0; -} - -char const * cliapp_flag_prefix( int flag ){ - char const * flags[4] = {"+", "", "-", "--"}; - assert(flag>=-1 && flag<=2); - return flag>=-1 && flag<=2 ? flags[flag+1] : ""; -} - -void cliapp_switches_visit( CliAppSwitch_visitor_f visitor, - void * state ){ - CliAppSwitch const * s = cliApp.switches; - assert(s); - for( ; !cliapp__switch_is_end(s); ++s){ - if(visitor(s, state)) break; - } -} - -void cliapp_args_visit( CliAppArg_visitor_f visitor, void * state, - unsigned short skipArgs ){ - int i = skipArgs; - CliAppArg const * a = i < cliApp.argc - ? &cliApp.argv[i] : NULL; - for( ; i < cliApp.argc; ++i, ++a ){ - if(a->key && visitor(a, i, state)) break; - } -} - -void cliapp_printv(char const *fmt, va_list vargs){ - if(cliApp.print){ - cliApp.print(fmt, vargs); - } -} - -void cliapp_print(char const *fmt, ...){ - if(cliApp.print){ - va_list vargs; - va_start(vargs,fmt); - cliApp.print(fmt, vargs); - va_end(vargs); - } -} - -void cliapp_warn(char const *fmt, ...){ - va_list vargs; - va_start(vargs,fmt); - vfprintf(stderr, fmt, vargs); - va_end(vargs); -} - -#if 0 -static void cliapp_perr(char const *fmt, ...){ - va_list vargs; - va_start(vargs,fmt); - cliapp_verrmsg(fmt,vargs); - va_end(vargs); - va_start(vargs,fmt); - vfprintf(stderr, fmt, vargs); - va_end(vargs); -} -#endif - -/** - The list of arguments pointed to by cliApp.argv. -*/ -static CliAppArg cliAppArgv[CLIAPP_ARGV_COUNT]; -/** - An internal buffer used to store --flag keys for those keys which - require transformation. This is: for --flag=value, we copy the - "flag" part to this buffer so we can NUL-terminate it. For flags - with no '=' we simply refer to the original argv string pointers, - as those are NUL terminated. (We "could" modify the original - globals instead, but the thought of doing so makes me a ill.) -*/ -static char cliAppKeyBuf[CLIAPP_ARGV_KBUF_SIZE] -/* Store all NUL-terminated flag keys here, stripped of their - leading dashes and terminated at their '=' (if they had - one). */; - -/** - Internal helper for cliapp_process_argv() which checks list to see - if s is contained in it. list must be terminated by a NULL pointer. -*/ -static char cliapp_check_seen( CliAppSwitch const * const * list, - CliAppSwitch const * s ){ - int i = 0; - CliAppSwitch const * p; - assert(s); - while(1){ - p = list[i++]; - if(p == s) return 1; - else if(!p) break; - } - return 0; -} - -int cliapp_process_argv(int argc, char const * const * argv, - unsigned int reserved ){ - /*static CliAppSwitch const * sPending = 0; - static CliAppArg * aPending = 0;*/ - int i, rc = 0, doubleDashPos = 0; - char * k = &cliAppKeyBuf[0]; - char const *errMsg = 0; - CliAppSwitch const * switchPendingVal = 0 - /* Switch with the CLIAPP_F_SPACE_VALUE which is expecting - a value in the next argument. */; - CliAppArg * argPendingVal = 0 - /* arg counterpart of switchPendingVal */; - CliAppSwitch const * appSwitch = 0; - CliAppSwitch const * seenList[CLIAPP_ARGV_COUNT+1] - /* switches we've seen so far, so we can check for/enforce - the CLIAPP_F_ONCE flag */; - int seenCount = 0 /* number of entries in seenList */; - if(reserved){/*unused*/} - memset(seenList, 0, sizeof(seenList)); - assert(cliApp.switches - && "cliApp.switches must be set by the client " - "before calling this."); - cliApp.argv = &cliAppArgv[0]; - memset(&cliAppArgv[0], 0, sizeof(cliAppArgv)); -#define KCHECK if(k>=&cliAppKeyBuf[0]+CLIAPP_ARGV_KBUF_SIZE) goto err_overflow -#define BADFLAG(MSG) errMsg=MSG; goto misuse - for(i = 0; i < argc && 0==doubleDashPos; ++i){ - CliAppArg * p; - char const * arg; - int dashes = 0 /* number of dashes on the current flag */; - int callbackIndex = i - /* index to pass to callbacks. Gets modified in one case */; - if(i == CLIAPP_ARGV_COUNT){ - cliapp_errmsg("Too many (%d) arguments: internal buffer " - "limit (%d) would be reached.", argc, - CLIAPP_ARGV_COUNT); - return CLIAPP_RC_RANGE; - } - appSwitch = 0; - p = cliApp.argv + i; - arg = argv[i]; - if(*arg=='+'){ - dashes = -1; - ++arg; - } - while(*arg && '-'==*arg && dashes<4){ - if(-1==dashes){ - dashes = 3 /* trigger error below */; - break; - } - ++dashes; - ++arg; - } - if(dashes>2){ - BADFLAG("Too many dashes on flag."); - } - p->dash = dashes; - p->key = dashes ? k : arg - /* dashed args get stored, without dashes, in cliAppKeyBuf so - that we can terminate them with a NUL at their '='. Args - with no dashes are referenced to as-is - there's no need to - copy them for termination purposes. We don't know, at this - point, whether a '=' is pending, but we pessimistically - (optimistically?) assume there is. - */; - while(*arg && '='!=*arg){ - if(dashes){ - *k++ = *arg++; - KCHECK; - } - else ++arg; - } - if(*arg && !*p->key){ - BADFLAG("Empty flag name."); - } - KCHECK; - if(*arg){ - assert('='==*arg); - if(-1==dashes && '='==*arg){ - BADFLAG("+flags may not have a value."); - } - p->value = ++arg; - }else if(!*p->key && 2==dashes && !doubleDashPos){ - doubleDashPos = i; - p->key = p->value = 0; - } - if(dashes){ - *k++ = 0; - } - if(doubleDashPos && !switchPendingVal){ - /* Once we've encountered --, we must not continue to process - flags because a flag after -- is typically intended for some - downstream process, not the app on whose behalf we're - running, and might semantically collide with flags from our - own app. Also, such flags might have syntaxes we cannot - handle, so even processing them as flags is potentially a - bug. Rather than process them, we point cliApp.doubleDash.* - to that state so the client can deal with it (possibly be - passing it back into this function!). - - If switchPendingVal is not NULL we need to fall through to - catch the error case of a missing value at the end of the - arguments. - */ - break; - }else if(!doubleDashPos){ - ++cliApp.argc; - } - if(0){ - MARKER(("Arg #%d %d %s %s %s\n", - i, p->dash, p->key, - p->value ? "=" : "", - p->value ? p->value : "")); - } - if(switchPendingVal){ - assert(argPendingVal); - if(p->dash){ - appSwitch = switchPendingVal /* for error string */; - BADFLAG("Got a flag while the previous flag was expecting " - "a value"); - }else{ - argPendingVal->value = p->key; - p->key = p->value = 0; - p->dash = 0; - p = argPendingVal /* for the upcoming callback(s) */; - argPendingVal = 0; - switchPendingVal = 0; - --callbackIndex; - } - } - assert(!doubleDashPos); - if(p->dash && p->key){ /* -flag/--flag/+flag */ -#if defined(DEBUG) - static int check = 0; - check = callbackIndex; - assert(cliapp_arg_flag(p->key, 0, &check)); - assert(check == callbackIndex); -#endif - appSwitch = cliapp_switch_for_arg(p, 1); - if(!appSwitch){ - BADFLAG("Unknown flag"); - } - else if((appSwitch->pflags & CLIAPP_F_ONCE) - && cliapp_check_seen(seenList, appSwitch)){ - BADFLAG("Flag may only be provided once."); - } - else if(appSwitch->value && !p->value){ - if(i==argc-1){ - BADFLAG("Flag expecting a value at the end of the arguments"); - } - switchPendingVal = appSwitch; - argPendingVal = p; - }else if(appSwitch->callback){ - rc = appSwitch->callback(callbackIndex, appSwitch, p); - if(rc) return rc; - } - if(!switchPendingVal){ - seenList[seenCount++] = appSwitch; - } - }else{ - assert(cliapp_arg_nonflag()==p); - } - if(!switchPendingVal && cliApp.argCallack){ - rc = cliApp.argCallack(callbackIndex, appSwitch, p); - if(rc) return rc; - } - }/*for(each arg)*/ - if(cliApp.argCallack){ - rc = cliApp.argCallack(i, 0, 0); - if(rc) return rc; - } - -#undef BADFLAG -#undef KCHECK - cliApp.cursorNonflag = 1 /* skip argv[0] */; - if(doubleDashPos && doubleDashPos+1dash) : "", - (CLIAPP_MSGBUF_SIZE/4), - appSwitch ? appSwitch->key : "", - /*(4)*/ - appSwitch && appSwitch->value ? "=" : "", - CLIAPP_MSGBUF_SIZE/4, - appSwitch ? appSwitch->value : ""); - return CLIAPP_RC_FLAG; - err_overflow: - cliapp_errmsg("Too many CLI flag keys: their accumulated names " - "would overrun our %d-byte buffer.", - CLIAPP_ARGV_KBUF_SIZE); - return CLIAPP_RC_RANGE; -} - -char * cliapp_lineedit_read(char const * prompt){ -#if CLIAPP_ENABLE_LINENOISE - return linenoise(prompt); -#elif CLIAPP_ENABLE_READLINE - return readline(prompt); -#else - if(prompt){/*avoid unused param warning*/} - return 0; -#endif -} - -void cliapp_lineedit_free(char * line){ -#if CLIAPP_ENABLE_LINENOISE || CLIAPP_ENABLE_READLINE - free(line); -#else - if(line){ - assert(!"Where did this memory come from?"); - } -#endif -} - -int cliapp_lineedit_load(char const * fname){ - if(!fname) fname = cliApp.lineread.historyFile; - if(!fname || !*fname) return 0; -#if CLIAPP_ENABLE_LINENOISE - return linenoiseHistoryLoad(fname); -#elif CLIAPP_ENABLE_READLINE - return read_history(fname); -#else - if(fname){/*avoid unused param warning*/} - return CLIAPP_RC_UNSUPPORTED; -#endif -} - -int cliapp_lineedit_save(char const * fname){ - int rc = 0; - if(!fname) fname = cliApp.lineread.historyFile; - if(!cliApp.lineread.needsSave - || !fname || !*fname) return 0; -#if CLIAPP_ENABLE_LINENOISE - rc = linenoiseHistorySave(fname) ? CLIAPP_RC_IO : 0; -#elif CLIAPP_ENABLE_READLINE - rc = write_history(fname) ? CLIAPP_RC_IO : 0; -#else - if(fname){/*avoid unused param warning*/} - rc = CLIAPP_RC_UNSUPPORTED; -#endif - if(!rc) cliApp.lineread.needsSave = 0; - return rc; -} - -int cliapp_lineedit_add(char const * line){ - assert(line); -#if CLIAPP_ENABLE_LINENOISE - cliApp.lineread.needsSave = 1; - linenoiseHistoryAdd(line); - return 0; -#elif CLIAPP_ENABLE_READLINE - cliApp.lineread.needsSave = 1; - add_history(line); - return 0; -#else - if(line){/*avoid unused param warning*/} - return CLIAPP_RC_UNSUPPORTED; -#endif -} - -int cliapp_repl(CliApp_repl_f f, char const * const * prompt, - int addHistoryPolicy, void * state){ - char * line; - int rc = 0; - while( !rc && (line = cliapp_lineedit_read(*prompt)) ){ - if(addHistoryPolicy<0) cliapp_lineedit_add(line); - rc = f(line, state); - if(!rc && addHistoryPolicy>0) cliapp_lineedit_add(line); - cliapp_lineedit_free(line); - } - return rc; -} - -#undef cliapp__switch_is_end DELETED bindings/s2/cliapp.h Index: bindings/s2/cliapp.h ================================================================== --- bindings/s2/cliapp.h +++ bindings/s2/cliapp.h @@ -1,623 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=2 et sw=2 tw=80: */ -#ifndef NET_WH_CLIAPP_H_INCLUDED -#define NET_WH_CLIAPP_H_INCLUDED -/** - A mini-framework for handling some of the grunt work required by - CLI apps. It's main intent is to provide a halfway sane system for - handling CLI flags. It also provides an abstraction for CLI - editing, supporting either libreadline or liblinenoise, but only - supporting the most basic of editing facilities, not - library-specific customizations (e.g. custom key bindings). - - This API has no required dependencies beyond the C89 standard - libraries and requires no dynamic memory unless it's configured to - use an interactive line-reading backend. - - License: Public Domain - - Author: Stephan Beal -*/ - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/** - Flags for use with the CliAppSwitch::pflags field to modify - how cliapp_process_argv() handles the switch. -*/ -enum cliapp_switch_flags { -/** - Indicates that a CliAppSwitch is only allowed to be provided once. - If encountered more than once by cliapp_process_argv(), an error - is triggered. -*/ -CLIAPP_F_ONCE = 1, -/** - Indicates that a given CliAppSwitch requires a value and accepts - its value either in the form (-switch=value) or (-switch value). - When such a flag is encountered, cliapp_process_argv() will report - an error if the switch has no value (even if the flag appears at - the end of the arguments list or immediately before the - special-case "--" flag). - - Without this flag, switch values are only recognized in the form - (-switch=flag). -*/ -CLIAPP_F_SPACE_VALUE = 2 -/*TODO?: CLIAPP_F_VALUE_REQUIRED = 4 (implied by CLIAPP_F_SPACE_VALUE) */ -}; - -/** - Result codes used by various library routines. -*/ -enum cliapp_rc { -/** The non-error code */ -CLIAPP_RC_OK = 0, -/** Indicates an error in flag processing. */ -CLIAPP_RC_FLAG = -1, -/** Indicates a range-related error, e.g. buffer overrun or too many - CLI arguments. */ -CLIAPP_RC_RANGE = -2, -/** Indicates that an unsupported operation was requested. */ -CLIAPP_RC_UNSUPPORTED = -3, -/** Indicates some sort of I/O error. */ -CLIAPP_RC_IO = -4 -}; - - -/** - Holds state for a single CLI argument, be it a flag or non-flag. -*/ -struct CliAppArg { - /** - Must be 1 for single-dash flags, 2 for double-dash flags, and -1 - for '+' flags, and 0 for non-flags. - */ - int dash; - /** - Fow switches, this holds the switch's key, without dashes. For - non-switches, it holds the argument's value. - **/ - char const * key; - /** - For switches, the description of their value (if any) is stored here. - For non-switches, this is 0. - */ - char const * value; - /** - Arbitrary value which may be set/used by the client. It's not - used/modifed by this API. - */ - int opaque; -}; -typedef struct CliAppArg CliAppArg; - -struct CliAppSwitch; - -/** - A callback type used by cliapp_process_argv() to notify the app - when a CLI argument is processed which matches one of the app's - defined flags. It is passed the argument index, the switch (if any) - and the argument. - - Note that when processing switches flagged with - CLIAPP_F_SPACE_VALUE, the indexes passed to this function might - have gaps, as they skip over the VAL part of (-f VAL), instead - effectively transforming that to (-f=VAL) before calling the - callback for the -f switch. - - If the switch argument is NULL, the argument will be a non-flag - value. Note that arguments starting at the special-case "--" flag - are not passed on to the callback. Instead, such arguments get - reported via the cliApp.doubleDash member. - - It gets passed two NULL values one time at the end of processing in - order to allow the client code to do any final validation. - - If it returns non-0, cliapp_process_argv() will fail and return the - callback's result. -*/ -typedef int (*CliAppSwitch_callback_f)(int ndx, struct CliAppSwitch const * appSwitch, - CliAppArg * arg); -/** - Models a single flag/switch for a CLI app. It's not called - CliAppFlag because that proved confusing together with CliAppArg. -*/ -struct CliAppSwitch { - /** - Can be used by clients to, e.g. group help items by type or - set various levels of help verbosity. - */ - int opaque; - /** - As documented for CliAppArg::dash. - */ - int dash; - /** - The flag name, without leading dashes. - */ - char const * key; - /** - A human-readable description of its expected value, or 0 if the - flag does not require a value. - - BUG? It may still be assigned a value by the caller. We - currently require that behaviour for a special-case arg handler - in s2sh2. - */ - char const * value; - /** - Brief help text. - */ - char const * brief; - /** - Optional detailed help text. - */ - char const * details; - - /** - Optional callback to be passed a CliAppArg instance after it's been - initialized and confirmed as being a valid arg (defined in - cliApp.switches). If cliApp.argCallack is also used, both - callbacks are called, but this one is called first. - */ - CliAppSwitch_callback_f callback; - - /** - Reserved for future use by the cliapp interface, e.g. marking - "has seen this flag before" in order to implement only-once - behaviour. - */ - int pflags; -}; -typedef struct CliAppSwitch CliAppSwitch; - -/** - Client-defined CliApp.argv arrays MUST end with an entry identical - to this one. The iteration-related APIs treat any entry which - memcmp()'s as equivalent to this entry as being the end of th list. - - @see cliapp_switch_is_end() -*/ -#define CliAppSwitch_sentinel {0,0,0,0,0,0,0,0} - -/** - Returns true (non-0) if the given object memcmp()'s as equivalent - to CliAppSwitch_sentinel. - */ -int cliapp_switch_is_end(CliAppSwitch const *s); - -/** - vprintf()-compatible logging/printing interface for use with - CliApp. -*/ -typedef int (*CliApp_print_f)(char const *, va_list); - -/** - A callback for use with cliapp_switches_visit(). It is passed the - switch object and an arbitrary state pointer provided by the - caller of that function. -*/ -typedef int (*CliAppSwitch_visitor_f)(CliAppSwitch const *, void *); - -/** - Global app state. This class is intended to represent a singleton, - the cliApp object. -*/ -struct CliApp { - /** - Number of arguments in this->argv. It is modified as - cliapp_process_argv() executes and only counts arguments - up to, but not including the special-case "--" flag. - */ - int argc; - - /** - Arguments processed by cliapp_process_argv(). Contains - this->argc entries. This memory is not valid until - cliapp_process_argv() has succeeded. - */ - CliAppArg * argv; - - /** - Internal cursor for traversing non-flag arguments using - cliapp_arg_nonflag(). Holds the *next* index to be used by that - function. - */ - int cursorNonflag; - - /** - May be set to an error description by certain APIs and it may - point to memory which can mutate. - */ - char const * errMsg; - - /** - Must be set up by the client *before* calling - cliapp_process_argv() and its final entry MUST be an object for - which cliapp_switch_is_end() returns true (that's how we know when - to stop processing). - */ - CliAppSwitch const * switches; - - /** - If this is non-NULL, cliapp_print() and friends will use it for - output, otherwise they will elide all output. This defaults to - vprintf(). - */ - CliApp_print_f print; - - /** - If set, it gets called each time cliapp_process_argv() processes - an argument. If it returns non-0, processing fails. - - After processing successfully completes, the callback is called - one final time with NULL arguments so that the callback can - perform any end-of-list validation or whatnot. - - Using this callback effectively turns cliapp_process_argv() into - a push parser, which turns out to be a pretty convenient way to - handle CLI flags. - */ - CliAppSwitch_callback_f argCallack; - - /** - If cliapp_process_argv() encounters the "--" flag, and additional - arguments follow it, this object gets filled out with information - about them. - - Note that encountering "--" with no following arugments is not - considered an error. - */ - struct { - /** - If cliapp_process_argv() encounters "--", this value gets set - to the number of arguments available in the original argv array - immediately following (but not including) the "--" flag - */ - int argc; - /** - If cliapp_process_argv() encounters "--", and there are - arguments after it, this value is set to the list of arguments - (from the original argv array) immediately following the "--" - flag. If "--" is not encountered, or there are no arguments - after it, this member's value is 0. - */ - char const * const * argv; - } doubleDash; - - /** - State related to interactive line-editing/reading. - */ - struct { - /** - If enabled at compile-time, this has a value of 1 (for - linenoise) or 2 (for readline), else it has a value of 0. - - To use libreadline, compile this code's C file with - CLIAPP_ENABLE_READLINE set to a true value. To use linenoise, - build with CLIAPP_ENABLE_LINENOISE set to a true value. - */ - int const enabled; - /** - If non-NULL, cliapp_lineedit_save(NULL) will use this name for - saving. - */ - char const * historyFile; - /** - Specifies whether or not the line editing history has been - modified since the last save. - - This initially has a value of 0 and it gets set to non-0 if - cliapp_lineedit_add() is called. - */ - int needsSave; - } lineread; -}; - -/** - Behold! The One True Instance of CliApp! -*/ -extern struct CliApp cliApp; - -/** - Visits all switches in cliApp.switches, calling - visitor(theSwitch,state) for each one. If the visitor returns - non-0, visitation halts without an error. - - It stops iterating when it encounters an entry for which - cliapp_switch_is_end() returns true. -*/ -void cliapp_switches_visit( CliAppSwitch_visitor_f visitor, - void * state ); - -/** - Callback signature for use with cliapp_args_visit(). - - It gets passed the CLI argument, the index of that argument in - cliApp.argv, and an optional client-specified state pointer. -*/ -typedef int (*CliAppArg_visitor_f)(CliAppArg const *, int ndx, void *); - -/** - Visits all args in cliApp.argv, calling visitor(theSwitch,itsIndex,state) - for each one. If skipArgs is greater than 0, that many are skipped - over before visiting. Behaviour is undefined if a visitor modifies - cliApp.argv or cliApp.argc. If the visitor returns non-0, - visitation halts without an error. - - CliAppArg entries with a NULL key are skipped over, under the assumption - that the client app has marked them as "removed". -*/ -void cliapp_args_visit( CliAppArg_visitor_f visitor, void * state, - unsigned short skipArgs ); - -/** - Initializes the argument-processing parts of the cliApp global - object with. It is intended to be passed the conventional argc/argv - arguments which are passed to the application's main(). - - The final parameter is reserved for future use in providing flags - to change this function's behaviour. A value of 0 is reserved as - meaning "the default behaviour." - - cliApp.switches must have been assigned to non-NULL before calling - this, or behaviour is undefined. If any given switch has a callback - assigned to it, it will be called when that switch is processed, - and processing fails if it returns non-0. (Potential TODO: allow a - NULL switches value to simply treat all flags a known switches.) - - If cliApp.argCallack is not-NULL, it is called for every - argument. It will be passed the CLI argument and, if it's a flag, - its corresponding CliAppSwitch instance (extracted from - cliApp.switches). For non-flag arguments, a NULL CliAppSwitch is - passed to it. If it returns non-0, processing fails. If processes - completes successfully, the callback is called one additional time - with NULL pointer values to indicate that the end has been - reached. This can be used to handle post-argument cleanup, perform - app-specific argument validation, or similar. - - If callbacks are set both on the switch and cliApp, both are called - in that order, but only the cliApp callback is called one final - time after processing is done. - - If this function returns 0, the client may manipulate the contents - of cliApp.argv, within reason, but must be certain to keep - cliApp.argc in sync with that list's entries. - - On error a non-0 code is returned, either propagated from a - callback or (if the error originates from this function) an entry - from the cliapp_rc enum. In the latter case, cliapp_err_get() will - contain information about why it failed. - - Encountering an argument which is neither a non-flag nor a flag - defined in cliApp.switches results in an error. - - Quirks: - - - Arguments after "--" are NOT processed by this - function. Processing them would be a bug-in-waiting because those - flags might collide with app-level flags and/or require syntaxes - which this code treats as an error, e.g. using three dashes instead - of 1 or 2. Instead, if "--" is encounter, cliApp.doubleDash is - populated with information about the flags so the client may deal - with them (which might mean passing them back into this routine!). - - - All argv-related cliApp state is reset on each call, so if this - function is called multiple times, any client-side pointers - referring to cliApp's state may then point to different information - than they expect and/or may become stale pointers. (cliApp-held - data, e.g. cliApp.argv, keeps the same pointers but re-populates - the state, but the lifetime of external pointers, - e.g. cliApp.doubleDash.argv, is client-dependent.) -*/ -int cliapp_process_argv(int argc, char const * const * argv, - unsigned int reserved); - -/** - If cliApp.print is not NULL, this passes on its arguments to that - function, else this is a no-op. -*/ -void cliapp_printv(char const *fmt, va_list); - -/** - Elipses-args form of cliapp_printv(). -*/ -void cliapp_print(char const *fmt, ...); - -/** - Outputs a printf-formatted message to stderr. -*/ -void cliapp_warn(char const *fmt, ...); - -/** - Returns the next entry in cliApp.argv which is a non-flag argument, - skipping over argv[0]. Returns 0 when the end of the list is - reached. -*/ -CliAppArg const * cliapp_arg_nonflag(); - -/** - Resets the traversal of cliapp_arg_nonflag() to start from - the beginning. -*/ -void cliapp_arg_nonflag_rewind(); - -/** - If the given argument matches an app-configured flag, that flag is - returned, else 0 is returned. - - If alsoFlag is true, the first argument and the corresponding - switch must also have matching flag values to be considered a - match. -*/ -CliAppSwitch const * cliapp_switch_for_arg(CliAppArg const * arg, - int alsoFlag); - -/** - Searches for a flag matching one of the given keys. Each entry - in cliApp.argv is checked, in order, against both of the given - keys, in the order they are provided. - - The conventional way to call it is to pass the short-form flag, - then the long-form flag, but that's just a convention. - - Either of the first two arguments may be NULL but both may not be - NULL. - - If the 3rd parameter is not NULL then: - - 1) *atPos indicates an index position to start the search at. (Note - that it should initially be 1, not 0, in order to skip over the - app's name, stored in argv[0].) - - 2) If non-NULL is returned, *atPos is set to the index at which the - argument was found. If NULL is returned, *argPos is not modified. - - Thus atPos can be used to iterate through multiple copies of a - flag, noting that its value points to the index at which the - previous entry was found, so needs to be incremented by 1 before - each subsequent iteration - - On a match, the corresponding CliAppArg is returned, else 0 is - returned. -*/ -CliAppArg const * cliapp_arg_flag(char const * key1, char const * key2, - int * atPos); - -/** - Given a flag value for a CliAppArg or CliAppSwitch, this - returns a prefix string depending on that value: - - 1 = "-", 2 = "--", 3 = "+" - - Anything else = "". The returned bytes are static. -*/ -char const * cliapp_flag_prefix( int flag ); - -/** - Given a CliAppArg, presumably one from cliapp_arg_flag() or - cliapp_arg_nonflag(), this searches for the next argument with the - same key. - - If the given argument is from outside cliApp.argv's memory range, - or is the last element in that list, 0 is returned. - - Bug? For non-flag arguments this does not update the internal - non-flag traversal cursor. -*/ -CliAppArg const * cliapp_arg_next_same(CliAppArg const * arg); - -/** - Clears any error state in the cliApp object. -*/ -void cliapp_err_clear(); - -/** - If cliApp has a current error message set, it is returned, else 0 - is returned. The memory is static and its contents may be modified - by any calls into this API. -*/ -char const * cliapp_err_get(); - - -/** - Tries to save the line-editing history to the given filename, or to - cliApp.lineedit.historyFile if fname is NULL. If both are NULL or - empty, or if cliApp.lineedit.needsSave is 0, this is a no-op and - returns 0. Returns CLIAPP_RC_UNSUPPORTED if line-editing is not - enabled. -*/ -int cliapp_lineedit_save(char const * fname); - -/** - Adds the given line to the line-edit history. If this function - returns 0, it also sets cliApp.lineedit.needsSave to a non-0 value. - - Returns 0 on success or CLIAPP_RC_UNSUPPORTED if line-editing is - not enabled. -*/ -int cliapp_lineedit_add(char const * line); - -/** - Tries to load the line-editing history from the given filename, or - to cliApp.lineedit.historyFile if fname is NULL. If both are NULL - or empty, this is a no-op. Returns CLIAPP_RC_UNSUPPORTED if - line-editing is not enabled. If the underlying line-editing backend - returns an error, CLIAPP_RC_IO is returned, under the assumption - that there was a problem with reading the file (e.g. unreadable), - as opposed to an allocation error or similar. -*/ -int cliapp_lineedit_load(char const * fname); - -/** - If cliApp.lineedit.enabled is true, this function passes its - argument to free(3), else it will (in debug builds) trigger an - assert if passed non-NULL. This must be called once for each line - fetched via cliapp_lineedit_read(). -*/ -void cliapp_lineedit_free(char * line); - -/** - If line-editing is enabled, this reads a single line using that - back-end and returns the new string, which must be passed to - cliapp_lineedit_free() after the caller is done with it. - - Returns 0 if line-editing is not enabled or if the caller taps the - platform's EOF sequence (Ctrl-D on Unix) at the start of the - line. Returns an empty string if the user simply taps ENTER. - - TODO: if no line-editing backend is built in, fall back to fgets() - on stdin. It ain't pretty, but it'll do in a pinch. -*/ -char * cliapp_lineedit_read(char const * prompt); - -/** - Callback type for use with cliapp_repl(). -*/ -typedef int (*CliApp_repl_f)(char const * line, void * state); - -/** - Enters a REPL (Read, Eval, Print Loop). Each iteration does - the following: - - 1) Fetch an input line using cliapp_lineedit_read(), passing it - *prompt. If that returns NULL, this function returns 0. - - 2) If addHistoryPolicy is <0 then the read line is added to the - history. - - 3) Calls callback(theReadLine, state). - - 4) If (3) returns 0 and addHistoryPolicy is >0, the read line - is added to the history. - - 5) Passes the read line to cliapp_lineedit_free(). - - 6) If (3) returns non-0, this function returns that value. - - Notes: - - - The prompt is a pointer to a pointer so that the caller may - modify it between loop iterations. This function derefences *prompt - on each iteration. - - - An addHistoryPolicy of 0 means that this function will not - automatically add input lines to the history. The callback is free - to do so. - - - This function never passes a NULL line value to the callback but - it may pass an empty line. -*/ -int cliapp_repl(CliApp_repl_f callback, char const * const * prompt, - int addHistoryPolicy, void * state); - -#ifdef __cplusplus -} -#endif -#endif /* NET_WH_CLIAPP_H_INCLUDED */ - DELETED bindings/s2/config.h Index: bindings/s2/config.h ================================================================== --- bindings/s2/config.h +++ bindings/s2/config.h @@ -1,5 +0,0 @@ -#define S2_OS_UNIX 1 -#define S2_HAVE_REALPATH 1 -#define S2_HAVE_STAT 1 -#define S2_HAVE_CHDIR 1 -#define CWAL_OBASE_ISA_HASH 1 DELETED bindings/s2/f-s2sh.s2 Index: bindings/s2/f-s2sh.s2 ================================================================== --- bindings/s2/f-s2sh.s2 +++ bindings/s2/f-s2sh.s2 @@ -1,152 +0,0 @@ -/* - Initialization script for s2sh. If it is named the same as the binary - (minus any ".exe" extension), with a ".s2" extension (and in the same directory), - s2sh will autoload this file at startup and fail if processing it fails. -*/ - -assert Fossil; -assert Fossil.Context; - -assert s2 && 'function' === typename s2.loadModule; -/** - An s2.loadModule() proxy which uses a PathFinder - instance to search for DLLs. The name argument must be the - base name part, optionally with a partial leading (sub-)path. - - The dest argument is passed as the last argument to s2.loadModule(), - and is returned to the caller on success. Well-behaved modules will - install their features in that object. - - If the S2_MODULE_PATH and/or S2_MODULE_EXTENSION environment - variables are set, they are treated as a semicolon- or - colon-separated list of directories resp. file extensions. If not - specified, some default set is used. - -*/ -s2.loadModule2 = function(name, dest = {}){ - affirm 'string' === typename name; - const fn = pf.search( name ); - fn || throw "Cannot find '". - concat(name, "' in search path ", pf.prefix.toJSONString()); - //print("Importing",name, '==>', fn); - return loadModule.call(this, realpath ? realpath(fn) : fn, dest); -}.importSymbols({ - loadModule: s2.loadModule, - realpath: s2.io ? s2.io.realpath : undefined, - pf: s2.PathFinder.new( - // Directories... - ('string' === typename (var s = s2.getenv('S2_MODULE_PATH'))) - ? s.split(s.indexOf(';') >= 0 ? ';' : ':') - : ['.'], - // Extensions... - ('string' === typename (s = s2.getenv('S2_MODULE_EXTENSIONS'))) - ? s.split(s.indexOf(';') >= 0 ? ';' : ':') - : ['.so','.dll'] - ) -}); - - -/** - For the given container, v, this displays (via s2.io.output() a - listing of its properties. Intended for getting an overview of an - object's API. -*/ -s2.vls = proc(v,label){ - label && print(label); - typeinfo(iscontainer v) && this.eachProperty.call(v,eachProp); -}.importSymbols({ - eachProp:proc(k,v){ - print('\t'+typeinfo(name k), k, '=', typeinfo(name v), v); - } -}); - -/** - For the given container, v, this displays (via s2.io.output() a - tree listing, recursively, of its properties. Intended for getting - an overview of an object's API. - - If includeProto is truthy, v.prototype is also dumped. If it is - less than 0, that is done recursively for all entries and their - prototypes. -*/ -s2.vtree = proc vtree(v,label,includeProto){ - typeinfo(iscontainer v) || return; - if(!typeinfo(isstring label) && undefined===includeProto){ - includeProto= label; - label = undefined; - } - const doMyProto = includeProto; - includeProto < 0 || (includeProto=0); - //print(__FLC,'argv =',argv); - label ?: (label = "%1$p".applyFormat(v)); - label && out(buf.toString(),label," [type: ",typeinfo(name v),'] ==>\n'); - ++buf.level; - buf.length(buf.level*4); - buf.fill(' '); - var ex = catch{ - // ^^^^ s2 bug: braces around this catch should not be necessary. - // Symptom: if the first if() passes then the 'else' is getting seen - // after catch resolves. - if(typeinfo(isarray v)){ - //out(' array ',v.toJSONString(0,true/*output cycles as strings*/),'\n'); - v.eachIndex(eachIndex); - }else{ - buf.prototype.eachProperty.call(v,eachProp); - } - }; - ex = catch if(!ex && v.prototype){ - doMyProto - ? vtree(v.prototype,label?label+'.prototype':0, includeProto) - : out(buf.toString(),label ? label+'.' : '', - 'prototype ==> [type: ', - typeinfo(name v.prototype),']\n'); - }; - --buf.level; - buf.length(buf.level * 4); - ex && throw ex; -}.importSymbols({ - buf: eval { - var b = new s2.Buffer(20); - b.level = 0; - b; - }, - out: s2.io.output, - eachProp:proc(k,v){ - if(typeinfo(isfunction v)){ - out(buf.toString(), (label ? label+'.'+k :k),'()\n'); - } - else if(typeinfo(iscontainer v) - && typeinfo(isfunction v.mayIterate)){ - v.mayIterate() - ? vtree(v,(label ? label+'.'+k : k), includeProto) - : out(buf.toString(),(label ? label+'.'+k : k), - " = \n".applyFormat(v)); - }else{ - out(buf.toString(), (label ? label+'.'+k :k), - ' = ', typeinfo(name v), ' ', v, '\n'); - } - }, - eachIndex:proc(v,k){ - if(typeinfo(isfunction v)){ - out(buf.toString(), (label ? label+'['+k+']','()\n')); - } - else if(typeinfo(iscontainer v) - && typeinfo(isfunction v.mayIterate)){ - v.mayIterate() - ? vtree(v,(label ? label+'['+k+']' : k), includeProto) - : out(buf.toString(),(label ? label+'['+k+']' : k), - " = \n".applyFormat(v)); - }else{ - out(buf.toString(), (label ? label+'['+k+']' :k), - ' = ', typeinfo(name v), ' ', v, '\n'); - } - } -}); - -/** - Add Fossil.require(), used in loading Fossil-aware modules. -*/ -Fossil.require = import( false, 'require.d/require.s2' ); - -// The rest of the initialization happens via here: -Fossil.require(['nocache!fsl/extendFossil'],proc(){}); DELETED bindings/s2/fslcgi Index: bindings/s2/fslcgi ================================================================== --- bindings/s2/fslcgi +++ bindings/s2/fslcgi @@ -1,63 +0,0 @@ -#!/bin/sh -######################################################################## -# Intended to be run as a CGI script. It is currently hard-coded to -# live in same dir as s2sh and the ./fslcgi.d directory and f-s2sh -# binary. -# -# A sample Apache vhost for this script looks like: -# -# -# ServerName s2.local -# ScriptAlias /cgi-bin/ /path/to/libfossil/s2 -# DocumentRoot /path/to/libfossil/s2 -# Options +FollowSymLinks -# -# -# AllowOverride All -# Options +ExecCGI +Indexes -# Order allow,deny -# Allow from all -# Require all granted -# DirectoryIndex fslcgi -# SetHandler cgi-script -# -######################################################################## - -S2_HOME=`dirname "$0"` -# PROXY_SCRIPT is the script-side entry point for the CGI app -PROXY_SCRIPT=$0.s2 -# Interpreter-level flags for s2sh: -S2_SHELL_FLAGS="-S -a -R" -S2_SHELL=$S2_HOME/f-s2sh -#S2_RC_DIR = "resource dir" for cgi bits. Passed via the --resource-dir CLI flag. -S2_RC_DIR=${S2_HOME}/fslcgi.d - -S2_MODULE_PATH=".:$S2_HOME:${S2_RC_DIR}/lib" -S2_INCLUDES_PATH=".:$S2_HOME:${S2_RC_DIR}/include" -#NYI: S2_AUTOLOAD_MODULES="module1,module2,module3" - -export S2_MODULE_PATH S2_INCLUDES_PATH S2_AUTOLOAD_MODULES - -#export S2_HOME - -# For libfossil.so: -LD_LIBRARY_PATH="${S2_HOME}/..:${LD_LIBRARY_PATH}" -export LD_LIBRARY_PATH - -# Tell the script world which repository file to use... -if [ -d ~/fossil ]; then - S2_CGI_REPO="~/fossil/libfossil.fsl" - true -else - S2_CGI_REPO="$S2_HOME/../../libfossil.fsl" - #S2_CGI_REPO="-R=$S2_HOME/../../fossil.fsl" -fi - -#S2_CGI_REP0='' -# Misc flags intended for consumption by scripts... -S2_REPO_URL=http://fossil.wanderinghorse.net/repos/libfossil/ -#S2_CGI_REPO=-C -S2_SCRIPT_FLAGS="--repo-db=${S2_CGI_REPO} --repo-url=${S2_REPO_URL} --resource-dir=${S2_RC_DIR}" -#S2_SCRIPT_FLAGS="${S2_SCRIPT_FLAGS} --repo-url=http://url-to-your/repo[.cgi]" - -exec $S2_SHELL ${S2_SHELL_FLAGS} -f $PROXY_SCRIPT -- $S2_SCRIPT_FLAGS DELETED bindings/s2/fslcgi.d/init.s2 Index: bindings/s2/fslcgi.d/init.s2 ================================================================== --- bindings/s2/fslcgi.d/init.s2 +++ bindings/s2/fslcgi.d/init.s2 @@ -1,197 +0,0 @@ -/** - Post-bootstrap initialization code for s2's fslcgi. Must live in the - root of "resource directory", but that (with sufficient hacking) may - live outside of the web-root. -*/ -affirm 'undefined' !== typename $CGI /* expecting CGI module to be loaded under this name */; -affirm Fossil.require; - - -$CGI.config = { - resourceDir: Fossil.file.canonicalName(__FILEDIR,true), - cgiRoot: '' -}; -scope { - const C = $CGI; - var uri = s2.getenv('SCRIPT_NAME'); - // Set up cgiRoot (the "standard" way of getting the root dir - // for link-building purposes). This kludgery is not generic... - if(uri) { C.config.cgiRoot = uri + '/' } - else{ - uri = s2.getenv('REQUEST_URI'); - C.request.ENV || (C.request.REQUEST_URI = uri); - if(uri){ - var head = uri.split('fslcgi',2).0;//, head = adj.0; - C.config.cgiRoot = head ||| '/empty'; - //('/' === head) ? head : head + '/'; //.concat('fslcgi', '/'); - } - } - - C.config.localServerMode = - (var serverName = s2.getenv('SERVER_NAME')) - && (0=0, - optStr = this.objToUrlOpt(urlOpt, !hasQ ); - return fmt.applyFormat( - $CGI.config.cgiRoot, - $CGI.urlencode(path)+(optStr ? hasQ ? '&' + optStr : optStr : ''), - label); - }.importSymbols({ - fmt: "%3$s" - }); -}; - - -$CGI.resourcePath = proc(name){ - return this.config.resourceDir + name; -}; - -$CGI.resolveResource = proc(name){ - const path = this.config.resourceDir + name; - return Fossil.file.isFile(path) ? path : undefined; -}; - -// incomplete... not yet sure what i want. -$CGI.request.pathInfoList = scope { - var ps, p = s2.getenv('PATH_INFO'); - if(p && '/'!==p){ - ps = p.split('/'); - // Trim leading/trailing null entries caused - // by leading/trailing slashes: - ps.0 || ps.shift(); - ps[ps.length()-1] || ps.pop(); - } - ps; -}; - -if(0){ // only for testing - $CGI.setContentType('application/json'); - print({request: $CGI.request, - config: $CGI.config}.toJSONString(2)); -}else if(1){ - const c = $CGI; - c.setContentType('text/plain'); - print("$CGI sanity checks..."); - c << 'Fossil.time.cpuTime() says: ' - << Fossil.time.cpuTime() - << '\n' - ; - - const f = c.fossilInstance; - f.db || f.openCheckout(); - c << 'Fossil context: ' << f << ' repo db: ' << f.db.repo.filename << '\n'; - c << "pathInfoList = "<" - << c.resourcePath('foo/bar.baz') - << '\n'; - c << "resolveResource('init.s2')==>" - << c.resolveResource('init.s2') - << '\n'; - c << "resolveResource('x')==>" - << c.resolveResource('x') - << '\n'; - - if(1) { - c << '$CGI.config = ' << $CGI.config.toJSONString(2) << '\n'; - } - - c << "Most recent timeline event: " - << f.db.selectRow('SELECT * FROM event ORDER BY mtime DESC') - .toJSONString(2) - << '\n'; - - if(0){ - // Workaround: c is a Native, and those are rejected - // by the C-level toJSON bits: - var obj = {}; - c.eachProperty(proc(k,v){obj[k]=v}); - c << '$CGI properties:\n' << obj.toJSONString(4) << '\n'; - } - if(1){ - c << 'objToUrlOpt: ' - << c.util.objToUrlOpt({a:3,c:'a b'}) - << '\n'; - c << 'objToUrlOpt again (should be empty): ' - << c.util.objToUrlOpt({},true) - << '\n'; - c << 'absoluteLink: ' - << c.util.absoluteLink('foo/bar/baz?x=y', 'link', {a:1,b:'hi !'}) - << '\n'; - c << 'absoluteLink again: ' - << c.util.absoluteLink('foo/bar/', 'link', {a:1,b:'hi !'}) - << '\n'; - c << 'Fossil.artifactTypes = '< 1; $ob.pop(), --obLevel) {} - if(obLevel){ $ob.clear() } - else { $ob.push() /* so our headers get sent properly */ } - if($CGI.httpStatus() < 500){ - $CGI.httpStatus(500, "Caught Exception"); - } - $CGI.scrubException && (err = $CGI.scrubException(err)); - $CGI.setContentType('application/json'); - print({exception:err}.toJSONString(-1)); -} -$CGI.send() /* will flush all $ob buffers after emiting headers */; DELETED bindings/s2/linenoise/linenoise.c Index: bindings/s2/linenoise/linenoise.c ================================================================== --- bindings/s2/linenoise/linenoise.c +++ bindings/s2/linenoise/linenoise.c @@ -1,1625 +0,0 @@ -/* linenoise.c -- guerrilla line editing library against the idea that a - * line editing lib needs to be 20,000 lines of C code. - * - * You can find the latest source code at: - * - * http://github.com/msteveb/linenoise - * (forked from http://github.com/antirez/linenoise) - * - * Does a number of crazy assumptions that happen to be true in 99.9999% of - * the 2010 UNIX computers around. - * - * ------------------------------------------------------------------------ - * - * Copyright (c) 2010, Salvatore Sanfilippo - * Copyright (c) 2010, Pieter Noordhuis - * Copyright (c) 2011, Steve Bennett - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * ------------------------------------------------------------------------ - * - * References: - * - http://invisible-island.net/xterm/ctlseqs/ctlseqs.html - * - http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html - * - * Bloat: - * - Completion? - * - * Unix/termios - * ------------ - * List of escape sequences used by this program, we do everything just - * a few sequences. In order to be so cheap we may have some - * flickering effect with some slow terminal, but the lesser sequences - * the more compatible. - * - * EL (Erase Line) - * Sequence: ESC [ n K - * Effect: if n is 0 or missing, clear from cursor to end of line - * Effect: if n is 1, clear from beginning of line to cursor - * Effect: if n is 2, clear entire line - * - * CUF (CUrsor Forward) - * Sequence: ESC [ n C - * Effect: moves cursor forward of n chars - * - * CR (Carriage Return) - * Sequence: \r - * Effect: moves cursor to column 1 - * - * The following are used to clear the screen: ESC [ H ESC [ 2 J - * This is actually composed of two sequences: - * - * cursorhome - * Sequence: ESC [ H - * Effect: moves the cursor to upper left corner - * - * ED2 (Clear entire screen) - * Sequence: ESC [ 2 J - * Effect: clear the whole screen - * - * == For highlighting control characters, we also use the following two == - * SO (enter StandOut) - * Sequence: ESC [ 7 m - * Effect: Uses some standout mode such as reverse video - * - * SE (Standout End) - * Sequence: ESC [ 0 m - * Effect: Exit standout mode - * - * == Only used if TIOCGWINSZ fails == - * DSR/CPR (Report cursor position) - * Sequence: ESC [ 6 n - * Effect: reports current cursor position as ESC [ NNN ; MMM R - * - * win32/console - * ------------- - * If __MINGW32__ is defined, the win32 console API is used. - * This could probably be made to work for the msvc compiler too. - * This support based in part on work by Jon Griffiths. - */ - -#ifdef _WIN32 /* Windows platform, either MinGW or Visual Studio (MSVC) */ -#include -#include -#define USE_WINCONSOLE -#ifdef __MINGW32__ -#define HAVE_UNISTD_H -#else -/* Microsoft headers don't like old POSIX names */ -#define strdup _strdup -#define snprintf _snprintf -#endif -#else -#include -#include -#include -#define USE_TERMIOS -#define HAVE_UNISTD_H -#endif - -#ifdef HAVE_UNISTD_H -#include -#endif -#include -#include -#include -#include -#include -#include -#include - -#include "linenoise.h" -#include "utf8.h" - -#define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100 -#define LINENOISE_MAX_LINE 4096 - -#define ctrl(C) ((C) - '@') - -/* Use -ve numbers here to co-exist with normal unicode chars */ -enum { - SPECIAL_NONE, - SPECIAL_UP = -20, - SPECIAL_DOWN = -21, - SPECIAL_LEFT = -22, - SPECIAL_RIGHT = -23, - SPECIAL_DELETE = -24, - SPECIAL_HOME = -25, - SPECIAL_END = -26, - SPECIAL_INSERT = -27, - SPECIAL_PAGE_UP = -28, - SPECIAL_PAGE_DOWN = -29 -}; - -static int history_max_len = LINENOISE_DEFAULT_HISTORY_MAX_LEN; -static int history_len = 0; -static char **history = NULL; - -/* Structure to contain the status of the current (being edited) line */ -struct current { - char *buf; /* Current buffer. Always null terminated */ - int bufmax; /* Size of the buffer, including space for the null termination */ - int len; /* Number of bytes in 'buf' */ - int chars; /* Number of chars in 'buf' (utf-8 chars) */ - int pos; /* Cursor position, measured in chars */ - int cols; /* Size of the window, in chars */ - const char *prompt; - char *capture; /* Allocated capture buffer, or NULL for none. Always null terminated */ -#if defined(USE_TERMIOS) - int fd; /* Terminal fd */ -#elif defined(USE_WINCONSOLE) - HANDLE outh; /* Console output handle */ - HANDLE inh; /* Console input handle */ - int rows; /* Screen rows */ - int x; /* Current column during output */ - int y; /* Current row */ -#endif -}; - -static int fd_read(struct current *current); -static int getWindowSize(struct current *current); - -void linenoiseHistoryFree(void) { - if (history) { - int j; - - for (j = 0; j < history_len; j++) - free(history[j]); - free(history); - history = NULL; - history_len = 0; - } -} - -#if defined(USE_TERMIOS) -static void linenoiseAtExit(void); -static struct termios orig_termios; /* in order to restore at exit */ -static int rawmode = 0; /* for atexit() function to check if restore is needed*/ -static int atexit_registered = 0; /* register atexit just 1 time */ - -static const char *unsupported_term[] = {"dumb","cons25",NULL}; - -static int isUnsupportedTerm(void) { - char *term = getenv("TERM"); - - if (term) { - int j; - for (j = 0; unsupported_term[j]; j++) { - if (strcmp(term, unsupported_term[j]) == 0) { - return 1; - } - } - } - return 0; -} - -static int enableRawMode(struct current *current) { - struct termios raw; - - current->fd = STDIN_FILENO; - current->cols = 0; - - if (!isatty(current->fd) || isUnsupportedTerm() || - tcgetattr(current->fd, &orig_termios) == -1) { -fatal: - errno = ENOTTY; - return -1; - } - - if (!atexit_registered) { - atexit(linenoiseAtExit); - atexit_registered = 1; - } - - raw = orig_termios; /* modify the original mode */ - /* input modes: no break, no CR to NL, no parity check, no strip char, - * no start/stop output control. */ - raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON); - /* output modes - disable post processing */ - raw.c_oflag &= ~(OPOST); - /* control modes - set 8 bit chars */ - raw.c_cflag |= (CS8); - /* local modes - choing off, canonical off, no extended functions, - * no signal chars (^Z,^C) */ - raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG); - /* control chars - set return condition: min number of bytes and timer. - * We want read to return every single byte, without timeout. */ - raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */ - - /* put terminal in raw mode after flushing */ - if (tcsetattr(current->fd,TCSADRAIN,&raw) < 0) { - goto fatal; - } - rawmode = 1; - return 0; -} - -static void disableRawMode(struct current *current) { - /* Don't even check the return value as it's too late. */ - if (rawmode && tcsetattr(current->fd,TCSADRAIN,&orig_termios) != -1) - rawmode = 0; -} - -/* At exit we'll try to fix the terminal to the initial conditions. */ -static void linenoiseAtExit(void) { - if (rawmode) { - tcsetattr(STDIN_FILENO, TCSADRAIN, &orig_termios); - } - linenoiseHistoryFree(); -} - -/* gcc/glibc insists that we care about the return code of write! - * Clarification: This means that a void-cast like "(void) (EXPR)" - * does not work. - */ -#define IGNORE_RC(EXPR) if (EXPR) {} - -/* This is fdprintf() on some systems, but use a different - * name to avoid conflicts - */ -static void fd_printf(int fd, const char *format, ...) -{ - va_list args; - char buf[64]; - int n; - - va_start(args, format); - n = vsnprintf(buf, sizeof(buf), format, args); - va_end(args); - IGNORE_RC(write(fd, buf, n)); -} - -static void clearScreen(struct current *current) -{ - fd_printf(current->fd, "\x1b[H\x1b[2J"); -} - -static void cursorToLeft(struct current *current) -{ - fd_printf(current->fd, "\r"); -} - -static int outputChars(struct current *current, const char *buf, int len) -{ - return write(current->fd, buf, len); -} - -static void outputControlChar(struct current *current, char ch) -{ - fd_printf(current->fd, "\x1b[7m^%c\x1b[0m", ch); -} - -static void eraseEol(struct current *current) -{ - fd_printf(current->fd, "\x1b[0K"); -} - -static void setCursorPos(struct current *current, int x) -{ - fd_printf(current->fd, "\r\x1b[%dC", x); -} - -/** - * Reads a char from 'fd', waiting at most 'timeout' milliseconds. - * - * A timeout of -1 means to wait forever. - * - * Returns -1 if no char is received within the time or an error occurs. - */ -static int fd_read_char(int fd, int timeout) -{ - struct pollfd p; - unsigned char c; - - p.fd = fd; - p.events = POLLIN; - - if (poll(&p, 1, timeout) == 0) { - /* timeout */ - return -1; - } - if (read(fd, &c, 1) != 1) { - return -1; - } - return c; -} - -/** - * Reads a complete utf-8 character - * and returns the unicode value, or -1 on error. - */ -static int fd_read(struct current *current) -{ -#ifdef USE_UTF8 - char buf[4]; - int n; - int i; - int c; - - if (read(current->fd, &buf[0], 1) != 1) { - return -1; - } - n = utf8_charlen(buf[0]); - if (n < 1 || n > 3) { - return -1; - } - for (i = 1; i < n; i++) { - if (read(current->fd, &buf[i], 1) != 1) { - return -1; - } - } - buf[n] = 0; - /* decode and return the character */ - utf8_tounicode(buf, &c); - return c; -#else - return fd_read_char(current->fd, -1); -#endif -} - -static int countColorControlChars(const char* prompt) -{ - /* ANSI color control sequences have the form: - * "\x1b" "[" [0-9;]* "m" - * We parse them with a simple state machine. - */ - - enum { - search_esc, - expect_bracket, - expect_trail - } state = search_esc; - int len = 0, found = 0; - char ch; - - /* XXX: Strictly we should be checking utf8 chars rather than - * bytes in case of the extremely unlikely scenario where - * an ANSI sequence is part of a utf8 sequence. - */ - while ((ch = *prompt++) != 0) { - switch (state) { - case search_esc: - if (ch == '\x1b') { - state = expect_bracket; - } - break; - case expect_bracket: - if (ch == '[') { - state = expect_trail; - /* 3 for "\e[ ... m" */ - len = 3; - break; - } - state = search_esc; - break; - case expect_trail: - if ((ch == ';') || ((ch >= '0' && ch <= '9'))) { - /* 0-9, or semicolon */ - len++; - break; - } - if (ch == 'm') { - found += len; - } - state = search_esc; - break; - } - } - - return found; -} - -/** - * Stores the current cursor column in '*cols'. - * Returns 1 if OK, or 0 if failed to determine cursor pos. - */ -static int queryCursor(int fd, int* cols) -{ - /* control sequence - report cursor location */ - fd_printf(fd, "\x1b[6n"); - - /* Parse the response: ESC [ rows ; cols R */ - if (fd_read_char(fd, 100) == 0x1b && - fd_read_char(fd, 100) == '[') { - - int n = 0; - while (1) { - int ch = fd_read_char(fd, 100); - if (ch == ';') { - /* Ignore rows */ - n = 0; - } - else if (ch == 'R') { - /* Got cols */ - if (n != 0 && n < 1000) { - *cols = n; - } - break; - } - else if (ch >= 0 && ch <= '9') { - n = n * 10 + ch - '0'; - } - else { - break; - } - } - return 1; - } - - return 0; -} - -/** - * Updates current->cols with the current window size (width) - */ -static int getWindowSize(struct current *current) -{ - struct winsize ws; - - if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0 && ws.ws_col != 0) { - current->cols = ws.ws_col; - return 0; - } - - /* Failed to query the window size. Perhaps we are on a serial terminal. - * Try to query the width by sending the cursor as far to the right - * and reading back the cursor position. - * Note that this is only done once per call to linenoise rather than - * every time the line is refreshed for efficiency reasons. - * - * In more detail, we: - * (a) request current cursor position, - * (b) move cursor far right, - * (c) request cursor position again, - * (d) at last move back to the old position. - * This gives us the width without messing with the externally - * visible cursor position. - */ - - if (current->cols == 0) { - int here; - - current->cols = 80; - - /* (a) */ - if (queryCursor (current->fd, &here)) { - /* (b) */ - fd_printf(current->fd, "\x1b[999C"); - - /* (c). Note: If (a) succeeded, then (c) should as well. - * For paranoia we still check and have a fallback action - * for (d) in case of failure.. - */ - if (!queryCursor (current->fd, ¤t->cols)) { - /* (d') Unable to get accurate position data, reset - * the cursor to the far left. While this may not - * restore the exact original position it should not - * be too bad. - */ - fd_printf(current->fd, "\r"); - } else { - /* (d) Reset the cursor back to the original location. */ - if (current->cols > here) { - fd_printf(current->fd, "\x1b[%dD", current->cols - here); - } - } - } /* 1st query failed, doing nothing => default 80 */ - } - - return 0; -} - -/** - * If escape (27) was received, reads subsequent - * chars to determine if this is a known special key. - * - * Returns SPECIAL_NONE if unrecognised, or -1 if EOF. - * - * If no additional char is received within a short time, - * 27 is returned. - */ -static int check_special(int fd) -{ - int c = fd_read_char(fd, 50); - int c2; - - if (c < 0) { - return 27; - } - - c2 = fd_read_char(fd, 50); - if (c2 < 0) { - return c2; - } - if (c == '[' || c == 'O') { - /* Potential arrow key */ - switch (c2) { - case 'A': - return SPECIAL_UP; - case 'B': - return SPECIAL_DOWN; - case 'C': - return SPECIAL_RIGHT; - case 'D': - return SPECIAL_LEFT; - case 'F': - return SPECIAL_END; - case 'H': - return SPECIAL_HOME; - } - } - if (c == '[' && c2 >= '1' && c2 <= '8') { - /* extended escape */ - c = fd_read_char(fd, 50); - if (c == '~') { - switch (c2) { - case '2': - return SPECIAL_INSERT; - case '3': - return SPECIAL_DELETE; - case '5': - return SPECIAL_PAGE_UP; - case '6': - return SPECIAL_PAGE_DOWN; - case '7': - return SPECIAL_HOME; - case '8': - return SPECIAL_END; - } - } - while (c != -1 && c != '~') { - /* .e.g \e[12~ or '\e[11;2~ discard the complete sequence */ - c = fd_read_char(fd, 50); - } - } - - return SPECIAL_NONE; -} -#elif defined(USE_WINCONSOLE) - -static DWORD orig_consolemode = 0; - -static int enableRawMode(struct current *current) { - DWORD n; - INPUT_RECORD irec; - - current->outh = GetStdHandle(STD_OUTPUT_HANDLE); - current->inh = GetStdHandle(STD_INPUT_HANDLE); - - if (!PeekConsoleInput(current->inh, &irec, 1, &n)) { - return -1; - } - if (getWindowSize(current) != 0) { - return -1; - } - if (GetConsoleMode(current->inh, &orig_consolemode)) { - SetConsoleMode(current->inh, ENABLE_PROCESSED_INPUT); - } - return 0; -} - -static void disableRawMode(struct current *current) -{ - SetConsoleMode(current->inh, orig_consolemode); -} - -static void clearScreen(struct current *current) -{ - COORD topleft = { 0, 0 }; - DWORD n; - - FillConsoleOutputCharacter(current->outh, ' ', - current->cols * current->rows, topleft, &n); - FillConsoleOutputAttribute(current->outh, - FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_GREEN, - current->cols * current->rows, topleft, &n); - SetConsoleCursorPosition(current->outh, topleft); -} - -static void cursorToLeft(struct current *current) -{ - COORD pos = { 0, (SHORT)current->y }; - DWORD n; - - FillConsoleOutputAttribute(current->outh, - FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_GREEN, current->cols, pos, &n); - current->x = 0; -} - -static int outputChars(struct current *current, const char *buf, int len) -{ - COORD pos = { (SHORT)current->x, (SHORT)current->y }; - DWORD n; - - WriteConsoleOutputCharacter(current->outh, buf, len, pos, &n); - current->x += len; - return 0; -} - -static void outputControlChar(struct current *current, char ch) -{ - COORD pos = { (SHORT)current->x, (SHORT)current->y }; - DWORD n; - - FillConsoleOutputAttribute(current->outh, BACKGROUND_INTENSITY, 2, pos, &n); - outputChars(current, "^", 1); - outputChars(current, &ch, 1); -} - -static void eraseEol(struct current *current) -{ - COORD pos = { (SHORT)current->x, (SHORT)current->y }; - DWORD n; - - FillConsoleOutputCharacter(current->outh, ' ', current->cols - current->x, pos, &n); -} - -static void setCursorPos(struct current *current, int x) -{ - COORD pos = { (SHORT)x, (SHORT)current->y }; - - SetConsoleCursorPosition(current->outh, pos); - current->x = x; -} - -static int fd_read(struct current *current) -{ - while (1) { - INPUT_RECORD irec; - DWORD n; - if (WaitForSingleObject(current->inh, INFINITE) != WAIT_OBJECT_0) { - break; - } - if (!ReadConsoleInput (current->inh, &irec, 1, &n)) { - break; - } - if (irec.EventType == KEY_EVENT && irec.Event.KeyEvent.bKeyDown) { - KEY_EVENT_RECORD *k = &irec.Event.KeyEvent; - if (k->dwControlKeyState & ENHANCED_KEY) { - switch (k->wVirtualKeyCode) { - case VK_LEFT: - return SPECIAL_LEFT; - case VK_RIGHT: - return SPECIAL_RIGHT; - case VK_UP: - return SPECIAL_UP; - case VK_DOWN: - return SPECIAL_DOWN; - case VK_INSERT: - return SPECIAL_INSERT; - case VK_DELETE: - return SPECIAL_DELETE; - case VK_HOME: - return SPECIAL_HOME; - case VK_END: - return SPECIAL_END; - case VK_PRIOR: - return SPECIAL_PAGE_UP; - case VK_NEXT: - return SPECIAL_PAGE_DOWN; - } - } - /* Note that control characters are already translated in AsciiChar */ - else if (k->wVirtualKeyCode == VK_CONTROL) - continue; - else { -#ifdef USE_UTF8 - return k->uChar.UnicodeChar; -#else - return k->uChar.AsciiChar; -#endif - } - } - } - return -1; -} - -static int countColorControlChars(const char* prompt) -{ - /* For windows we assume that there are no embedded ansi color - * control sequences. - */ - return 0; -} - -static int getWindowSize(struct current *current) -{ - CONSOLE_SCREEN_BUFFER_INFO info; - if (!GetConsoleScreenBufferInfo(current->outh, &info)) { - return -1; - } - current->cols = info.dwSize.X; - current->rows = info.dwSize.Y; - if (current->cols <= 0 || current->rows <= 0) { - current->cols = 80; - return -1; - } - current->y = info.dwCursorPosition.Y; - current->x = info.dwCursorPosition.X; - return 0; -} -#endif - -static int utf8_getchars(char *buf, int c) -{ -#ifdef USE_UTF8 - return utf8_fromunicode(buf, c); -#else - *buf = c; - return 1; -#endif -} - -/** - * Returns the unicode character at the given offset, - * or -1 if none. - */ -static int get_char(struct current *current, int pos) -{ - if (pos >= 0 && pos < current->chars) { - int c; - int i = utf8_index(current->buf, pos); - (void)utf8_tounicode(current->buf + i, &c); - return c; - } - return -1; -} - -static void refreshLine(const char *prompt, struct current *current) -{ - int plen; - int pchars; - int backup = 0; - int i; - const char *buf = current->buf; - int chars = current->chars; - int pos = current->pos; - int b; - int ch; - int n; - - /* Should intercept SIGWINCH. For now, just get the size every time */ - getWindowSize(current); - - plen = strlen(prompt); - pchars = utf8_strlen(prompt, plen); - - /* Scan the prompt for embedded ansi color control sequences and - * discount them as characters/columns. - */ - pchars -= countColorControlChars(prompt); - - /* Account for a line which is too long to fit in the window. - * Note that control chars require an extra column - */ - - /* How many cols are required to the left of 'pos'? - * The prompt, plus one extra for each control char - */ - n = pchars + utf8_strlen(buf, current->len); - b = 0; - for (i = 0; i < pos; i++) { - b += utf8_tounicode(buf + b, &ch); - if (ch < ' ') { - n++; - } - } - - /* If too many are needed, strip chars off the front of 'buf' - * until it fits. Note that if the current char is a control character, - * we need one extra col. - */ - if (current->pos < current->chars && get_char(current, current->pos) < ' ') { - n++; - } - - while (n >= current->cols && pos > 0) { - b = utf8_tounicode(buf, &ch); - if (ch < ' ') { - n--; - } - n--; - buf += b; - pos--; - chars--; - } - - /* Cursor to left edge, then the prompt */ - cursorToLeft(current); - outputChars(current, prompt, plen); - - /* Now the current buffer content */ - - /* Need special handling for control characters. - * If we hit 'cols', stop. - */ - b = 0; /* unwritted bytes */ - n = 0; /* How many control chars were written */ - for (i = 0; i < chars; i++) { - int ch; - int w = utf8_tounicode(buf + b, &ch); - if (ch < ' ') { - n++; - } - if (pchars + i + n >= current->cols) { - break; - } - if (ch < ' ') { - /* A control character, so write the buffer so far */ - outputChars(current, buf, b); - buf += b + w; - b = 0; - outputControlChar(current, ch + '@'); - if (i < pos) { - backup++; - } - } - else { - b += w; - } - } - outputChars(current, buf, b); - - /* Erase to right, move cursor to original position */ - eraseEol(current); - setCursorPos(current, pos + pchars + backup); -} - -static void set_current(struct current *current, const char *str) -{ - strncpy(current->buf, str, current->bufmax); - current->buf[current->bufmax - 1] = 0; - current->len = strlen(current->buf); - current->pos = current->chars = utf8_strlen(current->buf, current->len); -} - -static int has_room(struct current *current, int bytes) -{ - return current->len + bytes < current->bufmax - 1; -} - -/** - * Removes the char at 'pos'. - * - * Returns 1 if the line needs to be refreshed, 2 if not - * and 0 if nothing was removed - */ -static int remove_char(struct current *current, int pos) -{ - if (pos >= 0 && pos < current->chars) { - int p1, p2; - int ret = 1; - p1 = utf8_index(current->buf, pos); - p2 = p1 + utf8_index(current->buf + p1, 1); - -#ifdef USE_TERMIOS - /* optimise remove char in the case of removing the last char */ - if (current->pos == pos + 1 && current->pos == current->chars) { - if (current->buf[pos] >= ' ' && utf8_strlen(current->prompt, -1) + utf8_strlen(current->buf, current->len) < current->cols - 1) { - ret = 2; - fd_printf(current->fd, "\b \b"); - } - } -#endif - - /* Move the null char too */ - memmove(current->buf + p1, current->buf + p2, current->len - p2 + 1); - current->len -= (p2 - p1); - current->chars--; - - if (current->pos > pos) { - current->pos--; - } - return ret; - } - return 0; -} - -/** - * Insert 'ch' at position 'pos' - * - * Returns 1 if the line needs to be refreshed, 2 if not - * and 0 if nothing was inserted (no room) - */ -static int insert_char(struct current *current, int pos, int ch) -{ - char buf[3]; - int n = utf8_getchars(buf, ch); - - if (has_room(current, n) && pos >= 0 && pos <= current->chars) { - int p1, p2; - int ret = 1; - p1 = utf8_index(current->buf, pos); - p2 = p1 + n; - -#ifdef USE_TERMIOS - /* optimise the case where adding a single char to the end and no scrolling is needed */ - if (current->pos == pos && current->chars == pos) { - if (ch >= ' ' && utf8_strlen(current->prompt, -1) + utf8_strlen(current->buf, current->len) < current->cols - 1) { - IGNORE_RC(write(current->fd, buf, n)); - ret = 2; - } - } -#endif - - memmove(current->buf + p2, current->buf + p1, current->len - p1); - memcpy(current->buf + p1, buf, n); - current->len += n; - - current->chars++; - if (current->pos >= pos) { - current->pos++; - } - return ret; - } - return 0; -} - -/** - * Captures up to 'n' characters starting at 'pos' for the cut buffer. - * - * This replaces any existing characters in the cut buffer. - */ -static void capture_chars(struct current *current, int pos, int n) -{ - if (pos >= 0 && (pos + n - 1) < current->chars) { - int p1 = utf8_index(current->buf, pos); - int nbytes = utf8_index(current->buf + p1, n); - - if (nbytes) { - free(current->capture); - /* Include space for the null terminator */ - current->capture = (char *)malloc(nbytes + 1); - memcpy(current->capture, current->buf + p1, nbytes); - current->capture[nbytes] = '\0'; - } - } -} - -/** - * Removes up to 'n' characters at cursor position 'pos'. - * - * Returns 0 if no chars were removed or non-zero otherwise. - */ -static int remove_chars(struct current *current, int pos, int n) -{ - int removed = 0; - - /* First save any chars which will be removed */ - capture_chars(current, pos, n); - - while (n-- && remove_char(current, pos)) { - removed++; - } - return removed; -} -/** - * Inserts the characters (string) 'chars' at the cursor position 'pos'. - * - * Returns 0 if no chars were inserted or non-zero otherwise. - */ -static int insert_chars(struct current *current, int pos, const char *chars) -{ - int inserted = 0; - - while (*chars) { - int ch; - int n = utf8_tounicode(chars, &ch); - if (insert_char(current, pos, ch) == 0) { - break; - } - inserted++; - pos++; - chars += n; - } - return inserted; -} - -#ifndef NO_COMPLETION -static linenoiseCompletionCallback *completionCallback = NULL; - -static void beep() { -#ifdef USE_TERMIOS - fprintf(stderr, "\x7"); - fflush(stderr); -#endif -} - -static void freeCompletions(linenoiseCompletions *lc) { - size_t i; - for (i = 0; i < lc->len; i++) - free(lc->cvec[i]); - free(lc->cvec); -} - -static int completeLine(struct current *current) { - linenoiseCompletions lc = { 0, NULL }; - int c = 0; - - completionCallback(current->buf,&lc); - if (lc.len == 0) { - beep(); - } else { - size_t stop = 0, i = 0; - - while(!stop) { - /* Show completion or original buffer */ - if (i < lc.len) { - struct current tmp = *current; - tmp.buf = lc.cvec[i]; - tmp.pos = tmp.len = strlen(tmp.buf); - tmp.chars = utf8_strlen(tmp.buf, tmp.len); - refreshLine(current->prompt, &tmp); - } else { - refreshLine(current->prompt, current); - } - - c = fd_read(current); - if (c == -1) { - break; - } - - switch(c) { - case '\t': /* tab */ - i = (i+1) % (lc.len+1); - if (i == lc.len) beep(); - break; - case 27: /* escape */ - /* Re-show original buffer */ - if (i < lc.len) { - refreshLine(current->prompt, current); - } - stop = 1; - break; - default: - /* Update buffer and return */ - if (i < lc.len) { - set_current(current,lc.cvec[i]); - } - stop = 1; - break; - } - } - } - - freeCompletions(&lc); - return c; /* Return last read character */ -} - -/* Register a callback function to be called for tab-completion. - Returns the prior callback so that the caller may (if needed) - restore it when done. */ -linenoiseCompletionCallback * linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn) { - linenoiseCompletionCallback * old = completionCallback; - completionCallback = fn; - return old; -} - -void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str) { - lc->cvec = (char **)realloc(lc->cvec,sizeof(char*)*(lc->len+1)); - lc->cvec[lc->len++] = strdup(str); -} - -#endif - -static int linenoiseEdit(struct current *current) { - int history_index = 0; - - /* The latest history entry is always our current buffer, that - * initially is just an empty string. */ - linenoiseHistoryAdd(""); - - set_current(current, ""); - refreshLine(current->prompt, current); - - while(1) { - int dir = -1; - int c = fd_read(current); - -#ifndef NO_COMPLETION - /* Only autocomplete when the callback is set. It returns < 0 when - * there was an error reading from fd. Otherwise it will return the - * character that should be handled next. */ - if (c == '\t' && current->pos == current->chars && completionCallback != NULL) { - c = completeLine(current); - /* Return on errors */ - if (c < 0) return current->len; - /* Read next character when 0 */ - if (c == 0) continue; - } -#endif - -process_char: - if (c == -1) return current->len; -#ifdef USE_TERMIOS - if (c == 27) { /* escape sequence */ - c = check_special(current->fd); - } -#endif - switch(c) { - case '\r': /* enter */ - history_len--; - free(history[history_len]); - return current->len; - case ctrl('C'): /* ctrl-c */ - errno = EAGAIN; - return -1; - case 127: /* backspace */ - case ctrl('H'): - if (remove_char(current, current->pos - 1) == 1) { - refreshLine(current->prompt, current); - } - break; - case ctrl('D'): /* ctrl-d */ - if (current->len == 0) { - /* Empty line, so EOF */ - history_len--; - free(history[history_len]); - return -1; - } - /* Otherwise fall through to delete char to right of cursor */ - case SPECIAL_DELETE: - if (remove_char(current, current->pos) == 1) { - refreshLine(current->prompt, current); - } - break; - case SPECIAL_INSERT: - /* Ignore. Expansion Hook. - * Future possibility: Toggle Insert/Overwrite Modes - */ - break; - case ctrl('W'): /* ctrl-w, delete word at left. save deleted chars */ - /* eat any spaces on the left */ - { - int pos = current->pos; - while (pos > 0 && get_char(current, pos - 1) == ' ') { - pos--; - } - - /* now eat any non-spaces on the left */ - while (pos > 0 && get_char(current, pos - 1) != ' ') { - pos--; - } - - if (remove_chars(current, pos, current->pos - pos)) { - refreshLine(current->prompt, current); - } - } - break; - case ctrl('R'): /* ctrl-r */ - { - /* Display the reverse-i-search prompt and process chars */ - char rbuf[50]; - char rprompt[80]; - int rchars = 0; - int rlen = 0; - int searchpos = history_len - 1; - - rbuf[0] = 0; - while (1) { - int n = 0; - const char *p = NULL; - int skipsame = 0; - int searchdir = -1; - - snprintf(rprompt, sizeof(rprompt), "(reverse-i-search)'%s': ", rbuf); - refreshLine(rprompt, current); - c = fd_read(current); - if (c == ctrl('H') || c == 127) { - if (rchars) { - int p = utf8_index(rbuf, --rchars); - rbuf[p] = 0; - rlen = strlen(rbuf); - } - continue; - } -#ifdef USE_TERMIOS - if (c == 27) { - c = check_special(current->fd); - } -#endif - if (c == ctrl('P') || c == SPECIAL_UP) { - /* Search for the previous (earlier) match */ - if (searchpos > 0) { - searchpos--; - } - skipsame = 1; - } - else if (c == ctrl('N') || c == SPECIAL_DOWN) { - /* Search for the next (later) match */ - if (searchpos < history_len) { - searchpos++; - } - searchdir = 1; - skipsame = 1; - } - else if (c >= ' ') { - if (rlen >= (int)sizeof(rbuf) + 3) { - continue; - } - - n = utf8_getchars(rbuf + rlen, c); - rlen += n; - rchars++; - rbuf[rlen] = 0; - - /* Adding a new char resets the search location */ - searchpos = history_len - 1; - } - else { - /* Exit from incremental search mode */ - break; - } - - /* Now search through the history for a match */ - for (; searchpos >= 0 && searchpos < history_len; searchpos += searchdir) { - p = strstr(history[searchpos], rbuf); - if (p) { - /* Found a match */ - if (skipsame && strcmp(history[searchpos], current->buf) == 0) { - /* But it is identical, so skip it */ - continue; - } - /* Copy the matching line and set the cursor position */ - set_current(current,history[searchpos]); - current->pos = utf8_strlen(history[searchpos], p - history[searchpos]); - break; - } - } - if (!p && n) { - /* No match, so don't add it */ - rchars--; - rlen -= n; - rbuf[rlen] = 0; - } - } - if (c == ctrl('G') || c == ctrl('C')) { - /* ctrl-g terminates the search with no effect */ - set_current(current, ""); - c = 0; - } - else if (c == ctrl('J')) { - /* ctrl-j terminates the search leaving the buffer in place */ - c = 0; - } - /* Go process the char normally */ - refreshLine(current->prompt, current); - goto process_char; - } - break; - case ctrl('T'): /* ctrl-t */ - if (current->pos > 0 && current->pos <= current->chars) { - /* If cursor is at end, transpose the previous two chars */ - int fixer = (current->pos == current->chars); - c = get_char(current, current->pos - fixer); - remove_char(current, current->pos - fixer); - insert_char(current, current->pos - 1, c); - refreshLine(current->prompt, current); - } - break; - case ctrl('V'): /* ctrl-v */ - if (has_room(current, 3)) { - /* Insert the ^V first */ - if (insert_char(current, current->pos, c)) { - refreshLine(current->prompt, current); - /* Now wait for the next char. Can insert anything except \0 */ - c = fd_read(current); - - /* Remove the ^V first */ - remove_char(current, current->pos - 1); - if (c != -1) { - /* Insert the actual char */ - insert_char(current, current->pos, c); - } - refreshLine(current->prompt, current); - } - } - break; - case ctrl('B'): - case SPECIAL_LEFT: - if (current->pos > 0) { - current->pos--; - refreshLine(current->prompt, current); - } - break; - case ctrl('F'): - case SPECIAL_RIGHT: - if (current->pos < current->chars) { - current->pos++; - refreshLine(current->prompt, current); - } - break; - case SPECIAL_PAGE_UP: - dir = history_len - history_index - 1; /* move to start of history */ - goto history_navigation; - case SPECIAL_PAGE_DOWN: - dir = -history_index; /* move to 0 == end of history, i.e. current */ - goto history_navigation; - case ctrl('P'): - case SPECIAL_UP: - dir = 1; - goto history_navigation; - case ctrl('N'): - case SPECIAL_DOWN: -history_navigation: - if (history_len > 1) { - /* Update the current history entry before to - * overwrite it with tne next one. */ - free(history[history_len - 1 - history_index]); - history[history_len - 1 - history_index] = strdup(current->buf); - /* Show the new entry */ - history_index += dir; - if (history_index < 0) { - history_index = 0; - break; - } else if (history_index >= history_len) { - history_index = history_len - 1; - break; - } - set_current(current, history[history_len - 1 - history_index]); - refreshLine(current->prompt, current); - } - break; - case ctrl('A'): /* Ctrl+a, go to the start of the line */ - case SPECIAL_HOME: - current->pos = 0; - refreshLine(current->prompt, current); - break; - case ctrl('E'): /* ctrl+e, go to the end of the line */ - case SPECIAL_END: - current->pos = current->chars; - refreshLine(current->prompt, current); - break; - case ctrl('U'): /* Ctrl+u, delete to beginning of line, save deleted chars. */ - if (remove_chars(current, 0, current->pos)) { - refreshLine(current->prompt, current); - } - break; - case ctrl('K'): /* Ctrl+k, delete from current to end of line, save deleted chars. */ - if (remove_chars(current, current->pos, current->chars - current->pos)) { - refreshLine(current->prompt, current); - } - break; - case ctrl('Y'): /* Ctrl+y, insert saved chars at current position */ - if (current->capture && insert_chars(current, current->pos, current->capture)) { - refreshLine(current->prompt, current); - } - break; - case ctrl('L'): /* Ctrl+L, clear screen */ - clearScreen(current); - /* Force recalc of window size for serial terminals */ - current->cols = 0; - refreshLine(current->prompt, current); - break; - default: - /* Only tab is allowed without ^V */ - if (c == '\t' || c >= ' ') { - if (insert_char(current, current->pos, c) == 1) { - refreshLine(current->prompt, current); - } - } - break; - } - } - return current->len; -} - -int linenoiseColumns(void) -{ - struct current current; - enableRawMode (¤t); - getWindowSize (¤t); - disableRawMode (¤t); - return current.cols; -} - -char *linenoise(const char *prompt) -{ - int count; - struct current current; - char buf[LINENOISE_MAX_LINE]; - - if (enableRawMode(¤t) == -1) { - printf("%s", prompt); - fflush(stdout); - if (fgets(buf, sizeof(buf), stdin) == NULL) { - return NULL; - } - count = strlen(buf); - if (count && buf[count-1] == '\n') { - count--; - buf[count] = '\0'; - } - } - else - { - current.buf = buf; - current.bufmax = sizeof(buf); - current.len = 0; - current.chars = 0; - current.pos = 0; - current.prompt = prompt; - current.capture = NULL; - - count = linenoiseEdit(¤t); - - disableRawMode(¤t); - printf("\n"); - - free(current.capture); - if (count == -1) { - return NULL; - } - } - return strdup(buf); -} - -/* Using a circular buffer is smarter, but a bit more complex to handle. */ -int linenoiseHistoryAdd(const char *line) { - char *linecopy; - - if (history_max_len == 0) return 0; - if (history == NULL) { - history = (char **)malloc(sizeof(char*)*history_max_len); - if (history == NULL) return 0; - memset(history,0,(sizeof(char*)*history_max_len)); - } - - /* do not insert duplicate lines into history */ - if (history_len > 0 && strcmp(line, history[history_len - 1]) == 0) { - return 0; - } - - linecopy = strdup(line); - if (!linecopy) return 0; - if (history_len == history_max_len) { - free(history[0]); - memmove(history,history+1,sizeof(char*)*(history_max_len-1)); - history_len--; - } - history[history_len] = linecopy; - history_len++; - return 1; -} - -int linenoiseHistoryGetMaxLen(void) { - return history_max_len; -} - -int linenoiseHistorySetMaxLen(int len) { - char **newHistory; - - if (len < 1) return 0; - if (history) { - int tocopy = history_len; - - newHistory = (char **)malloc(sizeof(char*)*len); - if (newHistory == NULL) return 0; - - /* If we can't copy everything, free the elements we'll not use. */ - if (len < tocopy) { - int j; - - for (j = 0; j < tocopy-len; j++) free(history[j]); - tocopy = len; - } - memset(newHistory,0,sizeof(char*)*len); - memcpy(newHistory,history+(history_len-tocopy), sizeof(char*)*tocopy); - free(history); - history = newHistory; - } - history_max_len = len; - if (history_len > history_max_len) - history_len = history_max_len; - return 1; -} - -/* Save the history in the specified file. On success 0 is returned - * otherwise -1 is returned. */ -int linenoiseHistorySave(const char *filename) { - FILE *fp = fopen(filename,"w"); - int j; - - if (fp == NULL) return -1; - for (j = 0; j < history_len; j++) { - const char *str = history[j]; - /* Need to encode backslash, nl and cr */ - while (*str) { - if (*str == '\\') { - fputs("\\\\", fp); - } - else if (*str == '\n') { - fputs("\\n", fp); - } - else if (*str == '\r') { - fputs("\\r", fp); - } - else { - fputc(*str, fp); - } - str++; - } - fputc('\n', fp); - } - - fclose(fp); - return 0; -} - -/* Load the history from the specified file. If the file does not exist - * zero is returned and no operation is performed. - * - * If the file exists and the operation succeeded 0 is returned, otherwise - * on error -1 is returned. */ -int linenoiseHistoryLoad(const char *filename) { - FILE *fp = fopen(filename,"r"); - char buf[LINENOISE_MAX_LINE]; - - if (fp == NULL) return -1; - - while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) { - char *src, *dest; - - /* Decode backslash escaped values */ - for (src = dest = buf; *src; src++) { - char ch = *src; - - if (ch == '\\') { - src++; - if (*src == 'n') { - ch = '\n'; - } - else if (*src == 'r') { - ch = '\r'; - } else { - ch = *src; - } - } - *dest++ = ch; - } - /* Remove trailing newline */ - if (dest != buf && (dest[-1] == '\n' || dest[-1] == '\r')) { - dest--; - } - *dest = 0; - - linenoiseHistoryAdd(buf); - } - fclose(fp); - return 0; -} - -/* Provide access to the history buffer. - * - * If 'len' is not NULL, the length is stored in *len. - */ -char **linenoiseHistory(int *len) { - if (len) { - *len = history_len; - } - return history; -} DELETED bindings/s2/linenoise/linenoise.h Index: bindings/s2/linenoise/linenoise.h ================================================================== --- bindings/s2/linenoise/linenoise.h +++ bindings/s2/linenoise/linenoise.h @@ -1,120 +0,0 @@ -/* linenoise.h -- guerrilla line editing library against the idea that a - * line editing lib needs to be 20,000 lines of C code. - * - * See linenoise.c for more information. - * - * ------------------------------------------------------------------------ - * - * Copyright (c) 2010, Salvatore Sanfilippo - * Copyright (c) 2010, Pieter Noordhuis - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef __LINENOISE_H -#define __LINENOISE_H - -#ifndef NO_COMPLETION -typedef struct linenoiseCompletions { - size_t len; - char **cvec; -} linenoiseCompletions; - -/* - * The callback type for tab completion handlers. - */ -typedef void(linenoiseCompletionCallback)(const char *, linenoiseCompletions *); - -/* - * Sets the current tab completion handler and returns the previous one, or NULL - * if no prior one has been set. - */ -linenoiseCompletionCallback * linenoiseSetCompletionCallback(linenoiseCompletionCallback *); - -/* - * Adds a copy of the given string to the given completion list. The copy is owned - * by the linenoiseCompletions object. - */ -void linenoiseAddCompletion(linenoiseCompletions *, const char *); -#endif - -/* - * Prompts for input using the given string as the input - * prompt. Returns when the user has tapped ENTER or (on an empty - * line) EOF (Ctrl-D on Unix, Ctrl-Z on Windows). Returns either - * a copy of the entered string (for ENTER) or NULL (on EOF). The - * caller owns the returned string and must eventually free() it. - */ -char *linenoise(const char *prompt); - -/* - * Adds a copy of the given line of the command history. - */ -int linenoiseHistoryAdd(const char *line); - -/* - * Sets the maximum length of the command history, in lines. - * If the history is currently longer, it will be trimmed, - * retaining only the most recent entries. If len is 0 or less - * then this function does nothing. - */ -int linenoiseHistorySetMaxLen(int len); - -/* - * Returns the current maximum length of the history, in lines. - */ -int linenoiseHistoryGetMaxLen(void); - -/* - * Saves the current contents of the history to the given file. - * Returns 0 on success. - */ -int linenoiseHistorySave(const char *filename); - -/* - * Replaces the current history with the contents - * of the given file. Returns 0 on success. - */ -int linenoiseHistoryLoad(const char *filename); - -/* - * Frees all history entries, clearing the history. - */ -void linenoiseHistoryFree(void); - -/* - * Returns a pointer to the list of history entries, writing its - * length to *len if len is not NULL. The memory is owned by linenoise - * and must not be freed. - */ -char **linenoiseHistory(int *len); - -/* - * Returns the number of display columns in the current terminal. - */ -int linenoiseColumns(void); - -#endif /* __LINENOISE_H */ DELETED bindings/s2/linenoise/utf8.c Index: bindings/s2/linenoise/utf8.c ================================================================== --- bindings/s2/linenoise/utf8.c +++ bindings/s2/linenoise/utf8.c @@ -1,115 +0,0 @@ -/** - * UTF-8 utility functions - * - * (c) 2010 Steve Bennett - * - * See LICENCE for licence details. - */ - -#include -#include -#include -#include -#include "utf8.h" - -#ifdef USE_UTF8 -int utf8_fromunicode(char *p, unsigned short uc) -{ - if (uc <= 0x7f) { - *p = uc; - return 1; - } - else if (uc <= 0x7ff) { - *p++ = 0xc0 | ((uc & 0x7c0) >> 6); - *p = 0x80 | (uc & 0x3f); - return 2; - } - else { - *p++ = 0xe0 | ((uc & 0xf000) >> 12); - *p++ = 0x80 | ((uc & 0xfc0) >> 6); - *p = 0x80 | (uc & 0x3f); - return 3; - } -} - -int utf8_charlen(int c) -{ - if ((c & 0x80) == 0) { - return 1; - } - if ((c & 0xe0) == 0xc0) { - return 2; - } - if ((c & 0xf0) == 0xe0) { - return 3; - } - if ((c & 0xf8) == 0xf0) { - return 4; - } - /* Invalid sequence */ - return -1; -} - -int utf8_strlen(const char *str, int bytelen) -{ - int charlen = 0; - if (bytelen < 0) { - bytelen = strlen(str); - } - while (bytelen) { - int c; - int l = utf8_tounicode(str, &c); - charlen++; - str += l; - bytelen -= l; - } - return charlen; -} - -int utf8_index(const char *str, int index) -{ - const char *s = str; - while (index--) { - int c; - s += utf8_tounicode(s, &c); - } - return s - str; -} - -int utf8_charequal(const char *s1, const char *s2) -{ - int c1, c2; - - utf8_tounicode(s1, &c1); - utf8_tounicode(s2, &c2); - - return c1 == c2; -} - -int utf8_tounicode(const char *str, int *uc) -{ - unsigned const char *s = (unsigned const char *)str; - - if (s[0] < 0xc0) { - *uc = s[0]; - return 1; - } - if (s[0] < 0xe0) { - if ((s[1] & 0xc0) == 0x80) { - *uc = ((s[0] & ~0xc0) << 6) | (s[1] & ~0x80); - return 2; - } - } - else if (s[0] < 0xf0) { - if (((str[1] & 0xc0) == 0x80) && ((str[2] & 0xc0) == 0x80)) { - *uc = ((s[0] & ~0xe0) << 12) | ((s[1] & ~0x80) << 6) | (s[2] & ~0x80); - return 3; - } - } - - /* Invalid sequence, so just return the byte */ - *uc = *s; - return 1; -} - -#endif DELETED bindings/s2/linenoise/utf8.h Index: bindings/s2/linenoise/utf8.h ================================================================== --- bindings/s2/linenoise/utf8.h +++ bindings/s2/linenoise/utf8.h @@ -1,79 +0,0 @@ -#ifndef UTF8_UTIL_H -#define UTF8_UTIL_H -/** - * UTF-8 utility functions - * - * (c) 2010 Steve Bennett - * - * See LICENCE for licence details. - */ - -#ifndef USE_UTF8 -#include - -/* No utf-8 support. 1 byte = 1 char */ -#define utf8_strlen(S, B) ((B) < 0 ? (int)strlen(S) : (B)) -#define utf8_tounicode(S, CP) (*(CP) = (unsigned char)*(S), 1) -#define utf8_index(C, I) (I) -#define utf8_charlen(C) 1 - -#else -/** - * Converts the given unicode codepoint (0 - 0xffff) to utf-8 - * and stores the result at 'p'. - * - * Returns the number of utf-8 characters (1-3). - */ -int utf8_fromunicode(char *p, unsigned short uc); - -/** - * Returns the length of the utf-8 sequence starting with 'c'. - * - * Returns 1-4, or -1 if this is not a valid start byte. - * - * Note that charlen=4 is not supported by the rest of the API. - */ -int utf8_charlen(int c); - -/** - * Returns the number of characters in the utf-8 - * string of the given byte length. - * - * Any bytes which are not part of an valid utf-8 - * sequence are treated as individual characters. - * - * The string *must* be null terminated. - * - * Does not support unicode code points > \uffff - */ -int utf8_strlen(const char *str, int bytelen); - -/** - * Returns the byte index of the given character in the utf-8 string. - * - * The string *must* be null terminated. - * - * This will return the byte length of a utf-8 string - * if given the char length. - */ -int utf8_index(const char *str, int charindex); - -/** - * Returns the unicode codepoint corresponding to the - * utf-8 sequence 'str'. - * - * Stores the result in *uc and returns the number of bytes - * consumed. - * - * If 'str' is null terminated, then an invalid utf-8 sequence - * at the end of the string will be returned as individual bytes. - * - * If it is not null terminated, the length *must* be checked first. - * - * Does not support unicode code points > \uffff - */ -int utf8_tounicode(const char *str, int *uc); - -#endif - -#endif DELETED bindings/s2/r-tester.sh Index: bindings/s2/r-tester.sh ================================================================== --- bindings/s2/r-tester.sh +++ bindings/s2/r-tester.sh @@ -1,180 +0,0 @@ -#!/bin/bash -#HELP>##################################################################### -# Runs require.s2 unit test scripts. -# -# Usages: -# -# 1) $0 [flags] -# searches for *.test.s2 in $(dirname $0)/require.d and runs them. -# -# 2) $0 [flags] moduleName ...moduleNameN -# Expects that each argument is a require.s2 module name and -# expects moduleName.test.s2 to exist in the require.s2 module -# search path. -# -# Runs each test in its own s2sh instance and exits with non-0 if -# any test fails. -# -# Flags: -# -# -V enables VERBOSE mode, which simply outputs some extra output. -# -# -vg enables valgrind/massif tests IF valgrind is found in the path. -# These generate some files which one may peruse to collect allocation -# metrics. -# -# Any flags not handled by this script are passed on to the underlying -# s2sh call (quoting might be a problem - avoid complex flags). -# -#HELP<################################################################### - -dir=$(dirname $0) -#[[ '.' = "${dir}" ]] && dir=$PWD -s2sh=$dir/f-s2sh - -[[ -x "$s2sh" ]] || s2sh=$(which s2sh 2>/dev/null) -[[ -x "$s2sh" ]] || { - echo "s2sh not found :(. Looked in [${dir}] and \$PATH." 1>&2 - exit 1 -} -echo "s2sh = ${s2sh}" -rdir=${REQUIRES2_HOME} -[[ -d "$rdir" ]] || rdir=$dir/require.d -[[ -d "$rdir" ]] || { - echo "Missing 'required' dir: $rdir" 1>&2 - exit 2 -} -rdir=$(cd $rdir>/dev/null; echo $PWD) -export S2_HOME=$PWD # used by require.s2 - -requireCall="(s2.require ||| import('${rdir}/require.s2'))" - -DO_VG=0 -VERBOSE=0 -S2SH_ADD_FLAGS="${S2SH_XFLAGS}" -DO_DEBUG=0 - -list='' -for i in "$@"; do - case $i in - -V) VERBOSE=1 - ;; - -vg) DO_VG=1 - ;; - -debug) - DO_DEBUG=1 - ;; - -\?|--help) - echo "$0:" - sed -n '/^#HELP/,/^#HELP/p' < $0 | grep -v -e '^#HELP' \ - | sed -e 's/^#/ /g' - exit 0; - ;; - -*) - S2SH_ADD_FLAGS="${S2SH_ADD_FLAGS} $i" - ;; - *) list="$list $i.test" - ;; - esac -done - -[[ x = "x${list}" ]] && { - cd $rdir || exit $? # oh, come on, steve, this isn't C! - list=$(find . -name '*.test.s2' | cut -c3- | sed -e 's/\.s2$//g' | sort) - cd - >/dev/null -} - -[[ "x" = "x${list}" ]] && { - echo "Didn't find any *.test.s2 scripts :(" 1>&2 - exit 3 -} -list=$(echo $list) # remove newlines -#echo "Unit test list: $list" - -function verbose(){ - [[ x1 = "x${VERBOSE}" ]] && echo $@ -} - -function vgTest(){ - local test=$1 - shift - local flags="$@" - local tmp=tmp.$test - local vgout=vg.$test - cat < $tmp -${requireCall}(['nocache!${test}']); -EOF - local cmd="$vg --leak-check=full -v --show-reachable=yes --track-origins=yes $s2sh ${S2SHFLAGS} -f ${tmp} ${flags}" - echo "Valgrind: $test" - verbose -e "\t$cmd" - $cmd &> $vgout || { - rc=$? - rm -f $tmp - echo "Valgrind failed. Output is in ${vgout}" - exit $rc - } - #rm -f $vgout - echo "Valground: $test [==>$vgout]" - vgout=massif.$test - local msp=ms_print.$test - cmd="$massif --massif-out-file=$msp $s2sh ${S2SHFLAGS} -f ${tmp} ${flags}" - echo "Massifying: $test" - verbose -e "\t$cmd" - $cmd &> $vgout || { - rc=$? - rm -f $tmp - echo "Massif failed. Output is in ${vgout}" - exit $rc - } - echo "Massified $test: try: ms_print ${msp} | less" -} - -#if [ -e f-s2sh ]; then -# # kludge for the libfossil source tree -# S2SH_ADD_FLAGS="${S2SH_ADD_FLAGS}" -#fi -if [[ x1 = x${DO_DEBUG} ]]; then - s2sh="gdb --args $s2sh" -fi -S2SHFLAGS="-rv -si ${S2SH_ADD_FLAGS}" -# Reminder: some fsl modules rely on code set up by s2sh init script, -# so we cannot use the --a option in libfossil. -echo S2SHFLAGS=$S2SHFLAGS -for test in $list; do - echo "Running require.s2 test: ${test}" - outfile=${rdir}/${test}.test_out - verbose "Output going to: $outfile" - rm -f "$outfile" - tmpfile=${rdir}/${test}.tmp - echo "${requireCall}(['nocache!${test}']);" > $tmpfile - cmd="$s2sh ${S2SHFLAGS} -o ${outfile} -f ${tmpfile}" - echo "Running test [${test}]: $cmd" - $cmd - rc=$? - [[ 0 -eq $rc ]] || { - echo "Test '${test}' failed. Script output (if any) saved to [${outfile}]" 1>&2 - exit $rc - } - #echo "Test did not fail: ${test}" - rm -f $tmpfile - if [[ -s "$outfile" ]]; then - verbose -e "\tOutput is in: ${outfile}" - else - rm -f "${outfile}" - fi -done - -if [[ x1 = "x$DO_VG" ]]; then - vg=$(which valgrind) - if [[ -x "$vg" ]]; then - echo "Runing test(s) through valgrind..." - massif="${vg} --tool=massif --time-unit=ms --heap-admin=0" - for test in $list; do - outfile=$rdir/${test}.test_out - rm -f "$outfile" - vgTest $test -o "${outfile}" - done - fi -fi - -echo "Done! Tests run: ${list}" DELETED bindings/s2/require-demo.s2 Index: bindings/s2/require-demo.s2 ================================================================== --- bindings/s2/require-demo.s2 +++ bindings/s2/require-demo.s2 @@ -1,106 +0,0 @@ -// Alias our requirejs workalike for convenience... -assert Fossil.require /* gets set via f-s2sh.s2 */; -const R = Fossil.require; -if(!R.fsl){ - /* kludge to avoid requiring a CLI flag to provide a repo */ - const f = R(['fsl/context']).0; - affirm f === R.fsl; - affirm R.fsl.db; - R.fsl.openCheckout(); -}/* else a downstream module will open the repo as needed */ - - -print('require() plugins:', R.plugins.propertyKeys()); - -// Use it like requirejs: -R([// Resources to load: those with a '!' are "plugins", not script files - 'fsl/wikiByName!download', - 'text!require-demo.s2', - 'fsl/blob!rid:1', - 'fsl/manifest!trunk' - ], // Callback to pass the resources to: - function(page, thisScript, rid1, trunk){ - print(__FLC, typeinfo(name page), typeinfo(name thisScript), typeinfo(name rid1)); - print("Wiki page [", page.L,"] is", page.W.lengthBytes(),"bytes long."); - print("This script is",thisScript.lengthBytes(),"bytes long."); - print("RID 1's manifest is", rid1.length(), "bytes long."); - print("trunk has", trunk.F.length(), "F-cards."); - }); - - -R(['fsl/context', // shared/cached Fossil.Context instance - 'fsl/wiki/util' // various Wiki utilities - ], - function(fsl, wikiUtil){ - var pages = []; - wikiUtil.getPageNames(). - eachIndex(proc(name){ - pages[] = fsl.loadManifest( wikiUtil.getLatestRid(name) ); - }); - print(pages.length(),"wiki pages found:"); - const j2h = Fossil.time.julianToHuman; - 0 && pages.sort(function(l,r){ - // It seems we have a bug in/around cwal_array_sort_stateful(), as - // the sorted result here is very unexpected. But i'm too tired - // to fight it. - // print('',j2h(r.D), '\n', j2h(l.D), j2h(r.D).compare(j2h(l.D))); - //return j2h(r.D).compare(j2h(l.D)); - //print(r.D, l.D, r.D.compare(l.D)); - //return (r.D * 10000000).toInt() - (l.D * 10000000).toInt(); - return r.D.compare(l.D); - }); - pages.eachIndex(proc(page){ - print( " %1$-25s @ %2$s by %3$s %4$d bytes". - applyFormat(page.L, - j2h(page.D), - page.U, - page.W.lengthBytes())); - }); - print(""); - }); - -R(['fsl/timeline/basic', // list of most recent rows from the event table - 'ostream' // output utility for fans of C++ - ], - proc(tl, os){ - os << "Most recent timeline entries:\n"; - tl.eachIndex(proc(v){ - os << v.type << ' ' << v.uuid.substr(0,10) - << ' @ ' << Fossil.time.julianToHuman(v.mtime) - << ' by ' - << (v.euser ||| v.user) - << '\n\t' - << (v.ecomment ||| v.comment) - << '\n'; - }); - os << '\n'; - }); - -// An auto-loaded (not pre-registered) plugin: -R(['demo!foo', - 'demo!bar?a=1&b&c=hi there' - ], - proc(demo, d2){ - print("Demo auto-loaded plugin:",demo); - assert d2 === demo /* because of how this particular plugin works */; - assert 2 === demo.counter; - assert 'bar' === demo.lastArgs.0; - assert 'hi there' === demo.lastArgs.1.c; - }); - -if(Fossil.file.isFile('cgimod.so')){ - R(['dll!cgimod', // the CGI API (loadable module) - 'dll!cgimod', // same instance (cached) - 'dll!cgimod?checkingCache' // params bypass caching - /* reminder: 2 instances of this module is semantically - invalid in a real CGI context. We're just testing that - R()'s docs regarding caching matches its behaviour. */ - ], - proc(cgi, cgi2, cgi3){ - assert cgi === cgi2; - assert cgi !== cgi3; - print("Loaded cgi module: "+cgi); - }); -}else{ - print("cgimod DLL not found."); -} DELETED bindings/s2/require.d/BufferFactory.s2 Index: bindings/s2/require.d/BufferFactory.s2 ================================================================== --- bindings/s2/require.d/BufferFactory.s2 +++ bindings/s2/require.d/BufferFactory.s2 @@ -1,18 +0,0 @@ -/** - A require.s2 module which returns an object containing "factory - methods" for creating Buffers. -*/ -return { - /** - Usage: - - var buffer = thisObj.new([reservedMemorySize=0]); - */ - new: s2.Buffer.new, - /** - Usage: - - var buffer = thisObj.readFile(filename); - */ - readFile: s2.Buffer.readFile -} DELETED bindings/s2/require.d/BufferFactory.test.s2 Index: bindings/s2/require.d/BufferFactory.test.s2 ================================================================== --- bindings/s2/require.d/BufferFactory.test.s2 +++ bindings/s2/require.d/BufferFactory.test.s2 @@ -1,14 +0,0 @@ -/** - A require.s2 module which returns an object containing "factory - methods" for creating Buffers. -*/ -requireS2( -['BufferFactory'], -proc(bfac){ - var b = bfac.new(100); - affirm b.capacity()>=100; - - b = bfac.readFile(__FILE); - affirm 'buffer' === typename b; - affirm b.length()>50; -}); DELETED bindings/s2/require.d/DataModels/TestModel.s2 Index: bindings/s2/require.d/DataModels/TestModel.s2 ================================================================== --- bindings/s2/require.d/DataModels/TestModel.s2 +++ bindings/s2/require.d/DataModels/TestModel.s2 @@ -1,43 +0,0 @@ -/** - Test/demo require.s2 DataModel module the modeler module - and/or the DataModel plugin. -*/ -return { - //__typename: 'Testing that this will not get overwritten', - /** - Gets called by the modeler framework when this module's - (inherited) new() method is called. In the context of this - function, "this" will be the new Model instance, which inherits - this object. - - The return value is ignored by the modeler framework. - */ - initialize: proc(a,b,c){ - print(__FLC, 'initialize()ing', typename this, this); - print(__FLC, 'argv =', argv); - print(__FLC, 'super =',super); - assert __FILE.indexOf(typename this)>=0 - /* __typename gets automatically set from the file name - when the model is loaded if it does not set one itself. */; - this.attr('a',a) - .attr('b',b) - .attr('c',c); - }, - /** - Attributes defined in the prototype are visible via the - inherited attr() method, but do not get serialized via the - inherited toJSON() method unless their values have been - explicitly set in the most-derived model instance. - */ - attributes:{ - foo: -1 - } -}; -/*.withThis(proc(){ - return ('undefined' === typename requireS2) - ? this - : ((const that=this), - requireS2(['modeler'],proc(M){ - return M.extendModel(that) - })); -});*/ DELETED bindings/s2/require.d/Ticker.s2 Index: bindings/s2/require.d/Ticker.s2 ================================================================== --- bindings/s2/require.d/Ticker.s2 +++ bindings/s2/require.d/Ticker.s2 @@ -1,315 +0,0 @@ -/** - A require.s2 module implementing an abstract timer class. See the - inlined docs (down below) for details. - - Example usage: - - - const Ticker = require(['Ticker']).0; - const t = new Ticker(); - t.addEvent(1, true, proc(){print("repeating event")}); - t.addEvent(3, proc(){print("one-time event")}); - - t.tick(); - t.tick(); - t.tick(); - // or: t.tick(3) - - Will output the following, though the order of events at firing at - the same logical time (the last two lines here) is not defined and - may change during the lifetime of repeating events or differ - depending on whether the clock is incremented one tick at a time or - more than one: - - repeating event - repeating event - one-time event - repeating event -*/ -/** - Ticker is a utility class implementing an abstract - timer. It doesn't know anything about time - it keeps - track of time in abstract ticks. Events can be added - to it which are fired after a certain number of ticks, - optionally repeating every N ticks. - - To create a new instance, call this function. Its return - value inherits this function. - - It's functionally similar to JavaScript's setTimeout() - and setInterval() except for: - - a) It is strictly synchronous. - - b) It has no clock. The client has to tell it that X amount of - (abstract) time has passed. - - c) It currently has no way to properly remove events (and doing so - from an event handler may mess up its iteration for the time being). -*/ - - -return { - __typename: 'Ticker', - /** Internal list of events */ - //tlist: [], - - /** Current timestamp (tick counter) */ - //ts: 0, - - /** Internal helper to sort event entries by their timestamp. - Empty/null entries are sorted as less than any others - because this make them easy to remove. - */ - sortEvents:function f(){ - f.sorter || (f.sorter=function(l,r){ - // sort nulls to the LEFT (easier (but more memmov'ing) to lop them off that way) - l || return r ? -1 : 0; - r || return 1; - return compare(l.when, r.when) ||| - compare(l.priority, r.priority) ||| - compare(l.ts,r.ts) ||| - compare(l.id,r.id); - }); - this.tlist.sort(f.sorter); - }.importSymbols({compare: function(l,r){ - return (lr) ? 1 : 0); - }}), - - /** - Returns an incremental integer value on each call. - */ - nextEventId: function(){ - this.idCounter || (this.idCounter = 0); - return ++this.idCounter; - }, - - /** - Adds a timer event to (potentially) be triggered - via advancement of the timer (see tick()). - - 'when' is the relative tick number (in the future) in which - to fire the event. Must be a positive value. - - 'repeats' is a boolean. Repeating events trigger every 'when' - ticks. - - 'what' is a Function which gets called when the event timer - is triggered. When called, what's 'this' will be the - event Object containing 'what'. - - If called with two arguments then it is treated as if - (when, false, what) are passed in. - - If called with one argument then it is equivalent to calling - addEvent2(). - - Returns an Object describing the event. Clients may add - their own properties to it and use those from the - what() handler (accessible via this.PROPERTY). - - Callers can control the ordering of events fired at - the same time by setting a priority numeric property - on the returned event object. Priority sorts using - normal numeric comparison, so lower values sort first. - The default priority is 0 and negative values are legal. - - This class supports the following event object properties - (and ignores all others): - - id: has no meaning but is used as a fallback option when sorting. - Clients may set this to what they wish, and a default value - (incremental integers) is set. - - ts: the current "timestamp", in ticks, of this ticker. It is - incremented by calling tick(). - - when: the tick time at which the event will next fire. - - what: the function to call when the event fires. - - interval: an integer specifying that the event should repeat - every this-many ticks. If not set, or set to a falsy value, - the event is a one-time event and will be removed after firing - by the tick() process. - - priority: an integer value which determines run order for - events firing at the same tick (lower values sort first). For - "overlapping" ticks (with a time span of more than one tick) - this order might be somewhat intuitive: all "overlap" runs of - a given event handler are processed before the next - event. i.e. the priority order is maintained, but each event - may be run multiple times in succession before another event - with a higher (or the same) priority value. - - client: this property name is reserved solely for use by - client code. This API promises never to use that property - key in event objects. - */ - addEvent:function(when, repeats, what ){ - const argc = argv.length(); - (1===argc) && return this.addEvent2(when); - if(2===argc && typeinfo(isfunction repeats)){ - what = repeats; - repeats = false; - } - affirm when>0; - affirm typeinfo(isfunction what); - this.idCounter || (this.idCounter = 0); - const ev = { - id: this.nextEventId(), - ts: this.ts, - when: this.ts + when, - what: what, - priority: 0 - }; - repeats && (ev.interval = when); - this.tlist.push(ev); - return ev; - }, - - /** - An alternate form of addEvent() which takes an object. - - Returns the object passed to it, after enriching it - with event state and adding it to the list. - - If the object has a an 'interval' property but no 'when' - property then its 'when' is set to the interval value. - Likewise, if 'when' is set and 'repeats' is set to a truthy - value, 'interval' gets set to 'when'. - - Example: - - ticker.addEvent({interval: 3, what:myFunc}); - - will set up a repeating event, firing first in 3 ticks, - and then ever 3 ticks after that. - */ - addEvent2:function(obj){ - affirm typeinfo(iscontainer obj); - affirm typeinfo(isfunction obj.what); - if(obj.repeats && !obj.interval){ - obj.interval = obj.when; - } - unset obj.repeats; - if(obj.interval && !obj.when){ - obj.when = obj.interval; - } - affirm obj.when > 0; - obj.ts = this.ts; - obj.priority || (obj.priority = 0); - obj.id || (obj.id = this.nextEventId()); - this.tlist[] = obj; - return obj; - }, - - /** - Removes all event handlers and resets the tick counter to 0. - */ - reset: function(){ - this.ts = 0; - this.tlist.clear(); - return this; - }, - - /** - Increments the tick count by incr (default=1) and triggers any - events whose time comes. If incr is greater than one and a - repeating event would normally have been triggered multiple - times within that span, this function calls it the number of - times it would have been called had tick() been called in - increments of 1. The order of event callbacks is unspecified - by default - they continually get re-sorted based on their - trigger time. Clients can control the order of like-timed - events by setting a priority level on an event - see - addEvent() for details. - - Events added to this object by an event handler will NOT - be called in this invocation of tick() - they are queued up - and added to the event list after tick() has finished processing - any pending handlers. - - Returns this object. - */ - tick: function(incr=1){ - affirm typeinfo(isinteger incr); - affirm incr >= 0; // a tick value of 0 might be interesting for something - const li = this.tlist; - var n = li.length(); - affirm typeinfo(isarray li); - this.ts += incr; - n || return this; - - /* Remove any expired-and-fired events here (as opposed to afterwards) - because (it turns out) this simplifies things. */ - this.sortEvents(); // moves nulls to the left - while(n && !li.0){ - /* Remove any expired events */ - li.shift(); - --n; - } - n || return this; - - // Move this.tlist so that adding events while looping does not affect us. - const listSentry = this.tlist; - this.tlist = []; - - /* - Loop over events until we find one with a 'when' - set in the future. All current events will be to the - left of that one. - */ - const tm = this.ts; - for(var i = 0, e, shiftCount = 0, repeater = 0; - itm){ break } /* first in-the-future event. */ - else { - affirm e.when > e.ts; - if(var err=catch{e.what()}){ - print(__FLC,"WARNING: tick handler threw. Removing it.",e,err); - unset e.interval; - } - if(e.interval){ /* Set this one up to run again */ - e.ts = e.ts + e.interval; - e.when = e.ts + e.interval; - if(e.when <= tm){ - /* timespan skipped one or more intervals. Run them now. */ - //print(__FLC,"firing again for overlap:",e); - --i /* fudge the loop counter to repeat this entry. - May break this.tlist is modified by - callback. */; - repeater = e; - continue; - } - }else{ /* remove the event */ - li[i] = undefined; - ++shiftCount; - } - } - } - /* Move this.tlist back... */ - if(this.tlist.isEmpty()){ /* no changes made during iteration */ - this.tlist = listSentry; - }else{ - /* Events added while looping. Integrate them now. - We swap tlist here so that we can keep the original - array (as a minor potential allocation optimization). */ - this.tlist.eachIndex(integrateTlist); - this.tlist = listSentry; - } - return this; - }/*tick()*/.importSymbols({ - integrateTlist: proc(i,v){ listSentry.push(v) } - }), - /** - Constructor function for new instances. - */ - __new: proc(){ - this.tlist = []; - this.ts = 0; - } -}; DELETED bindings/s2/require.d/Ticker.test.s2 Index: bindings/s2/require.d/Ticker.test.s2 ================================================================== --- bindings/s2/require.d/Ticker.test.s2 +++ bindings/s2/require.d/Ticker.test.s2 @@ -1,64 +0,0 @@ -requireS2(['time','nocache!Ticker'], proc(time, Ticker){ - affirm 'Ticker' === typeinfo(name Ticker); - const t = new Ticker(); - affirm t inherits Ticker; - affirm 'Ticker' === typeinfo(name t); - const callback = proc(){print('fired:',this.name)}; - var ev; - affirm typeinfo(isfunction callback); - // Repeating event, every 3rd tick: - ev = t.addEvent(3, true, callback); - - ev.name = "threeer"; - ev.priority = 3; - /* - Event priority is used to break ties for events firing at - the same virtual time. It sorts by value, so a lower value - has a higher priority. Events have a default priority of 0. - */ - - // Add a repeating event which fires every tick: - ev = t.addEvent(1, true, callback); - ev.name = "oner"; - ev.priority = -1; - - - // Add a one-time event, fired once, four ticks from now: - affirm typeinfo(isfunction callback); - ev = t.addEvent(4, callback); - ev.name = "fourer"; - ev.priority = 4; - - // Add a repeating event, firing every 2nd tick: - ev = t.addEvent({interval: 2, what: callback, name: "twoer"}); - - print(__FLC,typeinfo(name t),':',t); - - // Now advance our virtual clock a few times... - var i = 1, max = 10, sleepTimeMs = 100; - - print("Ticking",max,"times, sleeping",sleepTimeMs," millis between ticks..."); - //const timeFmt = {%Y-%m-%d %H:%M:%S} - //const startTime = strftime(timeFmt, time()) - for( ;i<=max; i=i+1){ - print("TICK #"+i); - time.mssleep(sleepTimeMs); - t.tick(); - } - //const endTime = strftime(timeFmt, time()); - print('After loop: Tick =',t.ts); - //print('Start time:',startTime,'\nEnd time :',endTime); - if(0) { - print('"Manually" ticking...'); - t.tick(6); // note how priority sorting kinda breaks down here - // potential workaround: run ticks>1 in a loop of smaller ticks, - // but how small? Maybe set tickerInstance.timeUnit=integer to - // set the smallest time unit, and loop in increments of that unit? - } - //t.tick(5); - //print(__FLC,"Done:",t); - - //dumpInternedStrings(); - t.reset(); - affirm t.tlist.isEmpty(); -}); DELETED bindings/s2/require.d/cliargs.s2 Index: bindings/s2/require.d/cliargs.s2 ================================================================== --- bindings/s2/require.d/cliargs.s2 +++ bindings/s2/require.d/cliargs.s2 @@ -1,101 +0,0 @@ -/** - A require.s2 module which returns a utility object for working with - the CLI arguments provided via s2.ARGV. - - "Script arguments" are those passes to s2sh after any '--' flag. - Those get imported into s2.ARGV (which is not set if no script - flags are provided). - - s2.ARGV, if set, is an Array containing all flags passed after - '--', plus possibly containing these two properties: - - .flags: an object of --flag=value pairs, where --flags with no - value are treated as boolean true. - - .nonFlags: any script argument which does not start with '-' is - assumed to be a filename or some other string, and is appended - to this array. - - Either property will be undefined if no flags resp. non-flags - are provided. -*/ -return { - - /** - Holds an Array of all arguments passed after '--' to s2sh - resp. any app which installs that particular binding. It is - undefined (not an empty array) if there are no such flags. - */ - args: s2.ARGV, - /** - An object (or not) containing any -flags. The keys are stripped - of any number of leading dashes and if a given flag is - duplicated, the last one currently wins (as opposed to getting - an array of values, though that might be a useful addition). - */ - flags: s2.ARGV ? s2.ARGV.flags : undefined, - - /** - An array (or not) of any non-flags passed after --, - in the order they were passed in. - */ - nonFlags: s2.ARGV ? s2.ARGV.nonFlags : undefined, - - /** - If the given flag (minus any number of prefixing "-") was passed in - the "script flags" (any flags passed after '--' to the s2sh - interpreter), its value is returned, otherwise dflt is returned. - */ - getFlag: proc(flag, dflt){ - return this.flags - ? (this.flags[flag] ?: dflt) - : dflt; - }, - - /** - If the given flag (minus any number of prefixing "-") was - passed in the "script flags" (any flags passed after '--' to - the s2sh interpreter), its is removed from the flags and its - value is returned, otherwise dflt is returned. - - When the last flag is removed, this.flags is unset. - */ - takeFlag: proc(flag, dflt){ - this.flags || return dflt; - if(undefined !== const v = this.flags[flag]){ - unset this.flags[flag]; - this.flags.# || unset this.flags; - return rc; - }else return dflt; - }, - - /** - Returns true if the CLI flags (still) contain any flags, - otherwise false. - */ - hasFlags: proc(){ - return this.flags ? this.flags.#>0 : false; - }, - - /** - Returns true if the CLI flags (still) contain any non-flags, - otherwise false. - */ - hasNonFlags: proc(){ - return this.nonFlags ? !this.nonFlags.isEmpty() : false; - }, - - /** - Removes the first non-flag from the list and returns - it. Returns undefined if there are no non-flags (or none - remaining). - - When the last entry is removed, this.nonFlags is unset. - */ - nextNonFlag: proc(){ - this.nonFlags || return undefined; - var rc = this.nonFlags.shift(); - (0===this.nonFlags.length()) && unset this.nonFlags; - return rc; - } -}; DELETED bindings/s2/require.d/fsl/context.s2 Index: bindings/s2/require.d/fsl/context.s2 ================================================================== --- bindings/s2/require.d/fsl/context.s2 +++ bindings/s2/require.d/fsl/context.s2 @@ -1,7 +0,0 @@ -/** - require() plugin which simply resolves to the shared Fossil.Context - instance set up by the f-s2sh bootstrap code. This instance should - be used by all other modules so that everybody is using the same - database handles. -*/ -return requireS2.fsl ||| (requireS2.fsl = new Fossil.Context()); DELETED bindings/s2/require.d/fsl/db/checkout.s2 Index: bindings/s2/require.d/fsl/db/checkout.s2 ================================================================== --- bindings/s2/require.d/fsl/db/checkout.s2 +++ bindings/s2/require.d/fsl/db/checkout.s2 @@ -1,14 +0,0 @@ -/** - require() plugin which returns a handle to the repo Db object for - Fossil.require's shared Fossil.Context. If no checkout has been - opened when this is called, openCheckout() is called on the - context, otherwise there are no side effects. -*/ -return requireS2(['fsl/context'], proc(F){ - affirm const d = F.db; - if(!d.checkout){ - F.openCheckout(); - } - affirm d.repo; - return d.repo; -}); DELETED bindings/s2/require.d/fsl/db/config.s2 Index: bindings/s2/require.d/fsl/db/config.s2 ================================================================== --- bindings/s2/require.d/fsl/db/config.s2 +++ bindings/s2/require.d/fsl/db/config.s2 @@ -1,11 +0,0 @@ -/* require() plugin which returns a handle to the repo Db object for - Fossil.require's shared Fossil.Context. If no repo has been opened - when this is called, it opens the repo specified via the - --repo-db|-R=FILENAME CLI script flag. -*/ -return requireS2(['fsl/context'], proc(F,args){ - affirm const d = F.db; - d.config || F.openConfig(); - affirm d.config; - return d.config; -}); DELETED bindings/s2/require.d/fsl/db/main.s2 Index: bindings/s2/require.d/fsl/db/main.s2 ================================================================== --- bindings/s2/require.d/fsl/db/main.s2 +++ bindings/s2/require.d/fsl/db/main.s2 @@ -1,5 +0,0 @@ -/** - require.s2 module which returns the "main" db handle of - the shared Fossil.Context instance. -*/ -return requireS2(['fsl/context']).0.db; DELETED bindings/s2/require.d/fsl/db/repo.s2 Index: bindings/s2/require.d/fsl/db/repo.s2 ================================================================== --- bindings/s2/require.d/fsl/db/repo.s2 +++ bindings/s2/require.d/fsl/db/repo.s2 @@ -1,18 +0,0 @@ -/* require() plugin which returns a handle to the repo Db object for - Fossil.require's shared Fossil.Context. If no repo has been opened - when this is called, it opens the repo specified via the - --repo-db|-R=FILENAME CLI script flag. -*/ -return requireS2(['fsl/context','cliargs'], proc(F,args){ - affirm const d = F.db; - if(!d.repo){ - const f = args.takeFlag('repo-db',args.takeFlag('R')) - ||| throw "No repo db specified. "+ - "Pass the --repo-db|-R=filename "+ - "SCRIPT flag (after --) to the interpreter or open a checkout."; - ('string' === typename f) || throw "Invalid argument type for the --repo-db|-R=DBFILE flag"; - F.openRepo(f); - } - affirm d.repo; - return d.repo; -}); DELETED bindings/s2/require.d/fsl/db/repoOrCheckout.s2 Index: bindings/s2/require.d/fsl/db/repoOrCheckout.s2 ================================================================== --- bindings/s2/require.d/fsl/db/repoOrCheckout.s2 +++ bindings/s2/require.d/fsl/db/repoOrCheckout.s2 @@ -1,16 +0,0 @@ -/** - require.s2 module which returns either the repo db (specified by - the -R|--repo-db=DBFILE script flags) or (if that fails) the repo - db associated with the current checkout. Throws if it can neither - open a checkout nor figure out the db from the CLI args. -*/ -return requireS2(['fsl/context'], proc(F){ - affirm F.db; - F.db.repo && return F.db.repo; - F.db.checkout && return F.db.checkout; - catch return requireS2(['fsl/db/repo']).0; // fails if no -R|--repo-db=DBFILE flag specified - requireS2(['fsl/db/checkout']) /* opens the checkout */; - assert F.db.checkout; - return F.db.repo; -}); - DELETED bindings/s2/require.d/fsl/extendFossil.s2 Index: bindings/s2/require.d/fsl/extendFossil.s2 ================================================================== --- bindings/s2/require.d/fsl/extendFossil.s2 +++ bindings/s2/require.d/fsl/extendFossil.s2 @@ -1,153 +0,0 @@ -/* - A require.s2 module which adds some functionality - to the various Fossil classes. - - This module is not intended to be used more than once and should not - be cached. Thus, to use it: - - Fossil.require(['nocache!fsl/extendFossil'],proc(){}) -*/ - - -assert Fossil; -assert Fossil.Context; -Fossil.artifactTypes && return Fossil /* already ran this module */; - - -//Fossil.loadModule = s2.loadModule2; -//Fossil.importScript = s2.import2; - -/** - Counterpart of the C-level fsl_catype_e enum. -*/ -Fossil.artifactTypes = { - ANY: 0, - CHECKIN: 1, - CLUSTER: 2, - CONTROL: 3, - WIKI: 4, - TICKET: 5, - ATTACHMENT: 6, - EVENT: 7 -}; - -/** - Fetches the first row from the given SQL statement (String or - Buffer) and returns it as an Object (if asArray is false) or an - Array (if asArray is true). - - If the bind argument is passed in then it is passed on to the - Stmt.bind() method of the underlying statement. Use an array to - bind multiple values. To specify the third parameter when there is - nothing to bind, pass the undefined value as the second argument. - i.e. bind===undefined is treated as "nothing to bind," instead of - binding undefined/null. - - Throws on error. Returns undefined if no row is found. -*/ -Fossil.Db.selectRow = proc(sql, bind = undefined, asArray = false){ - affirm this inherits Fossil.Db; - const st = this.prepare(sql); - var rc; - const ex = catch { - st.bind(bind); - rc = asArray ? st.stepArray() : st.stepObject(); - }; - st.finalize(); - ex ? throw ex : return rc; -}; - -/** - Returns an array containing the complete results of each row in the - given SQL's result set. If asArray is true, each row is returned as - an array of column values in the same order as the result set's, - else each is returned an an Object of column name/value pairs with - columns in an an unspecified order. - - The bind parameter may hold value(s) to bind to the given SQL. -*/ -Fossil.Db.selectAll = proc(sql, bind = undefined, asArray = true){ - affirm this inherits Fossil.Db; - const rc = []; - this.each({ - sql: sql, - bind: bind, - mode: asArray ? 1 : 0, - callback: 'rc[] = this', - }); - return rc; -}; - -/** - Given a SELECT-style query and optional bind parameters - (either a single value for a single param or an array - of multiple params), this routine simply dumps out - the results of the query. bind===undefined is treated - as "nothing to bind," instead of binding undefined/null. -*/ -Fossil.Db.dumpQuery = proc(sql,bind = undefined, separator='\t'){ - affirm this inherits Fossil.Db; - return this.each({ - sql:sql, - bind:bind, // note that undefined value is treated as non-existent here - callback:proc(){ - (1===rowNumber) && print(columnNames.join(separator)); - print(this.join(separator)); - } - }); -}; - -/** - Stmt.each() loops over this.step(), calling func(N) on each - iteration, where N is the current row number (1-based). If func() - returns a literal false, looping stops without an error. In the - context of the call, 'this' is the Stmt object. - - Returns this object. -*/ -Fossil.Db.Stmt.each = proc(func){ - affirm this inherits Fossil.Db.Stmt; - affirm typeinfo(iscallable func) && typeinfo(iscallable func.call); - for(var rowNum = 1; this.step(); ++rowNum){ - (false === func.call(this, rowNum)) && break; - //^^^^^^^^ emulate Db.each() - } - return this; -}; - - -/** - Changes to the given dir and pushes the (old) current dir - to the directory stack. To change back to the pre-pushd() - directory, call Fossil.file.popd(). This function relies - on this 'this' object beeing Fossil.file. Throws if it - cannot change directories. - - The array of pushed directory names is available after calling - this function one time via the property - Fossil.file.pushd.dirStack. The most recent directory is at the - end of that array. If that property is undefined, pushd() has - never been called (or someone removed the property). If it is an - empty array, there are currently no directories in the stack. -*/ -Fossil.file.pushd = proc callee(dir){ - affirm 'string' === typename dir; - const curdir = this.currentDir(); - this.chdir(dir); - (callee.dirStack ||| (callee.dirStack = [])).push( curdir ); -}; - -/** - Pops the directory mostly recently pushed by Fossil.file.pushd() - off of the directory stack and changes to that directory. Throws - if called when no directories can be popped. -*/ -Fossil.file.popd = proc(){ - const list = this.pushd.dirStack; - const len = (list ? list.length() : 0) - ||| throw "Directory stack is empty."; - this.chdir(list[len-1]); - return list.pop() -}; - -return Fossil; DELETED bindings/s2/require.d/fsl/reports/common.s2 Index: bindings/s2/require.d/fsl/reports/common.s2 ================================================================== --- bindings/s2/require.d/fsl/reports/common.s2 +++ bindings/s2/require.d/fsl/reports/common.s2 @@ -1,67 +0,0 @@ -/** - INCOMPLETE helper module for pending timeline/reporting bits. -*/ -return requireS2(['fsl/db/repo'], -proc(db){ - const mod = { - db: db, - - /*eventTypeMap:{ - '*': 'all', - ci: 'checkins', - w: 'wiki', - g: 'tags', - e: 'events', - t: 'tickets' - },*/ - - /** - Returns an array of years (integers) representing - the years for which there is timeline activity in - this repo. The entries are sorted ascending. - */ - getActiveYears:proc(){ - return this.db.selectValues(<< 0; - - const isLibfossil = 'libfossil' === rutil.getConfig('project-name'); - - if(isLibfossil){ - affirm x.indexOf(2014) >= 0; - affirm x.indexOf(1972) < 0; - } - - x = rcom.getActiveWeeksForYear(2014); - affirm 'array' === typename x; - affirm x.length() > 0; - - if(isLibfossil){ - affirm 1 === x.0; - affirm x.indexOf(22) < 0 /* no activity that week */; - affirm x.indexOf(41) > 0 /* when this test was added */; - } - - x = rcom.getActiveYearsAndWeeks(); - affirm 'array' === typename x; - affirm x.length() > 0; - affirm 'integer' === typename x.0.year; - affirm 'array' === typename x.0.weeks; - -}); DELETED bindings/s2/require.d/fsl/timeline/basic.s2 Index: bindings/s2/require.d/fsl/timeline/basic.s2 ================================================================== --- bindings/s2/require.d/fsl/timeline/basic.s2 +++ bindings/s2/require.d/fsl/timeline/basic.s2 @@ -1,20 +0,0 @@ -/** - require() module which returns an array of Objects from the event - table. Each includes all fields from the event table plus the - associated blob's uuid. -*/ -return requireS2( - ['fsl/db/repo'], - proc(repo){ - var rc = []; - repo.each({ - mode: 0, - sql:<<<_SQL - SELECT e.*, b.uuid uuid - FROM event e JOIN blob b ON e.objid=b.rid - ORDER BY e.mtime DESC LIMIT 5 - _SQL, - callback:'rc[] = this' - }); - return rc; -}); DELETED bindings/s2/require.d/fsl/util/repo.s2 Index: bindings/s2/require.d/fsl/util/repo.s2 ================================================================== --- bindings/s2/require.d/fsl/util/repo.s2 +++ bindings/s2/require.d/fsl/util/repo.s2 @@ -1,25 +0,0 @@ -/** - In-progress set of utilities for working with repo db tables. -*/ -requireS2(['fsl/db/repoOrCheckout'], proc(repo){ - return { - db: repo, - /** - Fetches an array of strings from this.db, each one being - the name of a user in the current repository. They are - sorted by name. - */ - getUserList: proc(){ - return this.db.selectValues('select login from user order by login'); - }, - - /** - Returns the value of the repoDb.config field with the given key, - or undefined if no such row is found. - */ - getConfig: proc(key){ - affirm 'string' === typename key /* expecting a legal repo.config.key value */; - return this.db.selectValue('SELECT value FROM config WHERE name=?',key); - } - }; -}); DELETED bindings/s2/require.d/fsl/util/repo.test.s2 Index: bindings/s2/require.d/fsl/util/repo.test.s2 ================================================================== --- bindings/s2/require.d/fsl/util/repo.test.s2 +++ bindings/s2/require.d/fsl/util/repo.test.s2 @@ -1,19 +0,0 @@ -/** - In-progress set of utilities for working with repo db tables. -*/ -requireS2(['fsl/db/checkout'/*force repo db open*/,'fsl/util/repo'], -proc(ignored, repo){ - const db = repo.db; - affirm db; - affirm repo.getUserList; - var x = repo.getUserList(); - affirm 'array' === typename x; - affirm x.length() > 0; - affirm x.indexOf('anonymous') >= 0; - - x = repo.getConfig('project-name'); - affirm 'string' === typename x; - x = repo.getConfig('no-such-key'); - affirm undefined === x; - affirm catch{repo.getConfig()}.message.indexOf("'string'") >0; -}); DELETED bindings/s2/require.d/fsl/wiki/pageNames.s2 Index: bindings/s2/require.d/fsl/wiki/pageNames.s2 ================================================================== --- bindings/s2/require.d/fsl/wiki/pageNames.s2 +++ bindings/s2/require.d/fsl/wiki/pageNames.s2 @@ -1,4 +0,0 @@ -return requireS2( - ['fsl/wiki/util'], - proc(util){ return util.getPageNames(); } -); DELETED bindings/s2/require.d/fsl/wiki/util.s2 Index: bindings/s2/require.d/fsl/wiki/util.s2 ================================================================== --- bindings/s2/require.d/fsl/wiki/util.s2 +++ bindings/s2/require.d/fsl/wiki/util.s2 @@ -1,39 +0,0 @@ -/** - A set of wiki-related utilities. -*/ -return requireS2( - ['fsl/context', 'fsl/db/repo'], - proc(fsl, repo){ - return { - getPageNames: proc( caseSensitive ){ - const st = repo.prepare(<<<_SQL - select distinct(substr(tagname,6)) name from tag t, - tagxref x where x.tagid=t.tagid and t.tagname - like 'wiki-%' order by name _SQL - + (caseSensitive - ? '' : ' collate nocase')); - var rc = []; - const ex = catch { - while(st.step()) rc[] = st.get(0); - }; - st.finalize(); - ex ? throw ex : return rc; - }.importSymbols(nameof repo), - - getLatestRid: proc(pageName){ - affirm pageName && 'string' === typename pageName; - return repo.selectValue(<<<_SQL - SELECT x.rid FROM tag t, tagxref x - WHERE x.tagid=t.tagid - AND t.tagname=? - ORDER BY mtime DESC LIMIT 1 - _SQL, - 'wiki-'+pageName - ); - }.importSymbols(nameof repo), - - loadPageArtifact: proc(pageName){ - return fsl.loadManifest( this.getLatestRid(pageName) ); - }.importSymbols(nameof fsl) - } - }); DELETED bindings/s2/require.d/io.s2 Index: bindings/s2/require.d/io.s2 ================================================================== --- bindings/s2/require.d/io.s2 +++ bindings/s2/require.d/io.s2 @@ -1,5 +0,0 @@ -/* a require.s2 module which "hides" s2.io via the module - interface. It could optionally load 'dll!mod_io', but that's - an internal impl detail. -*/ -return s2.io; DELETED bindings/s2/require.d/json.s2 Index: bindings/s2/require.d/json.s2 ================================================================== --- bindings/s2/require.d/json.s2 +++ bindings/s2/require.d/json.s2 @@ -1,5 +0,0 @@ -/* a require.s2 module which "hides" s2.json via the module - interface. It could optionally load 'dll!mod_json', but that's - an internal impl detail. -*/ -return s2.json; DELETED bindings/s2/require.d/json2.s2 Index: bindings/s2/require.d/json2.s2 ================================================================== --- bindings/s2/require.d/json2.s2 +++ bindings/s2/require.d/json2.s2 @@ -1,204 +0,0 @@ -affirm s2.json /* we need this as our basis */; -affirm s2.json.stringify /* was added later, might not be in all (two?) trees yet (ha!) */; -/** - This object basically acts as a (mostly) drop-in replacement for - s2.json, and it uses s2.json to implement most of its - functionality. It uses a custom, script-side stringify() which is - orders of magnitude less efficient (on several levels) than - s2.json.stringify() (which is implemented in C), but allows - overriding of to-JSON behaviour on a per-container or per-prototype - basis. -*/ -return { - /** See s2.json.parse(). */ - parse: s2.json.parse, - /** See s2.json.parseFile(). */ - parseFile: s2.json.parseFile, - /** - Converts the value v into a JSON string (or throws while trying). - - indention may be either a falsy value (for no intenation), a - string (which gets prepended N times for N levels of - indentation), or an integer: a positive value indents that many - spaces and a negative value indents that many tabs. - - v need not be a root-level value (Object or Array), but may be - a string, number, or boolean. - - Returns a string on success, throws on error. - - Notes about special cases: - - - If v or a prototype of v contains a function property named - toJSON() then v.toJSON() is used in place of v for - to-JSON-string conversion. The function must return some - JSON-able form of v. e.g. an implementation for a Hashtable - might return an Object in the form {keys:[...], values:[...]}. - - - Object _keys_ which are _not_ of type (string, integer, double) - are elided from the output. Keys of numeric types are converted - to strings for JSON key purposes. - - - Objects elide any keys which have value counterpart of - undefined. JSON does not know 'undefined'. We "could" translate - it to null here, but we instead opt to elide it. - - - The undefined value: if passed to this function, the string - 'null' is returned. undefined is also translated to 'null' in - the context of array empty entries. - */ - stringify: proc stringify(v, indention = stringify.config.indention){ - affirm ++stringify.level > 0; - const ex = catch{ - typeinfo(isderefable v) && typeinfo(iscallable v.toJSON) && (v = v.toJSON()); - const f = tmap # typename v; - affirm f /* Argument must be a known JSON-able type or have a toJSON() method. */; - if('string'===typename f){ - affirm --stringify.level>=0; - return f; - }else if(!f.buffered){ - /* "Simple" conversions which do not recurse */ - const rc = f(v); - affirm --stringify.level>=0; - return rc; - }else if(stringify.level>stringify.config.maxOutputDepth){ - throw exception('CWAL_RC_RANGE', - "Output depth limit ("+stringify.config.maxOutputDepth+ - ") exceeded while generating JSON."); - }else{ - affirm f.buffered /* f.buffered is set, so... */; - const jbuf = s2.Buffer.new() /* gets appended to by f() */; - f(v) /* appends all output to jbuf */; - affirm --stringify.level>=0; - affirm !jbuf.isEmpty(); - return jbuf.takeString(); - } - }; - affirm --stringify.level>=0; - assert ex /* or we couldn't have gotten this far */; - throw ex; - }.withThis(proc(){ - /** - Public configuration for stringify(). Change these - options to modify the defaults. - */ - this.config = { - /* Default indention used by stringify(). */ - indention: undefined, - /* Separator for entries in arrays and object lists. */ - commaSeparator: ', ', - /* Separator for keys and value in objects. */ - keyValSeparator: ': ', - /* Max object/array depth to allow before erroring - out. Remember that cycles will generally be detected - before this happens, so this doesn't necessarily - indicate that any cycles were encountered. - */ - maxOutputDepth: 15 - }; - this.level = 0; - return this; - }).importSymbols({ - // some crazy scoping and var accesses going on here... - /** - Indents the output, if appropriate, based on the current - call level (or the level specified by the 2nd - parameter). If addNL is true, a newline is appended before - the indentation. This is a no-op if stringify() is called - with a falsy indention parameter. - */ - indent: proc callee(addNL=true, level = stringify.level){ - indention || return; - callee.idbuf || (callee.idbuf = s2.Buffer.new(64)); - if(callee.prevLevel !== level){ - callee.prevLevel = level; - if('integer'===typename indention){ - const len = (indention<0) ? -indention : indention; - affirm len >= 0; - callee.idbuf.length( len * level ) - .fill((indention<0) ? 0x09 : 0x20); - }else if('string' === typename indention){ - callee.idbuf.reset(); - for(var i = 0; i < level; ++i){ - callee.idbuf << indention; - } - } - } - addNL && (jbuf << '\n'); - jbuf << callee.idbuf; - }, - /** - A hashtable mapping typenames to either strings (for static - conversions) or a function taking a value parameter. Those - functions normally return a string, but if the function has - a 'buffered' property which is truthy then its return - result is ignored and instead a Buffer value named jbuf is - made available to them, and they are expected to append all - output there. - */ - tmap: scope { - const proxy4Obj = proc(v){ - v.mayIterate() || throw exception('CWAL_RC_CYCLES_DETECTED',"Cycles detected."); - jbuf << '{'; - proxyEachProp.first = true; - //proxyEachProp('LEVEL', stringify.level); - const ex = catch v.eachProperty(proxyEachProp); - indention && indent(true,stringify.level-1); - jbuf << '}'; - ex && throw ex; - }.importSymbols({ - // Object.eachProperty() proxy. - proxyEachProp: proc callee(k,v){ - undefined === v && return; - callee.first - ? callee.first = false - : jbuf << stringify.config.commaSeparator; - indention && indent(); - const tk = typename k; - if('string'===tk){ - jbuf << k.toJSONString(); - }else if('integer'===tk||'double'===tk){ - jbuf << '"' << k << '"'; - }else{ - return; - } - jbuf << stringify.config.keyValSeparator - << stringify(v,indention); - } - }); - const proxy4Array = proc(v){ - v.mayIterate() || throw exception('CWAL_RC_CYCLES_DETECTED',"Cycles detected."); - jbuf << '['; - proxyEachIndex.first = true; - v.eachIndex(proxyEachIndex); - indention && indent(true,stringify.level-1); - jbuf << ']'; - }.importSymbols({ - proxyEachIndex: proc callee(v){ - callee.first - ? callee.first = false - : jbuf << stringify.config.commaSeparator; - indention && indent(); - jbuf << stringify(v,indention); - } - }); - - proxy4Obj.buffered = - proxy4Array.buffered = true - /* tells stringify() to set up a buffer to send the - results to. */; - const nativeImpl = s2.json.stringify; - {# - array: proxy4Array, - bool: nativeImpl, - double: nativeImpl, - exception: proxy4Obj, - integer: nativeImpl, - null: 'null', - object: proxy4Obj, - string: nativeImpl, - undefined: 'null' - }; // scope result - } - })/*stringify()*/ -}; DELETED bindings/s2/require.d/json2.test.s2 Index: bindings/s2/require.d/json2.test.s2 ================================================================== --- bindings/s2/require.d/json2.test.s2 +++ bindings/s2/require.d/json2.test.s2 @@ -1,74 +0,0 @@ -requireS2(['json2'],proc(JSON){ - //JSON.stringify.config.indention = -1; - const str = proc(v,indent=-1){ - return JSON.stringify(v,indent); - }; - var s; - assert '1' === str(1); - assert '1.23' === str(1.23); - assert '"hi, \\"there\\""' === str('hi, "there"'); - assert 'null' === str(null); - assert 'null' === str(undefined) - /* undefined will be elided in some contexts (object properties), - translated to null in others (e.g. arrays). */; - assert 'false' === str(false); - assert 'true' === str(true); - s = str({x:1, y:{z:'hi "there"', a:[1,2,"yo"]}, u: undefined, n: null}); - assert s.indexOf('"u":') < 0; - assert s.indexOf('"n": null')>0; - - s = JSON.parse(str(exception(-1,"not an error"))); - assert 'not an error' === s.message; - assert -1 === s.code; - - s = JSON.parse(str({a:{b:{1:2,3:4}}})); - assert 2 === s.a.b.1; - assert 4 === s.a.b.3 - /** - BUT ACHTUNG: the integer _keys_ got converted to strings in the - round trip because JSON only supports strings as - keys. Supporting round-trip fideltity for non-string keys - requires a layer of indirection, as demonstrated next... - */; - - // Customizing toJSON for a non-POD type... - var h = s2.Hash.new(); - - // A stringify()-compliant toJSON() impl for Hashtables. - h.toJSON = proc(){ - return { - keys: this.entryKeys(), - values: this.entryValues() - } - }; - - // Just for symmetry (not used by the JSON API)... - h.fromJSON = proc(jsonObj){ - ('string' === typename jsonObj) && (jsonObj = JSON.parse(jsonObj)); - this.clearEntries(); - if(('array' === typename jsonObj.keys) && - ('array' === typename jsonObj.values)){ - const that = this; - jsonObj.keys.eachIndex(proc(v,i){ - that.insert(v, jsonObj.values[i]); - }); - } - return this; - }.importSymbols(nameof JSON); - - // Now try serializing a hash... - h.insert(1, "one"); - h.insert(2, "two"); - s = JSON.parse(str(h)); - assert 2 === s.keys.length(); - assert 2 === s.values.length(); - assert s.keys.indexOf(2)>=0; - assert s.values.indexOf('two')>=0; - - h.clearEntries(); - assert undefined === h # 2; - - h.fromJSON(s); - assert 'two' === h # 2; - -}); DELETED bindings/s2/require.d/ob.s2 Index: bindings/s2/require.d/ob.s2 ================================================================== --- bindings/s2/require.d/ob.s2 +++ bindings/s2/require.d/ob.s2 @@ -1,5 +0,0 @@ -/* a require.s2 module which "hides" s2.ob via the module - interface. It could optionally load 'dll!mod_ob', but that's - an internal impl detail. -*/ -return s2.ob; DELETED bindings/s2/require.d/ostream.s2 Index: bindings/s2/require.d/ostream.s2 ================================================================== --- bindings/s2/require.d/ostream.s2 +++ bindings/s2/require.d/ostream.s2 @@ -1,13 +0,0 @@ -/** - A require() module providing an "ostream" object. It overloads the - << operator and sends all arguments to s2out. - - This module was written before the s2out keyword existed. That - keyword does the same thing but does so more efficiently, making - this module entirely superfluous. It is retained solely as a basic - example of how to write a require.s2 module. -*/ -affirm typeinfo(iscallable s2out); -return { - 'operator<<': proc(){s2out<= 0 ? ';' : ':') - : ['.'], - suffix: ('string' === typename (dllTmp = s2.getenv('S2_MODULE_EXTENSIONS'))) - ? dllTmp.split(dllTmp.indexOf(';') >= 0 ? ';' : ':') - : ['.so','.dll'], - load: function(name,opt){ - var rc; - affirm name && 'string' === typename name; - rc = (opt && opt.entryPoint) - ? s2.loadModule(name, opt.entryPoint, {}) - : s2.loadModule(name, {}); - affirm rc; - if(opt && opt.hasOwnProperty('moduleProperty')){ - rc = rc[opt.moduleProperty]; - }else if(var keys=rc.propertyKeys(); - 1===keys.length()){ - rc = rc[keys.0]; - } - return rc; - } -}; - -mod.prefix.push( requireS2.home + s2.io.dirSeparator + 'dll' ); - -return mod; DELETED bindings/s2/require.d/plugins/fsl/blob.s2 Index: bindings/s2/require.d/plugins/fsl/blob.s2 ================================================================== --- bindings/s2/require.d/plugins/fsl/blob.s2 +++ bindings/s2/require.d/plugins/fsl/blob.s2 @@ -1,22 +0,0 @@ -/** - require() plugin which fetches a blob from the repo db. It - interprets its argument as a symbolic blob name (anything - libfossil's symbol-to-RID conversions support). -*/ -return requireS2( - ['fsl/context', - 'fsl/db/repo' // so that we are ensured that repo is opened by this point - ], - proc(fsl){ - return { - isVirtual: true, - _F: fsl, - load: function(sym){ - return this._F.loadBlob(sym) - } - /* If we wanted to be really pedantic, we would - require(['fsl/db/repo']...) inside load(). - Overkill. - */ - } - }); DELETED bindings/s2/require.d/plugins/fsl/manifest.s2 Index: bindings/s2/require.d/plugins/fsl/manifest.s2 ================================================================== --- bindings/s2/require.d/plugins/fsl/manifest.s2 +++ bindings/s2/require.d/plugins/fsl/manifest.s2 @@ -1,21 +0,0 @@ -/** - require() plugin which fetches a Manifest from the repo db, - in the form of an Object which mimics the fsl_deck structure - (see Fossil.Context.loadManifest()). - - It interprets its argument as a symbolic blob name (anything - libfossil's symbol-to-RID conversions support). -*/ -return requireS2( - ['fsl/context', - 'fsl/db/repo' // so that we are ensured that repo is opened by this point - ], - proc(fsl){ - return { - isVirtual: true, - _F: fsl, - load: function(sym){ - return this._F.loadManifest(sym); - } - } - }); DELETED bindings/s2/require.d/plugins/fsl/wikiByName.s2 Index: bindings/s2/require.d/plugins/fsl/wikiByName.s2 ================================================================== --- bindings/s2/require.d/plugins/fsl/wikiByName.s2 +++ bindings/s2/require.d/plugins/fsl/wikiByName.s2 @@ -1,25 +0,0 @@ -/** - require() plugin which fetches a wiki page from the repo db, - in the form of an Object which mimics the fsl_deck structure - (see Fossil.Context.loadManifest()). - - It interprets its argument as a wiki page name and throws if not - found. -*/ -return requireS2(['fsl/context', 'fsl/db/repo'], proc(fsl, repo){ - return { - isVirtual: true, - _F: fsl, - _sql: <<<_SQL - SELECT x.rid FROM tag t, tagxref x - WHERE x.tagid=t.tagid - AND t.tagname='wiki-%1$q' - ORDER BY mtime DESC LIMIT 1 _SQL, - load: function(name){ - return this._F.loadManifest( - this._F.db.selectValue(this._sql.applyFormat(name)) - ||| throw "No wiki such wiki page: "+name - ); - } - }; -}); DELETED bindings/s2/require.d/plugins/json-cached.s2 Index: bindings/s2/require.d/plugins/json-cached.s2 ================================================================== --- bindings/s2/require.d/plugins/json-cached.s2 +++ bindings/s2/require.d/plugins/json-cached.s2 @@ -1,4 +0,0 @@ -/** A clone of the json plugin, except that cacheIt is set to true. */ -const mod = requireS2.getPlugin('json').copyPropertiesTo({}); -mod.cacheIt = true; -return mod; DELETED bindings/s2/require.d/plugins/json.s2 Index: bindings/s2/require.d/plugins/json.s2 ================================================================== --- bindings/s2/require.d/plugins/json.s2 +++ bindings/s2/require.d/plugins/json.s2 @@ -1,21 +0,0 @@ -/** A require.s2 plugin which loads file content as JSON, - using s2.json.parseFile(). It does _not_ cache its - results. Use the json-cached plugin for the same - effect but with cached results. -*/ -return { - cacheIt: false /* - We _generally_ don't want these cached because - they are "probably" used only once in most cases. - - Use the 'json-cached' plugin if you want cached - JSON files. - */, - suffix: ['.json'], - prefix: // Append '/json' to all paths in the default plugin's path - ((const p = [], suffix = s2.io.dirSeparator+'json'), - requireS2.getPlugin('default').prefix.eachIndex(proc(v){ - p[] = v+suffix; - }), p), - load: proc(file){return s2.json.parseFile(file)} -}; DELETED bindings/s2/require.d/plugins/placeholder.s2 Index: bindings/s2/require.d/plugins/placeholder.s2 ================================================================== --- bindings/s2/require.d/plugins/placeholder.s2 +++ bindings/s2/require.d/plugins/placeholder.s2 @@ -1,6 +0,0 @@ -/* a placeholder. you'll know if you need it. */ -return { - isVirtual: true, - cacheIt: true, - load: proc(){ return {} } -}; DELETED bindings/s2/require.d/plugins/tmpl-compiled.s2 Index: bindings/s2/require.d/plugins/tmpl-compiled.s2 ================================================================== --- bindings/s2/require.d/plugins/tmpl-compiled.s2 +++ bindings/s2/require.d/plugins/tmpl-compiled.s2 @@ -1,12 +0,0 @@ -/** - Works like the tmpl plugin, but passes the file's contents - throughs s2.tmpl() before returning it. -*/ -return { - cacheIt: false, - // prefix: uses the defaults - suffix: ['.tmpl'], - load: proc(fn){ - return s2.tmpl(s2.Buffer.readFile(fn)) - } -}; DELETED bindings/s2/require.d/plugins/tmpl.s2 Index: bindings/s2/require.d/plugins/tmpl.s2 ================================================================== --- bindings/s2/require.d/plugins/tmpl.s2 +++ bindings/s2/require.d/plugins/tmpl.s2 @@ -1,10 +0,0 @@ -/** Loads file content as a buffer, intended - for use with .tmpl files (for s2.tmpl()). */ -return { - cacheIt: false, - // prefix: uses the defaults - suffix: ['.tmpl'], - load: function(name){ - return s2.Buffer.readFile(name); - } -}; DELETED bindings/s2/require.d/pubsub.s2 Index: bindings/s2/require.d/pubsub.s2 ================================================================== --- bindings/s2/require.d/pubsub.s2 +++ bindings/s2/require.d/pubsub.s2 @@ -1,117 +0,0 @@ -/** - A require.s2 module implementing a basic publish-subscriber - manager. - - Example usage: - - http://fossil.wanderinghorse.net/repos/cwal/index.cgi/finfo?name=s2/require.d/pubsub.test.s2 - - Returns a class, each instance of which manages its own list - of publishers and subscribers. -*/ -return { - __typename: 'PubSub', - prototype: undefined, - - /** - Constructor for use with the 'new' keyword. - - var pubber = new thisObj(); - assert pubber inherits thisObj; // this will hold - - Each instance maintains its own, independent list of - subscriptions. - */ - __new: proc(){ - this.reset(); - }, - - /** - Subscribes a callback to events published for a given key. - key may be of any value type. func must be-a Function. - - Returns a unique-per-subscription value (of an unspecified - type) which can be passed to unsub() to opt out of a - subscription. For a permanent subscription, simply ignore the - result value. - */ - sub:proc callee(key, func){ - affirm typeinfo(iscallable func) /* is Function-like */; - const m = (this.$map[key] ||| (this.$map[key]={prototype:null})), - i = enum{k:key}.k; - m[i] = func; - return i; - }, - - /** - Expects id to be a value returned by this.sub() and - unsubscribes a subscriber registered with that id. - - Returns this object. - */ - unsub: proc(id){ - affirm typeinfo(isunique id); - (const c = this.$map[id.value]) && unset c[id]; - return this; - }, - - /** - Publishes an event to all subscribers (if any) of the key - (event type) given as the first argument. - Important notes: - - a) Subscribers are notified in an UNSPECIFIED and (very) - POSSIBLY CHANGING order. - - b) Any arguments given after the event key are passed to each - subscriber callback function, in the order they are passed in - here. e.g. if this function is passed ('foo', 'bar', 1) then - each subscriber will be called with ('bar', 1). Pedantic - side-note: each callback gets its own copy of the arguments - array, to avoid unintended side-effects if a callback modifies - its argv. - - Returns this object (for lack of a better option). - - It propagates any exceptions thrown by a subscriber, and any - pending subscribers won't get called. - - Pedantic side-node: each subscriber gets its own copy of the - arguments array, so it's safe to change it or keep a reference - to it in the subscribers without affecting others. - */ - pub:proc(/*key, event args...*/){ - return this.pubWithThis(argv.shift(), undefined, @argv); - }, - - /** - A special case of pub() useful in certain code constellations. - - For each listener of event type e, its callback is called using - t as the callback's "this" and passing on all arguments after - the second. If t is undefined then each callback is its own - 'this' (as is conventional for s2). - - Returns this object. - - See pub() for more details. - */ - pubWithThis: proc(e,t/*...*/){ - const m = this.$map[e] ||| return this; - affirm typeinfo(isobject m); - argv.shift(2); - foreach(m=>k,f) f.apply(t?:f, argv.slice()); - return this; - }, - - /** - Removes all subscriptions for the given key or (if no arguments - are passed) all subscriptions for all keys. - - Returns this object (for lack of a better option). - */ - reset:proc(/*key*/){ - argv.# ? unset this.$map[argv.0] : this.$map = {prototype:null}; - return this; - } -}; DELETED bindings/s2/require.d/pubsub.test.s2 Index: bindings/s2/require.d/pubsub.test.s2 ================================================================== --- bindings/s2/require.d/pubsub.test.s2 +++ bindings/s2/require.d/pubsub.test.s2 @@ -1,55 +0,0 @@ -/* Short demo of the pubsub require.s2 module. */ -requireS2( - ['nocache!pubsub'], - proc(P){ - const p = new P(); - assert 'object' === typename p.$map /* testing internals */; - print(__FLC, 'pubsub:'); - foreach(p=>k,v) print('\t',k,v); - var counter = 0; - const id = p.sub('hi', proc(){ - ++counter; - print(__FLC,'hi handler 1',argv); - }); - const id2 = p.sub('bye', proc(){ - ++counter; - print(__FLC,'bye handler',argv); - }); - - const id3 = p.sub('hi', proc(){ - ++counter; - print(__FLC,'hi handler 2',argv); - }); - - print(__FLC, 'subscription IDs =',id, id2, id3); - print("Publishing events..."); - p.pub('hi',0, __FLC); - assert 2 === counter; - - p.pub('nope',1, __FLC); - assert 2 === counter; - - p.pub('bye', 2, __FLC); - assert 3 === counter; - - p.pub('hi',3, __FLC); - assert 5 === counter; - p.unsub(id); - p.pub('hi',4, __FLC); - assert 6 === counter; - p.pub('bye', 5, __FLC); - assert 7 === counter; - print(__FLC, 'done'); - - var p2 = new P(); - assert p2.$map; - assert p2.$map !== p.map; - assert p2 !== p; - assert !(p2 inherits p); - assert p2 inherits p.prototype; - assert p2.sub === p.sub; - - print(__FLC, 'really done'); - return p; - } -); DELETED bindings/s2/require.d/require.s2 Index: bindings/s2/require.d/require.s2 ================================================================== --- bindings/s2/require.d/require.s2 +++ bindings/s2/require.d/require.s2 @@ -1,559 +0,0 @@ -/** - Implements a basic script module loading API similar to - require.js (http://requirejs.org). - - In short, this module acts as a loader for arbitrary other content, - be it s2 script code, raw file content, or "virtual" (non-file) - content plugged in by the user. Its usage is modelled very much of - off requirejs, and it will look familiar to anyone who has used - that library. - - See the API docs in this module for more details. For even more - details (or other details, in any case), see this public Google - Doc: - - https://docs.google.com/document/d/14gRP4f-WWgWNS64KM_BI7YjQqBLl4WT3jIrmNmFefYU/view - - Example usage: - - Assume the files r1.s2 and r2.s2 live somewhere in this module's - search path and that both return an Object with a foo() method. - This is how we might import and use them: - - @code - const R = import('path/to/require.s2'); - - R(['r1', 'r2'], proc(r1, r2){ - r1.counter = r2.counter = 1; - print(__FLC,r1); - print(__FLC,r2); - r1.foo(); - r2.foo(); - ++r1.counter; - ++r2.counter; - }); - - R(['r2', 'r1'], proc(r2, r1){ - assert 2 === r2.counter; - assert 2 === r1.counter; - // ^^^ because imported script results are cached - }); - @endcode - -*/ -affirm s2.fs; -affirm s2.Buffer; -affirm typeinfo(isfunction s2.getenv); -affirm typeinfo(isfunction s2.fs.realpath); -affirm typeinfo(isfunction s2.Buffer.readFile); -const /* saves some var lookup time */ -s2 = s2, -realpath = s2.fs.realpath, -getenv = s2.getenv, -cliFlags = (s2.ARGV ? s2.ARGV.flags : 0) ||| {prototype:null} -; - -const importFileBuffer = s2.Buffer.readFile; -const importFileText = proc(fn) using(importFileBuffer) { - return importFileBuffer(fn).takeString(); -}; -/** - If a string-type CLI flag OR environment variable (in that - order) with the given name is found, this function returns an - array of its contents, tokenized using - s2.PathFinder.tokenizePath(). If no flag/environment variable - is found, or a CLI flag with a non-string value is found, - undefined is returned. - - Interpretation of the arguments is as follows: - - - If only 1 argument is provided, this routine looks for both a - CLI flag and environment var (in that order) with that name. - - - If 2 arguments are provided, the 1st is checked as a CLI flag - and the 2nd as an environment variable (in that order). -*/ -const pathFromEnv = proc(f,e=f){ - const p = F[f] ||| E(e); - return typeinfo(isstring p) - ? P.tokenizePath(p) - : undefined; -} using { - E: getenv, - P: s2.PathFinder, - F: cliFlags -}; - -/** - Internal utility to convert almost-URL-encoded plugin options - to some value form. Treats non-existent values (===undefined) - as a boolean true flag. -*/ -const convertQValue = proc(v){ - undefined === v && return true; - 'true' === v && return true; - 'false' === v && return false; - 'null' === v && return null; - return 0.parseNumber(v) ?: v; -}; - -/** - Module-internal cache of import() responses. -*/ -const modCache = new s2.Hash(0.nthPrime(15)); - -/** - The main "require" module object. -*/ -const mod = { - __typename: 'require.s2', - /** - Used for doing file lookups. Its search path and extensions - get continually swapped out by require() and friends to use - whatever search path the current context requires. - */ - pf: new s2.PathFinder(), - pathFromEnv, - /* Exposed for corner-case use by plugins. */ - modCache -}; - -/** - This "default" plugin (A) acts as the default - implementation for fetching require()'d files, (B) is - where the interface for other plugins is documented. -*/ -const PluginModel ={ - /** - Clear the prototype - we don't really need it for - this object. - */ - prototype: undefined, - /** If true, require() does not search for the filename it - is given. (It is assumed to be some form of virtual - unique identifier, and may be empty.) - */ - isVirtual: false, - - /** - cacheIt tells require whether or not to cache the results - of requests to this plugin. If it is true, then this.load() - will only be called for the first request, and its result - will be returned on subsequent requests. EXCEPTION: if - a plugin is called with arguments (see load()) the cache - is ignored/bypassed. - - The default is expected (by client code) to always be true - for the default plugin! - */ - cacheIt: true, - - /** - For file-based plugins, prefix specifies the search - directories (array of strings, excluding any trailing slash - on the directory parts unless they refer to the root - directory). - */ - prefix: pathFromEnv('s2.require.path', 'S2_REQUIRE_PATH') ||| ['.'], - /** - For file-based plugins, suffix specifies the search - extensions (array of strings, including any '.' part, - e.g. use ".foo" instead of "foo" unless you're searching - for partial extensions). - */ - suffix: pathFromEnv('s2.require.extensions', 'S2_REQUIRE_EXTENSIONS') ||| ['.s2'], - - /** - Called by require() to "load" a given module. load() must - accept a module name, "load" that module, for a given - definition of "load", and return its contents or - result. (It need not actually load anything from anywhere, - much less a file: it might simply return a predefined - object or other value.) - - In the call context, 'this' will be this plugin - configuration object. - - The first argument is the "name" part of the string passed - to require. - - The second argument part is either undefined or an object: - if the file string contains '?', anything after the ? is - assumed to be encoded in the form a=b&c=d... (URL-like, but - _without_ the URL encoding), and that gets transformed into - an Object of key/value pairs before passing them to this - function (the default value, if no "=" is provided, is boolean - true). HOWEVER: passing any arguments after '?' will - cause caching to be bypassed, because the arguments presumably - change how the plugin works. Note that if nothing follows - the '?' then no options object is created. - - Caveats regarding the opt parameter: - - 1) all of the values in the opt object will originally be - of type string, but numeric-looking strings and the strings - ("true", "false", "null") get converted to their - script-native type. - - 2) Only one level of opt object is supported, not nested - objects, arrays, etc. - */ - load: proc(f/*, opt*/) using({ - b: s2.Buffer.readFile, - r: mod - }) { - return b(f).evalContents(f,{requireS2: r}); - } - /* Reminder to self: we cannot simply alias to s2.import() because - any extra non-string arguments would be passed to it (doing the - wrong thing). Reminder #2: adding comments outside of function - bodies, instead of if them, uses less memory, since they don't - get allocated as part of the function body. That's especially - significant when the length of the comments outweigh the rest - of the source, as in this case. */ -}; - -/** - The funkiness we do with 'this' vs 'mod' in may places places - below is so that this stuff still works when clients copy the - returned module into a property of another object. i.e. the following - usages are equivalent: - - var x = mod; - obj.x = mod; - x([...],...); - obj.x([...],...); - - Both calls (because of these extra bindings) use the same "this" - inside the call (the local 'mod' symbol), which is important for - identical/correct semantics in both uses. -*/ - -/** - All the plugins are stored in this object, and any number may - potentially be loaded (and added here) via client-side use. -*/ -mod.plugins = { - /** - The name 'default' is magic and assumes certain - plugin-level defaults. It also provides the default .prefix - and .suffix properties for other non-isVirtual (file-using) - plugins (used only if a given plugin does not define them - itself). - */ - default: PluginModel, - /** - Works just like the default plugin but bypasses - the cache. - */ - nocache: { - cacheIt: false, - load: PluginModel.load - }, - /** Loads file content as a string. */ - text: { - cacheIt: false, - // prefix: uses the defaults - suffix: ['.txt', '.s2', '.html'], - load: importFileText - }, - /** Loads file content as a buffer. */ - buffer: { - cacheIt: false, - // prefix: uses the defaults - suffix: ['.txt', '.s2', '.html'], - load: importFileBuffer - } - - /** - Demonstration of a "virtual" plugin (one which does not - use files). - - virtualDemo:{ - isVirtual: true, - cacheIt: true, // not strictly necessary, plugin-dependent - load: proc f(fn,opt){ - print("Example of a 'virtual' handler. Arguments:",argv); - return opt ||| this; - } - } - */ - -}; - -/** - Installs one or more plugins into this object. - - If called with an initial string arugment then: - - - Adds a new plugin. name must be a string and pluginObj must - be an object which follows the PluginModel interface. Returns - pluginObj on success. - - If called with a non-string argument then: - - - name is assumed to be a container. Each of its properties is - assumed to be a module definition, and each one gets installed - via a call back into this function, passing it each key and - value. Returns this object. - - Throws on error. -*/ -mod.addPlugin = proc callee(name, pluginObj){ - if(name && !pluginObj && typeinfo(iscontainer name)){ - foreach(name=>k,v) callee(k,v); - return this; - } - affirm 'string' === typeinfo(name name); - affirm name /* name must be non-empty */; - affirm typeinfo(iscontainer pluginObj) && typeinfo(iscallable pluginObj.load); - mod.plugins[name] = pluginObj; - return mod; -} using(mod); - -/** - Searches for a plugin script by using this.plugins.default's - search path and the name ("plugins/"+name). Returns undefined - if not found, else the result of s2.import()'ing that file. It - does not check if the plugin is already installed, but installs - (or overwrites) it into mod.plugins[name]. -*/ -mod.searchAndInstallPlugin = proc(name){ - mod.pf.prefix = mod.plugins.default.prefix; - mod.pf.suffix = mod.plugins.default.suffix; - const fn = mod.pf.search('plugins/'+name); - return fn - ? mod.plugins[name] = ((const requireS2=mod), import(false,R(fn))) - : undefined; -} using {mod, R: realpath}, - -/** - If the given plugin name is already installed, it is returned, - otherwise it is sought for, installed, and returned. An - exception is thrown if it cannot be found or if installing it - fails. -*/ -mod.getPlugin = proc(name) using(mod) { - return mod.plugins[name] ||| mod.searchAndInstallPlugin(name); -}, - -/** - Attempts to resolve a file name using a given plugin's search - path. basename is the unresolved name of the file to search for - and forPlugin is either a plugin object or the name of a - plugin. The search path/extensions use are those of the given - plugin or (if that plugin has none), the default plugin. If the - given plugin has the isVirtual flag, no search is performed and - the undefined value is returned. -*/ -mod.resolveFilename = proc(basename,forPlugin='default') using(mod){ - const pConf = typeinfo(isobject forPlugin) ? forPlugin : mod.getPlugin(forPlugin); - affirm typeinfo(isobject pConf); - const pf = (pConf.isVirtual ? undefined : mod.pf) ||| return; - pf.prefix = pConf.prefix ||| mod.plugins.default.prefix; - pf.suffix = pConf.suffix ||| mod.plugins.default.suffix; - return pf.search(basename,0); -}; - -/** - Given a base filename... - - 1) If the given name does not contain a '!' character, - it searches for an exact-match name in the cache. If it - finds one, it returns that value. - - 2) It searches for the file using the configured search - paths/extensions (from this.plugins). If found, it is passed to - the import() function specified for the import type (see - below). - - By default this.plugins.default is used to search for and - import the file. If a "special" type of name is provided to - this function, though (meaning the base name looks like - with "SOMETHING!basename"), then this.plugins[SOMETHING] is - used (if set), which may change the caching behaviour and - how the content of the file is interpreted. - - Depending on the configuration options, requests might get - cached. Subsequent calls which expand to the same file name - will return the same (cached) result value on each - subsequent call. -*/ -mod.import = proc(basename){ - affirm 'string' === typeinfo(name basename); - if(basename.indexOf('!')<0 && const c = C#basename){ - return c; - } - var pluginName; - /* Check for pluginName!... */ - if((var ndx = basename.indexOf('!'))>0){ - pluginName = basename.substr(0,ndx); - basename = basename.substr(ndx+1); - } - pluginName || (pluginName ='default'); - /* Configuration for this plugin... */ - const pConf = mod.getPlugin(pluginName); - pConf || throw "Could not load plugin '"+pluginName+"'."; - const pf = pConf.isVirtual ? undefined : mod.pf /* PathFinder */; - if(pf){ - // Set up/reset file lookup paths/suffixes... - pf.prefix = pConf.prefix ||| mod.plugins.default.prefix; - pf.suffix = pConf.suffix ||| mod.plugins.default.suffix; - } - /* Treat ?a=b&c=d... almost like a URL-encoded - as query string, but without the URL encoding. - */ - var qArgs, useCache = pConf.cacheIt; - if(basename.indexOf('?')>=0){ - /* Parse args. If any are provided, bypass the cache. */ - const sp = basename.split('?',2); - basename = sp.0; - (qArgs = Q(sp.1)) && (useCache = false); - } - /* Find the file, if necessary... */ - var fn = pConf.isVirtual - ? basename - : (basename ? pf.search(basename, 0) : false) - ||| throw "Plugin '%1$s' cannot find '%2$s' in search path %3$J with extensions %4$J.". - applyFormat(pluginName, basename, pf.prefix, pf.suffix); - // expand to the fully qualified path for non-virtual plugins... - pConf.isVirtual || (fn = P(fn)); - //print(__FLC,"fn=",fn,"useCache=",useCache,"qArgs =",qArgs,pluginName,pConf); - //print(__FLC,'pConf.cacheIt=',pConf.cacheIt,', fn=',fn); - //print(__FLC,cache.toJSONString(2)); - const requireS2 = mod /* public API symbol, potentially - needed by anything which - uses anyPlugin.load() */; - return useCache - ? (const k = - (pluginName ? pluginName+'!'+fn : fn), - cacheCheck = (C # k)) - ? cacheCheck - : C.insert(k, pConf.load(fn, qArgs)) - : pConf.load(fn, qArgs); -} using(mod, { - C: modCache, - P: realpath, - Q: proc(str) using {q:convertQValue} { - str || return str; - var r; - foreach(@str.split('&')=>v){ - const s = v.split('=',2); - (r ||| (r = {prototype:null}))[s.0] = s.1 ? q(s.1) : (v.indexOf('=')>0 ? s.1 : true); - }; - return r; - } -}); - -/** - For each base filename in the given array/tuple, this function - calls this.import(basename) and appends the results to a new - array. Returns an array of the results to each import() call, - the order of the array's elements being the same as the calls - to import(). Throws if list is not an array or is empty or if - loading any resources fails. Propagates any exceptions. -*/ -mod.importList = function(list) using(mod) { - affirm typeinfo(islist list) /* expecting an Array or Tuple */; - affirm !list.isEmpty() /* expecting a non-empty list of module names */; - const imps = []; - foreach(@list=>v) imps.push(mod.import(v)); - return imps; -}; - -/** - Imports a list of script modules and optionally calls a - callback after loading all of them. - - list is an array of strings - script file base names to import. - func is an optional function or code string which gets called - resp. eval'd after importing all of the scripts. If it's a - function, it is passed one argument for each entry in the list, - in the same order they are imported. If it is a code string - then it is eval'd in a scope with the array 'modules' defined - to the resolved list of modules. - - In either case, it declares the const symbol requireS2 to be - the require() module, so that these callbacks may recursively - invoke require() via a call to requireS2(). (It is often useful - to do so, it turns out, and this consolidates the convention - across modules originally written for different code bases.) - - Returns the result of calling the function (if any) or the - array of loaded modules (if passed no function/string). - - Example: - - assert 42 === thisObj( - ['module1', 'module2'], - function(mod1, mod2){ - print('result of module1 import:' mod1); - print('result of module2 import:' mod2); - return 42; - } - ); - - - _Potential_ TODOs: - - - If passed a non-string value where a name is expected, use it - as-is as the result of the loading. i suspect we might have - some interesting uses for that, but want a use case before trying - it out. -*/ -mod.require = function(list, func) using(mod) { - func && affirm (typeinfo(iscallable func) || typeinfo(isstring func)); - list = mod.importList(list); - func || return list; - if(typeinfo(iscallable func)){ - const requireS2=mod, s2 = s2; - return func.apply(func, list); - }else{ - return func.evalContents('require() script',{ - s2: s2, - requireS2: mod, - modules: list - }); - } -}; - -/** - Installs a cached entry for the given module name, such that - future calls to import() or require() which use that exact name - will return the given result object. Note that the name need - not be filesystem-friendly. e.g. "" is perfectly - legal. The only limitation is that it "really should not" - contain an exclamation point, as that may confuse import() - because that character is used to denote a plugin. -*/ -mod.installModule = function(name, result) using(modCache){ - modCache.insert(name, result); - return this; -}; - - -// Try to determine some useful directories to search for scripts in... -if(typeinfo(isstring var d = cliFlags['s2.require.home'])){ - mod.home = realpath(d); - mod.plugins.default.prefix.push( mod.home ); -} -else if((d=(cliFlags['s2.home']|||getenv('S2_HOME'))) - && (d=realpath(d+'/require.d'))){ - mod.plugins.default.prefix.push( mod.home = d ); -} -if((var d = __FILEDIR ? realpath(__FILEDIR) : 0) - && (mod.home !== d)){ - mod.plugins.default.prefix.push( d ); - mod.home || (mod.home = d); -} -/* __FILEDIR may be a synthetic __FILE name - (e.g. via eval or Buffer.evalContents()) */ -mod.home || (mod.home=""); - -/* We set mod.require.home so that plugins can construct paths via - requireS2.home. */ - -/* Make it so that call()ing this object calls mod.require() */ -mod.prototype = mod.require /** Holy cow! We've just inherited our - own member function. */; -mod /* script result */; DELETED bindings/s2/require.d/require.test.s2 Index: bindings/s2/require.d/require.test.s2 ================================================================== --- bindings/s2/require.d/require.test.s2 +++ bindings/s2/require.d/require.test.s2 @@ -1,50 +0,0 @@ - -affirm requireS2; -affirm 'string' === typename requireS2.home; -affirm requireS2.home.indexOf('/')>-1 || requireS2.home.indexOf('\\')>-1; -//print(__FLC,'requireS2.home =',requireS2.home); -/** - A quite incomplete test of require.s2. Since this cannot even - be loaded by require.s2 if require.s2 isn't at least basically - working, just getting here already tells us much. -*/ -requireS2.addPlugin('dummy',{ - isVirtual: true, - cacheIt: false, - load: proc(n,opt){ - return { - name: n, - opt: opt - }; - } -}); - -requireS2.addPlugin({ - dummy2:{ - isVirtual: true, - chachIt: true, - load: proc(n,opt){ - return 1; - } - }, - dummy3:{ - isVirtual: true, - chachIt: true, - load: proc(n,opt){ - return 0; - } - } -}); - -requireS2(['dummy!fred?a=1'],proc(obj){ - affirm 'fred' === obj.name; - affirm 1 === obj.opt.a; - - assert true === requireS2(['dummy!barny', 'dummy2!', 'dummy3!'],proc(d, d2, d3){ - assert 'barny' === d.name; - assert !d.opt; - assert 1 === d2; - assert 0 === d3; - return true; - }); -}); DELETED bindings/s2/require.d/time.s2 Index: bindings/s2/require.d/time.s2 ================================================================== --- bindings/s2/require.d/time.s2 +++ bindings/s2/require.d/time.s2 @@ -1,5 +0,0 @@ -/* a require.s2 module which "hides" s2.time via the module - interface. It could optionally load 'dll!mod_time', but that's - an internal impl detail. -*/ -return s2.time; DELETED bindings/s2/require.d/tmpl.s2 Index: bindings/s2/require.d/tmpl.s2 ================================================================== --- bindings/s2/require.d/tmpl.s2 +++ bindings/s2/require.d/tmpl.s2 @@ -1,60 +0,0 @@ -/** - The tmpl module (as distinct from the tmpl plugin!) provides - utilities for working with s2.tmpl(). - -*/ -return { - /** - "Processes" a s2.tmpl() template as follows... - - The first argument is a tmpl()-compiled script (of type Buffer) - or a non-compiled script of type String (in which case this - function compiles it and uses the original value as the 3rd - parameter). - - The second parameter is an optional container holding key/value - pairs which get imported into the current scope before - evaluating the script. This allows one to easily create - mini-templates for use in loops and such. If you _have_ - to pass a value but don't have an object, any falsy value - will do. - - The final argument is intended to hold the uncompiled script - and is only used in error reporting, and is stored in any - exception propagated via evaluating a template. It is ignored - when the first argument has a typename of 'string'. - */ - process: proc(template, opt, tmplUncompiled){ - if(typeinfo(isstring template)){ - tmplUncompiled = template; - template = this.compile(template); - } - affirm typeinfo(isbuffer template); - if(const ex = catch template.evalContents(opt|||{})){ - ex && throw { - message: "Error evaluating compiled template (location info is relative to the compiled script).", - exception: ex, - template: { - compiled: template.toString(), - uncompiled: tmplUncompiled ? tmplUncompiled.toString() : undefined - } - }; - } - }, - - processFile: proc(fn, opt){ - return this.process( this.load(fn, true), opt ); - }, - - /** - A proxy for s2.tmpl(). - */ - compile: s2.tmpl, - /** - Uses the tmpl! plugin to load the given file - and optionally compile it using this.compile() - */ - load: proc(fn, compile){ - return requireS2([(compile ? 'tmpl-compiled!' : 'tmpl!')+fn]).0; - } using (requireS2) -}; DELETED bindings/s2/require.d/tmpl.test.s2 Index: bindings/s2/require.d/tmpl.test.s2 ================================================================== --- bindings/s2/require.d/tmpl.test.s2 +++ bindings/s2/require.d/tmpl.test.s2 @@ -1,42 +0,0 @@ -/* A brief test of the 'tmpl' require.s2 module. */ -requireS2( -['ob', - 'nocache!tmpl' - // bug: ^^^^ reading a directory (by accident) is reported as OOM. - // Fixed by not allowing PathFinder to resolve directory names, but - // that support is missing for Windows (patches welcomed). -], -proc(ob, t){ - const src = 'a=<% a %>, b=<%b%>, c=<%c%>\n'; - const obLevel = ob.level(); - var str; - ob.push(); - var ex = catch{ - t.process(src,{ - a:'hi', - b:'there', - c:'world' - }); - str = ob.pop(-1); - }; - while(ob.level()>obLevel) ob.pop(); - ex && throw ex; - affirm "a=hi, b=there, c=world\n" === str; - - scope { - const src2 = '<%a%>,<%b%>,<%c%>\n', - compiled = t.compile(src2), - opt = { a:-1, b:0, c:1 } - ,TMPLOUT = proc(){} /* eval'd template uses this func, if defined */ - ; - const XYZ = 'hi'; - t.process('<% XYZ %>\n', null); - for(var i = 0; i < 5; ++i, ++opt.a, ++opt.b, ++opt.c ){ - t.process(compiled, opt, src); - } - affirm 4==opt.a; - affirm 5==opt.b; - affirm 6==opt.c; - }; - print(__FLC,'done!'); -}); DELETED bindings/s2/s2_amalgamation.c Index: bindings/s2/s2_amalgamation.c ================================================================== --- bindings/s2/s2_amalgamation.c +++ bindings/s2/s2_amalgamation.c @@ -1,62674 +0,0 @@ -#include "s2_amalgamation.h" -#if S2_INTERNAL_MINIZ -/* start of file miniz-sgb.c */ -#undef MINIZ_NO_STDIO -#define MINIZ_NO_STDIO -#undef MINIZ_NO_ARCHIVE_APIS -#define MINIZ_NO_ARCHIVE_APIS -/* miniz.c 2.0.6 beta - public domain deflate/inflate, zlib-subset, ZIP reading/writing/appending, PNG writing - See "unlicense" statement at the end of this file. - Rich Geldreich , last updated Oct. 13, 2013 - Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951: http://www.ietf.org/rfc/rfc1951.txt - - Most API's defined in miniz.c are optional. For example, to disable the archive related functions just define - MINIZ_NO_ARCHIVE_APIS, or to get rid of all stdio usage define MINIZ_NO_STDIO (see the list below for more macros). - - * Low-level Deflate/Inflate implementation notes: - - Compression: Use the "tdefl" API's. The compressor supports raw, static, and dynamic blocks, lazy or - greedy parsing, match length filtering, RLE-only, and Huffman-only streams. It performs and compresses - approximately as well as zlib. - - Decompression: Use the "tinfl" API's. The entire decompressor is implemented as a single function - coroutine: see tinfl_decompress(). It supports decompression into a 32KB (or larger power of 2) wrapping buffer, or into a memory - block large enough to hold the entire file. - - The low-level tdefl/tinfl API's do not make any use of dynamic memory allocation. - - * zlib-style API notes: - - miniz.c implements a fairly large subset of zlib. There's enough functionality present for it to be a drop-in - zlib replacement in many apps: - The z_stream struct, optional memory allocation callbacks - deflateInit/deflateInit2/deflate/deflateReset/deflateEnd/deflateBound - inflateInit/inflateInit2/inflate/inflateEnd - compress, compress2, compressBound, uncompress - CRC-32, Adler-32 - Using modern, minimal code size, CPU cache friendly routines. - Supports raw deflate streams or standard zlib streams with adler-32 checking. - - Limitations: - The callback API's are not implemented yet. No support for gzip headers or zlib static dictionaries. - I've tried to closely emulate zlib's various flavors of stream flushing and return status codes, but - there are no guarantees that miniz.c pulls this off perfectly. - - * PNG writing: See the tdefl_write_image_to_png_file_in_memory() function, originally written by - Alex Evans. Supports 1-4 bytes/pixel images. - - * ZIP archive API notes: - - The ZIP archive API's where designed with simplicity and efficiency in mind, with just enough abstraction to - get the job done with minimal fuss. There are simple API's to retrieve file information, read files from - existing archives, create new archives, append new files to existing archives, or clone archive data from - one archive to another. It supports archives located in memory or the heap, on disk (using stdio.h), - or you can specify custom file read/write callbacks. - - - Archive reading: Just call this function to read a single file from a disk archive: - - void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, - size_t *pSize, mz_uint zip_flags); - - For more complex cases, use the "mz_zip_reader" functions. Upon opening an archive, the entire central - directory is located and read as-is into memory, and subsequent file access only occurs when reading individual files. - - - Archives file scanning: The simple way is to use this function to scan a loaded archive for a specific file: - - int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); - - The locate operation can optionally check file comments too, which (as one example) can be used to identify - multiple versions of the same file in an archive. This function uses a simple linear search through the central - directory, so it's not very fast. - - Alternately, you can iterate through all the files in an archive (using mz_zip_reader_get_num_files()) and - retrieve detailed info on each file by calling mz_zip_reader_file_stat(). - - - Archive creation: Use the "mz_zip_writer" functions. The ZIP writer immediately writes compressed file data - to disk and builds an exact image of the central directory in memory. The central directory image is written - all at once at the end of the archive file when the archive is finalized. - - The archive writer can optionally align each file's local header and file data to any power of 2 alignment, - which can be useful when the archive will be read from optical media. Also, the writer supports placing - arbitrary data blobs at the very beginning of ZIP archives. Archives written using either feature are still - readable by any ZIP tool. - - - Archive appending: The simple way to add a single file to an archive is to call this function: - - mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, - const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); - - The archive will be created if it doesn't already exist, otherwise it'll be appended to. - Note the appending is done in-place and is not an atomic operation, so if something goes wrong - during the operation it's possible the archive could be left without a central directory (although the local - file headers and file data will be fine, so the archive will be recoverable). - - For more complex archive modification scenarios: - 1. The safest way is to use a mz_zip_reader to read the existing archive, cloning only those bits you want to - preserve into a new archive using using the mz_zip_writer_add_from_zip_reader() function (which compiles the - compressed file data as-is). When you're done, delete the old archive and rename the newly written archive, and - you're done. This is safe but requires a bunch of temporary disk space or heap memory. - - 2. Or, you can convert an mz_zip_reader in-place to an mz_zip_writer using mz_zip_writer_init_from_reader(), - append new files as needed, then finalize the archive which will write an updated central directory to the - original archive. (This is basically what mz_zip_add_mem_to_archive_file_in_place() does.) There's a - possibility that the archive's central directory could be lost with this method if anything goes wrong, though. - - - ZIP archive support limitations: - No zip64 or spanning support. Extraction functions can only handle unencrypted, stored or deflated files. - Requires streams capable of seeking. - - * This is a header file library, like stb_image.c. To get only a header file, either cut and paste the - below header, or create miniz.h, #define MINIZ_HEADER_FILE_ONLY, and then include miniz.c from it. - - * Important: For best perf. be sure to customize the below macros for your target platform: - #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 - #define MINIZ_LITTLE_ENDIAN 1 - #define MINIZ_HAS_64BIT_REGISTERS 1 - - * On platforms using glibc, Be sure to "#define _LARGEFILE64_SOURCE 1" before including miniz.c to ensure miniz - uses the 64-bit variants: fopen64(), stat64(), etc. Otherwise you won't be able to process large files - (i.e. 32-bit stat() fails for me on files > 0x7FFFFFFF bytes). -*/ - - - - - -/* Defines to completely disable specific portions of miniz.c: - If all macros here are defined the only functionality remaining will be CRC-32, adler-32, tinfl, and tdefl. */ - -/* Define MINIZ_NO_STDIO to disable all usage and any functions which rely on stdio for file I/O. */ -/*#define MINIZ_NO_STDIO */ - -/* If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able to get the current time, or */ -/* get/set file times, and the C run-time funcs that get/set times won't be called. */ -/* The current downside is the times written to your archives will be from 1979. */ -/*#define MINIZ_NO_TIME */ - -/* Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's. */ -/*#define MINIZ_NO_ARCHIVE_APIS */ - -/* Define MINIZ_NO_ARCHIVE_WRITING_APIS to disable all writing related ZIP archive API's. */ -/*#define MINIZ_NO_ARCHIVE_WRITING_APIS */ - -/* Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression API's. */ -/*#define MINIZ_NO_ZLIB_APIS */ - -/* Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent conflicts against stock zlib. */ -/*#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES */ - -/* Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc. - Note if MINIZ_NO_MALLOC is defined then the user must always provide custom user alloc/free/realloc - callbacks to the zlib and archive API's, and a few stand-alone helper API's which don't provide custom user - functions (such as tdefl_compress_mem_to_heap() and tinfl_decompress_mem_to_heap()) won't work. */ -/*#define MINIZ_NO_MALLOC */ - -#if defined(__TINYC__) && (defined(__linux) || defined(__linux__)) -/* TODO: Work around "error: include file 'sys\utime.h' when compiling with tcc on Linux */ -#define MINIZ_NO_TIME -#endif - -#include - -#if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS) -#include -#endif - -#if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || defined(__i386) || defined(__i486__) || defined(__i486) || defined(i386) || defined(__ia64__) || defined(__x86_64__) -/* MINIZ_X86_OR_X64_CPU is only used to help set the below macros. */ -#define MINIZ_X86_OR_X64_CPU 1 -#else -#define MINIZ_X86_OR_X64_CPU 0 -#endif - -#if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU -/* Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian. */ -#define MINIZ_LITTLE_ENDIAN 1 -#else -#define MINIZ_LITTLE_ENDIAN 0 -#endif - -#if MINIZ_X86_OR_X64_CPU -/* Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient integer loads and stores from unaligned addresses. */ -#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 -#else -#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 0 -#endif - -#if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || defined(_LP64) || defined(__LP64__) || defined(__ia64__) || defined(__x86_64__) -/* Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are reasonably fast (and don't involve compiler generated calls to helper functions). */ -#define MINIZ_HAS_64BIT_REGISTERS 1 -#else -#define MINIZ_HAS_64BIT_REGISTERS 0 -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -/* ------------------- zlib-style API Definitions. */ - -/* For more compatibility with zlib, miniz.c uses unsigned long for some parameters/struct members. Beware: mz_ulong can be either 32 or 64-bits! */ -typedef unsigned long mz_ulong; - -/* mz_free() internally uses the MZ_FREE() macro (which by default calls free() unless you've modified the MZ_MALLOC macro) to release a block allocated from the heap. */ -void mz_free(void *p); - -#define MZ_ADLER32_INIT (1) -/* mz_adler32() returns the initial adler-32 value to use when called with ptr==NULL. */ -mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len); - -#define MZ_CRC32_INIT (0) -/* mz_crc32() returns the initial CRC-32 value to use when called with ptr==NULL. */ -mz_ulong mz_crc32(mz_ulong crc, const unsigned char *ptr, size_t buf_len); - -/* Compression strategies. */ -enum -{ - MZ_DEFAULT_STRATEGY = 0, - MZ_FILTERED = 1, - MZ_HUFFMAN_ONLY = 2, - MZ_RLE = 3, - MZ_FIXED = 4 -}; - -/* Method */ -#define MZ_DEFLATED 8 - -/* Heap allocation callbacks. -Note that mz_alloc_func parameter types purpsosely differ from zlib's: items/size is size_t, not unsigned long. */ -typedef void *(*mz_alloc_func)(void *opaque, size_t items, size_t size); -typedef void (*mz_free_func)(void *opaque, void *address); -typedef void *(*mz_realloc_func)(void *opaque, void *address, size_t items, size_t size); - -/* Compression levels: 0-9 are the standard zlib-style levels, 10 is best possible compression (not zlib compatible, and may be very slow), MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL. */ -enum -{ - MZ_NO_COMPRESSION = 0, - MZ_BEST_SPEED = 1, - MZ_BEST_COMPRESSION = 9, - MZ_UBER_COMPRESSION = 10, - MZ_DEFAULT_LEVEL = 6, - MZ_DEFAULT_COMPRESSION = -1 -}; - -#define MZ_VERSION "10.0.1" -#define MZ_VERNUM 0xA010 -#define MZ_VER_MAJOR 10 -#define MZ_VER_MINOR 0 -#define MZ_VER_REVISION 1 -#define MZ_VER_SUBREVISION 0 - -#ifndef MINIZ_NO_ZLIB_APIS - -/* Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The other values are for advanced use (refer to the zlib docs). */ -enum -{ - MZ_NO_FLUSH = 0, - MZ_PARTIAL_FLUSH = 1, - MZ_SYNC_FLUSH = 2, - MZ_FULL_FLUSH = 3, - MZ_FINISH = 4, - MZ_BLOCK = 5 -}; - -/* Return status codes. MZ_PARAM_ERROR is non-standard. */ -enum -{ - MZ_OK = 0, - MZ_STREAM_END = 1, - MZ_NEED_DICT = 2, - MZ_ERRNO = -1, - MZ_STREAM_ERROR = -2, - MZ_DATA_ERROR = -3, - MZ_MEM_ERROR = -4, - MZ_BUF_ERROR = -5, - MZ_VERSION_ERROR = -6, - MZ_PARAM_ERROR = -10000 -}; - -/* Window bits */ -#define MZ_DEFAULT_WINDOW_BITS 15 - -struct mz_internal_state; - -/* Compression/decompression stream struct. */ -typedef struct mz_stream_s -{ - const unsigned char *next_in; /* pointer to next byte to read */ - unsigned int avail_in; /* number of bytes available at next_in */ - mz_ulong total_in; /* total number of bytes consumed so far */ - - unsigned char *next_out; /* pointer to next byte to write */ - unsigned int avail_out; /* number of bytes that can be written to next_out */ - mz_ulong total_out; /* total number of bytes produced so far */ - - char *msg; /* error msg (unused) */ - struct mz_internal_state *state; /* internal state, allocated by zalloc/zfree */ - - mz_alloc_func zalloc; /* optional heap allocation function (defaults to malloc) */ - mz_free_func zfree; /* optional heap free function (defaults to free) */ - void *opaque; /* heap alloc function user pointer */ - - int data_type; /* data_type (unused) */ - mz_ulong adler; /* adler32 of the source or uncompressed data */ - mz_ulong reserved; /* not used */ -} mz_stream; - -typedef mz_stream *mz_streamp; - -/* Returns the version string of miniz.c. */ -const char *mz_version(void); - -/* mz_deflateInit() initializes a compressor with default options: */ -/* Parameters: */ -/* pStream must point to an initialized mz_stream struct. */ -/* level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION]. */ -/* level 1 enables a specially optimized compression function that's been optimized purely for performance, not ratio. */ -/* (This special func. is currently only enabled when MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.) */ -/* Return values: */ -/* MZ_OK on success. */ -/* MZ_STREAM_ERROR if the stream is bogus. */ -/* MZ_PARAM_ERROR if the input parameters are bogus. */ -/* MZ_MEM_ERROR on out of memory. */ -int mz_deflateInit(mz_streamp pStream, int level); - -/* mz_deflateInit2() is like mz_deflate(), except with more control: */ -/* Additional parameters: */ -/* method must be MZ_DEFLATED */ -/* window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with zlib header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no header or footer) */ -/* mem_level must be between [1, 9] (it's checked but ignored by miniz.c) */ -int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy); - -/* Quickly resets a compressor without having to reallocate anything. Same as calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2(). */ -int mz_deflateReset(mz_streamp pStream); - -/* mz_deflate() compresses the input to output, consuming as much of the input and producing as much output as possible. */ -/* Parameters: */ -/* pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members. */ -/* flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or MZ_FINISH. */ -/* Return values: */ -/* MZ_OK on success (when flushing, or if more input is needed but not available, and/or there's more output to be written but the output buffer is full). */ -/* MZ_STREAM_END if all input has been consumed and all output bytes have been written. Don't call mz_deflate() on the stream anymore. */ -/* MZ_STREAM_ERROR if the stream is bogus. */ -/* MZ_PARAM_ERROR if one of the parameters is invalid. */ -/* MZ_BUF_ERROR if no forward progress is possible because the input and/or output buffers are empty. (Fill up the input buffer or free up some output space and try again.) */ -int mz_deflate(mz_streamp pStream, int flush); - -/* mz_deflateEnd() deinitializes a compressor: */ -/* Return values: */ -/* MZ_OK on success. */ -/* MZ_STREAM_ERROR if the stream is bogus. */ -int mz_deflateEnd(mz_streamp pStream); - -/* mz_deflateBound() returns a (very) conservative upper bound on the amount of data that could be generated by deflate(), assuming flush is set to only MZ_NO_FLUSH or MZ_FINISH. */ -mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len); - -/* Single-call compression functions mz_compress() and mz_compress2(): */ -/* Returns MZ_OK on success, or one of the error codes from mz_deflate() on failure. */ -int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); -int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level); - -/* mz_compressBound() returns a (very) conservative upper bound on the amount of data that could be generated by calling mz_compress(). */ -mz_ulong mz_compressBound(mz_ulong source_len); - -/* Initializes a decompressor. */ -int mz_inflateInit(mz_streamp pStream); - -/* mz_inflateInit2() is like mz_inflateInit() with an additional option that controls the window size and whether or not the stream has been wrapped with a zlib header/footer: */ -/* window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate). */ -int mz_inflateInit2(mz_streamp pStream, int window_bits); - -/* Decompresses the input stream to the output, consuming only as much of the input as needed, and writing as much to the output as possible. */ -/* Parameters: */ -/* pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members. */ -/* flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH. */ -/* On the first call, if flush is MZ_FINISH it's assumed the input and output buffers are both sized large enough to decompress the entire stream in a single call (this is slightly faster). */ -/* MZ_FINISH implies that there are no more source bytes available beside what's already in the input buffer, and that the output buffer is large enough to hold the rest of the decompressed data. */ -/* Return values: */ -/* MZ_OK on success. Either more input is needed but not available, and/or there's more output to be written but the output buffer is full. */ -/* MZ_STREAM_END if all needed input has been consumed and all output bytes have been written. For zlib streams, the adler-32 of the decompressed data has also been verified. */ -/* MZ_STREAM_ERROR if the stream is bogus. */ -/* MZ_DATA_ERROR if the deflate stream is invalid. */ -/* MZ_PARAM_ERROR if one of the parameters is invalid. */ -/* MZ_BUF_ERROR if no forward progress is possible because the input buffer is empty but the inflater needs more input to continue, or if the output buffer is not large enough. Call mz_inflate() again */ -/* with more input data, or with more room in the output buffer (except when using single call decompression, described above). */ -int mz_inflate(mz_streamp pStream, int flush); - -/* Deinitializes a decompressor. */ -int mz_inflateEnd(mz_streamp pStream); - -/* Single-call decompression. */ -/* Returns MZ_OK on success, or one of the error codes from mz_inflate() on failure. */ -int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); - -/* Returns a string description of the specified error code, or NULL if the error code is invalid. */ -const char *mz_error(int err); - -/* Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used as a drop-in replacement for the subset of zlib that miniz.c supports. */ -/* Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you use zlib in the same project. */ -#ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES -typedef unsigned char Byte; -typedef unsigned int uInt; -typedef mz_ulong uLong; -typedef Byte Bytef; -typedef uInt uIntf; -typedef char charf; -typedef int intf; -typedef void *voidpf; -typedef uLong uLongf; -typedef void *voidp; -typedef void *const voidpc; -#define Z_NULL 0 -#define Z_NO_FLUSH MZ_NO_FLUSH -#define Z_PARTIAL_FLUSH MZ_PARTIAL_FLUSH -#define Z_SYNC_FLUSH MZ_SYNC_FLUSH -#define Z_FULL_FLUSH MZ_FULL_FLUSH -#define Z_FINISH MZ_FINISH -#define Z_BLOCK MZ_BLOCK -#define Z_OK MZ_OK -#define Z_STREAM_END MZ_STREAM_END -#define Z_NEED_DICT MZ_NEED_DICT -#define Z_ERRNO MZ_ERRNO -#define Z_STREAM_ERROR MZ_STREAM_ERROR -#define Z_DATA_ERROR MZ_DATA_ERROR -#define Z_MEM_ERROR MZ_MEM_ERROR -#define Z_BUF_ERROR MZ_BUF_ERROR -#define Z_VERSION_ERROR MZ_VERSION_ERROR -#define Z_PARAM_ERROR MZ_PARAM_ERROR -#define Z_NO_COMPRESSION MZ_NO_COMPRESSION -#define Z_BEST_SPEED MZ_BEST_SPEED -#define Z_BEST_COMPRESSION MZ_BEST_COMPRESSION -#define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION -#define Z_DEFAULT_STRATEGY MZ_DEFAULT_STRATEGY -#define Z_FILTERED MZ_FILTERED -#define Z_HUFFMAN_ONLY MZ_HUFFMAN_ONLY -#define Z_RLE MZ_RLE -#define Z_FIXED MZ_FIXED -#define Z_DEFLATED MZ_DEFLATED -#define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS -#define alloc_func mz_alloc_func -#define free_func mz_free_func -#define internal_state mz_internal_state -#define z_stream mz_stream -#define deflateInit mz_deflateInit -#define deflateInit2 mz_deflateInit2 -#define deflateReset mz_deflateReset -#define deflate mz_deflate -#define deflateEnd mz_deflateEnd -#define deflateBound mz_deflateBound -#define compress mz_compress -#define compress2 mz_compress2 -#define compressBound mz_compressBound -#define inflateInit mz_inflateInit -#define inflateInit2 mz_inflateInit2 -#define inflate mz_inflate -#define inflateEnd mz_inflateEnd -#define uncompress mz_uncompress -#define crc32 mz_crc32 -#define adler32 mz_adler32 -#define MAX_WBITS 15 -#define MAX_MEM_LEVEL 9 -#define zError mz_error -#define ZLIB_VERSION MZ_VERSION -#define ZLIB_VERNUM MZ_VERNUM -#define ZLIB_VER_MAJOR MZ_VER_MAJOR -#define ZLIB_VER_MINOR MZ_VER_MINOR -#define ZLIB_VER_REVISION MZ_VER_REVISION -#define ZLIB_VER_SUBREVISION MZ_VER_SUBREVISION -#define zlibVersion mz_version -#define zlib_version mz_version() -#endif /* #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES */ - -#endif /* MINIZ_NO_ZLIB_APIS */ - -#ifdef __cplusplus -} -#endif -#include -#include -#include -#include - -/* ------------------- Types and macros */ -typedef unsigned char mz_uint8; -typedef signed short mz_int16; -typedef unsigned short mz_uint16; -typedef unsigned int mz_uint32; -typedef unsigned int mz_uint; -typedef int64_t mz_int64; -typedef uint64_t mz_uint64; -typedef int mz_bool; - -#define MZ_FALSE (0) -#define MZ_TRUE (1) - -/* Works around MSVC's spammy "warning C4127: conditional expression is constant" message. */ -#ifdef _MSC_VER -#define MZ_MACRO_END while (0, 0) -#else -#define MZ_MACRO_END while (0) -#endif - -#ifdef MINIZ_NO_STDIO -#define MZ_FILE void * -#else -#include -#define MZ_FILE FILE -#endif /* #ifdef MINIZ_NO_STDIO */ - -#ifdef MINIZ_NO_TIME -typedef struct mz_dummy_time_t_tag -{ - int m_dummy; -} mz_dummy_time_t; -#define MZ_TIME_T mz_dummy_time_t -#else -#define MZ_TIME_T time_t -#endif - -#define MZ_ASSERT(x) assert(x) - -#ifdef MINIZ_NO_MALLOC -#define MZ_MALLOC(x) NULL -#define MZ_FREE(x) (void)x, ((void)0) -#define MZ_REALLOC(p, x) NULL -#else -#define MZ_MALLOC(x) malloc(x) -#define MZ_FREE(x) free(x) -#define MZ_REALLOC(p, x) realloc(p, x) -#endif - -#define MZ_MAX(a, b) (((a) > (b)) ? (a) : (b)) -#define MZ_MIN(a, b) (((a) < (b)) ? (a) : (b)) -#define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj)) - -#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN -#define MZ_READ_LE16(p) *((const mz_uint16 *)(p)) -#define MZ_READ_LE32(p) *((const mz_uint32 *)(p)) -#else -#define MZ_READ_LE16(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U)) -#define MZ_READ_LE32(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | ((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | ((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U)) -#endif - -#define MZ_READ_LE64(p) (((mz_uint64)MZ_READ_LE32(p)) | (((mz_uint64)MZ_READ_LE32((const mz_uint8 *)(p) + sizeof(mz_uint32))) << 32U)) - -#ifdef _MSC_VER -#define MZ_FORCEINLINE __forceinline -#elif defined(__GNUC__) -#define MZ_FORCEINLINE __inline__ __attribute__((__always_inline__)) -#else -#define MZ_FORCEINLINE inline -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -extern void *miniz_def_alloc_func(void *opaque, size_t items, size_t size); -extern void miniz_def_free_func(void *opaque, void *address); -extern void *miniz_def_realloc_func(void *opaque, void *address, size_t items, size_t size); - -#define MZ_UINT16_MAX (0xFFFFU) -#define MZ_UINT32_MAX (0xFFFFFFFFU) - -#ifdef __cplusplus -} -#endif - - -#ifdef __cplusplus -extern "C" { -#endif -/* ------------------- Low-level Compression API Definitions */ - -/* Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly slower, and raw/dynamic blocks will be output more frequently). */ -#define TDEFL_LESS_MEMORY 0 - -/* tdefl_init() compression flags logically OR'd together (low 12 bits contain the max. number of probes per dictionary search): */ -/* TDEFL_DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes per dictionary search. 0=Huffman only, 1=Huffman+LZ (fastest/crap compression), 4095=Huffman+LZ (slowest/best compression). */ -enum -{ - TDEFL_HUFFMAN_ONLY = 0, - TDEFL_DEFAULT_MAX_PROBES = 128, - TDEFL_MAX_PROBES_MASK = 0xFFF -}; - -/* TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before the deflate data, and the Adler-32 of the source data at the end. Otherwise, you'll get raw deflate data. */ -/* TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even when not writing zlib headers). */ -/* TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more efficient lazy parsing. */ -/* TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's initialization time to the minimum, but the output may vary from run to run given the same input (depending on the contents of memory). */ -/* TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1) */ -/* TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled. */ -/* TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables. */ -/* TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks. */ -/* The low 12 bits are reserved to control the max # of hash probes per dictionary lookup (see TDEFL_MAX_PROBES_MASK). */ -enum -{ - TDEFL_WRITE_ZLIB_HEADER = 0x01000, - TDEFL_COMPUTE_ADLER32 = 0x02000, - TDEFL_GREEDY_PARSING_FLAG = 0x04000, - TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000, - TDEFL_RLE_MATCHES = 0x10000, - TDEFL_FILTER_MATCHES = 0x20000, - TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000, - TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000 -}; - -/* High level compression functions: */ -/* tdefl_compress_mem_to_heap() compresses a block in memory to a heap block allocated via malloc(). */ -/* On entry: */ -/* pSrc_buf, src_buf_len: Pointer and size of source block to compress. */ -/* flags: The max match finder probes (default is 128) logically OR'd against the above flags. Higher probes are slower but improve compression. */ -/* On return: */ -/* Function returns a pointer to the compressed data, or NULL on failure. */ -/* *pOut_len will be set to the compressed data's size, which could be larger than src_buf_len on uncompressible data. */ -/* The caller must free() the returned block when it's no longer needed. */ -void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); - -/* tdefl_compress_mem_to_mem() compresses a block in memory to another block in memory. */ -/* Returns 0 on failure. */ -size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); - -/* Compresses an image to a compressed PNG file in memory. */ -/* On entry: */ -/* pImage, w, h, and num_chans describe the image to compress. num_chans may be 1, 2, 3, or 4. */ -/* The image pitch in bytes per scanline will be w*num_chans. The leftmost pixel on the top scanline is stored first in memory. */ -/* level may range from [0,10], use MZ_NO_COMPRESSION, MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc. or a decent default is MZ_DEFAULT_LEVEL */ -/* If flip is true, the image will be flipped on the Y axis (useful for OpenGL apps). */ -/* On return: */ -/* Function returns a pointer to the compressed data, or NULL on failure. */ -/* *pLen_out will be set to the size of the PNG image file. */ -/* The caller must mz_free() the returned heap block (which will typically be larger than *pLen_out) when it's no longer needed. */ -void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip); -void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out); - -/* Output stream interface. The compressor uses this interface to write compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time. */ -typedef mz_bool (*tdefl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser); - -/* tdefl_compress_mem_to_output() compresses a block to an output stream. The above helpers use this function internally. */ -mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); - -enum -{ - TDEFL_MAX_HUFF_TABLES = 3, - TDEFL_MAX_HUFF_SYMBOLS_0 = 288, - TDEFL_MAX_HUFF_SYMBOLS_1 = 32, - TDEFL_MAX_HUFF_SYMBOLS_2 = 19, - TDEFL_LZ_DICT_SIZE = 32768, - TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1, - TDEFL_MIN_MATCH_LEN = 3, - TDEFL_MAX_MATCH_LEN = 258 -}; - -/* TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed output block (using static/fixed Huffman codes). */ -#if TDEFL_LESS_MEMORY -enum -{ - TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024, - TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10, - TDEFL_MAX_HUFF_SYMBOLS = 288, - TDEFL_LZ_HASH_BITS = 12, - TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, - TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, - TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS -}; -#else -enum -{ - TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024, - TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10, - TDEFL_MAX_HUFF_SYMBOLS = 288, - TDEFL_LZ_HASH_BITS = 15, - TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, - TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, - TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS -}; -#endif - -/* The low-level tdefl functions below may be used directly if the above helper functions aren't flexible enough. The low-level functions don't make any heap allocations, unlike the above helper functions. */ -typedef enum { - TDEFL_STATUS_BAD_PARAM = -2, - TDEFL_STATUS_PUT_BUF_FAILED = -1, - TDEFL_STATUS_OKAY = 0, - TDEFL_STATUS_DONE = 1 -} tdefl_status; - -/* Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums */ -typedef enum { - TDEFL_NO_FLUSH = 0, - TDEFL_SYNC_FLUSH = 2, - TDEFL_FULL_FLUSH = 3, - TDEFL_FINISH = 4 -} tdefl_flush; - -/* tdefl's compression state structure. */ -typedef struct -{ - tdefl_put_buf_func_ptr m_pPut_buf_func; - void *m_pPut_buf_user; - mz_uint m_flags, m_max_probes[2]; - int m_greedy_parsing; - mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size; - mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end; - mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in, m_bit_buffer; - mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit, m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index, m_wants_to_finish; - tdefl_status m_prev_return_status; - const void *m_pIn_buf; - void *m_pOut_buf; - size_t *m_pIn_buf_size, *m_pOut_buf_size; - tdefl_flush m_flush; - const mz_uint8 *m_pSrc; - size_t m_src_buf_left, m_out_buf_ofs; - mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1]; - mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; - mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; - mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; - mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE]; - mz_uint16 m_next[TDEFL_LZ_DICT_SIZE]; - mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE]; - mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE]; -} tdefl_compressor; - -/* Initializes the compressor. */ -/* There is no corresponding deinit() function because the tdefl API's do not dynamically allocate memory. */ -/* pBut_buf_func: If NULL, output data will be supplied to the specified callback. In this case, the user should call the tdefl_compress_buffer() API for compression. */ -/* If pBut_buf_func is NULL the user should always call the tdefl_compress() API. */ -/* flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER, etc.) */ -tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); - -/* Compresses a block of data, consuming as much of the specified input buffer as possible, and writing as much compressed data to the specified output buffer as possible. */ -tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush); - -/* tdefl_compress_buffer() is only usable when the tdefl_init() is called with a non-NULL tdefl_put_buf_func_ptr. */ -/* tdefl_compress_buffer() always consumes the entire input buffer. */ -tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush); - -tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d); -mz_uint32 tdefl_get_adler32(tdefl_compressor *d); - -/* Create tdefl_compress() flags given zlib-style compression parameters. */ -/* level may range from [0,10] (where 10 is absolute max compression, but may be much slower on some files) */ -/* window_bits may be -15 (raw deflate) or 15 (zlib) */ -/* strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY, MZ_RLE, or MZ_FIXED */ -mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy); - -/* Allocate the tdefl_compressor structure in C so that */ -/* non-C language bindings to tdefl_ API don't need to worry about */ -/* structure size and allocation mechanism. */ -tdefl_compressor *tdefl_compressor_alloc(); -void tdefl_compressor_free(tdefl_compressor *pComp); - -#ifdef __cplusplus -} -#endif - -/* ------------------- Low-level Decompression API Definitions */ - -#ifdef __cplusplus -extern "C" { -#endif -/* Decompression flags used by tinfl_decompress(). */ -/* TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the input is a raw deflate stream. */ -/* TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available beyond the end of the supplied input buffer. If clear, the input buffer contains all remaining input. */ -/* TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large enough to hold the entire decompressed stream. If clear, the output buffer is at least the size of the dictionary (typically 32KB). */ -/* TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the decompressed bytes. */ -enum -{ - TINFL_FLAG_PARSE_ZLIB_HEADER = 1, - TINFL_FLAG_HAS_MORE_INPUT = 2, - TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4, - TINFL_FLAG_COMPUTE_ADLER32 = 8 -}; - -/* High level decompression functions: */ -/* tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block allocated via malloc(). */ -/* On entry: */ -/* pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data to decompress. */ -/* On return: */ -/* Function returns a pointer to the decompressed data, or NULL on failure. */ -/* *pOut_len will be set to the decompressed data's size, which could be larger than src_buf_len on uncompressible data. */ -/* The caller must call mz_free() on the returned block when it's no longer needed. */ -void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); - -/* tinfl_decompress_mem_to_mem() decompresses a block in memory to another block in memory. */ -/* Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes written on success. */ -#define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1)) -size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); - -/* tinfl_decompress_mem_to_callback() decompresses a block in memory to an internal 32KB buffer, and a user provided callback function will be called to flush the buffer. */ -/* Returns 1 on success or 0 on failure. */ -typedef int (*tinfl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser); -int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); - -struct tinfl_decompressor_tag; -typedef struct tinfl_decompressor_tag tinfl_decompressor; - -/* Allocate the tinfl_decompressor structure in C so that */ -/* non-C language bindings to tinfl_ API don't need to worry about */ -/* structure size and allocation mechanism. */ - -tinfl_decompressor *tinfl_decompressor_alloc(); -void tinfl_decompressor_free(tinfl_decompressor *pDecomp); - -/* Max size of LZ dictionary. */ -#define TINFL_LZ_DICT_SIZE 32768 - -/* Return status. */ -typedef enum { - /* This flags indicates the inflator needs 1 or more input bytes to make forward progress, but the caller is indicating that no more are available. The compressed data */ - /* is probably corrupted. If you call the inflator again with more bytes it'll try to continue processing the input but this is a BAD sign (either the data is corrupted or you called it incorrectly). */ - /* If you call it again with no input you'll just get TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS again. */ - TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS = -4, - - /* This flag indicates that one or more of the input parameters was obviously bogus. (You can try calling it again, but if you get this error the calling code is wrong.) */ - TINFL_STATUS_BAD_PARAM = -3, - - /* This flags indicate the inflator is finished but the adler32 check of the uncompressed data didn't match. If you call it again it'll return TINFL_STATUS_DONE. */ - TINFL_STATUS_ADLER32_MISMATCH = -2, - - /* This flags indicate the inflator has somehow failed (bad code, corrupted input, etc.). If you call it again without resetting via tinfl_init() it it'll just keep on returning the same status failure code. */ - TINFL_STATUS_FAILED = -1, - - /* Any status code less than TINFL_STATUS_DONE must indicate a failure. */ - - /* This flag indicates the inflator has returned every byte of uncompressed data that it can, has consumed every byte that it needed, has successfully reached the end of the deflate stream, and */ - /* if zlib headers and adler32 checking enabled that it has successfully checked the uncompressed data's adler32. If you call it again you'll just get TINFL_STATUS_DONE over and over again. */ - TINFL_STATUS_DONE = 0, - - /* This flag indicates the inflator MUST have more input data (even 1 byte) before it can make any more forward progress, or you need to clear the TINFL_FLAG_HAS_MORE_INPUT */ - /* flag on the next call if you don't have any more source data. If the source data was somehow corrupted it's also possible (but unlikely) for the inflator to keep on demanding input to */ - /* proceed, so be sure to properly set the TINFL_FLAG_HAS_MORE_INPUT flag. */ - TINFL_STATUS_NEEDS_MORE_INPUT = 1, - - /* This flag indicates the inflator definitely has 1 or more bytes of uncompressed data available, but it cannot write this data into the output buffer. */ - /* Note if the source compressed data was corrupted it's possible for the inflator to return a lot of uncompressed data to the caller. I've been assuming you know how much uncompressed data to expect */ - /* (either exact or worst case) and will stop calling the inflator and fail after receiving too much. In pure streaming scenarios where you have no idea how many bytes to expect this may not be possible */ - /* so I may need to add some code to address this. */ - TINFL_STATUS_HAS_MORE_OUTPUT = 2 -} tinfl_status; - -/* Initializes the decompressor to its initial state. */ -#define tinfl_init(r) \ - do \ - { \ - (r)->m_state = 0; \ - } \ - MZ_MACRO_END -#define tinfl_get_adler32(r) (r)->m_check_adler32 - -/* Main low-level decompressor coroutine function. This is the only function actually needed for decompression. All the other functions are just high-level helpers for improved usability. */ -/* This is a universal API, i.e. it can be used as a building block to build any desired higher level decompression API. In the limit case, it can be called once per every byte input or output. */ -tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags); - -/* Internal/private bits follow. */ -enum -{ - TINFL_MAX_HUFF_TABLES = 3, - TINFL_MAX_HUFF_SYMBOLS_0 = 288, - TINFL_MAX_HUFF_SYMBOLS_1 = 32, - TINFL_MAX_HUFF_SYMBOLS_2 = 19, - TINFL_FAST_LOOKUP_BITS = 10, - TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS -}; - -typedef struct -{ - mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0]; - mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE], m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2]; -} tinfl_huff_table; - -#if MINIZ_HAS_64BIT_REGISTERS -#define TINFL_USE_64BIT_BITBUF 1 -#else -#define TINFL_USE_64BIT_BITBUF 0 -#endif - -#if TINFL_USE_64BIT_BITBUF -typedef mz_uint64 tinfl_bit_buf_t; -#define TINFL_BITBUF_SIZE (64) -#else -typedef mz_uint32 tinfl_bit_buf_t; -#define TINFL_BITBUF_SIZE (32) -#endif - -struct tinfl_decompressor_tag -{ - mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type, m_check_adler32, m_dist, m_counter, m_num_extra, m_table_sizes[TINFL_MAX_HUFF_TABLES]; - tinfl_bit_buf_t m_bit_buf; - size_t m_dist_from_out_buf_start; - tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES]; - mz_uint8 m_raw_header[4], m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137]; -}; - -#ifdef __cplusplus -} -#endif - - - -/* ------------------- ZIP archive reading/writing */ - -#ifndef MINIZ_NO_ARCHIVE_APIS - -#ifdef __cplusplus -extern "C" { -#endif - -enum -{ - /* Note: These enums can be reduced as needed to save memory or stack space - they are pretty conservative. */ - MZ_ZIP_MAX_IO_BUF_SIZE = 64 * 1024, - MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 512, - MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 512 -}; - -typedef struct -{ - /* Central directory file index. */ - mz_uint32 m_file_index; - - /* Byte offset of this entry in the archive's central directory. Note we currently only support up to UINT_MAX or less bytes in the central dir. */ - mz_uint64 m_central_dir_ofs; - - /* These fields are copied directly from the zip's central dir. */ - mz_uint16 m_version_made_by; - mz_uint16 m_version_needed; - mz_uint16 m_bit_flag; - mz_uint16 m_method; - -#ifndef MINIZ_NO_TIME - MZ_TIME_T m_time; -#endif - - /* CRC-32 of uncompressed data. */ - mz_uint32 m_crc32; - - /* File's compressed size. */ - mz_uint64 m_comp_size; - - /* File's uncompressed size. Note, I've seen some old archives where directory entries had 512 bytes for their uncompressed sizes, but when you try to unpack them you actually get 0 bytes. */ - mz_uint64 m_uncomp_size; - - /* Zip internal and external file attributes. */ - mz_uint16 m_internal_attr; - mz_uint32 m_external_attr; - - /* Entry's local header file offset in bytes. */ - mz_uint64 m_local_header_ofs; - - /* Size of comment in bytes. */ - mz_uint32 m_comment_size; - - /* MZ_TRUE if the entry appears to be a directory. */ - mz_bool m_is_directory; - - /* MZ_TRUE if the entry uses encryption/strong encryption (which miniz_zip doesn't support) */ - mz_bool m_is_encrypted; - - /* MZ_TRUE if the file is not encrypted, a patch file, and if it uses a compression method we support. */ - mz_bool m_is_supported; - - /* Filename. If string ends in '/' it's a subdirectory entry. */ - /* Guaranteed to be zero terminated, may be truncated to fit. */ - char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE]; - - /* Comment field. */ - /* Guaranteed to be zero terminated, may be truncated to fit. */ - char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE]; - -} mz_zip_archive_file_stat; - -typedef size_t (*mz_file_read_func)(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n); -typedef size_t (*mz_file_write_func)(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n); -typedef mz_bool (*mz_file_needs_keepalive)(void *pOpaque); - -struct mz_zip_internal_state_tag; -typedef struct mz_zip_internal_state_tag mz_zip_internal_state; - -typedef enum { - MZ_ZIP_MODE_INVALID = 0, - MZ_ZIP_MODE_READING = 1, - MZ_ZIP_MODE_WRITING = 2, - MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3 -} mz_zip_mode; - -typedef enum { - MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100, - MZ_ZIP_FLAG_IGNORE_PATH = 0x0200, - MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400, - MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800, - MZ_ZIP_FLAG_VALIDATE_LOCATE_FILE_FLAG = 0x1000, /* if enabled, mz_zip_reader_locate_file() will be called on each file as its validated to ensure the func finds the file in the central dir (intended for testing) */ - MZ_ZIP_FLAG_VALIDATE_HEADERS_ONLY = 0x2000, /* validate the local headers, but don't decompress the entire file and check the crc32 */ - MZ_ZIP_FLAG_WRITE_ZIP64 = 0x4000, /* always use the zip64 file format, instead of the original zip file format with automatic switch to zip64. Use as flags parameter with mz_zip_writer_init*_v2 */ - MZ_ZIP_FLAG_WRITE_ALLOW_READING = 0x8000, - MZ_ZIP_FLAG_ASCII_FILENAME = 0x10000 -} mz_zip_flags; - -typedef enum { - MZ_ZIP_TYPE_INVALID = 0, - MZ_ZIP_TYPE_USER, - MZ_ZIP_TYPE_MEMORY, - MZ_ZIP_TYPE_HEAP, - MZ_ZIP_TYPE_FILE, - MZ_ZIP_TYPE_CFILE, - MZ_ZIP_TOTAL_TYPES -} mz_zip_type; - -/* miniz error codes. Be sure to update mz_zip_get_error_string() if you add or modify this enum. */ -typedef enum { - MZ_ZIP_NO_ERROR = 0, - MZ_ZIP_UNDEFINED_ERROR, - MZ_ZIP_TOO_MANY_FILES, - MZ_ZIP_FILE_TOO_LARGE, - MZ_ZIP_UNSUPPORTED_METHOD, - MZ_ZIP_UNSUPPORTED_ENCRYPTION, - MZ_ZIP_UNSUPPORTED_FEATURE, - MZ_ZIP_FAILED_FINDING_CENTRAL_DIR, - MZ_ZIP_NOT_AN_ARCHIVE, - MZ_ZIP_INVALID_HEADER_OR_CORRUPTED, - MZ_ZIP_UNSUPPORTED_MULTIDISK, - MZ_ZIP_DECOMPRESSION_FAILED, - MZ_ZIP_COMPRESSION_FAILED, - MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE, - MZ_ZIP_CRC_CHECK_FAILED, - MZ_ZIP_UNSUPPORTED_CDIR_SIZE, - MZ_ZIP_ALLOC_FAILED, - MZ_ZIP_FILE_OPEN_FAILED, - MZ_ZIP_FILE_CREATE_FAILED, - MZ_ZIP_FILE_WRITE_FAILED, - MZ_ZIP_FILE_READ_FAILED, - MZ_ZIP_FILE_CLOSE_FAILED, - MZ_ZIP_FILE_SEEK_FAILED, - MZ_ZIP_FILE_STAT_FAILED, - MZ_ZIP_INVALID_PARAMETER, - MZ_ZIP_INVALID_FILENAME, - MZ_ZIP_BUF_TOO_SMALL, - MZ_ZIP_INTERNAL_ERROR, - MZ_ZIP_FILE_NOT_FOUND, - MZ_ZIP_ARCHIVE_TOO_LARGE, - MZ_ZIP_VALIDATION_FAILED, - MZ_ZIP_WRITE_CALLBACK_FAILED, - MZ_ZIP_TOTAL_ERRORS -} mz_zip_error; - -typedef struct -{ - mz_uint64 m_archive_size; - mz_uint64 m_central_directory_file_ofs; - - /* We only support up to UINT32_MAX files in zip64 mode. */ - mz_uint32 m_total_files; - mz_zip_mode m_zip_mode; - mz_zip_type m_zip_type; - mz_zip_error m_last_error; - - mz_uint64 m_file_offset_alignment; - - mz_alloc_func m_pAlloc; - mz_free_func m_pFree; - mz_realloc_func m_pRealloc; - void *m_pAlloc_opaque; - - mz_file_read_func m_pRead; - mz_file_write_func m_pWrite; - mz_file_needs_keepalive m_pNeeds_keepalive; - void *m_pIO_opaque; - - mz_zip_internal_state *m_pState; - -} mz_zip_archive; - -typedef struct -{ - mz_zip_archive *pZip; - mz_uint flags; - - int status; -#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS - mz_uint file_crc32; -#endif - mz_uint64 read_buf_size, read_buf_ofs, read_buf_avail, comp_remaining, out_buf_ofs, cur_file_ofs; - mz_zip_archive_file_stat file_stat; - void *pRead_buf; - void *pWrite_buf; - - size_t out_blk_remain; - - tinfl_decompressor inflator; - -} mz_zip_reader_extract_iter_state; - -/* -------- ZIP reading */ - -/* Inits a ZIP archive reader. */ -/* These functions read and validate the archive's central directory. */ -mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint flags); - -mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint flags); - -#ifndef MINIZ_NO_STDIO -/* Read a archive from a disk file. */ -/* file_start_ofs is the file offset where the archive actually begins, or 0. */ -/* actual_archive_size is the true total size of the archive, which may be smaller than the file's actual size on disk. If zero the entire file is treated as the archive. */ -mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags); -mz_bool mz_zip_reader_init_file_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint flags, mz_uint64 file_start_ofs, mz_uint64 archive_size); - -/* Read an archive from an already opened FILE, beginning at the current file position. */ -/* The archive is assumed to be archive_size bytes long. If archive_size is < 0, then the entire rest of the file is assumed to contain the archive. */ -/* The FILE will NOT be closed when mz_zip_reader_end() is called. */ -mz_bool mz_zip_reader_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile, mz_uint64 archive_size, mz_uint flags); -#endif - -/* Ends archive reading, freeing all allocations, and closing the input archive file if mz_zip_reader_init_file() was used. */ -mz_bool mz_zip_reader_end(mz_zip_archive *pZip); - -/* -------- ZIP reading or writing */ - -/* Clears a mz_zip_archive struct to all zeros. */ -/* Important: This must be done before passing the struct to any mz_zip functions. */ -void mz_zip_zero_struct(mz_zip_archive *pZip); - -mz_zip_mode mz_zip_get_mode(mz_zip_archive *pZip); -mz_zip_type mz_zip_get_type(mz_zip_archive *pZip); - -/* Returns the total number of files in the archive. */ -mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip); - -mz_uint64 mz_zip_get_archive_size(mz_zip_archive *pZip); -mz_uint64 mz_zip_get_archive_file_start_offset(mz_zip_archive *pZip); -MZ_FILE *mz_zip_get_cfile(mz_zip_archive *pZip); - -/* Reads n bytes of raw archive data, starting at file offset file_ofs, to pBuf. */ -size_t mz_zip_read_archive_data(mz_zip_archive *pZip, mz_uint64 file_ofs, void *pBuf, size_t n); - -/* Attempts to locates a file in the archive's central directory. */ -/* Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH */ -/* Returns -1 if the file cannot be found. */ -int mz_zip_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); -/* Returns MZ_FALSE if the file cannot be found. */ -mz_bool mz_zip_locate_file_v2(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags, mz_uint32 *pIndex); - -/* All mz_zip funcs set the m_last_error field in the mz_zip_archive struct. These functions retrieve/manipulate this field. */ -/* Note that the m_last_error functionality is not thread safe. */ -mz_zip_error mz_zip_set_last_error(mz_zip_archive *pZip, mz_zip_error err_num); -mz_zip_error mz_zip_peek_last_error(mz_zip_archive *pZip); -mz_zip_error mz_zip_clear_last_error(mz_zip_archive *pZip); -mz_zip_error mz_zip_get_last_error(mz_zip_archive *pZip); -const char *mz_zip_get_error_string(mz_zip_error mz_err); - -/* MZ_TRUE if the archive file entry is a directory entry. */ -mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index); - -/* MZ_TRUE if the file is encrypted/strong encrypted. */ -mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index); - -/* MZ_TRUE if the compression method is supported, and the file is not encrypted, and the file is not a compressed patch file. */ -mz_bool mz_zip_reader_is_file_supported(mz_zip_archive *pZip, mz_uint file_index); - -/* Retrieves the filename of an archive file entry. */ -/* Returns the number of bytes written to pFilename, or if filename_buf_size is 0 this function returns the number of bytes needed to fully store the filename. */ -mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size); - -/* Attempts to locates a file in the archive's central directory. */ -/* Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH */ -/* Returns -1 if the file cannot be found. */ -int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); -int mz_zip_reader_locate_file_v2(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags, mz_uint32 *file_index); - -/* Returns detailed information about an archive file entry. */ -mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat); - -/* MZ_TRUE if the file is in zip64 format. */ -/* A file is considered zip64 if it contained a zip64 end of central directory marker, or if it contained any zip64 extended file information fields in the central directory. */ -mz_bool mz_zip_is_zip64(mz_zip_archive *pZip); - -/* Returns the total central directory size in bytes. */ -/* The current max supported size is <= MZ_UINT32_MAX. */ -size_t mz_zip_get_central_dir_size(mz_zip_archive *pZip); - -/* Extracts a archive file to a memory buffer using no memory allocation. */ -/* There must be at least enough room on the stack to store the inflator's state (~34KB or so). */ -mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); -mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); - -/* Extracts a archive file to a memory buffer. */ -mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags); -mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags); - -/* Extracts a archive file to a dynamically allocated heap buffer. */ -/* The memory will be allocated via the mz_zip_archive's alloc/realloc functions. */ -/* Returns NULL and sets the last error on failure. */ -void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags); -void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags); - -/* Extracts a archive file using a callback function to output the file's data. */ -mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); -mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); - -/* Extract a file iteratively */ -mz_zip_reader_extract_iter_state* mz_zip_reader_extract_iter_new(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags); -mz_zip_reader_extract_iter_state* mz_zip_reader_extract_file_iter_new(mz_zip_archive *pZip, const char *pFilename, mz_uint flags); -size_t mz_zip_reader_extract_iter_read(mz_zip_reader_extract_iter_state* pState, void* pvBuf, size_t buf_size); -mz_bool mz_zip_reader_extract_iter_free(mz_zip_reader_extract_iter_state* pState); - -#ifndef MINIZ_NO_STDIO -/* Extracts a archive file to a disk file and sets its last accessed and modified times. */ -/* This function only extracts files, not archive directory records. */ -mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags); -mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags); - -/* Extracts a archive file starting at the current position in the destination FILE stream. */ -mz_bool mz_zip_reader_extract_to_cfile(mz_zip_archive *pZip, mz_uint file_index, MZ_FILE *File, mz_uint flags); -mz_bool mz_zip_reader_extract_file_to_cfile(mz_zip_archive *pZip, const char *pArchive_filename, MZ_FILE *pFile, mz_uint flags); -#endif - -#if 0 -/* TODO */ - typedef void *mz_zip_streaming_extract_state_ptr; - mz_zip_streaming_extract_state_ptr mz_zip_streaming_extract_begin(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags); - uint64_t mz_zip_streaming_extract_get_size(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState); - uint64_t mz_zip_streaming_extract_get_cur_ofs(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState); - mz_bool mz_zip_streaming_extract_seek(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState, uint64_t new_ofs); - size_t mz_zip_streaming_extract_read(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState, void *pBuf, size_t buf_size); - mz_bool mz_zip_streaming_extract_end(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState); -#endif - -/* This function compares the archive's local headers, the optional local zip64 extended information block, and the optional descriptor following the compressed data vs. the data in the central directory. */ -/* It also validates that each file can be successfully uncompressed unless the MZ_ZIP_FLAG_VALIDATE_HEADERS_ONLY is specified. */ -mz_bool mz_zip_validate_file(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags); - -/* Validates an entire archive by calling mz_zip_validate_file() on each file. */ -mz_bool mz_zip_validate_archive(mz_zip_archive *pZip, mz_uint flags); - -/* Misc utils/helpers, valid for ZIP reading or writing */ -mz_bool mz_zip_validate_mem_archive(const void *pMem, size_t size, mz_uint flags, mz_zip_error *pErr); -mz_bool mz_zip_validate_file_archive(const char *pFilename, mz_uint flags, mz_zip_error *pErr); - -/* Universal end function - calls either mz_zip_reader_end() or mz_zip_writer_end(). */ -mz_bool mz_zip_end(mz_zip_archive *pZip); - -/* -------- ZIP writing */ - -#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS - -/* Inits a ZIP archive writer. */ -/*Set pZip->m_pWrite (and pZip->m_pIO_opaque) before calling mz_zip_writer_init or mz_zip_writer_init_v2*/ -/*The output is streamable, i.e. file_ofs in mz_file_write_func always increases only by n*/ -mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size); -mz_bool mz_zip_writer_init_v2(mz_zip_archive *pZip, mz_uint64 existing_size, mz_uint flags); - -mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size); -mz_bool mz_zip_writer_init_heap_v2(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size, mz_uint flags); - -#ifndef MINIZ_NO_STDIO -mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning); -mz_bool mz_zip_writer_init_file_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning, mz_uint flags); -mz_bool mz_zip_writer_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile, mz_uint flags); -#endif - -/* Converts a ZIP archive reader object into a writer object, to allow efficient in-place file appends to occur on an existing archive. */ -/* For archives opened using mz_zip_reader_init_file, pFilename must be the archive's filename so it can be reopened for writing. If the file can't be reopened, mz_zip_reader_end() will be called. */ -/* For archives opened using mz_zip_reader_init_mem, the memory block must be growable using the realloc callback (which defaults to realloc unless you've overridden it). */ -/* Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's user provided m_pWrite function cannot be NULL. */ -/* Note: In-place archive modification is not recommended unless you know what you're doing, because if execution stops or something goes wrong before */ -/* the archive is finalized the file's central directory will be hosed. */ -mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename); -mz_bool mz_zip_writer_init_from_reader_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint flags); - -/* Adds the contents of a memory buffer to an archive. These functions record the current local time into the archive. */ -/* To add a directory entry, call this method with an archive name ending in a forwardslash with an empty buffer. */ -/* level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. */ -mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags); - -/* Like mz_zip_writer_add_mem(), except you can specify a file comment field, and optionally supply the function with already compressed data. */ -/* uncomp_size/uncomp_crc32 are only used if the MZ_ZIP_FLAG_COMPRESSED_DATA flag is specified. */ -mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, - mz_uint64 uncomp_size, mz_uint32 uncomp_crc32); - -mz_bool mz_zip_writer_add_mem_ex_v2(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, - mz_uint64 uncomp_size, mz_uint32 uncomp_crc32, MZ_TIME_T *last_modified, const char *user_extra_data_local, mz_uint user_extra_data_local_len, - const char *user_extra_data_central, mz_uint user_extra_data_central_len); - -#ifndef MINIZ_NO_STDIO -/* Adds the contents of a disk file to an archive. This function also records the disk file's modified time into the archive. */ -/* level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. */ -mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); - -/* Like mz_zip_writer_add_file(), except the file data is read from the specified FILE stream. */ -mz_bool mz_zip_writer_add_cfile(mz_zip_archive *pZip, const char *pArchive_name, MZ_FILE *pSrc_file, mz_uint64 size_to_add, - const MZ_TIME_T *pFile_time, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, const char *user_extra_data_local, mz_uint user_extra_data_local_len, - const char *user_extra_data_central, mz_uint user_extra_data_central_len); -#endif - -/* Adds a file to an archive by fully cloning the data from another archive. */ -/* This function fully clones the source file's compressed data (no recompression), along with its full filename, extra data (it may add or modify the zip64 local header extra data field), and the optional descriptor following the compressed data. */ -mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint src_file_index); - -/* Finalizes the archive by writing the central directory records followed by the end of central directory record. */ -/* After an archive is finalized, the only valid call on the mz_zip_archive struct is mz_zip_writer_end(). */ -/* An archive must be manually finalized by calling this function for it to be valid. */ -mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip); - -/* Finalizes a heap archive, returning a poiner to the heap block and its size. */ -/* The heap block will be allocated using the mz_zip_archive's alloc/realloc callbacks. */ -mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **ppBuf, size_t *pSize); - -/* Ends archive writing, freeing all allocations, and closing the output file if mz_zip_writer_init_file() was used. */ -/* Note for the archive to be valid, it *must* have been finalized before ending (this function will not do it for you). */ -mz_bool mz_zip_writer_end(mz_zip_archive *pZip); - -/* -------- Misc. high-level helper functions: */ - -/* mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically) appends a memory blob to a ZIP archive. */ -/* Note this is NOT a fully safe operation. If it crashes or dies in some way your archive can be left in a screwed up state (without a central directory). */ -/* level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. */ -/* TODO: Perhaps add an option to leave the existing central dir in place in case the add dies? We could then truncate the file (so the old central dir would be at the end) if something goes wrong. */ -mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); -mz_bool mz_zip_add_mem_to_archive_file_in_place_v2(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_zip_error *pErr); - -/* Reads a single file from an archive into a heap block. */ -/* If pComment is not NULL, only the file with the specified comment will be extracted. */ -/* Returns NULL on failure. */ -void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint flags); -void *mz_zip_extract_archive_file_to_heap_v2(const char *pZip_filename, const char *pArchive_name, const char *pComment, size_t *pSize, mz_uint flags, mz_zip_error *pErr); - -#endif /* #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS */ - -#ifdef __cplusplus -} -#endif - -#endif /* MINIZ_NO_ARCHIVE_APIS */ -/************************************************************************** - * - * Copyright 2013-2014 RAD Game Tools and Valve Software - * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC - * All Rights Reserved. - * - * 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. - * - **************************************************************************/ - - -typedef unsigned char mz_validate_uint16[sizeof(mz_uint16) == 2 ? 1 : -1]; -typedef unsigned char mz_validate_uint32[sizeof(mz_uint32) == 4 ? 1 : -1]; -typedef unsigned char mz_validate_uint64[sizeof(mz_uint64) == 8 ? 1 : -1]; - -#ifdef __cplusplus -extern "C" { -#endif - -/* ------------------- zlib-style API's */ - -mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len) -{ - mz_uint32 i, s1 = (mz_uint32)(adler & 0xffff), s2 = (mz_uint32)(adler >> 16); - size_t block_len = buf_len % 5552; - if (!ptr) - return MZ_ADLER32_INIT; - while (buf_len) - { - for (i = 0; i + 7 < block_len; i += 8, ptr += 8) - { - s1 += ptr[0], s2 += s1; - s1 += ptr[1], s2 += s1; - s1 += ptr[2], s2 += s1; - s1 += ptr[3], s2 += s1; - s1 += ptr[4], s2 += s1; - s1 += ptr[5], s2 += s1; - s1 += ptr[6], s2 += s1; - s1 += ptr[7], s2 += s1; - } - for (; i < block_len; ++i) - s1 += *ptr++, s2 += s1; - s1 %= 65521U, s2 %= 65521U; - buf_len -= block_len; - block_len = 5552; - } - return (s2 << 16) + s1; -} - -/* Karl Malbrain's compact CRC-32. See "A compact CCITT crc16 and crc32 C implementation that balances processor cache usage against speed": http://www.geocities.com/malbrain/ */ -#if 0 - mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len) - { - static const mz_uint32 s_crc32[16] = { 0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c, - 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c }; - mz_uint32 crcu32 = (mz_uint32)crc; - if (!ptr) - return MZ_CRC32_INIT; - crcu32 = ~crcu32; - while (buf_len--) - { - mz_uint8 b = *ptr++; - crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b & 0xF)]; - crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b >> 4)]; - } - return ~crcu32; - } -#else -/* Faster, but larger CPU cache footprint. - */ -mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len) -{ - static const mz_uint32 s_crc_table[256] = - { - 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, - 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, - 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, - 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, - 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, - 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, - 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, - 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, - 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, - 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, - 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, - 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, - 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, - 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, - 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, - 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, - 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, - 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, - 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, - 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, - 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, - 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, - 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, - 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, - 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, - 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, - 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, - 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, - 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, - 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, - 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, - 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, - 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, - 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, - 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, - 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, - 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D - }; - - mz_uint32 crc32 = (mz_uint32)crc ^ 0xFFFFFFFF; - const mz_uint8 *pByte_buf = (const mz_uint8 *)ptr; - - while (buf_len >= 4) - { - crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[0]) & 0xFF]; - crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[1]) & 0xFF]; - crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[2]) & 0xFF]; - crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[3]) & 0xFF]; - pByte_buf += 4; - buf_len -= 4; - } - - while (buf_len) - { - crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[0]) & 0xFF]; - ++pByte_buf; - --buf_len; - } - - return ~crc32; -} -#endif - -void mz_free(void *p) -{ - MZ_FREE(p); -} - -void *miniz_def_alloc_func(void *opaque, size_t items, size_t size) -{ - (void)opaque, (void)items, (void)size; - return MZ_MALLOC(items * size); -} -void miniz_def_free_func(void *opaque, void *address) -{ - (void)opaque, (void)address; - MZ_FREE(address); -} -void *miniz_def_realloc_func(void *opaque, void *address, size_t items, size_t size) -{ - (void)opaque, (void)address, (void)items, (void)size; - return MZ_REALLOC(address, items * size); -} - -const char *mz_version(void) -{ - return MZ_VERSION; -} - -#ifndef MINIZ_NO_ZLIB_APIS - -int mz_deflateInit(mz_streamp pStream, int level) -{ - return mz_deflateInit2(pStream, level, MZ_DEFLATED, MZ_DEFAULT_WINDOW_BITS, 9, MZ_DEFAULT_STRATEGY); -} - -int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy) -{ - tdefl_compressor *pComp; - mz_uint comp_flags = TDEFL_COMPUTE_ADLER32 | tdefl_create_comp_flags_from_zip_params(level, window_bits, strategy); - - if (!pStream) - return MZ_STREAM_ERROR; - if ((method != MZ_DEFLATED) || ((mem_level < 1) || (mem_level > 9)) || ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS))) - return MZ_PARAM_ERROR; - - pStream->data_type = 0; - pStream->adler = MZ_ADLER32_INIT; - pStream->msg = NULL; - pStream->reserved = 0; - pStream->total_in = 0; - pStream->total_out = 0; - if (!pStream->zalloc) - pStream->zalloc = miniz_def_alloc_func; - if (!pStream->zfree) - pStream->zfree = miniz_def_free_func; - - pComp = (tdefl_compressor *)pStream->zalloc(pStream->opaque, 1, sizeof(tdefl_compressor)); - if (!pComp) - return MZ_MEM_ERROR; - - pStream->state = (struct mz_internal_state *)pComp; - - if (tdefl_init(pComp, NULL, NULL, comp_flags) != TDEFL_STATUS_OKAY) - { - mz_deflateEnd(pStream); - return MZ_PARAM_ERROR; - } - - return MZ_OK; -} - -int mz_deflateReset(mz_streamp pStream) -{ - if ((!pStream) || (!pStream->state) || (!pStream->zalloc) || (!pStream->zfree)) - return MZ_STREAM_ERROR; - pStream->total_in = pStream->total_out = 0; - tdefl_init((tdefl_compressor *)pStream->state, NULL, NULL, ((tdefl_compressor *)pStream->state)->m_flags); - return MZ_OK; -} - -int mz_deflate(mz_streamp pStream, int flush) -{ - size_t in_bytes, out_bytes; - mz_ulong orig_total_in, orig_total_out; - int mz_status = MZ_OK; - - if ((!pStream) || (!pStream->state) || (flush < 0) || (flush > MZ_FINISH) || (!pStream->next_out)) - return MZ_STREAM_ERROR; - if (!pStream->avail_out) - return MZ_BUF_ERROR; - - if (flush == MZ_PARTIAL_FLUSH) - flush = MZ_SYNC_FLUSH; - - if (((tdefl_compressor *)pStream->state)->m_prev_return_status == TDEFL_STATUS_DONE) - return (flush == MZ_FINISH) ? MZ_STREAM_END : MZ_BUF_ERROR; - - orig_total_in = pStream->total_in; - orig_total_out = pStream->total_out; - for (;;) - { - tdefl_status defl_status; - in_bytes = pStream->avail_in; - out_bytes = pStream->avail_out; - - defl_status = tdefl_compress((tdefl_compressor *)pStream->state, pStream->next_in, &in_bytes, pStream->next_out, &out_bytes, (tdefl_flush)flush); - pStream->next_in += (mz_uint)in_bytes; - pStream->avail_in -= (mz_uint)in_bytes; - pStream->total_in += (mz_uint)in_bytes; - pStream->adler = tdefl_get_adler32((tdefl_compressor *)pStream->state); - - pStream->next_out += (mz_uint)out_bytes; - pStream->avail_out -= (mz_uint)out_bytes; - pStream->total_out += (mz_uint)out_bytes; - - if (defl_status < 0) - { - mz_status = MZ_STREAM_ERROR; - break; - } - else if (defl_status == TDEFL_STATUS_DONE) - { - mz_status = MZ_STREAM_END; - break; - } - else if (!pStream->avail_out) - break; - else if ((!pStream->avail_in) && (flush != MZ_FINISH)) - { - if ((flush) || (pStream->total_in != orig_total_in) || (pStream->total_out != orig_total_out)) - break; - return MZ_BUF_ERROR; /* Can't make forward progress without some input. - */ - } - } - return mz_status; -} - -int mz_deflateEnd(mz_streamp pStream) -{ - if (!pStream) - return MZ_STREAM_ERROR; - if (pStream->state) - { - pStream->zfree(pStream->opaque, pStream->state); - pStream->state = NULL; - } - return MZ_OK; -} - -mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len) -{ - (void)pStream; - /* This is really over conservative. (And lame, but it's actually pretty tricky to compute a true upper bound given the way tdefl's blocking works.) */ - return MZ_MAX(128 + (source_len * 110) / 100, 128 + source_len + ((source_len / (31 * 1024)) + 1) * 5); -} - -int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level) -{ - int status; - mz_stream stream; - memset(&stream, 0, sizeof(stream)); - - /* In case mz_ulong is 64-bits (argh I hate longs). */ - if ((source_len | *pDest_len) > 0xFFFFFFFFU) - return MZ_PARAM_ERROR; - - stream.next_in = pSource; - stream.avail_in = (mz_uint32)source_len; - stream.next_out = pDest; - stream.avail_out = (mz_uint32)*pDest_len; - - status = mz_deflateInit(&stream, level); - if (status != MZ_OK) - return status; - - status = mz_deflate(&stream, MZ_FINISH); - if (status != MZ_STREAM_END) - { - mz_deflateEnd(&stream); - return (status == MZ_OK) ? MZ_BUF_ERROR : status; - } - - *pDest_len = stream.total_out; - return mz_deflateEnd(&stream); -} - -int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len) -{ - return mz_compress2(pDest, pDest_len, pSource, source_len, MZ_DEFAULT_COMPRESSION); -} - -mz_ulong mz_compressBound(mz_ulong source_len) -{ - return mz_deflateBound(NULL, source_len); -} - -typedef struct -{ - tinfl_decompressor m_decomp; - mz_uint m_dict_ofs, m_dict_avail, m_first_call, m_has_flushed; - int m_window_bits; - mz_uint8 m_dict[TINFL_LZ_DICT_SIZE]; - tinfl_status m_last_status; -} inflate_state; - -int mz_inflateInit2(mz_streamp pStream, int window_bits) -{ - inflate_state *pDecomp; - if (!pStream) - return MZ_STREAM_ERROR; - if ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS)) - return MZ_PARAM_ERROR; - - pStream->data_type = 0; - pStream->adler = 0; - pStream->msg = NULL; - pStream->total_in = 0; - pStream->total_out = 0; - pStream->reserved = 0; - if (!pStream->zalloc) - pStream->zalloc = miniz_def_alloc_func; - if (!pStream->zfree) - pStream->zfree = miniz_def_free_func; - - pDecomp = (inflate_state *)pStream->zalloc(pStream->opaque, 1, sizeof(inflate_state)); - if (!pDecomp) - return MZ_MEM_ERROR; - - pStream->state = (struct mz_internal_state *)pDecomp; - - tinfl_init(&pDecomp->m_decomp); - pDecomp->m_dict_ofs = 0; - pDecomp->m_dict_avail = 0; - pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT; - pDecomp->m_first_call = 1; - pDecomp->m_has_flushed = 0; - pDecomp->m_window_bits = window_bits; - - return MZ_OK; -} - -int mz_inflateInit(mz_streamp pStream) -{ - return mz_inflateInit2(pStream, MZ_DEFAULT_WINDOW_BITS); -} - -int mz_inflate(mz_streamp pStream, int flush) -{ - inflate_state *pState; - mz_uint n, first_call, decomp_flags = TINFL_FLAG_COMPUTE_ADLER32; - size_t in_bytes, out_bytes, orig_avail_in; - tinfl_status status; - - if ((!pStream) || (!pStream->state)) - return MZ_STREAM_ERROR; - if (flush == MZ_PARTIAL_FLUSH) - flush = MZ_SYNC_FLUSH; - if ((flush) && (flush != MZ_SYNC_FLUSH) && (flush != MZ_FINISH)) - return MZ_STREAM_ERROR; - - pState = (inflate_state *)pStream->state; - if (pState->m_window_bits > 0) - decomp_flags |= TINFL_FLAG_PARSE_ZLIB_HEADER; - orig_avail_in = pStream->avail_in; - - first_call = pState->m_first_call; - pState->m_first_call = 0; - if (pState->m_last_status < 0) - return MZ_DATA_ERROR; - - if (pState->m_has_flushed && (flush != MZ_FINISH)) - return MZ_STREAM_ERROR; - pState->m_has_flushed |= (flush == MZ_FINISH); - - if ((flush == MZ_FINISH) && (first_call)) - { - /* MZ_FINISH on the first call implies that the input and output buffers are large enough to hold the entire compressed/decompressed file. */ - decomp_flags |= TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF; - in_bytes = pStream->avail_in; - out_bytes = pStream->avail_out; - status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pStream->next_out, pStream->next_out, &out_bytes, decomp_flags); - pState->m_last_status = status; - pStream->next_in += (mz_uint)in_bytes; - pStream->avail_in -= (mz_uint)in_bytes; - pStream->total_in += (mz_uint)in_bytes; - pStream->adler = tinfl_get_adler32(&pState->m_decomp); - pStream->next_out += (mz_uint)out_bytes; - pStream->avail_out -= (mz_uint)out_bytes; - pStream->total_out += (mz_uint)out_bytes; - - if (status < 0) - return MZ_DATA_ERROR; - else if (status != TINFL_STATUS_DONE) - { - pState->m_last_status = TINFL_STATUS_FAILED; - return MZ_BUF_ERROR; - } - return MZ_STREAM_END; - } - /* flush != MZ_FINISH then we must assume there's more input. */ - if (flush != MZ_FINISH) - decomp_flags |= TINFL_FLAG_HAS_MORE_INPUT; - - if (pState->m_dict_avail) - { - n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); - memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); - pStream->next_out += n; - pStream->avail_out -= n; - pStream->total_out += n; - pState->m_dict_avail -= n; - pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); - return ((pState->m_last_status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; - } - - for (;;) - { - in_bytes = pStream->avail_in; - out_bytes = TINFL_LZ_DICT_SIZE - pState->m_dict_ofs; - - status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pState->m_dict, pState->m_dict + pState->m_dict_ofs, &out_bytes, decomp_flags); - pState->m_last_status = status; - - pStream->next_in += (mz_uint)in_bytes; - pStream->avail_in -= (mz_uint)in_bytes; - pStream->total_in += (mz_uint)in_bytes; - pStream->adler = tinfl_get_adler32(&pState->m_decomp); - - pState->m_dict_avail = (mz_uint)out_bytes; - - n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); - memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); - pStream->next_out += n; - pStream->avail_out -= n; - pStream->total_out += n; - pState->m_dict_avail -= n; - pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); - - if (status < 0) - return MZ_DATA_ERROR; /* Stream is corrupted (there could be some uncompressed data left in the output dictionary - oh well). */ - else if ((status == TINFL_STATUS_NEEDS_MORE_INPUT) && (!orig_avail_in)) - return MZ_BUF_ERROR; /* Signal caller that we can't make forward progress without supplying more input or by setting flush to MZ_FINISH. */ - else if (flush == MZ_FINISH) - { - /* The output buffer MUST be large to hold the remaining uncompressed data when flush==MZ_FINISH. */ - if (status == TINFL_STATUS_DONE) - return pState->m_dict_avail ? MZ_BUF_ERROR : MZ_STREAM_END; - /* status here must be TINFL_STATUS_HAS_MORE_OUTPUT, which means there's at least 1 more byte on the way. If there's no more room left in the output buffer then something is wrong. */ - else if (!pStream->avail_out) - return MZ_BUF_ERROR; - } - else if ((status == TINFL_STATUS_DONE) || (!pStream->avail_in) || (!pStream->avail_out) || (pState->m_dict_avail)) - break; - } - - return ((status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; -} - -int mz_inflateEnd(mz_streamp pStream) -{ - if (!pStream) - return MZ_STREAM_ERROR; - if (pStream->state) - { - pStream->zfree(pStream->opaque, pStream->state); - pStream->state = NULL; - } - return MZ_OK; -} - -int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len) -{ - mz_stream stream; - int status; - memset(&stream, 0, sizeof(stream)); - - /* In case mz_ulong is 64-bits (argh I hate longs). */ - if ((source_len | *pDest_len) > 0xFFFFFFFFU) - return MZ_PARAM_ERROR; - - stream.next_in = pSource; - stream.avail_in = (mz_uint32)source_len; - stream.next_out = pDest; - stream.avail_out = (mz_uint32)*pDest_len; - - status = mz_inflateInit(&stream); - if (status != MZ_OK) - return status; - - status = mz_inflate(&stream, MZ_FINISH); - if (status != MZ_STREAM_END) - { - mz_inflateEnd(&stream); - return ((status == MZ_BUF_ERROR) && (!stream.avail_in)) ? MZ_DATA_ERROR : status; - } - *pDest_len = stream.total_out; - - return mz_inflateEnd(&stream); -} - -const char *mz_error(int err) -{ - static struct - { - int m_err; - const char *m_pDesc; - } s_error_descs[] = - { - { MZ_OK, "" }, { MZ_STREAM_END, "stream end" }, { MZ_NEED_DICT, "need dictionary" }, { MZ_ERRNO, "file error" }, { MZ_STREAM_ERROR, "stream error" }, { MZ_DATA_ERROR, "data error" }, { MZ_MEM_ERROR, "out of memory" }, { MZ_BUF_ERROR, "buf error" }, { MZ_VERSION_ERROR, "version error" }, { MZ_PARAM_ERROR, "parameter error" } - }; - mz_uint i; - for (i = 0; i < sizeof(s_error_descs) / sizeof(s_error_descs[0]); ++i) - if (s_error_descs[i].m_err == err) - return s_error_descs[i].m_pDesc; - return NULL; -} - -#endif /*MINIZ_NO_ZLIB_APIS */ - -#ifdef __cplusplus -} -#endif - -/* - This is free and unencumbered software released into the public domain. - - Anyone is free to copy, modify, publish, use, compile, sell, or - distribute this software, either in source code form or as a compiled - binary, for any purpose, commercial or non-commercial, and by any - means. - - In jurisdictions that recognize copyright laws, the author or authors - of this software dedicate any and all copyright interest in the - software to the public domain. We make this dedication for the benefit - of the public at large and to the detriment of our heirs and - successors. We intend this dedication to be an overt act of - relinquishment in perpetuity of all present and future rights to this - software under copyright law. - - 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 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. - - For more information, please refer to -*/ -/************************************************************************** - * - * Copyright 2013-2014 RAD Game Tools and Valve Software - * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC - * All Rights Reserved. - * - * 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. - * - **************************************************************************/ - - - - -#ifdef __cplusplus -extern "C" { -#endif - -/* ------------------- Low-level Compression (independent from all decompression API's) */ - -/* Purposely making these tables static for faster init and thread safety. */ -static const mz_uint16 s_tdefl_len_sym[256] = - { - 257, 258, 259, 260, 261, 262, 263, 264, 265, 265, 266, 266, 267, 267, 268, 268, 269, 269, 269, 269, 270, 270, 270, 270, 271, 271, 271, 271, 272, 272, 272, 272, - 273, 273, 273, 273, 273, 273, 273, 273, 274, 274, 274, 274, 274, 274, 274, 274, 275, 275, 275, 275, 275, 275, 275, 275, 276, 276, 276, 276, 276, 276, 276, 276, - 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, - 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, - 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, - 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, - 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, - 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 285 - }; - -static const mz_uint8 s_tdefl_len_extra[256] = - { - 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, - 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0 - }; - -static const mz_uint8 s_tdefl_small_dist_sym[512] = - { - 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, - 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, - 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, - 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, - 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, - 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, - 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, - 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, - 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17 - }; - -static const mz_uint8 s_tdefl_small_dist_extra[512] = - { - 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, - 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, - 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, - 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, - 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, - 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, - 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, - 7, 7, 7, 7, 7, 7, 7, 7 - }; - -static const mz_uint8 s_tdefl_large_dist_sym[128] = - { - 0, 0, 18, 19, 20, 20, 21, 21, 22, 22, 22, 22, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, - 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, - 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29 - }; - -static const mz_uint8 s_tdefl_large_dist_extra[128] = - { - 0, 0, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, - 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, - 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13 - }; - -/* Radix sorts tdefl_sym_freq[] array by 16-bit key m_key. Returns ptr to sorted values. */ -typedef struct -{ - mz_uint16 m_key, m_sym_index; -} tdefl_sym_freq; -static tdefl_sym_freq *tdefl_radix_sort_syms(mz_uint num_syms, tdefl_sym_freq *pSyms0, tdefl_sym_freq *pSyms1) -{ - mz_uint32 total_passes = 2, pass_shift, pass, i, hist[256 * 2]; - tdefl_sym_freq *pCur_syms = pSyms0, *pNew_syms = pSyms1; - MZ_CLEAR_OBJ(hist); - for (i = 0; i < num_syms; i++) - { - mz_uint freq = pSyms0[i].m_key; - hist[freq & 0xFF]++; - hist[256 + ((freq >> 8) & 0xFF)]++; - } - while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256])) - total_passes--; - for (pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8) - { - const mz_uint32 *pHist = &hist[pass << 8]; - mz_uint offsets[256], cur_ofs = 0; - for (i = 0; i < 256; i++) - { - offsets[i] = cur_ofs; - cur_ofs += pHist[i]; - } - for (i = 0; i < num_syms; i++) - pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] = pCur_syms[i]; - { - tdefl_sym_freq *t = pCur_syms; - pCur_syms = pNew_syms; - pNew_syms = t; - } - } - return pCur_syms; -} - -/* tdefl_calculate_minimum_redundancy() originally written by: Alistair Moffat, alistair@cs.mu.oz.au, Jyrki Katajainen, jyrki@diku.dk, November 1996. */ -static void tdefl_calculate_minimum_redundancy(tdefl_sym_freq *A, int n) -{ - int root, leaf, next, avbl, used, dpth; - if (n == 0) - return; - else if (n == 1) - { - A[0].m_key = 1; - return; - } - A[0].m_key += A[1].m_key; - root = 0; - leaf = 2; - for (next = 1; next < n - 1; next++) - { - if (leaf >= n || A[root].m_key < A[leaf].m_key) - { - A[next].m_key = A[root].m_key; - A[root++].m_key = (mz_uint16)next; - } - else - A[next].m_key = A[leaf++].m_key; - if (leaf >= n || (root < next && A[root].m_key < A[leaf].m_key)) - { - A[next].m_key = (mz_uint16)(A[next].m_key + A[root].m_key); - A[root++].m_key = (mz_uint16)next; - } - else - A[next].m_key = (mz_uint16)(A[next].m_key + A[leaf++].m_key); - } - A[n - 2].m_key = 0; - for (next = n - 3; next >= 0; next--) - A[next].m_key = A[A[next].m_key].m_key + 1; - avbl = 1; - used = dpth = 0; - root = n - 2; - next = n - 1; - while (avbl > 0) - { - while (root >= 0 && (int)A[root].m_key == dpth) - { - used++; - root--; - } - while (avbl > used) - { - A[next--].m_key = (mz_uint16)(dpth); - avbl--; - } - avbl = 2 * used; - dpth++; - used = 0; - } -} - -/* Limits canonical Huffman code table's max code size. */ -enum -{ - TDEFL_MAX_SUPPORTED_HUFF_CODESIZE = 32 -}; -static void tdefl_huffman_enforce_max_code_size(int *pNum_codes, int code_list_len, int max_code_size) -{ - int i; - mz_uint32 total = 0; - if (code_list_len <= 1) - return; - for (i = max_code_size + 1; i <= TDEFL_MAX_SUPPORTED_HUFF_CODESIZE; i++) - pNum_codes[max_code_size] += pNum_codes[i]; - for (i = max_code_size; i > 0; i--) - total += (((mz_uint32)pNum_codes[i]) << (max_code_size - i)); - while (total != (1UL << max_code_size)) - { - pNum_codes[max_code_size]--; - for (i = max_code_size - 1; i > 0; i--) - if (pNum_codes[i]) - { - pNum_codes[i]--; - pNum_codes[i + 1] += 2; - break; - } - total--; - } -} - -static void tdefl_optimize_huffman_table(tdefl_compressor *d, int table_num, int table_len, int code_size_limit, int static_table) -{ - int i, j, l, num_codes[1 + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE]; - mz_uint next_code[TDEFL_MAX_SUPPORTED_HUFF_CODESIZE + 1]; - MZ_CLEAR_OBJ(num_codes); - if (static_table) - { - for (i = 0; i < table_len; i++) - num_codes[d->m_huff_code_sizes[table_num][i]]++; - } - else - { - tdefl_sym_freq syms0[TDEFL_MAX_HUFF_SYMBOLS], syms1[TDEFL_MAX_HUFF_SYMBOLS], *pSyms; - int num_used_syms = 0; - const mz_uint16 *pSym_count = &d->m_huff_count[table_num][0]; - for (i = 0; i < table_len; i++) - if (pSym_count[i]) - { - syms0[num_used_syms].m_key = (mz_uint16)pSym_count[i]; - syms0[num_used_syms++].m_sym_index = (mz_uint16)i; - } - - pSyms = tdefl_radix_sort_syms(num_used_syms, syms0, syms1); - tdefl_calculate_minimum_redundancy(pSyms, num_used_syms); - - for (i = 0; i < num_used_syms; i++) - num_codes[pSyms[i].m_key]++; - - tdefl_huffman_enforce_max_code_size(num_codes, num_used_syms, code_size_limit); - - MZ_CLEAR_OBJ(d->m_huff_code_sizes[table_num]); - MZ_CLEAR_OBJ(d->m_huff_codes[table_num]); - for (i = 1, j = num_used_syms; i <= code_size_limit; i++) - for (l = num_codes[i]; l > 0; l--) - d->m_huff_code_sizes[table_num][pSyms[--j].m_sym_index] = (mz_uint8)(i); - } - - next_code[1] = 0; - for (j = 0, i = 2; i <= code_size_limit; i++) - next_code[i] = j = ((j + num_codes[i - 1]) << 1); - - for (i = 0; i < table_len; i++) - { - mz_uint rev_code = 0, code, code_size; - if ((code_size = d->m_huff_code_sizes[table_num][i]) == 0) - continue; - code = next_code[code_size]++; - for (l = code_size; l > 0; l--, code >>= 1) - rev_code = (rev_code << 1) | (code & 1); - d->m_huff_codes[table_num][i] = (mz_uint16)rev_code; - } -} - -#define TDEFL_PUT_BITS(b, l) \ - do \ - { \ - mz_uint bits = b; \ - mz_uint len = l; \ - MZ_ASSERT(bits <= ((1U << len) - 1U)); \ - d->m_bit_buffer |= (bits << d->m_bits_in); \ - d->m_bits_in += len; \ - while (d->m_bits_in >= 8) \ - { \ - if (d->m_pOutput_buf < d->m_pOutput_buf_end) \ - *d->m_pOutput_buf++ = (mz_uint8)(d->m_bit_buffer); \ - d->m_bit_buffer >>= 8; \ - d->m_bits_in -= 8; \ - } \ - } \ - MZ_MACRO_END - -#define TDEFL_RLE_PREV_CODE_SIZE() \ - { \ - if (rle_repeat_count) \ - { \ - if (rle_repeat_count < 3) \ - { \ - d->m_huff_count[2][prev_code_size] = (mz_uint16)(d->m_huff_count[2][prev_code_size] + rle_repeat_count); \ - while (rle_repeat_count--) \ - packed_code_sizes[num_packed_code_sizes++] = prev_code_size; \ - } \ - else \ - { \ - d->m_huff_count[2][16] = (mz_uint16)(d->m_huff_count[2][16] + 1); \ - packed_code_sizes[num_packed_code_sizes++] = 16; \ - packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_repeat_count - 3); \ - } \ - rle_repeat_count = 0; \ - } \ - } - -#define TDEFL_RLE_ZERO_CODE_SIZE() \ - { \ - if (rle_z_count) \ - { \ - if (rle_z_count < 3) \ - { \ - d->m_huff_count[2][0] = (mz_uint16)(d->m_huff_count[2][0] + rle_z_count); \ - while (rle_z_count--) \ - packed_code_sizes[num_packed_code_sizes++] = 0; \ - } \ - else if (rle_z_count <= 10) \ - { \ - d->m_huff_count[2][17] = (mz_uint16)(d->m_huff_count[2][17] + 1); \ - packed_code_sizes[num_packed_code_sizes++] = 17; \ - packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 3); \ - } \ - else \ - { \ - d->m_huff_count[2][18] = (mz_uint16)(d->m_huff_count[2][18] + 1); \ - packed_code_sizes[num_packed_code_sizes++] = 18; \ - packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 11); \ - } \ - rle_z_count = 0; \ - } \ - } - -static mz_uint8 s_tdefl_packed_code_size_syms_swizzle[] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; - -static void tdefl_start_dynamic_block(tdefl_compressor *d) -{ - int num_lit_codes, num_dist_codes, num_bit_lengths; - mz_uint i, total_code_sizes_to_pack, num_packed_code_sizes, rle_z_count, rle_repeat_count, packed_code_sizes_index; - mz_uint8 code_sizes_to_pack[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], packed_code_sizes[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], prev_code_size = 0xFF; - - d->m_huff_count[0][256] = 1; - - tdefl_optimize_huffman_table(d, 0, TDEFL_MAX_HUFF_SYMBOLS_0, 15, MZ_FALSE); - tdefl_optimize_huffman_table(d, 1, TDEFL_MAX_HUFF_SYMBOLS_1, 15, MZ_FALSE); - - for (num_lit_codes = 286; num_lit_codes > 257; num_lit_codes--) - if (d->m_huff_code_sizes[0][num_lit_codes - 1]) - break; - for (num_dist_codes = 30; num_dist_codes > 1; num_dist_codes--) - if (d->m_huff_code_sizes[1][num_dist_codes - 1]) - break; - - memcpy(code_sizes_to_pack, &d->m_huff_code_sizes[0][0], num_lit_codes); - memcpy(code_sizes_to_pack + num_lit_codes, &d->m_huff_code_sizes[1][0], num_dist_codes); - total_code_sizes_to_pack = num_lit_codes + num_dist_codes; - num_packed_code_sizes = 0; - rle_z_count = 0; - rle_repeat_count = 0; - - memset(&d->m_huff_count[2][0], 0, sizeof(d->m_huff_count[2][0]) * TDEFL_MAX_HUFF_SYMBOLS_2); - for (i = 0; i < total_code_sizes_to_pack; i++) - { - mz_uint8 code_size = code_sizes_to_pack[i]; - if (!code_size) - { - TDEFL_RLE_PREV_CODE_SIZE(); - if (++rle_z_count == 138) - { - TDEFL_RLE_ZERO_CODE_SIZE(); - } - } - else - { - TDEFL_RLE_ZERO_CODE_SIZE(); - if (code_size != prev_code_size) - { - TDEFL_RLE_PREV_CODE_SIZE(); - d->m_huff_count[2][code_size] = (mz_uint16)(d->m_huff_count[2][code_size] + 1); - packed_code_sizes[num_packed_code_sizes++] = code_size; - } - else if (++rle_repeat_count == 6) - { - TDEFL_RLE_PREV_CODE_SIZE(); - } - } - prev_code_size = code_size; - } - if (rle_repeat_count) - { - TDEFL_RLE_PREV_CODE_SIZE(); - } - else - { - TDEFL_RLE_ZERO_CODE_SIZE(); - } - - tdefl_optimize_huffman_table(d, 2, TDEFL_MAX_HUFF_SYMBOLS_2, 7, MZ_FALSE); - - TDEFL_PUT_BITS(2, 2); - - TDEFL_PUT_BITS(num_lit_codes - 257, 5); - TDEFL_PUT_BITS(num_dist_codes - 1, 5); - - for (num_bit_lengths = 18; num_bit_lengths >= 0; num_bit_lengths--) - if (d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[num_bit_lengths]]) - break; - num_bit_lengths = MZ_MAX(4, (num_bit_lengths + 1)); - TDEFL_PUT_BITS(num_bit_lengths - 4, 4); - for (i = 0; (int)i < num_bit_lengths; i++) - TDEFL_PUT_BITS(d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[i]], 3); - - for (packed_code_sizes_index = 0; packed_code_sizes_index < num_packed_code_sizes;) - { - mz_uint code = packed_code_sizes[packed_code_sizes_index++]; - MZ_ASSERT(code < TDEFL_MAX_HUFF_SYMBOLS_2); - TDEFL_PUT_BITS(d->m_huff_codes[2][code], d->m_huff_code_sizes[2][code]); - if (code >= 16) - TDEFL_PUT_BITS(packed_code_sizes[packed_code_sizes_index++], "\02\03\07"[code - 16]); - } -} - -static void tdefl_start_static_block(tdefl_compressor *d) -{ - mz_uint i; - mz_uint8 *p = &d->m_huff_code_sizes[0][0]; - - for (i = 0; i <= 143; ++i) - *p++ = 8; - for (; i <= 255; ++i) - *p++ = 9; - for (; i <= 279; ++i) - *p++ = 7; - for (; i <= 287; ++i) - *p++ = 8; - - memset(d->m_huff_code_sizes[1], 5, 32); - - tdefl_optimize_huffman_table(d, 0, 288, 15, MZ_TRUE); - tdefl_optimize_huffman_table(d, 1, 32, 15, MZ_TRUE); - - TDEFL_PUT_BITS(1, 2); -} - -static const mz_uint mz_bitmasks[17] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF }; - -#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS -static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) -{ - mz_uint flags; - mz_uint8 *pLZ_codes; - mz_uint8 *pOutput_buf = d->m_pOutput_buf; - mz_uint8 *pLZ_code_buf_end = d->m_pLZ_code_buf; - mz_uint64 bit_buffer = d->m_bit_buffer; - mz_uint bits_in = d->m_bits_in; - -#define TDEFL_PUT_BITS_FAST(b, l) \ - { \ - bit_buffer |= (((mz_uint64)(b)) << bits_in); \ - bits_in += (l); \ - } - - flags = 1; - for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < pLZ_code_buf_end; flags >>= 1) - { - if (flags == 1) - flags = *pLZ_codes++ | 0x100; - - if (flags & 1) - { - mz_uint s0, s1, n0, n1, sym, num_extra_bits; - mz_uint match_len = pLZ_codes[0], match_dist = *(const mz_uint16 *)(pLZ_codes + 1); - pLZ_codes += 3; - - MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); - TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); - TDEFL_PUT_BITS_FAST(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]); - - /* This sequence coaxes MSVC into using cmov's vs. jmp's. */ - s0 = s_tdefl_small_dist_sym[match_dist & 511]; - n0 = s_tdefl_small_dist_extra[match_dist & 511]; - s1 = s_tdefl_large_dist_sym[match_dist >> 8]; - n1 = s_tdefl_large_dist_extra[match_dist >> 8]; - sym = (match_dist < 512) ? s0 : s1; - num_extra_bits = (match_dist < 512) ? n0 : n1; - - MZ_ASSERT(d->m_huff_code_sizes[1][sym]); - TDEFL_PUT_BITS_FAST(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]); - TDEFL_PUT_BITS_FAST(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits); - } - else - { - mz_uint lit = *pLZ_codes++; - MZ_ASSERT(d->m_huff_code_sizes[0][lit]); - TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); - - if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) - { - flags >>= 1; - lit = *pLZ_codes++; - MZ_ASSERT(d->m_huff_code_sizes[0][lit]); - TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); - - if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) - { - flags >>= 1; - lit = *pLZ_codes++; - MZ_ASSERT(d->m_huff_code_sizes[0][lit]); - TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); - } - } - } - - if (pOutput_buf >= d->m_pOutput_buf_end) - return MZ_FALSE; - - *(mz_uint64 *)pOutput_buf = bit_buffer; - pOutput_buf += (bits_in >> 3); - bit_buffer >>= (bits_in & ~7); - bits_in &= 7; - } - -#undef TDEFL_PUT_BITS_FAST - - d->m_pOutput_buf = pOutput_buf; - d->m_bits_in = 0; - d->m_bit_buffer = 0; - - while (bits_in) - { - mz_uint32 n = MZ_MIN(bits_in, 16); - TDEFL_PUT_BITS((mz_uint)bit_buffer & mz_bitmasks[n], n); - bit_buffer >>= n; - bits_in -= n; - } - - TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); - - return (d->m_pOutput_buf < d->m_pOutput_buf_end); -} -#else -static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) -{ - mz_uint flags; - mz_uint8 *pLZ_codes; - - flags = 1; - for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < d->m_pLZ_code_buf; flags >>= 1) - { - if (flags == 1) - flags = *pLZ_codes++ | 0x100; - if (flags & 1) - { - mz_uint sym, num_extra_bits; - mz_uint match_len = pLZ_codes[0], match_dist = (pLZ_codes[1] | (pLZ_codes[2] << 8)); - pLZ_codes += 3; - - MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); - TDEFL_PUT_BITS(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); - TDEFL_PUT_BITS(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]); - - if (match_dist < 512) - { - sym = s_tdefl_small_dist_sym[match_dist]; - num_extra_bits = s_tdefl_small_dist_extra[match_dist]; - } - else - { - sym = s_tdefl_large_dist_sym[match_dist >> 8]; - num_extra_bits = s_tdefl_large_dist_extra[match_dist >> 8]; - } - MZ_ASSERT(d->m_huff_code_sizes[1][sym]); - TDEFL_PUT_BITS(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]); - TDEFL_PUT_BITS(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits); - } - else - { - mz_uint lit = *pLZ_codes++; - MZ_ASSERT(d->m_huff_code_sizes[0][lit]); - TDEFL_PUT_BITS(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); - } - } - - TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); - - return (d->m_pOutput_buf < d->m_pOutput_buf_end); -} -#endif /* MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS */ - -static mz_bool tdefl_compress_block(tdefl_compressor *d, mz_bool static_block) -{ - if (static_block) - tdefl_start_static_block(d); - else - tdefl_start_dynamic_block(d); - return tdefl_compress_lz_codes(d); -} - -static int tdefl_flush_block(tdefl_compressor *d, int flush) -{ - mz_uint saved_bit_buf, saved_bits_in; - mz_uint8 *pSaved_output_buf; - mz_bool comp_block_succeeded = MZ_FALSE; - int n, use_raw_block = ((d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS) != 0) && (d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size; - mz_uint8 *pOutput_buf_start = ((d->m_pPut_buf_func == NULL) && ((*d->m_pOut_buf_size - d->m_out_buf_ofs) >= TDEFL_OUT_BUF_SIZE)) ? ((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs) : d->m_output_buf; - - d->m_pOutput_buf = pOutput_buf_start; - d->m_pOutput_buf_end = d->m_pOutput_buf + TDEFL_OUT_BUF_SIZE - 16; - - MZ_ASSERT(!d->m_output_flush_remaining); - d->m_output_flush_ofs = 0; - d->m_output_flush_remaining = 0; - - *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> d->m_num_flags_left); - d->m_pLZ_code_buf -= (d->m_num_flags_left == 8); - - if ((d->m_flags & TDEFL_WRITE_ZLIB_HEADER) && (!d->m_block_index)) - { - TDEFL_PUT_BITS(0x78, 8); - TDEFL_PUT_BITS(0x01, 8); - } - - TDEFL_PUT_BITS(flush == TDEFL_FINISH, 1); - - pSaved_output_buf = d->m_pOutput_buf; - saved_bit_buf = d->m_bit_buffer; - saved_bits_in = d->m_bits_in; - - if (!use_raw_block) - comp_block_succeeded = tdefl_compress_block(d, (d->m_flags & TDEFL_FORCE_ALL_STATIC_BLOCKS) || (d->m_total_lz_bytes < 48)); - - /* If the block gets expanded, forget the current contents of the output buffer and send a raw block instead. */ - if (((use_raw_block) || ((d->m_total_lz_bytes) && ((d->m_pOutput_buf - pSaved_output_buf + 1U) >= d->m_total_lz_bytes))) && - ((d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size)) - { - mz_uint i; - d->m_pOutput_buf = pSaved_output_buf; - d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; - TDEFL_PUT_BITS(0, 2); - if (d->m_bits_in) - { - TDEFL_PUT_BITS(0, 8 - d->m_bits_in); - } - for (i = 2; i; --i, d->m_total_lz_bytes ^= 0xFFFF) - { - TDEFL_PUT_BITS(d->m_total_lz_bytes & 0xFFFF, 16); - } - for (i = 0; i < d->m_total_lz_bytes; ++i) - { - TDEFL_PUT_BITS(d->m_dict[(d->m_lz_code_buf_dict_pos + i) & TDEFL_LZ_DICT_SIZE_MASK], 8); - } - } - /* Check for the extremely unlikely (if not impossible) case of the compressed block not fitting into the output buffer when using dynamic codes. */ - else if (!comp_block_succeeded) - { - d->m_pOutput_buf = pSaved_output_buf; - d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; - tdefl_compress_block(d, MZ_TRUE); - } - - if (flush) - { - if (flush == TDEFL_FINISH) - { - if (d->m_bits_in) - { - TDEFL_PUT_BITS(0, 8 - d->m_bits_in); - } - if (d->m_flags & TDEFL_WRITE_ZLIB_HEADER) - { - mz_uint i, a = d->m_adler32; - for (i = 0; i < 4; i++) - { - TDEFL_PUT_BITS((a >> 24) & 0xFF, 8); - a <<= 8; - } - } - } - else - { - mz_uint i, z = 0; - TDEFL_PUT_BITS(0, 3); - if (d->m_bits_in) - { - TDEFL_PUT_BITS(0, 8 - d->m_bits_in); - } - for (i = 2; i; --i, z ^= 0xFFFF) - { - TDEFL_PUT_BITS(z & 0xFFFF, 16); - } - } - } - - MZ_ASSERT(d->m_pOutput_buf < d->m_pOutput_buf_end); - - memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); - memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); - - d->m_pLZ_code_buf = d->m_lz_code_buf + 1; - d->m_pLZ_flags = d->m_lz_code_buf; - d->m_num_flags_left = 8; - d->m_lz_code_buf_dict_pos += d->m_total_lz_bytes; - d->m_total_lz_bytes = 0; - d->m_block_index++; - - if ((n = (int)(d->m_pOutput_buf - pOutput_buf_start)) != 0) - { - if (d->m_pPut_buf_func) - { - *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf; - if (!(*d->m_pPut_buf_func)(d->m_output_buf, n, d->m_pPut_buf_user)) - return (d->m_prev_return_status = TDEFL_STATUS_PUT_BUF_FAILED); - } - else if (pOutput_buf_start == d->m_output_buf) - { - int bytes_to_copy = (int)MZ_MIN((size_t)n, (size_t)(*d->m_pOut_buf_size - d->m_out_buf_ofs)); - memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf, bytes_to_copy); - d->m_out_buf_ofs += bytes_to_copy; - if ((n -= bytes_to_copy) != 0) - { - d->m_output_flush_ofs = bytes_to_copy; - d->m_output_flush_remaining = n; - } - } - else - { - d->m_out_buf_ofs += n; - } - } - - return d->m_output_flush_remaining; -} - -#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES -#ifdef MINIZ_UNALIGNED_USE_MEMCPY -static inline mz_uint16 TDEFL_READ_UNALIGNED_WORD(const mz_uint8* p) -{ - mz_uint16 ret; - memcpy(&ret, p, sizeof(mz_uint16)); - return ret; -} -static inline mz_uint16 TDEFL_READ_UNALIGNED_WORD2(const mz_uint16* p) -{ - mz_uint16 ret; - memcpy(&ret, p, sizeof(mz_uint16)); - return ret; -} -#else -#define TDEFL_READ_UNALIGNED_WORD(p) *(const mz_uint16 *)(p) -#define TDEFL_READ_UNALIGNED_WORD2(p) *(const mz_uint16 *)(p) -#endif -static MZ_FORCEINLINE void tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) -{ - mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; - mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; - const mz_uint16 *s = (const mz_uint16 *)(d->m_dict + pos), *p, *q; - mz_uint16 c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]), s01 = TDEFL_READ_UNALIGNED_WORD2(s); - MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); - if (max_match_len <= match_len) - return; - for (;;) - { - for (;;) - { - if (--num_probes_left == 0) - return; -#define TDEFL_PROBE \ - next_probe_pos = d->m_next[probe_pos]; \ - if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \ - return; \ - probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ - if (TDEFL_READ_UNALIGNED_WORD(&d->m_dict[probe_pos + match_len - 1]) == c01) \ - break; - TDEFL_PROBE; - TDEFL_PROBE; - TDEFL_PROBE; - } - if (!dist) - break; - q = (const mz_uint16 *)(d->m_dict + probe_pos); - if (TDEFL_READ_UNALIGNED_WORD2(q) != s01) - continue; - p = s; - probe_len = 32; - do - { - } while ((TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && - (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && (--probe_len > 0)); - if (!probe_len) - { - *pMatch_dist = dist; - *pMatch_len = MZ_MIN(max_match_len, (mz_uint)TDEFL_MAX_MATCH_LEN); - break; - } - else if ((probe_len = ((mz_uint)(p - s) * 2) + (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q)) > match_len) - { - *pMatch_dist = dist; - if ((*pMatch_len = match_len = MZ_MIN(max_match_len, probe_len)) == max_match_len) - break; - c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]); - } - } -} -#else -static MZ_FORCEINLINE void tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) -{ - mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; - mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; - const mz_uint8 *s = d->m_dict + pos, *p, *q; - mz_uint8 c0 = d->m_dict[pos + match_len], c1 = d->m_dict[pos + match_len - 1]; - MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); - if (max_match_len <= match_len) - return; - for (;;) - { - for (;;) - { - if (--num_probes_left == 0) - return; -#define TDEFL_PROBE \ - next_probe_pos = d->m_next[probe_pos]; \ - if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \ - return; \ - probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ - if ((d->m_dict[probe_pos + match_len] == c0) && (d->m_dict[probe_pos + match_len - 1] == c1)) \ - break; - TDEFL_PROBE; - TDEFL_PROBE; - TDEFL_PROBE; - } - if (!dist) - break; - p = s; - q = d->m_dict + probe_pos; - for (probe_len = 0; probe_len < max_match_len; probe_len++) - if (*p++ != *q++) - break; - if (probe_len > match_len) - { - *pMatch_dist = dist; - if ((*pMatch_len = match_len = probe_len) == max_match_len) - return; - c0 = d->m_dict[pos + match_len]; - c1 = d->m_dict[pos + match_len - 1]; - } - } -} -#endif /* #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES */ - -#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN -static mz_bool tdefl_compress_fast(tdefl_compressor *d) -{ - /* Faster, minimally featured LZRW1-style match+parse loop with better register utilization. Intended for applications where raw throughput is valued more highly than ratio. */ - mz_uint lookahead_pos = d->m_lookahead_pos, lookahead_size = d->m_lookahead_size, dict_size = d->m_dict_size, total_lz_bytes = d->m_total_lz_bytes, num_flags_left = d->m_num_flags_left; - mz_uint8 *pLZ_code_buf = d->m_pLZ_code_buf, *pLZ_flags = d->m_pLZ_flags; - mz_uint cur_pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; - - while ((d->m_src_buf_left) || ((d->m_flush) && (lookahead_size))) - { - const mz_uint TDEFL_COMP_FAST_LOOKAHEAD_SIZE = 4096; - mz_uint dst_pos = (lookahead_pos + lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; - mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(d->m_src_buf_left, TDEFL_COMP_FAST_LOOKAHEAD_SIZE - lookahead_size); - d->m_src_buf_left -= num_bytes_to_process; - lookahead_size += num_bytes_to_process; - - while (num_bytes_to_process) - { - mz_uint32 n = MZ_MIN(TDEFL_LZ_DICT_SIZE - dst_pos, num_bytes_to_process); - memcpy(d->m_dict + dst_pos, d->m_pSrc, n); - if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) - memcpy(d->m_dict + TDEFL_LZ_DICT_SIZE + dst_pos, d->m_pSrc, MZ_MIN(n, (TDEFL_MAX_MATCH_LEN - 1) - dst_pos)); - d->m_pSrc += n; - dst_pos = (dst_pos + n) & TDEFL_LZ_DICT_SIZE_MASK; - num_bytes_to_process -= n; - } - - dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - lookahead_size, dict_size); - if ((!d->m_flush) && (lookahead_size < TDEFL_COMP_FAST_LOOKAHEAD_SIZE)) - break; - - while (lookahead_size >= 4) - { - mz_uint cur_match_dist, cur_match_len = 1; - mz_uint8 *pCur_dict = d->m_dict + cur_pos; - mz_uint first_trigram = (*(const mz_uint32 *)pCur_dict) & 0xFFFFFF; - mz_uint hash = (first_trigram ^ (first_trigram >> (24 - (TDEFL_LZ_HASH_BITS - 8)))) & TDEFL_LEVEL1_HASH_SIZE_MASK; - mz_uint probe_pos = d->m_hash[hash]; - d->m_hash[hash] = (mz_uint16)lookahead_pos; - - if (((cur_match_dist = (mz_uint16)(lookahead_pos - probe_pos)) <= dict_size) && ((*(const mz_uint32 *)(d->m_dict + (probe_pos &= TDEFL_LZ_DICT_SIZE_MASK)) & 0xFFFFFF) == first_trigram)) - { - const mz_uint16 *p = (const mz_uint16 *)pCur_dict; - const mz_uint16 *q = (const mz_uint16 *)(d->m_dict + probe_pos); - mz_uint32 probe_len = 32; - do - { - } while ((TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && - (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && (--probe_len > 0)); - cur_match_len = ((mz_uint)(p - (const mz_uint16 *)pCur_dict) * 2) + (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q); - if (!probe_len) - cur_match_len = cur_match_dist ? TDEFL_MAX_MATCH_LEN : 0; - - if ((cur_match_len < TDEFL_MIN_MATCH_LEN) || ((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U * 1024U))) - { - cur_match_len = 1; - *pLZ_code_buf++ = (mz_uint8)first_trigram; - *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); - d->m_huff_count[0][(mz_uint8)first_trigram]++; - } - else - { - mz_uint32 s0, s1; - cur_match_len = MZ_MIN(cur_match_len, lookahead_size); - - MZ_ASSERT((cur_match_len >= TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 1) && (cur_match_dist <= TDEFL_LZ_DICT_SIZE)); - - cur_match_dist--; - - pLZ_code_buf[0] = (mz_uint8)(cur_match_len - TDEFL_MIN_MATCH_LEN); - *(mz_uint16 *)(&pLZ_code_buf[1]) = (mz_uint16)cur_match_dist; - pLZ_code_buf += 3; - *pLZ_flags = (mz_uint8)((*pLZ_flags >> 1) | 0x80); - - s0 = s_tdefl_small_dist_sym[cur_match_dist & 511]; - s1 = s_tdefl_large_dist_sym[cur_match_dist >> 8]; - d->m_huff_count[1][(cur_match_dist < 512) ? s0 : s1]++; - - d->m_huff_count[0][s_tdefl_len_sym[cur_match_len - TDEFL_MIN_MATCH_LEN]]++; - } - } - else - { - *pLZ_code_buf++ = (mz_uint8)first_trigram; - *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); - d->m_huff_count[0][(mz_uint8)first_trigram]++; - } - - if (--num_flags_left == 0) - { - num_flags_left = 8; - pLZ_flags = pLZ_code_buf++; - } - - total_lz_bytes += cur_match_len; - lookahead_pos += cur_match_len; - dict_size = MZ_MIN(dict_size + cur_match_len, (mz_uint)TDEFL_LZ_DICT_SIZE); - cur_pos = (cur_pos + cur_match_len) & TDEFL_LZ_DICT_SIZE_MASK; - MZ_ASSERT(lookahead_size >= cur_match_len); - lookahead_size -= cur_match_len; - - if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) - { - int n; - d->m_lookahead_pos = lookahead_pos; - d->m_lookahead_size = lookahead_size; - d->m_dict_size = dict_size; - d->m_total_lz_bytes = total_lz_bytes; - d->m_pLZ_code_buf = pLZ_code_buf; - d->m_pLZ_flags = pLZ_flags; - d->m_num_flags_left = num_flags_left; - if ((n = tdefl_flush_block(d, 0)) != 0) - return (n < 0) ? MZ_FALSE : MZ_TRUE; - total_lz_bytes = d->m_total_lz_bytes; - pLZ_code_buf = d->m_pLZ_code_buf; - pLZ_flags = d->m_pLZ_flags; - num_flags_left = d->m_num_flags_left; - } - } - - while (lookahead_size) - { - mz_uint8 lit = d->m_dict[cur_pos]; - - total_lz_bytes++; - *pLZ_code_buf++ = lit; - *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); - if (--num_flags_left == 0) - { - num_flags_left = 8; - pLZ_flags = pLZ_code_buf++; - } - - d->m_huff_count[0][lit]++; - - lookahead_pos++; - dict_size = MZ_MIN(dict_size + 1, (mz_uint)TDEFL_LZ_DICT_SIZE); - cur_pos = (cur_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; - lookahead_size--; - - if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) - { - int n; - d->m_lookahead_pos = lookahead_pos; - d->m_lookahead_size = lookahead_size; - d->m_dict_size = dict_size; - d->m_total_lz_bytes = total_lz_bytes; - d->m_pLZ_code_buf = pLZ_code_buf; - d->m_pLZ_flags = pLZ_flags; - d->m_num_flags_left = num_flags_left; - if ((n = tdefl_flush_block(d, 0)) != 0) - return (n < 0) ? MZ_FALSE : MZ_TRUE; - total_lz_bytes = d->m_total_lz_bytes; - pLZ_code_buf = d->m_pLZ_code_buf; - pLZ_flags = d->m_pLZ_flags; - num_flags_left = d->m_num_flags_left; - } - } - } - - d->m_lookahead_pos = lookahead_pos; - d->m_lookahead_size = lookahead_size; - d->m_dict_size = dict_size; - d->m_total_lz_bytes = total_lz_bytes; - d->m_pLZ_code_buf = pLZ_code_buf; - d->m_pLZ_flags = pLZ_flags; - d->m_num_flags_left = num_flags_left; - return MZ_TRUE; -} -#endif /* MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN */ - -static MZ_FORCEINLINE void tdefl_record_literal(tdefl_compressor *d, mz_uint8 lit) -{ - d->m_total_lz_bytes++; - *d->m_pLZ_code_buf++ = lit; - *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> 1); - if (--d->m_num_flags_left == 0) - { - d->m_num_flags_left = 8; - d->m_pLZ_flags = d->m_pLZ_code_buf++; - } - d->m_huff_count[0][lit]++; -} - -static MZ_FORCEINLINE void tdefl_record_match(tdefl_compressor *d, mz_uint match_len, mz_uint match_dist) -{ - mz_uint32 s0, s1; - - MZ_ASSERT((match_len >= TDEFL_MIN_MATCH_LEN) && (match_dist >= 1) && (match_dist <= TDEFL_LZ_DICT_SIZE)); - - d->m_total_lz_bytes += match_len; - - d->m_pLZ_code_buf[0] = (mz_uint8)(match_len - TDEFL_MIN_MATCH_LEN); - - match_dist -= 1; - d->m_pLZ_code_buf[1] = (mz_uint8)(match_dist & 0xFF); - d->m_pLZ_code_buf[2] = (mz_uint8)(match_dist >> 8); - d->m_pLZ_code_buf += 3; - - *d->m_pLZ_flags = (mz_uint8)((*d->m_pLZ_flags >> 1) | 0x80); - if (--d->m_num_flags_left == 0) - { - d->m_num_flags_left = 8; - d->m_pLZ_flags = d->m_pLZ_code_buf++; - } - - s0 = s_tdefl_small_dist_sym[match_dist & 511]; - s1 = s_tdefl_large_dist_sym[(match_dist >> 8) & 127]; - d->m_huff_count[1][(match_dist < 512) ? s0 : s1]++; - - if (match_len >= TDEFL_MIN_MATCH_LEN) - d->m_huff_count[0][s_tdefl_len_sym[match_len - TDEFL_MIN_MATCH_LEN]]++; -} - -static mz_bool tdefl_compress_normal(tdefl_compressor *d) -{ - const mz_uint8 *pSrc = d->m_pSrc; - size_t src_buf_left = d->m_src_buf_left; - tdefl_flush flush = d->m_flush; - - while ((src_buf_left) || ((flush) && (d->m_lookahead_size))) - { - mz_uint len_to_move, cur_match_dist, cur_match_len, cur_pos; - /* Update dictionary and hash chains. Keeps the lookahead size equal to TDEFL_MAX_MATCH_LEN. */ - if ((d->m_lookahead_size + d->m_dict_size) >= (TDEFL_MIN_MATCH_LEN - 1)) - { - mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK, ins_pos = d->m_lookahead_pos + d->m_lookahead_size - 2; - mz_uint hash = (d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK]; - mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(src_buf_left, TDEFL_MAX_MATCH_LEN - d->m_lookahead_size); - const mz_uint8 *pSrc_end = pSrc + num_bytes_to_process; - src_buf_left -= num_bytes_to_process; - d->m_lookahead_size += num_bytes_to_process; - while (pSrc != pSrc_end) - { - mz_uint8 c = *pSrc++; - d->m_dict[dst_pos] = c; - if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) - d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; - hash = ((hash << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); - d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; - d->m_hash[hash] = (mz_uint16)(ins_pos); - dst_pos = (dst_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; - ins_pos++; - } - } - else - { - while ((src_buf_left) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) - { - mz_uint8 c = *pSrc++; - mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; - src_buf_left--; - d->m_dict[dst_pos] = c; - if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) - d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; - if ((++d->m_lookahead_size + d->m_dict_size) >= TDEFL_MIN_MATCH_LEN) - { - mz_uint ins_pos = d->m_lookahead_pos + (d->m_lookahead_size - 1) - 2; - mz_uint hash = ((d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << (TDEFL_LZ_HASH_SHIFT * 2)) ^ (d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); - d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; - d->m_hash[hash] = (mz_uint16)(ins_pos); - } - } - } - d->m_dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - d->m_lookahead_size, d->m_dict_size); - if ((!flush) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) - break; - - /* Simple lazy/greedy parsing state machine. */ - len_to_move = 1; - cur_match_dist = 0; - cur_match_len = d->m_saved_match_len ? d->m_saved_match_len : (TDEFL_MIN_MATCH_LEN - 1); - cur_pos = d->m_lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; - if (d->m_flags & (TDEFL_RLE_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS)) - { - if ((d->m_dict_size) && (!(d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) - { - mz_uint8 c = d->m_dict[(cur_pos - 1) & TDEFL_LZ_DICT_SIZE_MASK]; - cur_match_len = 0; - while (cur_match_len < d->m_lookahead_size) - { - if (d->m_dict[cur_pos + cur_match_len] != c) - break; - cur_match_len++; - } - if (cur_match_len < TDEFL_MIN_MATCH_LEN) - cur_match_len = 0; - else - cur_match_dist = 1; - } - } - else - { - tdefl_find_match(d, d->m_lookahead_pos, d->m_dict_size, d->m_lookahead_size, &cur_match_dist, &cur_match_len); - } - if (((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U * 1024U)) || (cur_pos == cur_match_dist) || ((d->m_flags & TDEFL_FILTER_MATCHES) && (cur_match_len <= 5))) - { - cur_match_dist = cur_match_len = 0; - } - if (d->m_saved_match_len) - { - if (cur_match_len > d->m_saved_match_len) - { - tdefl_record_literal(d, (mz_uint8)d->m_saved_lit); - if (cur_match_len >= 128) - { - tdefl_record_match(d, cur_match_len, cur_match_dist); - d->m_saved_match_len = 0; - len_to_move = cur_match_len; - } - else - { - d->m_saved_lit = d->m_dict[cur_pos]; - d->m_saved_match_dist = cur_match_dist; - d->m_saved_match_len = cur_match_len; - } - } - else - { - tdefl_record_match(d, d->m_saved_match_len, d->m_saved_match_dist); - len_to_move = d->m_saved_match_len - 1; - d->m_saved_match_len = 0; - } - } - else if (!cur_match_dist) - tdefl_record_literal(d, d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]); - else if ((d->m_greedy_parsing) || (d->m_flags & TDEFL_RLE_MATCHES) || (cur_match_len >= 128)) - { - tdefl_record_match(d, cur_match_len, cur_match_dist); - len_to_move = cur_match_len; - } - else - { - d->m_saved_lit = d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]; - d->m_saved_match_dist = cur_match_dist; - d->m_saved_match_len = cur_match_len; - } - /* Move the lookahead forward by len_to_move bytes. */ - d->m_lookahead_pos += len_to_move; - MZ_ASSERT(d->m_lookahead_size >= len_to_move); - d->m_lookahead_size -= len_to_move; - d->m_dict_size = MZ_MIN(d->m_dict_size + len_to_move, (mz_uint)TDEFL_LZ_DICT_SIZE); - /* Check if it's time to flush the current LZ codes to the internal output buffer. */ - if ((d->m_pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) || - ((d->m_total_lz_bytes > 31 * 1024) && (((((mz_uint)(d->m_pLZ_code_buf - d->m_lz_code_buf) * 115) >> 7) >= d->m_total_lz_bytes) || (d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS)))) - { - int n; - d->m_pSrc = pSrc; - d->m_src_buf_left = src_buf_left; - if ((n = tdefl_flush_block(d, 0)) != 0) - return (n < 0) ? MZ_FALSE : MZ_TRUE; - } - } - - d->m_pSrc = pSrc; - d->m_src_buf_left = src_buf_left; - return MZ_TRUE; -} - -static tdefl_status tdefl_flush_output_buffer(tdefl_compressor *d) -{ - if (d->m_pIn_buf_size) - { - *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf; - } - - if (d->m_pOut_buf_size) - { - size_t n = MZ_MIN(*d->m_pOut_buf_size - d->m_out_buf_ofs, d->m_output_flush_remaining); - memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf + d->m_output_flush_ofs, n); - d->m_output_flush_ofs += (mz_uint)n; - d->m_output_flush_remaining -= (mz_uint)n; - d->m_out_buf_ofs += n; - - *d->m_pOut_buf_size = d->m_out_buf_ofs; - } - - return (d->m_finished && !d->m_output_flush_remaining) ? TDEFL_STATUS_DONE : TDEFL_STATUS_OKAY; -} - -tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush) -{ - if (!d) - { - if (pIn_buf_size) - *pIn_buf_size = 0; - if (pOut_buf_size) - *pOut_buf_size = 0; - return TDEFL_STATUS_BAD_PARAM; - } - - d->m_pIn_buf = pIn_buf; - d->m_pIn_buf_size = pIn_buf_size; - d->m_pOut_buf = pOut_buf; - d->m_pOut_buf_size = pOut_buf_size; - d->m_pSrc = (const mz_uint8 *)(pIn_buf); - d->m_src_buf_left = pIn_buf_size ? *pIn_buf_size : 0; - d->m_out_buf_ofs = 0; - d->m_flush = flush; - - if (((d->m_pPut_buf_func != NULL) == ((pOut_buf != NULL) || (pOut_buf_size != NULL))) || (d->m_prev_return_status != TDEFL_STATUS_OKAY) || - (d->m_wants_to_finish && (flush != TDEFL_FINISH)) || (pIn_buf_size && *pIn_buf_size && !pIn_buf) || (pOut_buf_size && *pOut_buf_size && !pOut_buf)) - { - if (pIn_buf_size) - *pIn_buf_size = 0; - if (pOut_buf_size) - *pOut_buf_size = 0; - return (d->m_prev_return_status = TDEFL_STATUS_BAD_PARAM); - } - d->m_wants_to_finish |= (flush == TDEFL_FINISH); - - if ((d->m_output_flush_remaining) || (d->m_finished)) - return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); - -#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN - if (((d->m_flags & TDEFL_MAX_PROBES_MASK) == 1) && - ((d->m_flags & TDEFL_GREEDY_PARSING_FLAG) != 0) && - ((d->m_flags & (TDEFL_FILTER_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS | TDEFL_RLE_MATCHES)) == 0)) - { - if (!tdefl_compress_fast(d)) - return d->m_prev_return_status; - } - else -#endif /* #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN */ - { - if (!tdefl_compress_normal(d)) - return d->m_prev_return_status; - } - - if ((d->m_flags & (TDEFL_WRITE_ZLIB_HEADER | TDEFL_COMPUTE_ADLER32)) && (pIn_buf)) - d->m_adler32 = (mz_uint32)mz_adler32(d->m_adler32, (const mz_uint8 *)pIn_buf, d->m_pSrc - (const mz_uint8 *)pIn_buf); - - if ((flush) && (!d->m_lookahead_size) && (!d->m_src_buf_left) && (!d->m_output_flush_remaining)) - { - if (tdefl_flush_block(d, flush) < 0) - return d->m_prev_return_status; - d->m_finished = (flush == TDEFL_FINISH); - if (flush == TDEFL_FULL_FLUSH) - { - MZ_CLEAR_OBJ(d->m_hash); - MZ_CLEAR_OBJ(d->m_next); - d->m_dict_size = 0; - } - } - - return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); -} - -tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush) -{ - MZ_ASSERT(d->m_pPut_buf_func); - return tdefl_compress(d, pIn_buf, &in_buf_size, NULL, NULL, flush); -} - -tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) -{ - d->m_pPut_buf_func = pPut_buf_func; - d->m_pPut_buf_user = pPut_buf_user; - d->m_flags = (mz_uint)(flags); - d->m_max_probes[0] = 1 + ((flags & 0xFFF) + 2) / 3; - d->m_greedy_parsing = (flags & TDEFL_GREEDY_PARSING_FLAG) != 0; - d->m_max_probes[1] = 1 + (((flags & 0xFFF) >> 2) + 2) / 3; - if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG)) - MZ_CLEAR_OBJ(d->m_hash); - d->m_lookahead_pos = d->m_lookahead_size = d->m_dict_size = d->m_total_lz_bytes = d->m_lz_code_buf_dict_pos = d->m_bits_in = 0; - d->m_output_flush_ofs = d->m_output_flush_remaining = d->m_finished = d->m_block_index = d->m_bit_buffer = d->m_wants_to_finish = 0; - d->m_pLZ_code_buf = d->m_lz_code_buf + 1; - d->m_pLZ_flags = d->m_lz_code_buf; - d->m_num_flags_left = 8; - d->m_pOutput_buf = d->m_output_buf; - d->m_pOutput_buf_end = d->m_output_buf; - d->m_prev_return_status = TDEFL_STATUS_OKAY; - d->m_saved_match_dist = d->m_saved_match_len = d->m_saved_lit = 0; - d->m_adler32 = 1; - d->m_pIn_buf = NULL; - d->m_pOut_buf = NULL; - d->m_pIn_buf_size = NULL; - d->m_pOut_buf_size = NULL; - d->m_flush = TDEFL_NO_FLUSH; - d->m_pSrc = NULL; - d->m_src_buf_left = 0; - d->m_out_buf_ofs = 0; - if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG)) - MZ_CLEAR_OBJ(d->m_dict); - memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); - memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); - return TDEFL_STATUS_OKAY; -} - -tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d) -{ - return d->m_prev_return_status; -} - -mz_uint32 tdefl_get_adler32(tdefl_compressor *d) -{ - return d->m_adler32; -} - -mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) -{ - tdefl_compressor *pComp; - mz_bool succeeded; - if (((buf_len) && (!pBuf)) || (!pPut_buf_func)) - return MZ_FALSE; - pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); - if (!pComp) - return MZ_FALSE; - succeeded = (tdefl_init(pComp, pPut_buf_func, pPut_buf_user, flags) == TDEFL_STATUS_OKAY); - succeeded = succeeded && (tdefl_compress_buffer(pComp, pBuf, buf_len, TDEFL_FINISH) == TDEFL_STATUS_DONE); - MZ_FREE(pComp); - return succeeded; -} - -typedef struct -{ - size_t m_size, m_capacity; - mz_uint8 *m_pBuf; - mz_bool m_expandable; -} tdefl_output_buffer; - -static mz_bool tdefl_output_buffer_putter(const void *pBuf, int len, void *pUser) -{ - tdefl_output_buffer *p = (tdefl_output_buffer *)pUser; - size_t new_size = p->m_size + len; - if (new_size > p->m_capacity) - { - size_t new_capacity = p->m_capacity; - mz_uint8 *pNew_buf; - if (!p->m_expandable) - return MZ_FALSE; - do - { - new_capacity = MZ_MAX(128U, new_capacity << 1U); - } while (new_size > new_capacity); - pNew_buf = (mz_uint8 *)MZ_REALLOC(p->m_pBuf, new_capacity); - if (!pNew_buf) - return MZ_FALSE; - p->m_pBuf = pNew_buf; - p->m_capacity = new_capacity; - } - memcpy((mz_uint8 *)p->m_pBuf + p->m_size, pBuf, len); - p->m_size = new_size; - return MZ_TRUE; -} - -void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) -{ - tdefl_output_buffer out_buf; - MZ_CLEAR_OBJ(out_buf); - if (!pOut_len) - return MZ_FALSE; - else - *pOut_len = 0; - out_buf.m_expandable = MZ_TRUE; - if (!tdefl_compress_mem_to_output(pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) - return NULL; - *pOut_len = out_buf.m_size; - return out_buf.m_pBuf; -} - -size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags) -{ - tdefl_output_buffer out_buf; - MZ_CLEAR_OBJ(out_buf); - if (!pOut_buf) - return 0; - out_buf.m_pBuf = (mz_uint8 *)pOut_buf; - out_buf.m_capacity = out_buf_len; - if (!tdefl_compress_mem_to_output(pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) - return 0; - return out_buf.m_size; -} - -static const mz_uint s_tdefl_num_probes[11] = { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500 }; - -/* level may actually range from [0,10] (10 is a "hidden" max level, where we want a bit more compression and it's fine if throughput to fall off a cliff on some files). */ -mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy) -{ - mz_uint comp_flags = s_tdefl_num_probes[(level >= 0) ? MZ_MIN(10, level) : MZ_DEFAULT_LEVEL] | ((level <= 3) ? TDEFL_GREEDY_PARSING_FLAG : 0); - if (window_bits > 0) - comp_flags |= TDEFL_WRITE_ZLIB_HEADER; - - if (!level) - comp_flags |= TDEFL_FORCE_ALL_RAW_BLOCKS; - else if (strategy == MZ_FILTERED) - comp_flags |= TDEFL_FILTER_MATCHES; - else if (strategy == MZ_HUFFMAN_ONLY) - comp_flags &= ~TDEFL_MAX_PROBES_MASK; - else if (strategy == MZ_FIXED) - comp_flags |= TDEFL_FORCE_ALL_STATIC_BLOCKS; - else if (strategy == MZ_RLE) - comp_flags |= TDEFL_RLE_MATCHES; - - return comp_flags; -} - -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable : 4204) /* nonstandard extension used : non-constant aggregate initializer (also supported by GNU C and C99, so no big deal) */ -#endif - -/* Simple PNG writer function by Alex Evans, 2011. Released into the public domain: https://gist.github.com/908299, more context at - http://altdevblogaday.org/2011/04/06/a-smaller-jpg-encoder/. - This is actually a modification of Alex's original code so PNG files generated by this function pass pngcheck. */ -void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip) -{ - /* Using a local copy of this array here in case MINIZ_NO_ZLIB_APIS was defined. */ - static const mz_uint s_tdefl_png_num_probes[11] = { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500 }; - tdefl_compressor *pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); - tdefl_output_buffer out_buf; - int i, bpl = w * num_chans, y, z; - mz_uint32 c; - *pLen_out = 0; - if (!pComp) - return NULL; - MZ_CLEAR_OBJ(out_buf); - out_buf.m_expandable = MZ_TRUE; - out_buf.m_capacity = 57 + MZ_MAX(64, (1 + bpl) * h); - if (NULL == (out_buf.m_pBuf = (mz_uint8 *)MZ_MALLOC(out_buf.m_capacity))) - { - MZ_FREE(pComp); - return NULL; - } - /* write dummy header */ - for (z = 41; z; --z) - tdefl_output_buffer_putter(&z, 1, &out_buf); - /* compress image data */ - tdefl_init(pComp, tdefl_output_buffer_putter, &out_buf, s_tdefl_png_num_probes[MZ_MIN(10, level)] | TDEFL_WRITE_ZLIB_HEADER); - for (y = 0; y < h; ++y) - { - tdefl_compress_buffer(pComp, &z, 1, TDEFL_NO_FLUSH); - tdefl_compress_buffer(pComp, (mz_uint8 *)pImage + (flip ? (h - 1 - y) : y) * bpl, bpl, TDEFL_NO_FLUSH); - } - if (tdefl_compress_buffer(pComp, NULL, 0, TDEFL_FINISH) != TDEFL_STATUS_DONE) - { - MZ_FREE(pComp); - MZ_FREE(out_buf.m_pBuf); - return NULL; - } - /* write real header */ - *pLen_out = out_buf.m_size - 41; - { - static const mz_uint8 chans[] = { 0x00, 0x00, 0x04, 0x02, 0x06 }; - mz_uint8 pnghdr[41] = { 0x89, 0x50, 0x4e, 0x47, 0x0d, - 0x0a, 0x1a, 0x0a, 0x00, 0x00, - 0x00, 0x0d, 0x49, 0x48, 0x44, - 0x52, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x08, - 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x49, 0x44, 0x41, - 0x54 }; - pnghdr[18] = (mz_uint8)(w >> 8); - pnghdr[19] = (mz_uint8)w; - pnghdr[22] = (mz_uint8)(h >> 8); - pnghdr[23] = (mz_uint8)h; - pnghdr[25] = chans[num_chans]; - pnghdr[33] = (mz_uint8)(*pLen_out >> 24); - pnghdr[34] = (mz_uint8)(*pLen_out >> 16); - pnghdr[35] = (mz_uint8)(*pLen_out >> 8); - pnghdr[36] = (mz_uint8)*pLen_out; - c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, pnghdr + 12, 17); - for (i = 0; i < 4; ++i, c <<= 8) - ((mz_uint8 *)(pnghdr + 29))[i] = (mz_uint8)(c >> 24); - memcpy(out_buf.m_pBuf, pnghdr, 41); - } - /* write footer (IDAT CRC-32, followed by IEND chunk) */ - if (!tdefl_output_buffer_putter("\0\0\0\0\0\0\0\0\x49\x45\x4e\x44\xae\x42\x60\x82", 16, &out_buf)) - { - *pLen_out = 0; - MZ_FREE(pComp); - MZ_FREE(out_buf.m_pBuf); - return NULL; - } - c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, out_buf.m_pBuf + 41 - 4, *pLen_out + 4); - for (i = 0; i < 4; ++i, c <<= 8) - (out_buf.m_pBuf + out_buf.m_size - 16)[i] = (mz_uint8)(c >> 24); - /* compute final size of file, grab compressed data buffer and return */ - *pLen_out += 57; - MZ_FREE(pComp); - return out_buf.m_pBuf; -} -void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out) -{ - /* Level 6 corresponds to TDEFL_DEFAULT_MAX_PROBES or MZ_DEFAULT_LEVEL (but we can't depend on MZ_DEFAULT_LEVEL being available in case the zlib API's where #defined out) */ - return tdefl_write_image_to_png_file_in_memory_ex(pImage, w, h, num_chans, pLen_out, 6, MZ_FALSE); -} - -/* Allocate the tdefl_compressor and tinfl_decompressor structures in C so that */ -/* non-C language bindings to tdefL_ and tinfl_ API don't need to worry about */ -/* structure size and allocation mechanism. */ -tdefl_compressor *tdefl_compressor_alloc() -{ - return (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); -} - -void tdefl_compressor_free(tdefl_compressor *pComp) -{ - MZ_FREE(pComp); -} - -#ifdef _MSC_VER -#pragma warning(pop) -#endif - -#ifdef __cplusplus -} -#endif -/************************************************************************** - * - * Copyright 2013-2014 RAD Game Tools and Valve Software - * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC - * All Rights Reserved. - * - * 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. - * - **************************************************************************/ - - - -#ifdef __cplusplus -extern "C" { -#endif - -/* ------------------- Low-level Decompression (completely independent from all compression API's) */ - -#define TINFL_MEMCPY(d, s, l) memcpy(d, s, l) -#define TINFL_MEMSET(p, c, l) memset(p, c, l) - -#define TINFL_CR_BEGIN \ - switch (r->m_state) \ - { \ - case 0: -#define TINFL_CR_RETURN(state_index, result) \ - do \ - { \ - status = result; \ - r->m_state = state_index; \ - goto common_exit; \ - case state_index:; \ - } \ - MZ_MACRO_END -#define TINFL_CR_RETURN_FOREVER(state_index, result) \ - do \ - { \ - for (;;) \ - { \ - TINFL_CR_RETURN(state_index, result); \ - } \ - } \ - MZ_MACRO_END -#define TINFL_CR_FINISH } - -#define TINFL_GET_BYTE(state_index, c) \ - do \ - { \ - while (pIn_buf_cur >= pIn_buf_end) \ - { \ - TINFL_CR_RETURN(state_index, (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) ? TINFL_STATUS_NEEDS_MORE_INPUT : TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS); \ - } \ - c = *pIn_buf_cur++; \ - } \ - MZ_MACRO_END - -#define TINFL_NEED_BITS(state_index, n) \ - do \ - { \ - mz_uint c; \ - TINFL_GET_BYTE(state_index, c); \ - bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \ - num_bits += 8; \ - } while (num_bits < (mz_uint)(n)) -#define TINFL_SKIP_BITS(state_index, n) \ - do \ - { \ - if (num_bits < (mz_uint)(n)) \ - { \ - TINFL_NEED_BITS(state_index, n); \ - } \ - bit_buf >>= (n); \ - num_bits -= (n); \ - } \ - MZ_MACRO_END -#define TINFL_GET_BITS(state_index, b, n) \ - do \ - { \ - if (num_bits < (mz_uint)(n)) \ - { \ - TINFL_NEED_BITS(state_index, n); \ - } \ - b = bit_buf & ((1 << (n)) - 1); \ - bit_buf >>= (n); \ - num_bits -= (n); \ - } \ - MZ_MACRO_END - -/* TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes remaining in the input buffer falls below 2. */ -/* It reads just enough bytes from the input stream that are needed to decode the next Huffman code (and absolutely no more). It works by trying to fully decode a */ -/* Huffman code by using whatever bits are currently present in the bit buffer. If this fails, it reads another byte, and tries again until it succeeds or until the */ -/* bit buffer contains >=15 bits (deflate's max. Huffman code size). */ -#define TINFL_HUFF_BITBUF_FILL(state_index, pHuff) \ - do \ - { \ - temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \ - if (temp >= 0) \ - { \ - code_len = temp >> 9; \ - if ((code_len) && (num_bits >= code_len)) \ - break; \ - } \ - else if (num_bits > TINFL_FAST_LOOKUP_BITS) \ - { \ - code_len = TINFL_FAST_LOOKUP_BITS; \ - do \ - { \ - temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \ - } while ((temp < 0) && (num_bits >= (code_len + 1))); \ - if (temp >= 0) \ - break; \ - } \ - TINFL_GET_BYTE(state_index, c); \ - bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \ - num_bits += 8; \ - } while (num_bits < 15); - -/* TINFL_HUFF_DECODE() decodes the next Huffman coded symbol. It's more complex than you would initially expect because the zlib API expects the decompressor to never read */ -/* beyond the final byte of the deflate stream. (In other words, when this macro wants to read another byte from the input, it REALLY needs another byte in order to fully */ -/* decode the next Huffman code.) Handling this properly is particularly important on raw deflate (non-zlib) streams, which aren't followed by a byte aligned adler-32. */ -/* The slow path is only executed at the very end of the input buffer. */ -/* v1.16: The original macro handled the case at the very end of the passed-in input buffer, but we also need to handle the case where the user passes in 1+zillion bytes */ -/* following the deflate data and our non-conservative read-ahead path won't kick in here on this code. This is much trickier. */ -#define TINFL_HUFF_DECODE(state_index, sym, pHuff) \ - do \ - { \ - int temp; \ - mz_uint code_len, c; \ - if (num_bits < 15) \ - { \ - if ((pIn_buf_end - pIn_buf_cur) < 2) \ - { \ - TINFL_HUFF_BITBUF_FILL(state_index, pHuff); \ - } \ - else \ - { \ - bit_buf |= (((tinfl_bit_buf_t)pIn_buf_cur[0]) << num_bits) | (((tinfl_bit_buf_t)pIn_buf_cur[1]) << (num_bits + 8)); \ - pIn_buf_cur += 2; \ - num_bits += 16; \ - } \ - } \ - if ((temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) \ - code_len = temp >> 9, temp &= 511; \ - else \ - { \ - code_len = TINFL_FAST_LOOKUP_BITS; \ - do \ - { \ - temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \ - } while (temp < 0); \ - } \ - sym = temp; \ - bit_buf >>= code_len; \ - num_bits -= code_len; \ - } \ - MZ_MACRO_END - -tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags) -{ - static const int s_length_base[31] = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 }; - static const int s_length_extra[31] = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 0, 0 }; - static const int s_dist_base[32] = { 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0 }; - static const int s_dist_extra[32] = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 }; - static const mz_uint8 s_length_dezigzag[19] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; - static const int s_min_table_sizes[3] = { 257, 1, 4 }; - - tinfl_status status = TINFL_STATUS_FAILED; - mz_uint32 num_bits, dist, counter, num_extra; - tinfl_bit_buf_t bit_buf; - const mz_uint8 *pIn_buf_cur = pIn_buf_next, *const pIn_buf_end = pIn_buf_next + *pIn_buf_size; - mz_uint8 *pOut_buf_cur = pOut_buf_next, *const pOut_buf_end = pOut_buf_next + *pOut_buf_size; - size_t out_buf_size_mask = (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF) ? (size_t)-1 : ((pOut_buf_next - pOut_buf_start) + *pOut_buf_size) - 1, dist_from_out_buf_start; - - /* Ensure the output buffer's size is a power of 2, unless the output buffer is large enough to hold the entire output file (in which case it doesn't matter). */ - if (((out_buf_size_mask + 1) & out_buf_size_mask) || (pOut_buf_next < pOut_buf_start)) - { - *pIn_buf_size = *pOut_buf_size = 0; - return TINFL_STATUS_BAD_PARAM; - } - - num_bits = r->m_num_bits; - bit_buf = r->m_bit_buf; - dist = r->m_dist; - counter = r->m_counter; - num_extra = r->m_num_extra; - dist_from_out_buf_start = r->m_dist_from_out_buf_start; - TINFL_CR_BEGIN - - bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0; - r->m_z_adler32 = r->m_check_adler32 = 1; - if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) - { - TINFL_GET_BYTE(1, r->m_zhdr0); - TINFL_GET_BYTE(2, r->m_zhdr1); - counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) || (r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8)); - if (!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) - counter |= (((1U << (8U + (r->m_zhdr0 >> 4))) > 32768U) || ((out_buf_size_mask + 1) < (size_t)(1U << (8U + (r->m_zhdr0 >> 4))))); - if (counter) - { - TINFL_CR_RETURN_FOREVER(36, TINFL_STATUS_FAILED); - } - } - - do - { - TINFL_GET_BITS(3, r->m_final, 3); - r->m_type = r->m_final >> 1; - if (r->m_type == 0) - { - TINFL_SKIP_BITS(5, num_bits & 7); - for (counter = 0; counter < 4; ++counter) - { - if (num_bits) - TINFL_GET_BITS(6, r->m_raw_header[counter], 8); - else - TINFL_GET_BYTE(7, r->m_raw_header[counter]); - } - if ((counter = (r->m_raw_header[0] | (r->m_raw_header[1] << 8))) != (mz_uint)(0xFFFF ^ (r->m_raw_header[2] | (r->m_raw_header[3] << 8)))) - { - TINFL_CR_RETURN_FOREVER(39, TINFL_STATUS_FAILED); - } - while ((counter) && (num_bits)) - { - TINFL_GET_BITS(51, dist, 8); - while (pOut_buf_cur >= pOut_buf_end) - { - TINFL_CR_RETURN(52, TINFL_STATUS_HAS_MORE_OUTPUT); - } - *pOut_buf_cur++ = (mz_uint8)dist; - counter--; - } - while (counter) - { - size_t n; - while (pOut_buf_cur >= pOut_buf_end) - { - TINFL_CR_RETURN(9, TINFL_STATUS_HAS_MORE_OUTPUT); - } - while (pIn_buf_cur >= pIn_buf_end) - { - TINFL_CR_RETURN(38, (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) ? TINFL_STATUS_NEEDS_MORE_INPUT : TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS); - } - n = MZ_MIN(MZ_MIN((size_t)(pOut_buf_end - pOut_buf_cur), (size_t)(pIn_buf_end - pIn_buf_cur)), counter); - TINFL_MEMCPY(pOut_buf_cur, pIn_buf_cur, n); - pIn_buf_cur += n; - pOut_buf_cur += n; - counter -= (mz_uint)n; - } - } - else if (r->m_type == 3) - { - TINFL_CR_RETURN_FOREVER(10, TINFL_STATUS_FAILED); - } - else - { - if (r->m_type == 1) - { - mz_uint8 *p = r->m_tables[0].m_code_size; - mz_uint i; - r->m_table_sizes[0] = 288; - r->m_table_sizes[1] = 32; - TINFL_MEMSET(r->m_tables[1].m_code_size, 5, 32); - for (i = 0; i <= 143; ++i) - *p++ = 8; - for (; i <= 255; ++i) - *p++ = 9; - for (; i <= 279; ++i) - *p++ = 7; - for (; i <= 287; ++i) - *p++ = 8; - } - else - { - for (counter = 0; counter < 3; counter++) - { - TINFL_GET_BITS(11, r->m_table_sizes[counter], "\05\05\04"[counter]); - r->m_table_sizes[counter] += s_min_table_sizes[counter]; - } - MZ_CLEAR_OBJ(r->m_tables[2].m_code_size); - for (counter = 0; counter < r->m_table_sizes[2]; counter++) - { - mz_uint s; - TINFL_GET_BITS(14, s, 3); - r->m_tables[2].m_code_size[s_length_dezigzag[counter]] = (mz_uint8)s; - } - r->m_table_sizes[2] = 19; - } - for (; (int)r->m_type >= 0; r->m_type--) - { - int tree_next, tree_cur; - tinfl_huff_table *pTable; - mz_uint i, j, used_syms, total, sym_index, next_code[17], total_syms[16]; - pTable = &r->m_tables[r->m_type]; - MZ_CLEAR_OBJ(total_syms); - MZ_CLEAR_OBJ(pTable->m_look_up); - MZ_CLEAR_OBJ(pTable->m_tree); - for (i = 0; i < r->m_table_sizes[r->m_type]; ++i) - total_syms[pTable->m_code_size[i]]++; - used_syms = 0, total = 0; - next_code[0] = next_code[1] = 0; - for (i = 1; i <= 15; ++i) - { - used_syms += total_syms[i]; - next_code[i + 1] = (total = ((total + total_syms[i]) << 1)); - } - if ((65536 != total) && (used_syms > 1)) - { - TINFL_CR_RETURN_FOREVER(35, TINFL_STATUS_FAILED); - } - for (tree_next = -1, sym_index = 0; sym_index < r->m_table_sizes[r->m_type]; ++sym_index) - { - mz_uint rev_code = 0, l, cur_code, code_size = pTable->m_code_size[sym_index]; - if (!code_size) - continue; - cur_code = next_code[code_size]++; - for (l = code_size; l > 0; l--, cur_code >>= 1) - rev_code = (rev_code << 1) | (cur_code & 1); - if (code_size <= TINFL_FAST_LOOKUP_BITS) - { - mz_int16 k = (mz_int16)((code_size << 9) | sym_index); - while (rev_code < TINFL_FAST_LOOKUP_SIZE) - { - pTable->m_look_up[rev_code] = k; - rev_code += (1 << code_size); - } - continue; - } - if (0 == (tree_cur = pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)])) - { - pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)] = (mz_int16)tree_next; - tree_cur = tree_next; - tree_next -= 2; - } - rev_code >>= (TINFL_FAST_LOOKUP_BITS - 1); - for (j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--) - { - tree_cur -= ((rev_code >>= 1) & 1); - if (!pTable->m_tree[-tree_cur - 1]) - { - pTable->m_tree[-tree_cur - 1] = (mz_int16)tree_next; - tree_cur = tree_next; - tree_next -= 2; - } - else - tree_cur = pTable->m_tree[-tree_cur - 1]; - } - tree_cur -= ((rev_code >>= 1) & 1); - pTable->m_tree[-tree_cur - 1] = (mz_int16)sym_index; - } - if (r->m_type == 2) - { - for (counter = 0; counter < (r->m_table_sizes[0] + r->m_table_sizes[1]);) - { - mz_uint s; - TINFL_HUFF_DECODE(16, dist, &r->m_tables[2]); - if (dist < 16) - { - r->m_len_codes[counter++] = (mz_uint8)dist; - continue; - } - if ((dist == 16) && (!counter)) - { - TINFL_CR_RETURN_FOREVER(17, TINFL_STATUS_FAILED); - } - num_extra = "\02\03\07"[dist - 16]; - TINFL_GET_BITS(18, s, num_extra); - s += "\03\03\013"[dist - 16]; - TINFL_MEMSET(r->m_len_codes + counter, (dist == 16) ? r->m_len_codes[counter - 1] : 0, s); - counter += s; - } - if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != counter) - { - TINFL_CR_RETURN_FOREVER(21, TINFL_STATUS_FAILED); - } - TINFL_MEMCPY(r->m_tables[0].m_code_size, r->m_len_codes, r->m_table_sizes[0]); - TINFL_MEMCPY(r->m_tables[1].m_code_size, r->m_len_codes + r->m_table_sizes[0], r->m_table_sizes[1]); - } - } - for (;;) - { - mz_uint8 *pSrc; - for (;;) - { - if (((pIn_buf_end - pIn_buf_cur) < 4) || ((pOut_buf_end - pOut_buf_cur) < 2)) - { - TINFL_HUFF_DECODE(23, counter, &r->m_tables[0]); - if (counter >= 256) - break; - while (pOut_buf_cur >= pOut_buf_end) - { - TINFL_CR_RETURN(24, TINFL_STATUS_HAS_MORE_OUTPUT); - } - *pOut_buf_cur++ = (mz_uint8)counter; - } - else - { - int sym2; - mz_uint code_len; -#if TINFL_USE_64BIT_BITBUF - if (num_bits < 30) - { - bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE32(pIn_buf_cur)) << num_bits); - pIn_buf_cur += 4; - num_bits += 32; - } -#else - if (num_bits < 15) - { - bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); - pIn_buf_cur += 2; - num_bits += 16; - } -#endif - if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) - code_len = sym2 >> 9; - else - { - code_len = TINFL_FAST_LOOKUP_BITS; - do - { - sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; - } while (sym2 < 0); - } - counter = sym2; - bit_buf >>= code_len; - num_bits -= code_len; - if (counter & 256) - break; - -#if !TINFL_USE_64BIT_BITBUF - if (num_bits < 15) - { - bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); - pIn_buf_cur += 2; - num_bits += 16; - } -#endif - if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) - code_len = sym2 >> 9; - else - { - code_len = TINFL_FAST_LOOKUP_BITS; - do - { - sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; - } while (sym2 < 0); - } - bit_buf >>= code_len; - num_bits -= code_len; - - pOut_buf_cur[0] = (mz_uint8)counter; - if (sym2 & 256) - { - pOut_buf_cur++; - counter = sym2; - break; - } - pOut_buf_cur[1] = (mz_uint8)sym2; - pOut_buf_cur += 2; - } - } - if ((counter &= 511) == 256) - break; - - num_extra = s_length_extra[counter - 257]; - counter = s_length_base[counter - 257]; - if (num_extra) - { - mz_uint extra_bits; - TINFL_GET_BITS(25, extra_bits, num_extra); - counter += extra_bits; - } - - TINFL_HUFF_DECODE(26, dist, &r->m_tables[1]); - num_extra = s_dist_extra[dist]; - dist = s_dist_base[dist]; - if (num_extra) - { - mz_uint extra_bits; - TINFL_GET_BITS(27, extra_bits, num_extra); - dist += extra_bits; - } - - dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start; - if ((dist > dist_from_out_buf_start) && (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) - { - TINFL_CR_RETURN_FOREVER(37, TINFL_STATUS_FAILED); - } - - pSrc = pOut_buf_start + ((dist_from_out_buf_start - dist) & out_buf_size_mask); - - if ((MZ_MAX(pOut_buf_cur, pSrc) + counter) > pOut_buf_end) - { - while (counter--) - { - while (pOut_buf_cur >= pOut_buf_end) - { - TINFL_CR_RETURN(53, TINFL_STATUS_HAS_MORE_OUTPUT); - } - *pOut_buf_cur++ = pOut_buf_start[(dist_from_out_buf_start++ - dist) & out_buf_size_mask]; - } - continue; - } -#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES - else if ((counter >= 9) && (counter <= dist)) - { - const mz_uint8 *pSrc_end = pSrc + (counter & ~7); - do - { - ((mz_uint32 *)pOut_buf_cur)[0] = ((const mz_uint32 *)pSrc)[0]; - ((mz_uint32 *)pOut_buf_cur)[1] = ((const mz_uint32 *)pSrc)[1]; - pOut_buf_cur += 8; - } while ((pSrc += 8) < pSrc_end); - if ((counter &= 7) < 3) - { - if (counter) - { - pOut_buf_cur[0] = pSrc[0]; - if (counter > 1) - pOut_buf_cur[1] = pSrc[1]; - pOut_buf_cur += counter; - } - continue; - } - } -#endif - do - { - pOut_buf_cur[0] = pSrc[0]; - pOut_buf_cur[1] = pSrc[1]; - pOut_buf_cur[2] = pSrc[2]; - pOut_buf_cur += 3; - pSrc += 3; - } while ((int)(counter -= 3) > 2); - if ((int)counter > 0) - { - pOut_buf_cur[0] = pSrc[0]; - if ((int)counter > 1) - pOut_buf_cur[1] = pSrc[1]; - pOut_buf_cur += counter; - } - } - } - } while (!(r->m_final & 1)); - - /* Ensure byte alignment and put back any bytes from the bitbuf if we've looked ahead too far on gzip, or other Deflate streams followed by arbitrary data. */ - /* I'm being super conservative here. A number of simplifications can be made to the byte alignment part, and the Adler32 check shouldn't ever need to worry about reading from the bitbuf now. */ - TINFL_SKIP_BITS(32, num_bits & 7); - while ((pIn_buf_cur > pIn_buf_next) && (num_bits >= 8)) - { - --pIn_buf_cur; - num_bits -= 8; - } - bit_buf &= (tinfl_bit_buf_t)((((mz_uint64)1) << num_bits) - (mz_uint64)1); - MZ_ASSERT(!num_bits); /* if this assert fires then we've read beyond the end of non-deflate/zlib streams with following data (such as gzip streams). */ - - if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) - { - for (counter = 0; counter < 4; ++counter) - { - mz_uint s; - if (num_bits) - TINFL_GET_BITS(41, s, 8); - else - TINFL_GET_BYTE(42, s); - r->m_z_adler32 = (r->m_z_adler32 << 8) | s; - } - } - TINFL_CR_RETURN_FOREVER(34, TINFL_STATUS_DONE); - - TINFL_CR_FINISH - -common_exit: - /* As long as we aren't telling the caller that we NEED more input to make forward progress: */ - /* Put back any bytes from the bitbuf in case we've looked ahead too far on gzip, or other Deflate streams followed by arbitrary data. */ - /* We need to be very careful here to NOT push back any bytes we definitely know we need to make forward progress, though, or we'll lock the caller up into an inf loop. */ - if ((status != TINFL_STATUS_NEEDS_MORE_INPUT) && (status != TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS)) - { - while ((pIn_buf_cur > pIn_buf_next) && (num_bits >= 8)) - { - --pIn_buf_cur; - num_bits -= 8; - } - } - r->m_num_bits = num_bits; - r->m_bit_buf = bit_buf & (tinfl_bit_buf_t)((((mz_uint64)1) << num_bits) - (mz_uint64)1); - r->m_dist = dist; - r->m_counter = counter; - r->m_num_extra = num_extra; - r->m_dist_from_out_buf_start = dist_from_out_buf_start; - *pIn_buf_size = pIn_buf_cur - pIn_buf_next; - *pOut_buf_size = pOut_buf_cur - pOut_buf_next; - if ((decomp_flags & (TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) && (status >= 0)) - { - const mz_uint8 *ptr = pOut_buf_next; - size_t buf_len = *pOut_buf_size; - mz_uint32 i, s1 = r->m_check_adler32 & 0xffff, s2 = r->m_check_adler32 >> 16; - size_t block_len = buf_len % 5552; - while (buf_len) - { - for (i = 0; i + 7 < block_len; i += 8, ptr += 8) - { - s1 += ptr[0], s2 += s1; - s1 += ptr[1], s2 += s1; - s1 += ptr[2], s2 += s1; - s1 += ptr[3], s2 += s1; - s1 += ptr[4], s2 += s1; - s1 += ptr[5], s2 += s1; - s1 += ptr[6], s2 += s1; - s1 += ptr[7], s2 += s1; - } - for (; i < block_len; ++i) - s1 += *ptr++, s2 += s1; - s1 %= 65521U, s2 %= 65521U; - buf_len -= block_len; - block_len = 5552; - } - r->m_check_adler32 = (s2 << 16) + s1; - if ((status == TINFL_STATUS_DONE) && (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) && (r->m_check_adler32 != r->m_z_adler32)) - status = TINFL_STATUS_ADLER32_MISMATCH; - } - return status; -} - -/* Higher level helper functions. */ -void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) -{ - tinfl_decompressor decomp; - void *pBuf = NULL, *pNew_buf; - size_t src_buf_ofs = 0, out_buf_capacity = 0; - *pOut_len = 0; - tinfl_init(&decomp); - for (;;) - { - size_t src_buf_size = src_buf_len - src_buf_ofs, dst_buf_size = out_buf_capacity - *pOut_len, new_out_buf_capacity; - tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8 *)pSrc_buf + src_buf_ofs, &src_buf_size, (mz_uint8 *)pBuf, pBuf ? (mz_uint8 *)pBuf + *pOut_len : NULL, &dst_buf_size, - (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); - if ((status < 0) || (status == TINFL_STATUS_NEEDS_MORE_INPUT)) - { - MZ_FREE(pBuf); - *pOut_len = 0; - return NULL; - } - src_buf_ofs += src_buf_size; - *pOut_len += dst_buf_size; - if (status == TINFL_STATUS_DONE) - break; - new_out_buf_capacity = out_buf_capacity * 2; - if (new_out_buf_capacity < 128) - new_out_buf_capacity = 128; - pNew_buf = MZ_REALLOC(pBuf, new_out_buf_capacity); - if (!pNew_buf) - { - MZ_FREE(pBuf); - *pOut_len = 0; - return NULL; - } - pBuf = pNew_buf; - out_buf_capacity = new_out_buf_capacity; - } - return pBuf; -} - -size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags) -{ - tinfl_decompressor decomp; - tinfl_status status; - tinfl_init(&decomp); - status = tinfl_decompress(&decomp, (const mz_uint8 *)pSrc_buf, &src_buf_len, (mz_uint8 *)pOut_buf, (mz_uint8 *)pOut_buf, &out_buf_len, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); - return (status != TINFL_STATUS_DONE) ? TINFL_DECOMPRESS_MEM_TO_MEM_FAILED : out_buf_len; -} - -int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) -{ - int result = 0; - tinfl_decompressor decomp; - mz_uint8 *pDict = (mz_uint8 *)MZ_MALLOC(TINFL_LZ_DICT_SIZE); - size_t in_buf_ofs = 0, dict_ofs = 0; - if (!pDict) - return TINFL_STATUS_FAILED; - tinfl_init(&decomp); - for (;;) - { - size_t in_buf_size = *pIn_buf_size - in_buf_ofs, dst_buf_size = TINFL_LZ_DICT_SIZE - dict_ofs; - tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8 *)pIn_buf + in_buf_ofs, &in_buf_size, pDict, pDict + dict_ofs, &dst_buf_size, - (flags & ~(TINFL_FLAG_HAS_MORE_INPUT | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))); - in_buf_ofs += in_buf_size; - if ((dst_buf_size) && (!(*pPut_buf_func)(pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user))) - break; - if (status != TINFL_STATUS_HAS_MORE_OUTPUT) - { - result = (status == TINFL_STATUS_DONE); - break; - } - dict_ofs = (dict_ofs + dst_buf_size) & (TINFL_LZ_DICT_SIZE - 1); - } - MZ_FREE(pDict); - *pIn_buf_size = in_buf_ofs; - return result; -} - -tinfl_decompressor *tinfl_decompressor_alloc() -{ - tinfl_decompressor *pDecomp = (tinfl_decompressor *)MZ_MALLOC(sizeof(tinfl_decompressor)); - if (pDecomp) - tinfl_init(pDecomp); - return pDecomp; -} - -void tinfl_decompressor_free(tinfl_decompressor *pDecomp) -{ - MZ_FREE(pDecomp); -} - -#ifdef __cplusplus -} -#endif -/************************************************************************** - * - * Copyright 2013-2014 RAD Game Tools and Valve Software - * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC - * Copyright 2016 Martin Raiber - * All Rights Reserved. - * - * 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. - * - **************************************************************************/ - - -#ifndef MINIZ_NO_ARCHIVE_APIS - -#ifdef __cplusplus -extern "C" { -#endif - -/* ------------------- .ZIP archive reading */ - -#ifdef MINIZ_NO_STDIO -#define MZ_FILE void * -#else -#include - -#if defined(_MSC_VER) || defined(__MINGW64__) -static FILE *mz_fopen(const char *pFilename, const char *pMode) -{ - FILE *pFile = NULL; - fopen_s(&pFile, pFilename, pMode); - return pFile; -} -static FILE *mz_freopen(const char *pPath, const char *pMode, FILE *pStream) -{ - FILE *pFile = NULL; - if (freopen_s(&pFile, pPath, pMode, pStream)) - return NULL; - return pFile; -} -#ifndef MINIZ_NO_TIME -#include -#endif -#define MZ_FOPEN mz_fopen -#define MZ_FCLOSE fclose -#define MZ_FREAD fread -#define MZ_FWRITE fwrite -#define MZ_FTELL64 _ftelli64 -#define MZ_FSEEK64 _fseeki64 -#define MZ_FILE_STAT_STRUCT _stat -#define MZ_FILE_STAT _stat -#define MZ_FFLUSH fflush -#define MZ_FREOPEN mz_freopen -#define MZ_DELETE_FILE remove -#elif defined(__MINGW32__) -#ifndef MINIZ_NO_TIME -#include -#endif -#define MZ_FOPEN(f, m) fopen(f, m) -#define MZ_FCLOSE fclose -#define MZ_FREAD fread -#define MZ_FWRITE fwrite -#define MZ_FTELL64 ftello64 -#define MZ_FSEEK64 fseeko64 -#define MZ_FILE_STAT_STRUCT _stat -#define MZ_FILE_STAT _stat -#define MZ_FFLUSH fflush -#define MZ_FREOPEN(f, m, s) freopen(f, m, s) -#define MZ_DELETE_FILE remove -#elif defined(__TINYC__) -#ifndef MINIZ_NO_TIME -#include -#endif -#define MZ_FOPEN(f, m) fopen(f, m) -#define MZ_FCLOSE fclose -#define MZ_FREAD fread -#define MZ_FWRITE fwrite -#define MZ_FTELL64 ftell -#define MZ_FSEEK64 fseek -#define MZ_FILE_STAT_STRUCT stat -#define MZ_FILE_STAT stat -#define MZ_FFLUSH fflush -#define MZ_FREOPEN(f, m, s) freopen(f, m, s) -#define MZ_DELETE_FILE remove -#elif defined(__GNUC__) && _LARGEFILE64_SOURCE -#ifndef MINIZ_NO_TIME -#include -#endif -#define MZ_FOPEN(f, m) fopen64(f, m) -#define MZ_FCLOSE fclose -#define MZ_FREAD fread -#define MZ_FWRITE fwrite -#define MZ_FTELL64 ftello64 -#define MZ_FSEEK64 fseeko64 -#define MZ_FILE_STAT_STRUCT stat64 -#define MZ_FILE_STAT stat64 -#define MZ_FFLUSH fflush -#define MZ_FREOPEN(p, m, s) freopen64(p, m, s) -#define MZ_DELETE_FILE remove -#elif defined(__APPLE__) && _LARGEFILE64_SOURCE -#ifndef MINIZ_NO_TIME -#include -#endif -#define MZ_FOPEN(f, m) fopen(f, m) -#define MZ_FCLOSE fclose -#define MZ_FREAD fread -#define MZ_FWRITE fwrite -#define MZ_FTELL64 ftello -#define MZ_FSEEK64 fseeko -#define MZ_FILE_STAT_STRUCT stat -#define MZ_FILE_STAT stat -#define MZ_FFLUSH fflush -#define MZ_FREOPEN(p, m, s) freopen(p, m, s) -#define MZ_DELETE_FILE remove - -#else -#pragma message("Using fopen, ftello, fseeko, stat() etc. path for file I/O - this path may not support large files.") -#ifndef MINIZ_NO_TIME -#include -#endif -#define MZ_FOPEN(f, m) fopen(f, m) -#define MZ_FCLOSE fclose -#define MZ_FREAD fread -#define MZ_FWRITE fwrite -#ifdef __STRICT_ANSI__ -#define MZ_FTELL64 ftell -#define MZ_FSEEK64 fseek -#else -#define MZ_FTELL64 ftello -#define MZ_FSEEK64 fseeko -#endif -#define MZ_FILE_STAT_STRUCT stat -#define MZ_FILE_STAT stat -#define MZ_FFLUSH fflush -#define MZ_FREOPEN(f, m, s) freopen(f, m, s) -#define MZ_DELETE_FILE remove -#endif /* #ifdef _MSC_VER */ -#endif /* #ifdef MINIZ_NO_STDIO */ - -#define MZ_TOLOWER(c) ((((c) >= 'A') && ((c) <= 'Z')) ? ((c) - 'A' + 'a') : (c)) - -/* Various ZIP archive enums. To completely avoid cross platform compiler alignment and platform endian issues, miniz.c doesn't use structs for any of this stuff. */ -enum -{ - /* ZIP archive identifiers and record sizes */ - MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06054b50, - MZ_ZIP_CENTRAL_DIR_HEADER_SIG = 0x02014b50, - MZ_ZIP_LOCAL_DIR_HEADER_SIG = 0x04034b50, - MZ_ZIP_LOCAL_DIR_HEADER_SIZE = 30, - MZ_ZIP_CENTRAL_DIR_HEADER_SIZE = 46, - MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE = 22, - - /* ZIP64 archive identifier and record sizes */ - MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06064b50, - MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIG = 0x07064b50, - MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE = 56, - MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE = 20, - MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID = 0x0001, - MZ_ZIP_DATA_DESCRIPTOR_ID = 0x08074b50, - MZ_ZIP_DATA_DESCRIPTER_SIZE64 = 24, - MZ_ZIP_DATA_DESCRIPTER_SIZE32 = 16, - - /* Central directory header record offsets */ - MZ_ZIP_CDH_SIG_OFS = 0, - MZ_ZIP_CDH_VERSION_MADE_BY_OFS = 4, - MZ_ZIP_CDH_VERSION_NEEDED_OFS = 6, - MZ_ZIP_CDH_BIT_FLAG_OFS = 8, - MZ_ZIP_CDH_METHOD_OFS = 10, - MZ_ZIP_CDH_FILE_TIME_OFS = 12, - MZ_ZIP_CDH_FILE_DATE_OFS = 14, - MZ_ZIP_CDH_CRC32_OFS = 16, - MZ_ZIP_CDH_COMPRESSED_SIZE_OFS = 20, - MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS = 24, - MZ_ZIP_CDH_FILENAME_LEN_OFS = 28, - MZ_ZIP_CDH_EXTRA_LEN_OFS = 30, - MZ_ZIP_CDH_COMMENT_LEN_OFS = 32, - MZ_ZIP_CDH_DISK_START_OFS = 34, - MZ_ZIP_CDH_INTERNAL_ATTR_OFS = 36, - MZ_ZIP_CDH_EXTERNAL_ATTR_OFS = 38, - MZ_ZIP_CDH_LOCAL_HEADER_OFS = 42, - - /* Local directory header offsets */ - MZ_ZIP_LDH_SIG_OFS = 0, - MZ_ZIP_LDH_VERSION_NEEDED_OFS = 4, - MZ_ZIP_LDH_BIT_FLAG_OFS = 6, - MZ_ZIP_LDH_METHOD_OFS = 8, - MZ_ZIP_LDH_FILE_TIME_OFS = 10, - MZ_ZIP_LDH_FILE_DATE_OFS = 12, - MZ_ZIP_LDH_CRC32_OFS = 14, - MZ_ZIP_LDH_COMPRESSED_SIZE_OFS = 18, - MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS = 22, - MZ_ZIP_LDH_FILENAME_LEN_OFS = 26, - MZ_ZIP_LDH_EXTRA_LEN_OFS = 28, - MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR = 1 << 3, - - /* End of central directory offsets */ - MZ_ZIP_ECDH_SIG_OFS = 0, - MZ_ZIP_ECDH_NUM_THIS_DISK_OFS = 4, - MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS = 6, - MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 8, - MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS = 10, - MZ_ZIP_ECDH_CDIR_SIZE_OFS = 12, - MZ_ZIP_ECDH_CDIR_OFS_OFS = 16, - MZ_ZIP_ECDH_COMMENT_SIZE_OFS = 20, - - /* ZIP64 End of central directory locator offsets */ - MZ_ZIP64_ECDL_SIG_OFS = 0, /* 4 bytes */ - MZ_ZIP64_ECDL_NUM_DISK_CDIR_OFS = 4, /* 4 bytes */ - MZ_ZIP64_ECDL_REL_OFS_TO_ZIP64_ECDR_OFS = 8, /* 8 bytes */ - MZ_ZIP64_ECDL_TOTAL_NUMBER_OF_DISKS_OFS = 16, /* 4 bytes */ - - /* ZIP64 End of central directory header offsets */ - MZ_ZIP64_ECDH_SIG_OFS = 0, /* 4 bytes */ - MZ_ZIP64_ECDH_SIZE_OF_RECORD_OFS = 4, /* 8 bytes */ - MZ_ZIP64_ECDH_VERSION_MADE_BY_OFS = 12, /* 2 bytes */ - MZ_ZIP64_ECDH_VERSION_NEEDED_OFS = 14, /* 2 bytes */ - MZ_ZIP64_ECDH_NUM_THIS_DISK_OFS = 16, /* 4 bytes */ - MZ_ZIP64_ECDH_NUM_DISK_CDIR_OFS = 20, /* 4 bytes */ - MZ_ZIP64_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 24, /* 8 bytes */ - MZ_ZIP64_ECDH_CDIR_TOTAL_ENTRIES_OFS = 32, /* 8 bytes */ - MZ_ZIP64_ECDH_CDIR_SIZE_OFS = 40, /* 8 bytes */ - MZ_ZIP64_ECDH_CDIR_OFS_OFS = 48, /* 8 bytes */ - MZ_ZIP_VERSION_MADE_BY_DOS_FILESYSTEM_ID = 0, - MZ_ZIP_DOS_DIR_ATTRIBUTE_BITFLAG = 0x10, - MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED = 1, - MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG = 32, - MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION = 64, - MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_LOCAL_DIR_IS_MASKED = 8192, - MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_UTF8 = 1 << 11 -}; - -typedef struct -{ - void *m_p; - size_t m_size, m_capacity; - mz_uint m_element_size; -} mz_zip_array; - -struct mz_zip_internal_state_tag -{ - mz_zip_array m_central_dir; - mz_zip_array m_central_dir_offsets; - mz_zip_array m_sorted_central_dir_offsets; - - /* The flags passed in when the archive is initially opened. */ - uint32_t m_init_flags; - - /* MZ_TRUE if the archive has a zip64 end of central directory headers, etc. */ - mz_bool m_zip64; - - /* MZ_TRUE if we found zip64 extended info in the central directory (m_zip64 will also be slammed to true too, even if we didn't find a zip64 end of central dir header, etc.) */ - mz_bool m_zip64_has_extended_info_fields; - - /* These fields are used by the file, FILE, memory, and memory/heap read/write helpers. */ - MZ_FILE *m_pFile; - mz_uint64 m_file_archive_start_ofs; - - void *m_pMem; - size_t m_mem_size; - size_t m_mem_capacity; -}; - -#define MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(array_ptr, element_size) (array_ptr)->m_element_size = element_size - -#if defined(DEBUG) || defined(_DEBUG) || defined(NDEBUG) -static MZ_FORCEINLINE mz_uint mz_zip_array_range_check(const mz_zip_array *pArray, mz_uint index) -{ - MZ_ASSERT(index < pArray->m_size); - return index; -} -#define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) ((element_type *)((array_ptr)->m_p))[mz_zip_array_range_check(array_ptr, index)] -#else -#define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) ((element_type *)((array_ptr)->m_p))[index] -#endif - -static MZ_FORCEINLINE void mz_zip_array_init(mz_zip_array *pArray, mz_uint32 element_size) -{ - memset(pArray, 0, sizeof(mz_zip_array)); - pArray->m_element_size = element_size; -} - -static MZ_FORCEINLINE void mz_zip_array_clear(mz_zip_archive *pZip, mz_zip_array *pArray) -{ - pZip->m_pFree(pZip->m_pAlloc_opaque, pArray->m_p); - memset(pArray, 0, sizeof(mz_zip_array)); -} - -static mz_bool mz_zip_array_ensure_capacity(mz_zip_archive *pZip, mz_zip_array *pArray, size_t min_new_capacity, mz_uint growing) -{ - void *pNew_p; - size_t new_capacity = min_new_capacity; - MZ_ASSERT(pArray->m_element_size); - if (pArray->m_capacity >= min_new_capacity) - return MZ_TRUE; - if (growing) - { - new_capacity = MZ_MAX(1, pArray->m_capacity); - while (new_capacity < min_new_capacity) - new_capacity *= 2; - } - if (NULL == (pNew_p = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pArray->m_p, pArray->m_element_size, new_capacity))) - return MZ_FALSE; - pArray->m_p = pNew_p; - pArray->m_capacity = new_capacity; - return MZ_TRUE; -} - -static MZ_FORCEINLINE mz_bool mz_zip_array_reserve(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_capacity, mz_uint growing) -{ - if (new_capacity > pArray->m_capacity) - { - if (!mz_zip_array_ensure_capacity(pZip, pArray, new_capacity, growing)) - return MZ_FALSE; - } - return MZ_TRUE; -} - -static MZ_FORCEINLINE mz_bool mz_zip_array_resize(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_size, mz_uint growing) -{ - if (new_size > pArray->m_capacity) - { - if (!mz_zip_array_ensure_capacity(pZip, pArray, new_size, growing)) - return MZ_FALSE; - } - pArray->m_size = new_size; - return MZ_TRUE; -} - -static MZ_FORCEINLINE mz_bool mz_zip_array_ensure_room(mz_zip_archive *pZip, mz_zip_array *pArray, size_t n) -{ - return mz_zip_array_reserve(pZip, pArray, pArray->m_size + n, MZ_TRUE); -} - -static MZ_FORCEINLINE mz_bool mz_zip_array_push_back(mz_zip_archive *pZip, mz_zip_array *pArray, const void *pElements, size_t n) -{ - size_t orig_size = pArray->m_size; - if (!mz_zip_array_resize(pZip, pArray, orig_size + n, MZ_TRUE)) - return MZ_FALSE; - memcpy((mz_uint8 *)pArray->m_p + orig_size * pArray->m_element_size, pElements, n * pArray->m_element_size); - return MZ_TRUE; -} - -#ifndef MINIZ_NO_TIME -static MZ_TIME_T mz_zip_dos_to_time_t(int dos_time, int dos_date) -{ - struct tm tm; - memset(&tm, 0, sizeof(tm)); - tm.tm_isdst = -1; - tm.tm_year = ((dos_date >> 9) & 127) + 1980 - 1900; - tm.tm_mon = ((dos_date >> 5) & 15) - 1; - tm.tm_mday = dos_date & 31; - tm.tm_hour = (dos_time >> 11) & 31; - tm.tm_min = (dos_time >> 5) & 63; - tm.tm_sec = (dos_time << 1) & 62; - return mktime(&tm); -} - -#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS -static void mz_zip_time_t_to_dos_time(MZ_TIME_T time, mz_uint16 *pDOS_time, mz_uint16 *pDOS_date) -{ -#ifdef _MSC_VER - struct tm tm_struct; - struct tm *tm = &tm_struct; - errno_t err = localtime_s(tm, &time); - if (err) - { - *pDOS_date = 0; - *pDOS_time = 0; - return; - } -#else - struct tm *tm = localtime(&time); -#endif /* #ifdef _MSC_VER */ - - *pDOS_time = (mz_uint16)(((tm->tm_hour) << 11) + ((tm->tm_min) << 5) + ((tm->tm_sec) >> 1)); - *pDOS_date = (mz_uint16)(((tm->tm_year + 1900 - 1980) << 9) + ((tm->tm_mon + 1) << 5) + tm->tm_mday); -} -#endif /* MINIZ_NO_ARCHIVE_WRITING_APIS */ - -#ifndef MINIZ_NO_STDIO -#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS -static mz_bool mz_zip_get_file_modified_time(const char *pFilename, MZ_TIME_T *pTime) -{ - struct MZ_FILE_STAT_STRUCT file_stat; - - /* On Linux with x86 glibc, this call will fail on large files (I think >= 0x80000000 bytes) unless you compiled with _LARGEFILE64_SOURCE. Argh. */ - if (MZ_FILE_STAT(pFilename, &file_stat) != 0) - return MZ_FALSE; - - *pTime = file_stat.st_mtime; - - return MZ_TRUE; -} -#endif /* #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS*/ - -static mz_bool mz_zip_set_file_times(const char *pFilename, MZ_TIME_T access_time, MZ_TIME_T modified_time) -{ - struct utimbuf t; - - memset(&t, 0, sizeof(t)); - t.actime = access_time; - t.modtime = modified_time; - - return !utime(pFilename, &t); -} -#endif /* #ifndef MINIZ_NO_STDIO */ -#endif /* #ifndef MINIZ_NO_TIME */ - -static MZ_FORCEINLINE mz_bool mz_zip_set_error(mz_zip_archive *pZip, mz_zip_error err_num) -{ - if (pZip) - pZip->m_last_error = err_num; - return MZ_FALSE; -} - -static mz_bool mz_zip_reader_init_internal(mz_zip_archive *pZip, mz_uint flags) -{ - (void)flags; - if ((!pZip) || (pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - if (!pZip->m_pAlloc) - pZip->m_pAlloc = miniz_def_alloc_func; - if (!pZip->m_pFree) - pZip->m_pFree = miniz_def_free_func; - if (!pZip->m_pRealloc) - pZip->m_pRealloc = miniz_def_realloc_func; - - pZip->m_archive_size = 0; - pZip->m_central_directory_file_ofs = 0; - pZip->m_total_files = 0; - pZip->m_last_error = MZ_ZIP_NO_ERROR; - - if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) - return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - - memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); - MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8)); - MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32)); - MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32)); - pZip->m_pState->m_init_flags = flags; - pZip->m_pState->m_zip64 = MZ_FALSE; - pZip->m_pState->m_zip64_has_extended_info_fields = MZ_FALSE; - - pZip->m_zip_mode = MZ_ZIP_MODE_READING; - - return MZ_TRUE; -} - -static MZ_FORCEINLINE mz_bool mz_zip_reader_filename_less(const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, mz_uint r_index) -{ - const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE; - const mz_uint8 *pR = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, r_index)); - mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS), r_len = MZ_READ_LE16(pR + MZ_ZIP_CDH_FILENAME_LEN_OFS); - mz_uint8 l = 0, r = 0; - pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; - pR += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; - pE = pL + MZ_MIN(l_len, r_len); - while (pL < pE) - { - if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) - break; - pL++; - pR++; - } - return (pL == pE) ? (l_len < r_len) : (l < r); -} - -#define MZ_SWAP_UINT32(a, b) \ - do \ - { \ - mz_uint32 t = a; \ - a = b; \ - b = t; \ - } \ - MZ_MACRO_END - -/* Heap sort of lowercased filenames, used to help accelerate plain central directory searches by mz_zip_reader_locate_file(). (Could also use qsort(), but it could allocate memory.) */ -static void mz_zip_reader_sort_central_dir_offsets_by_filename(mz_zip_archive *pZip) -{ - mz_zip_internal_state *pState = pZip->m_pState; - const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; - const mz_zip_array *pCentral_dir = &pState->m_central_dir; - mz_uint32 *pIndices; - mz_uint32 start, end; - const mz_uint32 size = pZip->m_total_files; - - if (size <= 1U) - return; - - pIndices = &MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, mz_uint32, 0); - - start = (size - 2U) >> 1U; - for (;;) - { - mz_uint64 child, root = start; - for (;;) - { - if ((child = (root << 1U) + 1U) >= size) - break; - child += (((child + 1U) < size) && (mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1U]))); - if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) - break; - MZ_SWAP_UINT32(pIndices[root], pIndices[child]); - root = child; - } - if (!start) - break; - start--; - } - - end = size - 1; - while (end > 0) - { - mz_uint64 child, root = 0; - MZ_SWAP_UINT32(pIndices[end], pIndices[0]); - for (;;) - { - if ((child = (root << 1U) + 1U) >= end) - break; - child += (((child + 1U) < end) && mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1U])); - if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) - break; - MZ_SWAP_UINT32(pIndices[root], pIndices[child]); - root = child; - } - end--; - } -} - -static mz_bool mz_zip_reader_locate_header_sig(mz_zip_archive *pZip, mz_uint32 record_sig, mz_uint32 record_size, mz_int64 *pOfs) -{ - mz_int64 cur_file_ofs; - mz_uint32 buf_u32[4096 / sizeof(mz_uint32)]; - mz_uint8 *pBuf = (mz_uint8 *)buf_u32; - - /* Basic sanity checks - reject files which are too small */ - if (pZip->m_archive_size < record_size) - return MZ_FALSE; - - /* Find the record by scanning the file from the end towards the beginning. */ - cur_file_ofs = MZ_MAX((mz_int64)pZip->m_archive_size - (mz_int64)sizeof(buf_u32), 0); - for (;;) - { - int i, n = (int)MZ_MIN(sizeof(buf_u32), pZip->m_archive_size - cur_file_ofs); - - if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, n) != (mz_uint)n) - return MZ_FALSE; - - for (i = n - 4; i >= 0; --i) - { - mz_uint s = MZ_READ_LE32(pBuf + i); - if (s == record_sig) - { - if ((pZip->m_archive_size - (cur_file_ofs + i)) >= record_size) - break; - } - } - - if (i >= 0) - { - cur_file_ofs += i; - break; - } - - /* Give up if we've searched the entire file, or we've gone back "too far" (~64kb) */ - if ((!cur_file_ofs) || ((pZip->m_archive_size - cur_file_ofs) >= (MZ_UINT16_MAX + record_size))) - return MZ_FALSE; - - cur_file_ofs = MZ_MAX(cur_file_ofs - (sizeof(buf_u32) - 3), 0); - } - - *pOfs = cur_file_ofs; - return MZ_TRUE; -} - -static mz_bool mz_zip_reader_read_central_dir(mz_zip_archive *pZip, mz_uint flags) -{ - mz_uint cdir_size = 0, cdir_entries_on_this_disk = 0, num_this_disk = 0, cdir_disk_index = 0; - mz_uint64 cdir_ofs = 0; - mz_int64 cur_file_ofs = 0; - const mz_uint8 *p; - - mz_uint32 buf_u32[4096 / sizeof(mz_uint32)]; - mz_uint8 *pBuf = (mz_uint8 *)buf_u32; - mz_bool sort_central_dir = ((flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0); - mz_uint32 zip64_end_of_central_dir_locator_u32[(MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; - mz_uint8 *pZip64_locator = (mz_uint8 *)zip64_end_of_central_dir_locator_u32; - - mz_uint32 zip64_end_of_central_dir_header_u32[(MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; - mz_uint8 *pZip64_end_of_central_dir = (mz_uint8 *)zip64_end_of_central_dir_header_u32; - - mz_uint64 zip64_end_of_central_dir_ofs = 0; - - /* Basic sanity checks - reject files which are too small, and check the first 4 bytes of the file to make sure a local header is there. */ - if (pZip->m_archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) - return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); - - if (!mz_zip_reader_locate_header_sig(pZip, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE, &cur_file_ofs)) - return mz_zip_set_error(pZip, MZ_ZIP_FAILED_FINDING_CENTRAL_DIR); - - /* Read and verify the end of central directory record. */ - if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); - - if (MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_SIG_OFS) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) - return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); - - if (cur_file_ofs >= (MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE + MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE)) - { - if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs - MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE, pZip64_locator, MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) == MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) - { - if (MZ_READ_LE32(pZip64_locator + MZ_ZIP64_ECDL_SIG_OFS) == MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIG) - { - zip64_end_of_central_dir_ofs = MZ_READ_LE64(pZip64_locator + MZ_ZIP64_ECDL_REL_OFS_TO_ZIP64_ECDR_OFS); - if (zip64_end_of_central_dir_ofs > (pZip->m_archive_size - MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE)) - return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); - - if (pZip->m_pRead(pZip->m_pIO_opaque, zip64_end_of_central_dir_ofs, pZip64_end_of_central_dir, MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) == MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) - { - if (MZ_READ_LE32(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_SIG_OFS) == MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIG) - { - pZip->m_pState->m_zip64 = MZ_TRUE; - } - } - } - } - } - - pZip->m_total_files = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS); - cdir_entries_on_this_disk = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS); - num_this_disk = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_THIS_DISK_OFS); - cdir_disk_index = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS); - cdir_size = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_SIZE_OFS); - cdir_ofs = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_OFS_OFS); - - if (pZip->m_pState->m_zip64) - { - mz_uint32 zip64_total_num_of_disks = MZ_READ_LE32(pZip64_locator + MZ_ZIP64_ECDL_TOTAL_NUMBER_OF_DISKS_OFS); - mz_uint64 zip64_cdir_total_entries = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_TOTAL_ENTRIES_OFS); - mz_uint64 zip64_cdir_total_entries_on_this_disk = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS); - mz_uint64 zip64_size_of_end_of_central_dir_record = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_SIZE_OF_RECORD_OFS); - mz_uint64 zip64_size_of_central_directory = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_SIZE_OFS); - - if (zip64_size_of_end_of_central_dir_record < (MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE - 12)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - - if (zip64_total_num_of_disks != 1U) - return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK); - - /* Check for miniz's practical limits */ - if (zip64_cdir_total_entries > MZ_UINT32_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); - - pZip->m_total_files = (mz_uint32)zip64_cdir_total_entries; - - if (zip64_cdir_total_entries_on_this_disk > MZ_UINT32_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); - - cdir_entries_on_this_disk = (mz_uint32)zip64_cdir_total_entries_on_this_disk; - - /* Check for miniz's current practical limits (sorry, this should be enough for millions of files) */ - if (zip64_size_of_central_directory > MZ_UINT32_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); - - cdir_size = (mz_uint32)zip64_size_of_central_directory; - - num_this_disk = MZ_READ_LE32(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_NUM_THIS_DISK_OFS); - - cdir_disk_index = MZ_READ_LE32(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_NUM_DISK_CDIR_OFS); - - cdir_ofs = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_OFS_OFS); - } - - if (pZip->m_total_files != cdir_entries_on_this_disk) - return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK); - - if (((num_this_disk | cdir_disk_index) != 0) && ((num_this_disk != 1) || (cdir_disk_index != 1))) - return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK); - - if (cdir_size < pZip->m_total_files * MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - - if ((cdir_ofs + (mz_uint64)cdir_size) > pZip->m_archive_size) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - - pZip->m_central_directory_file_ofs = cdir_ofs; - - if (pZip->m_total_files) - { - mz_uint i, n; - /* Read the entire central directory into a heap block, and allocate another heap block to hold the unsorted central dir file record offsets, and possibly another to hold the sorted indices. */ - if ((!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir, cdir_size, MZ_FALSE)) || - (!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir_offsets, pZip->m_total_files, MZ_FALSE))) - return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - - if (sort_central_dir) - { - if (!mz_zip_array_resize(pZip, &pZip->m_pState->m_sorted_central_dir_offsets, pZip->m_total_files, MZ_FALSE)) - return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - } - - if (pZip->m_pRead(pZip->m_pIO_opaque, cdir_ofs, pZip->m_pState->m_central_dir.m_p, cdir_size) != cdir_size) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); - - /* Now create an index into the central directory file records, do some basic sanity checking on each record */ - p = (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p; - for (n = cdir_size, i = 0; i < pZip->m_total_files; ++i) - { - mz_uint total_header_size, disk_index, bit_flags, filename_size, ext_data_size; - mz_uint64 comp_size, decomp_size, local_header_ofs; - - if ((n < MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) || (MZ_READ_LE32(p) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - - MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, i) = (mz_uint32)(p - (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p); - - if (sort_central_dir) - MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_sorted_central_dir_offsets, mz_uint32, i) = i; - - comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); - decomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); - local_header_ofs = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS); - filename_size = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); - ext_data_size = MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS); - - if ((!pZip->m_pState->m_zip64_has_extended_info_fields) && - (ext_data_size) && - (MZ_MAX(MZ_MAX(comp_size, decomp_size), local_header_ofs) == MZ_UINT32_MAX)) - { - /* Attempt to find zip64 extended information field in the entry's extra data */ - mz_uint32 extra_size_remaining = ext_data_size; - - if (extra_size_remaining) - { - const mz_uint8 *pExtra_data = p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size; - - do - { - mz_uint32 field_id; - mz_uint32 field_data_size; - - if (extra_size_remaining < (sizeof(mz_uint16) * 2)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - - field_id = MZ_READ_LE16(pExtra_data); - field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); - - if ((field_data_size + sizeof(mz_uint16) * 2) > extra_size_remaining) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - - if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) - { - /* Ok, the archive didn't have any zip64 headers but it uses a zip64 extended information field so mark it as zip64 anyway (this can occur with infozip's zip util when it reads compresses files from stdin). */ - pZip->m_pState->m_zip64 = MZ_TRUE; - pZip->m_pState->m_zip64_has_extended_info_fields = MZ_TRUE; - break; - } - - pExtra_data += sizeof(mz_uint16) * 2 + field_data_size; - extra_size_remaining = extra_size_remaining - sizeof(mz_uint16) * 2 - field_data_size; - } while (extra_size_remaining); - } - } - - /* I've seen archives that aren't marked as zip64 that uses zip64 ext data, argh */ - if ((comp_size != MZ_UINT32_MAX) && (decomp_size != MZ_UINT32_MAX)) - { - if (((!MZ_READ_LE32(p + MZ_ZIP_CDH_METHOD_OFS)) && (decomp_size != comp_size)) || (decomp_size && !comp_size)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - } - - disk_index = MZ_READ_LE16(p + MZ_ZIP_CDH_DISK_START_OFS); - if ((disk_index == MZ_UINT16_MAX) || ((disk_index != num_this_disk) && (disk_index != 1))) - return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK); - - if (comp_size != MZ_UINT32_MAX) - { - if (((mz_uint64)MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS) + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + comp_size) > pZip->m_archive_size) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - } - - bit_flags = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); - if (bit_flags & MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_LOCAL_DIR_IS_MASKED) - return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); - - if ((total_header_size = MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS)) > n) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - - n -= total_header_size; - p += total_header_size; - } - } - - if (sort_central_dir) - mz_zip_reader_sort_central_dir_offsets_by_filename(pZip); - - return MZ_TRUE; -} - -void mz_zip_zero_struct(mz_zip_archive *pZip) -{ - if (pZip) - MZ_CLEAR_OBJ(*pZip); -} - -static mz_bool mz_zip_reader_end_internal(mz_zip_archive *pZip, mz_bool set_last_error) -{ - mz_bool status = MZ_TRUE; - - if (!pZip) - return MZ_FALSE; - - if ((!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) - { - if (set_last_error) - pZip->m_last_error = MZ_ZIP_INVALID_PARAMETER; - - return MZ_FALSE; - } - - if (pZip->m_pState) - { - mz_zip_internal_state *pState = pZip->m_pState; - pZip->m_pState = NULL; - - mz_zip_array_clear(pZip, &pState->m_central_dir); - mz_zip_array_clear(pZip, &pState->m_central_dir_offsets); - mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); - -#ifndef MINIZ_NO_STDIO - if (pState->m_pFile) - { - if (pZip->m_zip_type == MZ_ZIP_TYPE_FILE) - { - if (MZ_FCLOSE(pState->m_pFile) == EOF) - { - if (set_last_error) - pZip->m_last_error = MZ_ZIP_FILE_CLOSE_FAILED; - status = MZ_FALSE; - } - } - pState->m_pFile = NULL; - } -#endif /* #ifndef MINIZ_NO_STDIO */ - - pZip->m_pFree(pZip->m_pAlloc_opaque, pState); - } - pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; - - return status; -} - -mz_bool mz_zip_reader_end(mz_zip_archive *pZip) -{ - return mz_zip_reader_end_internal(pZip, MZ_TRUE); -} -mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint flags) -{ - if ((!pZip) || (!pZip->m_pRead)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - if (!mz_zip_reader_init_internal(pZip, flags)) - return MZ_FALSE; - - pZip->m_zip_type = MZ_ZIP_TYPE_USER; - pZip->m_archive_size = size; - - if (!mz_zip_reader_read_central_dir(pZip, flags)) - { - mz_zip_reader_end_internal(pZip, MZ_FALSE); - return MZ_FALSE; - } - - return MZ_TRUE; -} - -static size_t mz_zip_mem_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) -{ - mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; - size_t s = (file_ofs >= pZip->m_archive_size) ? 0 : (size_t)MZ_MIN(pZip->m_archive_size - file_ofs, n); - memcpy(pBuf, (const mz_uint8 *)pZip->m_pState->m_pMem + file_ofs, s); - return s; -} - -mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint flags) -{ - if (!pMem) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - if (size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) - return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); - - if (!mz_zip_reader_init_internal(pZip, flags)) - return MZ_FALSE; - - pZip->m_zip_type = MZ_ZIP_TYPE_MEMORY; - pZip->m_archive_size = size; - pZip->m_pRead = mz_zip_mem_read_func; - pZip->m_pIO_opaque = pZip; - pZip->m_pNeeds_keepalive = NULL; - -#ifdef __cplusplus - pZip->m_pState->m_pMem = const_cast(pMem); -#else - pZip->m_pState->m_pMem = (void *)pMem; -#endif - - pZip->m_pState->m_mem_size = size; - - if (!mz_zip_reader_read_central_dir(pZip, flags)) - { - mz_zip_reader_end_internal(pZip, MZ_FALSE); - return MZ_FALSE; - } - - return MZ_TRUE; -} - -#ifndef MINIZ_NO_STDIO -static size_t mz_zip_file_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) -{ - mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; - mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); - - file_ofs += pZip->m_pState->m_file_archive_start_ofs; - - if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) - return 0; - - return MZ_FREAD(pBuf, 1, n, pZip->m_pState->m_pFile); -} - -mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags) -{ - return mz_zip_reader_init_file_v2(pZip, pFilename, flags, 0, 0); -} - -mz_bool mz_zip_reader_init_file_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint flags, mz_uint64 file_start_ofs, mz_uint64 archive_size) -{ - mz_uint64 file_size; - MZ_FILE *pFile; - - if ((!pZip) || (!pFilename) || ((archive_size) && (archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE))) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - pFile = MZ_FOPEN(pFilename, "rb"); - if (!pFile) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); - - file_size = archive_size; - if (!file_size) - { - if (MZ_FSEEK64(pFile, 0, SEEK_END)) - { - MZ_FCLOSE(pFile); - return mz_zip_set_error(pZip, MZ_ZIP_FILE_SEEK_FAILED); - } - - file_size = MZ_FTELL64(pFile); - } - - /* TODO: Better sanity check archive_size and the # of actual remaining bytes */ - - if (file_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) - { - MZ_FCLOSE(pFile); - return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); - } - - if (!mz_zip_reader_init_internal(pZip, flags)) - { - MZ_FCLOSE(pFile); - return MZ_FALSE; - } - - pZip->m_zip_type = MZ_ZIP_TYPE_FILE; - pZip->m_pRead = mz_zip_file_read_func; - pZip->m_pIO_opaque = pZip; - pZip->m_pState->m_pFile = pFile; - pZip->m_archive_size = file_size; - pZip->m_pState->m_file_archive_start_ofs = file_start_ofs; - - if (!mz_zip_reader_read_central_dir(pZip, flags)) - { - mz_zip_reader_end_internal(pZip, MZ_FALSE); - return MZ_FALSE; - } - - return MZ_TRUE; -} - -mz_bool mz_zip_reader_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile, mz_uint64 archive_size, mz_uint flags) -{ - mz_uint64 cur_file_ofs; - - if ((!pZip) || (!pFile)) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); - - cur_file_ofs = MZ_FTELL64(pFile); - - if (!archive_size) - { - if (MZ_FSEEK64(pFile, 0, SEEK_END)) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_SEEK_FAILED); - - archive_size = MZ_FTELL64(pFile) - cur_file_ofs; - - if (archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) - return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); - } - - if (!mz_zip_reader_init_internal(pZip, flags)) - return MZ_FALSE; - - pZip->m_zip_type = MZ_ZIP_TYPE_CFILE; - pZip->m_pRead = mz_zip_file_read_func; - - pZip->m_pIO_opaque = pZip; - pZip->m_pState->m_pFile = pFile; - pZip->m_archive_size = archive_size; - pZip->m_pState->m_file_archive_start_ofs = cur_file_ofs; - - if (!mz_zip_reader_read_central_dir(pZip, flags)) - { - mz_zip_reader_end_internal(pZip, MZ_FALSE); - return MZ_FALSE; - } - - return MZ_TRUE; -} - -#endif /* #ifndef MINIZ_NO_STDIO */ - -static MZ_FORCEINLINE const mz_uint8 *mz_zip_get_cdh(mz_zip_archive *pZip, mz_uint file_index) -{ - if ((!pZip) || (!pZip->m_pState) || (file_index >= pZip->m_total_files)) - return NULL; - return &MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index)); -} - -mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index) -{ - mz_uint m_bit_flag; - const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index); - if (!p) - { - mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - return MZ_FALSE; - } - - m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); - return (m_bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION)) != 0; -} - -mz_bool mz_zip_reader_is_file_supported(mz_zip_archive *pZip, mz_uint file_index) -{ - mz_uint bit_flag; - mz_uint method; - - const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index); - if (!p) - { - mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - return MZ_FALSE; - } - - method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS); - bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); - - if ((method != 0) && (method != MZ_DEFLATED)) - { - mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); - return MZ_FALSE; - } - - if (bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION)) - { - mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); - return MZ_FALSE; - } - - if (bit_flag & MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG) - { - mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_FEATURE); - return MZ_FALSE; - } - - return MZ_TRUE; -} - -mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index) -{ - mz_uint filename_len, attribute_mapping_id, external_attr; - const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index); - if (!p) - { - mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - return MZ_FALSE; - } - - filename_len = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); - if (filename_len) - { - if (*(p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_len - 1) == '/') - return MZ_TRUE; - } - - /* Bugfix: This code was also checking if the internal attribute was non-zero, which wasn't correct. */ - /* Most/all zip writers (hopefully) set DOS file/directory attributes in the low 16-bits, so check for the DOS directory flag and ignore the source OS ID in the created by field. */ - /* FIXME: Remove this check? Is it necessary - we already check the filename. */ - attribute_mapping_id = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS) >> 8; - (void)attribute_mapping_id; - - external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); - if ((external_attr & MZ_ZIP_DOS_DIR_ATTRIBUTE_BITFLAG) != 0) - { - return MZ_TRUE; - } - - return MZ_FALSE; -} - -static mz_bool mz_zip_file_stat_internal(mz_zip_archive *pZip, mz_uint file_index, const mz_uint8 *pCentral_dir_header, mz_zip_archive_file_stat *pStat, mz_bool *pFound_zip64_extra_data) -{ - mz_uint n; - const mz_uint8 *p = pCentral_dir_header; - - if (pFound_zip64_extra_data) - *pFound_zip64_extra_data = MZ_FALSE; - - if ((!p) || (!pStat)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - /* Extract fields from the central directory record. */ - pStat->m_file_index = file_index; - pStat->m_central_dir_ofs = MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index); - pStat->m_version_made_by = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS); - pStat->m_version_needed = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_NEEDED_OFS); - pStat->m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); - pStat->m_method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS); -#ifndef MINIZ_NO_TIME - pStat->m_time = mz_zip_dos_to_time_t(MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_TIME_OFS), MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_DATE_OFS)); -#endif - pStat->m_crc32 = MZ_READ_LE32(p + MZ_ZIP_CDH_CRC32_OFS); - pStat->m_comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); - pStat->m_uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); - pStat->m_internal_attr = MZ_READ_LE16(p + MZ_ZIP_CDH_INTERNAL_ATTR_OFS); - pStat->m_external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); - pStat->m_local_header_ofs = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS); - - /* Copy as much of the filename and comment as possible. */ - n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); - n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE - 1); - memcpy(pStat->m_filename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); - pStat->m_filename[n] = '\0'; - - n = MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS); - n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE - 1); - pStat->m_comment_size = n; - memcpy(pStat->m_comment, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS), n); - pStat->m_comment[n] = '\0'; - - /* Set some flags for convienance */ - pStat->m_is_directory = mz_zip_reader_is_file_a_directory(pZip, file_index); - pStat->m_is_encrypted = mz_zip_reader_is_file_encrypted(pZip, file_index); - pStat->m_is_supported = mz_zip_reader_is_file_supported(pZip, file_index); - - /* See if we need to read any zip64 extended information fields. */ - /* Confusingly, these zip64 fields can be present even on non-zip64 archives (Debian zip on a huge files from stdin piped to stdout creates them). */ - if (MZ_MAX(MZ_MAX(pStat->m_comp_size, pStat->m_uncomp_size), pStat->m_local_header_ofs) == MZ_UINT32_MAX) - { - /* Attempt to find zip64 extended information field in the entry's extra data */ - mz_uint32 extra_size_remaining = MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS); - - if (extra_size_remaining) - { - const mz_uint8 *pExtra_data = p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); - - do - { - mz_uint32 field_id; - mz_uint32 field_data_size; - - if (extra_size_remaining < (sizeof(mz_uint16) * 2)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - - field_id = MZ_READ_LE16(pExtra_data); - field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); - - if ((field_data_size + sizeof(mz_uint16) * 2) > extra_size_remaining) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - - if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) - { - const mz_uint8 *pField_data = pExtra_data + sizeof(mz_uint16) * 2; - mz_uint32 field_data_remaining = field_data_size; - - if (pFound_zip64_extra_data) - *pFound_zip64_extra_data = MZ_TRUE; - - if (pStat->m_uncomp_size == MZ_UINT32_MAX) - { - if (field_data_remaining < sizeof(mz_uint64)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - - pStat->m_uncomp_size = MZ_READ_LE64(pField_data); - pField_data += sizeof(mz_uint64); - field_data_remaining -= sizeof(mz_uint64); - } - - if (pStat->m_comp_size == MZ_UINT32_MAX) - { - if (field_data_remaining < sizeof(mz_uint64)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - - pStat->m_comp_size = MZ_READ_LE64(pField_data); - pField_data += sizeof(mz_uint64); - field_data_remaining -= sizeof(mz_uint64); - } - - if (pStat->m_local_header_ofs == MZ_UINT32_MAX) - { - if (field_data_remaining < sizeof(mz_uint64)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - - pStat->m_local_header_ofs = MZ_READ_LE64(pField_data); - pField_data += sizeof(mz_uint64); - field_data_remaining -= sizeof(mz_uint64); - } - - break; - } - - pExtra_data += sizeof(mz_uint16) * 2 + field_data_size; - extra_size_remaining = extra_size_remaining - sizeof(mz_uint16) * 2 - field_data_size; - } while (extra_size_remaining); - } - } - - return MZ_TRUE; -} - -static MZ_FORCEINLINE mz_bool mz_zip_string_equal(const char *pA, const char *pB, mz_uint len, mz_uint flags) -{ - mz_uint i; - if (flags & MZ_ZIP_FLAG_CASE_SENSITIVE) - return 0 == memcmp(pA, pB, len); - for (i = 0; i < len; ++i) - if (MZ_TOLOWER(pA[i]) != MZ_TOLOWER(pB[i])) - return MZ_FALSE; - return MZ_TRUE; -} - -static MZ_FORCEINLINE int mz_zip_filename_compare(const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, const char *pR, mz_uint r_len) -{ - const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE; - mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS); - mz_uint8 l = 0, r = 0; - pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; - pE = pL + MZ_MIN(l_len, r_len); - while (pL < pE) - { - if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) - break; - pL++; - pR++; - } - return (pL == pE) ? (int)(l_len - r_len) : (l - r); -} - -static mz_bool mz_zip_locate_file_binary_search(mz_zip_archive *pZip, const char *pFilename, mz_uint32 *pIndex) -{ - mz_zip_internal_state *pState = pZip->m_pState; - const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; - const mz_zip_array *pCentral_dir = &pState->m_central_dir; - mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, mz_uint32, 0); - const uint32_t size = pZip->m_total_files; - const mz_uint filename_len = (mz_uint)strlen(pFilename); - - if (pIndex) - *pIndex = 0; - - if (size) - { - /* yes I could use uint32_t's, but then we would have to add some special case checks in the loop, argh, and */ - /* honestly the major expense here on 32-bit CPU's will still be the filename compare */ - mz_int64 l = 0, h = (mz_int64)size - 1; - - while (l <= h) - { - mz_int64 m = l + ((h - l) >> 1); - uint32_t file_index = pIndices[(uint32_t)m]; - - int comp = mz_zip_filename_compare(pCentral_dir, pCentral_dir_offsets, file_index, pFilename, filename_len); - if (!comp) - { - if (pIndex) - *pIndex = file_index; - return MZ_TRUE; - } - else if (comp < 0) - l = m + 1; - else - h = m - 1; - } - } - - return mz_zip_set_error(pZip, MZ_ZIP_FILE_NOT_FOUND); -} - -int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags) -{ - mz_uint32 index; - if (!mz_zip_reader_locate_file_v2(pZip, pName, pComment, flags, &index)) - return -1; - else - return (int)index; -} - -mz_bool mz_zip_reader_locate_file_v2(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags, mz_uint32 *pIndex) -{ - mz_uint file_index; - size_t name_len, comment_len; - - if (pIndex) - *pIndex = 0; - - if ((!pZip) || (!pZip->m_pState) || (!pName)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - /* See if we can use a binary search */ - if (((pZip->m_pState->m_init_flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0) && - (pZip->m_zip_mode == MZ_ZIP_MODE_READING) && - ((flags & (MZ_ZIP_FLAG_IGNORE_PATH | MZ_ZIP_FLAG_CASE_SENSITIVE)) == 0) && (!pComment) && (pZip->m_pState->m_sorted_central_dir_offsets.m_size)) - { - return mz_zip_locate_file_binary_search(pZip, pName, pIndex); - } - - /* Locate the entry by scanning the entire central directory */ - name_len = strlen(pName); - if (name_len > MZ_UINT16_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - comment_len = pComment ? strlen(pComment) : 0; - if (comment_len > MZ_UINT16_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - for (file_index = 0; file_index < pZip->m_total_files; file_index++) - { - const mz_uint8 *pHeader = &MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index)); - mz_uint filename_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_FILENAME_LEN_OFS); - const char *pFilename = (const char *)pHeader + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; - if (filename_len < name_len) - continue; - if (comment_len) - { - mz_uint file_extra_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_EXTRA_LEN_OFS), file_comment_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_COMMENT_LEN_OFS); - const char *pFile_comment = pFilename + filename_len + file_extra_len; - if ((file_comment_len != comment_len) || (!mz_zip_string_equal(pComment, pFile_comment, file_comment_len, flags))) - continue; - } - if ((flags & MZ_ZIP_FLAG_IGNORE_PATH) && (filename_len)) - { - int ofs = filename_len - 1; - do - { - if ((pFilename[ofs] == '/') || (pFilename[ofs] == '\\') || (pFilename[ofs] == ':')) - break; - } while (--ofs >= 0); - ofs++; - pFilename += ofs; - filename_len -= ofs; - } - if ((filename_len == name_len) && (mz_zip_string_equal(pName, pFilename, filename_len, flags))) - { - if (pIndex) - *pIndex = file_index; - return MZ_TRUE; - } - } - - return mz_zip_set_error(pZip, MZ_ZIP_FILE_NOT_FOUND); -} - -mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) -{ - int status = TINFL_STATUS_DONE; - mz_uint64 needed_size, cur_file_ofs, comp_remaining, out_buf_ofs = 0, read_buf_size, read_buf_ofs = 0, read_buf_avail; - mz_zip_archive_file_stat file_stat; - void *pRead_buf; - mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; - mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; - tinfl_decompressor inflator; - - if ((!pZip) || (!pZip->m_pState) || ((buf_size) && (!pBuf)) || ((user_read_buf_size) && (!pUser_read_buf)) || (!pZip->m_pRead)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) - return MZ_FALSE; - - /* A directory or zero length file */ - if ((file_stat.m_is_directory) || (!file_stat.m_comp_size)) - return MZ_TRUE; - - /* Encryption and patch files are not supported. */ - if (file_stat.m_bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG)) - return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); - - /* This function only supports decompressing stored and deflate. */ - if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) - return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); - - /* Ensure supplied output buffer is large enough. */ - needed_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? file_stat.m_comp_size : file_stat.m_uncomp_size; - if (buf_size < needed_size) - return mz_zip_set_error(pZip, MZ_ZIP_BUF_TOO_SMALL); - - /* Read and parse the local directory entry. */ - cur_file_ofs = file_stat.m_local_header_ofs; - if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); - - if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - - cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); - if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - - if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) - { - /* The file is stored or the caller has requested the compressed data. */ - if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, (size_t)needed_size) != needed_size) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); - -#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS - if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) == 0) - { - if (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32) - return mz_zip_set_error(pZip, MZ_ZIP_CRC_CHECK_FAILED); - } -#endif - - return MZ_TRUE; - } - - /* Decompress the file either directly from memory or from a file input buffer. */ - tinfl_init(&inflator); - - if (pZip->m_pState->m_pMem) - { - /* Read directly from the archive in memory. */ - pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; - read_buf_size = read_buf_avail = file_stat.m_comp_size; - comp_remaining = 0; - } - else if (pUser_read_buf) - { - /* Use a user provided read buffer. */ - if (!user_read_buf_size) - return MZ_FALSE; - pRead_buf = (mz_uint8 *)pUser_read_buf; - read_buf_size = user_read_buf_size; - read_buf_avail = 0; - comp_remaining = file_stat.m_comp_size; - } - else - { - /* Temporarily allocate a read buffer. */ - read_buf_size = MZ_MIN(file_stat.m_comp_size, (mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE); - if (((sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF)) - return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); - - if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) - return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - - read_buf_avail = 0; - comp_remaining = file_stat.m_comp_size; - } - - do - { - /* The size_t cast here should be OK because we've verified that the output buffer is >= file_stat.m_uncomp_size above */ - size_t in_buf_size, out_buf_size = (size_t)(file_stat.m_uncomp_size - out_buf_ofs); - if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) - { - read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); - if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) - { - status = TINFL_STATUS_FAILED; - mz_zip_set_error(pZip, MZ_ZIP_DECOMPRESSION_FAILED); - break; - } - cur_file_ofs += read_buf_avail; - comp_remaining -= read_buf_avail; - read_buf_ofs = 0; - } - in_buf_size = (size_t)read_buf_avail; - status = tinfl_decompress(&inflator, (mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pBuf, (mz_uint8 *)pBuf + out_buf_ofs, &out_buf_size, TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF | (comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0)); - read_buf_avail -= in_buf_size; - read_buf_ofs += in_buf_size; - out_buf_ofs += out_buf_size; - } while (status == TINFL_STATUS_NEEDS_MORE_INPUT); - - if (status == TINFL_STATUS_DONE) - { - /* Make sure the entire file was decompressed, and check its CRC. */ - if (out_buf_ofs != file_stat.m_uncomp_size) - { - mz_zip_set_error(pZip, MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE); - status = TINFL_STATUS_FAILED; - } -#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS - else if (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32) - { - mz_zip_set_error(pZip, MZ_ZIP_CRC_CHECK_FAILED); - status = TINFL_STATUS_FAILED; - } -#endif - } - - if ((!pZip->m_pState->m_pMem) && (!pUser_read_buf)) - pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); - - return status == TINFL_STATUS_DONE; -} - -mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) -{ - mz_uint32 file_index; - if (!mz_zip_reader_locate_file_v2(pZip, pFilename, NULL, flags, &file_index)) - return MZ_FALSE; - return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, pUser_read_buf, user_read_buf_size); -} - -mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags) -{ - return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, NULL, 0); -} - -mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags) -{ - return mz_zip_reader_extract_file_to_mem_no_alloc(pZip, pFilename, pBuf, buf_size, flags, NULL, 0); -} - -void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags) -{ - mz_uint64 comp_size, uncomp_size, alloc_size; - const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index); - void *pBuf; - - if (pSize) - *pSize = 0; - - if (!p) - { - mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - return NULL; - } - - comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); - uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); - - alloc_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? comp_size : uncomp_size; - if (((sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF)) - { - mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); - return NULL; - } - - if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)alloc_size))) - { - mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - return NULL; - } - - if (!mz_zip_reader_extract_to_mem(pZip, file_index, pBuf, (size_t)alloc_size, flags)) - { - pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); - return NULL; - } - - if (pSize) - *pSize = (size_t)alloc_size; - return pBuf; -} - -void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags) -{ - mz_uint32 file_index; - if (!mz_zip_reader_locate_file_v2(pZip, pFilename, NULL, flags, &file_index)) - { - if (pSize) - *pSize = 0; - return MZ_FALSE; - } - return mz_zip_reader_extract_to_heap(pZip, file_index, pSize, flags); -} - -mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags) -{ - int status = TINFL_STATUS_DONE; - mz_uint file_crc32 = MZ_CRC32_INIT; - mz_uint64 read_buf_size, read_buf_ofs = 0, read_buf_avail, comp_remaining, out_buf_ofs = 0, cur_file_ofs; - mz_zip_archive_file_stat file_stat; - void *pRead_buf = NULL; - void *pWrite_buf = NULL; - mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; - mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; - - if ((!pZip) || (!pZip->m_pState) || (!pCallback) || (!pZip->m_pRead)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) - return MZ_FALSE; - - /* A directory or zero length file */ - if ((file_stat.m_is_directory) || (!file_stat.m_comp_size)) - return MZ_TRUE; - - /* Encryption and patch files are not supported. */ - if (file_stat.m_bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG)) - return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); - - /* This function only supports decompressing stored and deflate. */ - if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) - return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); - - /* Read and do some minimal validation of the local directory entry (this doesn't crack the zip64 stuff, which we already have from the central dir) */ - cur_file_ofs = file_stat.m_local_header_ofs; - if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); - - if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - - cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); - if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - - /* Decompress the file either directly from memory or from a file input buffer. */ - if (pZip->m_pState->m_pMem) - { - pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; - read_buf_size = read_buf_avail = file_stat.m_comp_size; - comp_remaining = 0; - } - else - { - read_buf_size = MZ_MIN(file_stat.m_comp_size, (mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE); - if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) - return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - - read_buf_avail = 0; - comp_remaining = file_stat.m_comp_size; - } - - if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) - { - /* The file is stored or the caller has requested the compressed data. */ - if (pZip->m_pState->m_pMem) - { - if (((sizeof(size_t) == sizeof(mz_uint32))) && (file_stat.m_comp_size > MZ_UINT32_MAX)) - return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); - - if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)file_stat.m_comp_size) != file_stat.m_comp_size) - { - mz_zip_set_error(pZip, MZ_ZIP_WRITE_CALLBACK_FAILED); - status = TINFL_STATUS_FAILED; - } - else if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) - { -#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS - file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)file_stat.m_comp_size); -#endif - } - - cur_file_ofs += file_stat.m_comp_size; - out_buf_ofs += file_stat.m_comp_size; - comp_remaining = 0; - } - else - { - while (comp_remaining) - { - read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); - if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) - { - mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); - status = TINFL_STATUS_FAILED; - break; - } - -#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS - if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) - { - file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)read_buf_avail); - } -#endif - - if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) - { - mz_zip_set_error(pZip, MZ_ZIP_WRITE_CALLBACK_FAILED); - status = TINFL_STATUS_FAILED; - break; - } - - cur_file_ofs += read_buf_avail; - out_buf_ofs += read_buf_avail; - comp_remaining -= read_buf_avail; - } - } - } - else - { - tinfl_decompressor inflator; - tinfl_init(&inflator); - - if (NULL == (pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, TINFL_LZ_DICT_SIZE))) - { - mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - status = TINFL_STATUS_FAILED; - } - else - { - do - { - mz_uint8 *pWrite_buf_cur = (mz_uint8 *)pWrite_buf + (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); - size_t in_buf_size, out_buf_size = TINFL_LZ_DICT_SIZE - (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); - if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) - { - read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); - if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) - { - mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); - status = TINFL_STATUS_FAILED; - break; - } - cur_file_ofs += read_buf_avail; - comp_remaining -= read_buf_avail; - read_buf_ofs = 0; - } - - in_buf_size = (size_t)read_buf_avail; - status = tinfl_decompress(&inflator, (const mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pWrite_buf, pWrite_buf_cur, &out_buf_size, comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0); - read_buf_avail -= in_buf_size; - read_buf_ofs += in_buf_size; - - if (out_buf_size) - { - if (pCallback(pOpaque, out_buf_ofs, pWrite_buf_cur, out_buf_size) != out_buf_size) - { - mz_zip_set_error(pZip, MZ_ZIP_WRITE_CALLBACK_FAILED); - status = TINFL_STATUS_FAILED; - break; - } - -#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS - file_crc32 = (mz_uint32)mz_crc32(file_crc32, pWrite_buf_cur, out_buf_size); -#endif - if ((out_buf_ofs += out_buf_size) > file_stat.m_uncomp_size) - { - mz_zip_set_error(pZip, MZ_ZIP_DECOMPRESSION_FAILED); - status = TINFL_STATUS_FAILED; - break; - } - } - } while ((status == TINFL_STATUS_NEEDS_MORE_INPUT) || (status == TINFL_STATUS_HAS_MORE_OUTPUT)); - } - } - - if ((status == TINFL_STATUS_DONE) && (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) - { - /* Make sure the entire file was decompressed, and check its CRC. */ - if (out_buf_ofs != file_stat.m_uncomp_size) - { - mz_zip_set_error(pZip, MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE); - status = TINFL_STATUS_FAILED; - } -#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS - else if (file_crc32 != file_stat.m_crc32) - { - mz_zip_set_error(pZip, MZ_ZIP_DECOMPRESSION_FAILED); - status = TINFL_STATUS_FAILED; - } -#endif - } - - if (!pZip->m_pState->m_pMem) - pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); - - if (pWrite_buf) - pZip->m_pFree(pZip->m_pAlloc_opaque, pWrite_buf); - - return status == TINFL_STATUS_DONE; -} - -mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags) -{ - mz_uint32 file_index; - if (!mz_zip_reader_locate_file_v2(pZip, pFilename, NULL, flags, &file_index)) - return MZ_FALSE; - - return mz_zip_reader_extract_to_callback(pZip, file_index, pCallback, pOpaque, flags); -} - -mz_zip_reader_extract_iter_state* mz_zip_reader_extract_iter_new(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags) -{ - mz_zip_reader_extract_iter_state *pState; - mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; - mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; - - /* Argument sanity check */ - if ((!pZip) || (!pZip->m_pState)) - return NULL; - - /* Allocate an iterator status structure */ - pState = (mz_zip_reader_extract_iter_state*)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_reader_extract_iter_state)); - if (!pState) - { - mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - return NULL; - } - - /* Fetch file details */ - if (!mz_zip_reader_file_stat(pZip, file_index, &pState->file_stat)) - { - pZip->m_pFree(pZip->m_pAlloc_opaque, pState); - return NULL; - } - - /* Encryption and patch files are not supported. */ - if (pState->file_stat.m_bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG)) - { - mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); - pZip->m_pFree(pZip->m_pAlloc_opaque, pState); - return NULL; - } - - /* This function only supports decompressing stored and deflate. */ - if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (pState->file_stat.m_method != 0) && (pState->file_stat.m_method != MZ_DEFLATED)) - { - mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); - pZip->m_pFree(pZip->m_pAlloc_opaque, pState); - return NULL; - } - - /* Init state - save args */ - pState->pZip = pZip; - pState->flags = flags; - - /* Init state - reset variables to defaults */ - pState->status = TINFL_STATUS_DONE; -#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS - pState->file_crc32 = MZ_CRC32_INIT; -#endif - pState->read_buf_ofs = 0; - pState->out_buf_ofs = 0; - pState->pRead_buf = NULL; - pState->pWrite_buf = NULL; - pState->out_blk_remain = 0; - - /* Read and parse the local directory entry. */ - pState->cur_file_ofs = pState->file_stat.m_local_header_ofs; - if (pZip->m_pRead(pZip->m_pIO_opaque, pState->cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) - { - mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); - pZip->m_pFree(pZip->m_pAlloc_opaque, pState); - return NULL; - } - - if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) - { - mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - pZip->m_pFree(pZip->m_pAlloc_opaque, pState); - return NULL; - } - - pState->cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); - if ((pState->cur_file_ofs + pState->file_stat.m_comp_size) > pZip->m_archive_size) - { - mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - pZip->m_pFree(pZip->m_pAlloc_opaque, pState); - return NULL; - } - - /* Decompress the file either directly from memory or from a file input buffer. */ - if (pZip->m_pState->m_pMem) - { - pState->pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + pState->cur_file_ofs; - pState->read_buf_size = pState->read_buf_avail = pState->file_stat.m_comp_size; - pState->comp_remaining = pState->file_stat.m_comp_size; - } - else - { - if (!((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!pState->file_stat.m_method))) - { - /* Decompression required, therefore intermediate read buffer required */ - pState->read_buf_size = MZ_MIN(pState->file_stat.m_comp_size, MZ_ZIP_MAX_IO_BUF_SIZE); - if (NULL == (pState->pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)pState->read_buf_size))) - { - mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - pZip->m_pFree(pZip->m_pAlloc_opaque, pState); - return NULL; - } - } - else - { - /* Decompression not required - we will be reading directly into user buffer, no temp buf required */ - pState->read_buf_size = 0; - } - pState->read_buf_avail = 0; - pState->comp_remaining = pState->file_stat.m_comp_size; - } - - if (!((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!pState->file_stat.m_method))) - { - /* Decompression required, init decompressor */ - tinfl_init( &pState->inflator ); - - /* Allocate write buffer */ - if (NULL == (pState->pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, TINFL_LZ_DICT_SIZE))) - { - mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - if (pState->pRead_buf) - pZip->m_pFree(pZip->m_pAlloc_opaque, pState->pRead_buf); - pZip->m_pFree(pZip->m_pAlloc_opaque, pState); - return NULL; - } - } - - return pState; -} - -mz_zip_reader_extract_iter_state* mz_zip_reader_extract_file_iter_new(mz_zip_archive *pZip, const char *pFilename, mz_uint flags) -{ - mz_uint32 file_index; - - /* Locate file index by name */ - if (!mz_zip_reader_locate_file_v2(pZip, pFilename, NULL, flags, &file_index)) - return NULL; - - /* Construct iterator */ - return mz_zip_reader_extract_iter_new(pZip, file_index, flags); -} - -size_t mz_zip_reader_extract_iter_read(mz_zip_reader_extract_iter_state* pState, void* pvBuf, size_t buf_size) -{ - size_t copied_to_caller = 0; - - /* Argument sanity check */ - if ((!pState) || (!pState->pZip) || (!pState->pZip->m_pState) || (!pvBuf)) - return 0; - - if ((pState->flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!pState->file_stat.m_method)) - { - /* The file is stored or the caller has requested the compressed data, calc amount to return. */ - copied_to_caller = MZ_MIN( buf_size, pState->comp_remaining ); - - /* Zip is in memory....or requires reading from a file? */ - if (pState->pZip->m_pState->m_pMem) - { - /* Copy data to caller's buffer */ - memcpy( pvBuf, pState->pRead_buf, copied_to_caller ); - pState->pRead_buf = ((mz_uint8*)pState->pRead_buf) + copied_to_caller; - } - else - { - /* Read directly into caller's buffer */ - if (pState->pZip->m_pRead(pState->pZip->m_pIO_opaque, pState->cur_file_ofs, pvBuf, copied_to_caller) != copied_to_caller) - { - /* Failed to read all that was asked for, flag failure and alert user */ - mz_zip_set_error(pState->pZip, MZ_ZIP_FILE_READ_FAILED); - pState->status = TINFL_STATUS_FAILED; - copied_to_caller = 0; - } - } - -#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS - /* Compute CRC if not returning compressed data only */ - if (!(pState->flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) - pState->file_crc32 = (mz_uint32)mz_crc32(pState->file_crc32, (const mz_uint8 *)pvBuf, copied_to_caller); -#endif - - /* Advance offsets, dec counters */ - pState->cur_file_ofs += copied_to_caller; - pState->out_buf_ofs += copied_to_caller; - pState->comp_remaining -= copied_to_caller; - } - else - { - do - { - /* Calc ptr to write buffer - given current output pos and block size */ - mz_uint8 *pWrite_buf_cur = (mz_uint8 *)pState->pWrite_buf + (pState->out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); - - /* Calc max output size - given current output pos and block size */ - size_t in_buf_size, out_buf_size = TINFL_LZ_DICT_SIZE - (pState->out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); - - if (!pState->out_blk_remain) - { - /* Read more data from file if none available (and reading from file) */ - if ((!pState->read_buf_avail) && (!pState->pZip->m_pState->m_pMem)) - { - /* Calc read size */ - pState->read_buf_avail = MZ_MIN(pState->read_buf_size, pState->comp_remaining); - if (pState->pZip->m_pRead(pState->pZip->m_pIO_opaque, pState->cur_file_ofs, pState->pRead_buf, (size_t)pState->read_buf_avail) != pState->read_buf_avail) - { - mz_zip_set_error(pState->pZip, MZ_ZIP_FILE_READ_FAILED); - pState->status = TINFL_STATUS_FAILED; - break; - } - - /* Advance offsets, dec counters */ - pState->cur_file_ofs += pState->read_buf_avail; - pState->comp_remaining -= pState->read_buf_avail; - pState->read_buf_ofs = 0; - } - - /* Perform decompression */ - in_buf_size = (size_t)pState->read_buf_avail; - pState->status = tinfl_decompress(&pState->inflator, (const mz_uint8 *)pState->pRead_buf + pState->read_buf_ofs, &in_buf_size, (mz_uint8 *)pState->pWrite_buf, pWrite_buf_cur, &out_buf_size, pState->comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0); - pState->read_buf_avail -= in_buf_size; - pState->read_buf_ofs += in_buf_size; - - /* Update current output block size remaining */ - pState->out_blk_remain = out_buf_size; - } - - if (pState->out_blk_remain) - { - /* Calc amount to return. */ - size_t to_copy = MZ_MIN( (buf_size - copied_to_caller), pState->out_blk_remain ); - - /* Copy data to caller's buffer */ - memcpy( (uint8_t*)pvBuf + copied_to_caller, pWrite_buf_cur, to_copy ); - -#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS - /* Perform CRC */ - pState->file_crc32 = (mz_uint32)mz_crc32(pState->file_crc32, pWrite_buf_cur, to_copy); -#endif - - /* Decrement data consumed from block */ - pState->out_blk_remain -= to_copy; - - /* Inc output offset, while performing sanity check */ - if ((pState->out_buf_ofs += to_copy) > pState->file_stat.m_uncomp_size) - { - mz_zip_set_error(pState->pZip, MZ_ZIP_DECOMPRESSION_FAILED); - pState->status = TINFL_STATUS_FAILED; - break; - } - - /* Increment counter of data copied to caller */ - copied_to_caller += to_copy; - } - } while ( (copied_to_caller < buf_size) && ((pState->status == TINFL_STATUS_NEEDS_MORE_INPUT) || (pState->status == TINFL_STATUS_HAS_MORE_OUTPUT)) ); - } - - /* Return how many bytes were copied into user buffer */ - return copied_to_caller; -} - -mz_bool mz_zip_reader_extract_iter_free(mz_zip_reader_extract_iter_state* pState) -{ - int status; - - /* Argument sanity check */ - if ((!pState) || (!pState->pZip) || (!pState->pZip->m_pState)) - return MZ_FALSE; - - /* Was decompression completed and requested? */ - if ((pState->status == TINFL_STATUS_DONE) && (!(pState->flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) - { - /* Make sure the entire file was decompressed, and check its CRC. */ - if (pState->out_buf_ofs != pState->file_stat.m_uncomp_size) - { - mz_zip_set_error(pState->pZip, MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE); - pState->status = TINFL_STATUS_FAILED; - } -#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS - else if (pState->file_crc32 != pState->file_stat.m_crc32) - { - mz_zip_set_error(pState->pZip, MZ_ZIP_DECOMPRESSION_FAILED); - pState->status = TINFL_STATUS_FAILED; - } -#endif - } - - /* Free buffers */ - if (!pState->pZip->m_pState->m_pMem) - pState->pZip->m_pFree(pState->pZip->m_pAlloc_opaque, pState->pRead_buf); - if (pState->pWrite_buf) - pState->pZip->m_pFree(pState->pZip->m_pAlloc_opaque, pState->pWrite_buf); - - /* Save status */ - status = pState->status; - - /* Free context */ - pState->pZip->m_pFree(pState->pZip->m_pAlloc_opaque, pState); - - return status == TINFL_STATUS_DONE; -} - -#ifndef MINIZ_NO_STDIO -static size_t mz_zip_file_write_callback(void *pOpaque, mz_uint64 ofs, const void *pBuf, size_t n) -{ - (void)ofs; - - return MZ_FWRITE(pBuf, 1, n, (MZ_FILE *)pOpaque); -} - -mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags) -{ - mz_bool status; - mz_zip_archive_file_stat file_stat; - MZ_FILE *pFile; - - if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) - return MZ_FALSE; - - if ((file_stat.m_is_directory) || (!file_stat.m_is_supported)) - return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_FEATURE); - - pFile = MZ_FOPEN(pDst_filename, "wb"); - if (!pFile) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); - - status = mz_zip_reader_extract_to_callback(pZip, file_index, mz_zip_file_write_callback, pFile, flags); - - if (MZ_FCLOSE(pFile) == EOF) - { - if (status) - mz_zip_set_error(pZip, MZ_ZIP_FILE_CLOSE_FAILED); - - status = MZ_FALSE; - } - -#if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_STDIO) - if (status) - mz_zip_set_file_times(pDst_filename, file_stat.m_time, file_stat.m_time); -#endif - - return status; -} - -mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags) -{ - mz_uint32 file_index; - if (!mz_zip_reader_locate_file_v2(pZip, pArchive_filename, NULL, flags, &file_index)) - return MZ_FALSE; - - return mz_zip_reader_extract_to_file(pZip, file_index, pDst_filename, flags); -} - -mz_bool mz_zip_reader_extract_to_cfile(mz_zip_archive *pZip, mz_uint file_index, MZ_FILE *pFile, mz_uint flags) -{ - mz_zip_archive_file_stat file_stat; - - if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) - return MZ_FALSE; - - if ((file_stat.m_is_directory) || (!file_stat.m_is_supported)) - return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_FEATURE); - - return mz_zip_reader_extract_to_callback(pZip, file_index, mz_zip_file_write_callback, pFile, flags); -} - -mz_bool mz_zip_reader_extract_file_to_cfile(mz_zip_archive *pZip, const char *pArchive_filename, MZ_FILE *pFile, mz_uint flags) -{ - mz_uint32 file_index; - if (!mz_zip_reader_locate_file_v2(pZip, pArchive_filename, NULL, flags, &file_index)) - return MZ_FALSE; - - return mz_zip_reader_extract_to_cfile(pZip, file_index, pFile, flags); -} -#endif /* #ifndef MINIZ_NO_STDIO */ - -static size_t mz_zip_compute_crc32_callback(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) -{ - mz_uint32 *p = (mz_uint32 *)pOpaque; - (void)file_ofs; - *p = (mz_uint32)mz_crc32(*p, (const mz_uint8 *)pBuf, n); - return n; -} - -mz_bool mz_zip_validate_file(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags) -{ - mz_zip_archive_file_stat file_stat; - mz_zip_internal_state *pState; - const mz_uint8 *pCentral_dir_header; - mz_bool found_zip64_ext_data_in_cdir = MZ_FALSE; - mz_bool found_zip64_ext_data_in_ldir = MZ_FALSE; - mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; - mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; - mz_uint64 local_header_ofs = 0; - mz_uint32 local_header_filename_len, local_header_extra_len, local_header_crc32; - mz_uint64 local_header_comp_size, local_header_uncomp_size; - mz_uint32 uncomp_crc32 = MZ_CRC32_INIT; - mz_bool has_data_descriptor; - mz_uint32 local_header_bit_flags; - - mz_zip_array file_data_array; - mz_zip_array_init(&file_data_array, 1); - - if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (!pZip->m_pRead)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - if (file_index > pZip->m_total_files) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - pState = pZip->m_pState; - - pCentral_dir_header = mz_zip_get_cdh(pZip, file_index); - - if (!mz_zip_file_stat_internal(pZip, file_index, pCentral_dir_header, &file_stat, &found_zip64_ext_data_in_cdir)) - return MZ_FALSE; - - /* A directory or zero length file */ - if ((file_stat.m_is_directory) || (!file_stat.m_uncomp_size)) - return MZ_TRUE; - - /* Encryption and patch files are not supported. */ - if (file_stat.m_is_encrypted) - return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); - - /* This function only supports stored and deflate. */ - if ((file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) - return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); - - if (!file_stat.m_is_supported) - return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_FEATURE); - - /* Read and parse the local directory entry. */ - local_header_ofs = file_stat.m_local_header_ofs; - if (pZip->m_pRead(pZip->m_pIO_opaque, local_header_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); - - if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - - local_header_filename_len = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS); - local_header_extra_len = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); - local_header_comp_size = MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS); - local_header_uncomp_size = MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS); - local_header_crc32 = MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_CRC32_OFS); - local_header_bit_flags = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS); - has_data_descriptor = (local_header_bit_flags & 8) != 0; - - if (local_header_filename_len != strlen(file_stat.m_filename)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - - if ((local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + local_header_filename_len + local_header_extra_len + file_stat.m_comp_size) > pZip->m_archive_size) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - - if (!mz_zip_array_resize(pZip, &file_data_array, MZ_MAX(local_header_filename_len, local_header_extra_len), MZ_FALSE)) - return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - - if (local_header_filename_len) - { - if (pZip->m_pRead(pZip->m_pIO_opaque, local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE, file_data_array.m_p, local_header_filename_len) != local_header_filename_len) - { - mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); - goto handle_failure; - } - - /* I've seen 1 archive that had the same pathname, but used backslashes in the local dir and forward slashes in the central dir. Do we care about this? For now, this case will fail validation. */ - if (memcmp(file_stat.m_filename, file_data_array.m_p, local_header_filename_len) != 0) - { - mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); - goto handle_failure; - } - } - - if ((local_header_extra_len) && ((local_header_comp_size == MZ_UINT32_MAX) || (local_header_uncomp_size == MZ_UINT32_MAX))) - { - mz_uint32 extra_size_remaining = local_header_extra_len; - const mz_uint8 *pExtra_data = (const mz_uint8 *)file_data_array.m_p; - - if (pZip->m_pRead(pZip->m_pIO_opaque, local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + local_header_filename_len, file_data_array.m_p, local_header_extra_len) != local_header_extra_len) - { - mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); - goto handle_failure; - } - - do - { - mz_uint32 field_id, field_data_size, field_total_size; - - if (extra_size_remaining < (sizeof(mz_uint16) * 2)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - - field_id = MZ_READ_LE16(pExtra_data); - field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); - field_total_size = field_data_size + sizeof(mz_uint16) * 2; - - if (field_total_size > extra_size_remaining) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - - if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) - { - const mz_uint8 *pSrc_field_data = pExtra_data + sizeof(mz_uint32); - - if (field_data_size < sizeof(mz_uint64) * 2) - { - mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - goto handle_failure; - } - - local_header_uncomp_size = MZ_READ_LE64(pSrc_field_data); - local_header_comp_size = MZ_READ_LE64(pSrc_field_data + sizeof(mz_uint64)); - - found_zip64_ext_data_in_ldir = MZ_TRUE; - break; - } - - pExtra_data += field_total_size; - extra_size_remaining -= field_total_size; - } while (extra_size_remaining); - } - - /* TODO: parse local header extra data when local_header_comp_size is 0xFFFFFFFF! (big_descriptor.zip) */ - /* I've seen zips in the wild with the data descriptor bit set, but proper local header values and bogus data descriptors */ - if ((has_data_descriptor) && (!local_header_comp_size) && (!local_header_crc32)) - { - mz_uint8 descriptor_buf[32]; - mz_bool has_id; - const mz_uint8 *pSrc; - mz_uint32 file_crc32; - mz_uint64 comp_size = 0, uncomp_size = 0; - - mz_uint32 num_descriptor_uint32s = ((pState->m_zip64) || (found_zip64_ext_data_in_ldir)) ? 6 : 4; - - if (pZip->m_pRead(pZip->m_pIO_opaque, local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + local_header_filename_len + local_header_extra_len + file_stat.m_comp_size, descriptor_buf, sizeof(mz_uint32) * num_descriptor_uint32s) != (sizeof(mz_uint32) * num_descriptor_uint32s)) - { - mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); - goto handle_failure; - } - - has_id = (MZ_READ_LE32(descriptor_buf) == MZ_ZIP_DATA_DESCRIPTOR_ID); - pSrc = has_id ? (descriptor_buf + sizeof(mz_uint32)) : descriptor_buf; - - file_crc32 = MZ_READ_LE32(pSrc); - - if ((pState->m_zip64) || (found_zip64_ext_data_in_ldir)) - { - comp_size = MZ_READ_LE64(pSrc + sizeof(mz_uint32)); - uncomp_size = MZ_READ_LE64(pSrc + sizeof(mz_uint32) + sizeof(mz_uint64)); - } - else - { - comp_size = MZ_READ_LE32(pSrc + sizeof(mz_uint32)); - uncomp_size = MZ_READ_LE32(pSrc + sizeof(mz_uint32) + sizeof(mz_uint32)); - } - - if ((file_crc32 != file_stat.m_crc32) || (comp_size != file_stat.m_comp_size) || (uncomp_size != file_stat.m_uncomp_size)) - { - mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); - goto handle_failure; - } - } - else - { - if ((local_header_crc32 != file_stat.m_crc32) || (local_header_comp_size != file_stat.m_comp_size) || (local_header_uncomp_size != file_stat.m_uncomp_size)) - { - mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); - goto handle_failure; - } - } - - mz_zip_array_clear(pZip, &file_data_array); - - if ((flags & MZ_ZIP_FLAG_VALIDATE_HEADERS_ONLY) == 0) - { - if (!mz_zip_reader_extract_to_callback(pZip, file_index, mz_zip_compute_crc32_callback, &uncomp_crc32, 0)) - return MZ_FALSE; - - /* 1 more check to be sure, although the extract checks too. */ - if (uncomp_crc32 != file_stat.m_crc32) - { - mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); - return MZ_FALSE; - } - } - - return MZ_TRUE; - -handle_failure: - mz_zip_array_clear(pZip, &file_data_array); - return MZ_FALSE; -} - -mz_bool mz_zip_validate_archive(mz_zip_archive *pZip, mz_uint flags) -{ - mz_zip_internal_state *pState; - uint32_t i; - - if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (!pZip->m_pRead)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - pState = pZip->m_pState; - - /* Basic sanity checks */ - if (!pState->m_zip64) - { - if (pZip->m_total_files > MZ_UINT16_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); - - if (pZip->m_archive_size > MZ_UINT32_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); - } - else - { - if (pZip->m_total_files >= MZ_UINT32_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); - - if (pState->m_central_dir.m_size >= MZ_UINT32_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); - } - - for (i = 0; i < pZip->m_total_files; i++) - { - if (MZ_ZIP_FLAG_VALIDATE_LOCATE_FILE_FLAG & flags) - { - mz_uint32 found_index; - mz_zip_archive_file_stat stat; - - if (!mz_zip_reader_file_stat(pZip, i, &stat)) - return MZ_FALSE; - - if (!mz_zip_reader_locate_file_v2(pZip, stat.m_filename, NULL, 0, &found_index)) - return MZ_FALSE; - - /* This check can fail if there are duplicate filenames in the archive (which we don't check for when writing - that's up to the user) */ - if (found_index != i) - return mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); - } - - if (!mz_zip_validate_file(pZip, i, flags)) - return MZ_FALSE; - } - - return MZ_TRUE; -} - -mz_bool mz_zip_validate_mem_archive(const void *pMem, size_t size, mz_uint flags, mz_zip_error *pErr) -{ - mz_bool success = MZ_TRUE; - mz_zip_archive zip; - mz_zip_error actual_err = MZ_ZIP_NO_ERROR; - - if ((!pMem) || (!size)) - { - if (pErr) - *pErr = MZ_ZIP_INVALID_PARAMETER; - return MZ_FALSE; - } - - mz_zip_zero_struct(&zip); - - if (!mz_zip_reader_init_mem(&zip, pMem, size, flags)) - { - if (pErr) - *pErr = zip.m_last_error; - return MZ_FALSE; - } - - if (!mz_zip_validate_archive(&zip, flags)) - { - actual_err = zip.m_last_error; - success = MZ_FALSE; - } - - if (!mz_zip_reader_end_internal(&zip, success)) - { - if (!actual_err) - actual_err = zip.m_last_error; - success = MZ_FALSE; - } - - if (pErr) - *pErr = actual_err; - - return success; -} - -#ifndef MINIZ_NO_STDIO -mz_bool mz_zip_validate_file_archive(const char *pFilename, mz_uint flags, mz_zip_error *pErr) -{ - mz_bool success = MZ_TRUE; - mz_zip_archive zip; - mz_zip_error actual_err = MZ_ZIP_NO_ERROR; - - if (!pFilename) - { - if (pErr) - *pErr = MZ_ZIP_INVALID_PARAMETER; - return MZ_FALSE; - } - - mz_zip_zero_struct(&zip); - - if (!mz_zip_reader_init_file_v2(&zip, pFilename, flags, 0, 0)) - { - if (pErr) - *pErr = zip.m_last_error; - return MZ_FALSE; - } - - if (!mz_zip_validate_archive(&zip, flags)) - { - actual_err = zip.m_last_error; - success = MZ_FALSE; - } - - if (!mz_zip_reader_end_internal(&zip, success)) - { - if (!actual_err) - actual_err = zip.m_last_error; - success = MZ_FALSE; - } - - if (pErr) - *pErr = actual_err; - - return success; -} -#endif /* #ifndef MINIZ_NO_STDIO */ - -/* ------------------- .ZIP archive writing */ - -#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS - -static MZ_FORCEINLINE void mz_write_le16(mz_uint8 *p, mz_uint16 v) -{ - p[0] = (mz_uint8)v; - p[1] = (mz_uint8)(v >> 8); -} -static MZ_FORCEINLINE void mz_write_le32(mz_uint8 *p, mz_uint32 v) -{ - p[0] = (mz_uint8)v; - p[1] = (mz_uint8)(v >> 8); - p[2] = (mz_uint8)(v >> 16); - p[3] = (mz_uint8)(v >> 24); -} -static MZ_FORCEINLINE void mz_write_le64(mz_uint8 *p, mz_uint64 v) -{ - mz_write_le32(p, (mz_uint32)v); - mz_write_le32(p + sizeof(mz_uint32), (mz_uint32)(v >> 32)); -} - -#define MZ_WRITE_LE16(p, v) mz_write_le16((mz_uint8 *)(p), (mz_uint16)(v)) -#define MZ_WRITE_LE32(p, v) mz_write_le32((mz_uint8 *)(p), (mz_uint32)(v)) -#define MZ_WRITE_LE64(p, v) mz_write_le64((mz_uint8 *)(p), (mz_uint64)(v)) - -static size_t mz_zip_heap_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) -{ - mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; - mz_zip_internal_state *pState = pZip->m_pState; - mz_uint64 new_size = MZ_MAX(file_ofs + n, pState->m_mem_size); - - if (!n) - return 0; - - /* An allocation this big is likely to just fail on 32-bit systems, so don't even go there. */ - if ((sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF)) - { - mz_zip_set_error(pZip, MZ_ZIP_FILE_TOO_LARGE); - return 0; - } - - if (new_size > pState->m_mem_capacity) - { - void *pNew_block; - size_t new_capacity = MZ_MAX(64, pState->m_mem_capacity); - - while (new_capacity < new_size) - new_capacity *= 2; - - if (NULL == (pNew_block = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pState->m_pMem, 1, new_capacity))) - { - mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - return 0; - } - - pState->m_pMem = pNew_block; - pState->m_mem_capacity = new_capacity; - } - memcpy((mz_uint8 *)pState->m_pMem + file_ofs, pBuf, n); - pState->m_mem_size = (size_t)new_size; - return n; -} - -static mz_bool mz_zip_writer_end_internal(mz_zip_archive *pZip, mz_bool set_last_error) -{ - mz_zip_internal_state *pState; - mz_bool status = MZ_TRUE; - - if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || ((pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) && (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED))) - { - if (set_last_error) - mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - return MZ_FALSE; - } - - pState = pZip->m_pState; - pZip->m_pState = NULL; - mz_zip_array_clear(pZip, &pState->m_central_dir); - mz_zip_array_clear(pZip, &pState->m_central_dir_offsets); - mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); - -#ifndef MINIZ_NO_STDIO - if (pState->m_pFile) - { - if (pZip->m_zip_type == MZ_ZIP_TYPE_FILE) - { - if (MZ_FCLOSE(pState->m_pFile) == EOF) - { - if (set_last_error) - mz_zip_set_error(pZip, MZ_ZIP_FILE_CLOSE_FAILED); - status = MZ_FALSE; - } - } - - pState->m_pFile = NULL; - } -#endif /* #ifndef MINIZ_NO_STDIO */ - - if ((pZip->m_pWrite == mz_zip_heap_write_func) && (pState->m_pMem)) - { - pZip->m_pFree(pZip->m_pAlloc_opaque, pState->m_pMem); - pState->m_pMem = NULL; - } - - pZip->m_pFree(pZip->m_pAlloc_opaque, pState); - pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; - return status; -} - -mz_bool mz_zip_writer_init_v2(mz_zip_archive *pZip, mz_uint64 existing_size, mz_uint flags) -{ - mz_bool zip64 = (flags & MZ_ZIP_FLAG_WRITE_ZIP64) != 0; - - if ((!pZip) || (pZip->m_pState) || (!pZip->m_pWrite) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - if (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) - { - if (!pZip->m_pRead) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - } - - if (pZip->m_file_offset_alignment) - { - /* Ensure user specified file offset alignment is a power of 2. */ - if (pZip->m_file_offset_alignment & (pZip->m_file_offset_alignment - 1)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - } - - if (!pZip->m_pAlloc) - pZip->m_pAlloc = miniz_def_alloc_func; - if (!pZip->m_pFree) - pZip->m_pFree = miniz_def_free_func; - if (!pZip->m_pRealloc) - pZip->m_pRealloc = miniz_def_realloc_func; - - pZip->m_archive_size = existing_size; - pZip->m_central_directory_file_ofs = 0; - pZip->m_total_files = 0; - - if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) - return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - - memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); - - MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8)); - MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32)); - MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32)); - - pZip->m_pState->m_zip64 = zip64; - pZip->m_pState->m_zip64_has_extended_info_fields = zip64; - - pZip->m_zip_type = MZ_ZIP_TYPE_USER; - pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; - - return MZ_TRUE; -} - -mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size) -{ - return mz_zip_writer_init_v2(pZip, existing_size, 0); -} - -mz_bool mz_zip_writer_init_heap_v2(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size, mz_uint flags) -{ - pZip->m_pWrite = mz_zip_heap_write_func; - pZip->m_pNeeds_keepalive = NULL; - - if (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) - pZip->m_pRead = mz_zip_mem_read_func; - - pZip->m_pIO_opaque = pZip; - - if (!mz_zip_writer_init_v2(pZip, size_to_reserve_at_beginning, flags)) - return MZ_FALSE; - - pZip->m_zip_type = MZ_ZIP_TYPE_HEAP; - - if (0 != (initial_allocation_size = MZ_MAX(initial_allocation_size, size_to_reserve_at_beginning))) - { - if (NULL == (pZip->m_pState->m_pMem = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, initial_allocation_size))) - { - mz_zip_writer_end_internal(pZip, MZ_FALSE); - return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - } - pZip->m_pState->m_mem_capacity = initial_allocation_size; - } - - return MZ_TRUE; -} - -mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size) -{ - return mz_zip_writer_init_heap_v2(pZip, size_to_reserve_at_beginning, initial_allocation_size, 0); -} - -#ifndef MINIZ_NO_STDIO -static size_t mz_zip_file_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) -{ - mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; - mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); - - file_ofs += pZip->m_pState->m_file_archive_start_ofs; - - if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) - { - mz_zip_set_error(pZip, MZ_ZIP_FILE_SEEK_FAILED); - return 0; - } - - return MZ_FWRITE(pBuf, 1, n, pZip->m_pState->m_pFile); -} - -mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning) -{ - return mz_zip_writer_init_file_v2(pZip, pFilename, size_to_reserve_at_beginning, 0); -} - -mz_bool mz_zip_writer_init_file_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning, mz_uint flags) -{ - MZ_FILE *pFile; - - pZip->m_pWrite = mz_zip_file_write_func; - pZip->m_pNeeds_keepalive = NULL; - - if (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) - pZip->m_pRead = mz_zip_file_read_func; - - pZip->m_pIO_opaque = pZip; - - if (!mz_zip_writer_init_v2(pZip, size_to_reserve_at_beginning, flags)) - return MZ_FALSE; - - if (NULL == (pFile = MZ_FOPEN(pFilename, (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) ? "w+b" : "wb"))) - { - mz_zip_writer_end(pZip); - return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); - } - - pZip->m_pState->m_pFile = pFile; - pZip->m_zip_type = MZ_ZIP_TYPE_FILE; - - if (size_to_reserve_at_beginning) - { - mz_uint64 cur_ofs = 0; - char buf[4096]; - - MZ_CLEAR_OBJ(buf); - - do - { - size_t n = (size_t)MZ_MIN(sizeof(buf), size_to_reserve_at_beginning); - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_ofs, buf, n) != n) - { - mz_zip_writer_end(pZip); - return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); - } - cur_ofs += n; - size_to_reserve_at_beginning -= n; - } while (size_to_reserve_at_beginning); - } - - return MZ_TRUE; -} - -mz_bool mz_zip_writer_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile, mz_uint flags) -{ - pZip->m_pWrite = mz_zip_file_write_func; - pZip->m_pNeeds_keepalive = NULL; - - if (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) - pZip->m_pRead = mz_zip_file_read_func; - - pZip->m_pIO_opaque = pZip; - - if (!mz_zip_writer_init_v2(pZip, 0, flags)) - return MZ_FALSE; - - pZip->m_pState->m_pFile = pFile; - pZip->m_pState->m_file_archive_start_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); - pZip->m_zip_type = MZ_ZIP_TYPE_CFILE; - - return MZ_TRUE; -} -#endif /* #ifndef MINIZ_NO_STDIO */ - -mz_bool mz_zip_writer_init_from_reader_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint flags) -{ - mz_zip_internal_state *pState; - - if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - if (flags & MZ_ZIP_FLAG_WRITE_ZIP64) - { - /* We don't support converting a non-zip64 file to zip64 - this seems like more trouble than it's worth. (What about the existing 32-bit data descriptors that could follow the compressed data?) */ - if (!pZip->m_pState->m_zip64) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - } - - /* No sense in trying to write to an archive that's already at the support max size */ - if (pZip->m_pState->m_zip64) - { - if (pZip->m_total_files == MZ_UINT32_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); - } - else - { - if (pZip->m_total_files == MZ_UINT16_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); - - if ((pZip->m_archive_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) > MZ_UINT32_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_TOO_LARGE); - } - - pState = pZip->m_pState; - - if (pState->m_pFile) - { -#ifdef MINIZ_NO_STDIO - (void)pFilename; - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); -#else - if (pZip->m_pIO_opaque != pZip) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - if (pZip->m_zip_type == MZ_ZIP_TYPE_FILE) - { - if (!pFilename) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - /* Archive is being read from stdio and was originally opened only for reading. Try to reopen as writable. */ - if (NULL == (pState->m_pFile = MZ_FREOPEN(pFilename, "r+b", pState->m_pFile))) - { - /* The mz_zip_archive is now in a bogus state because pState->m_pFile is NULL, so just close it. */ - mz_zip_reader_end_internal(pZip, MZ_FALSE); - return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); - } - } - - pZip->m_pWrite = mz_zip_file_write_func; - pZip->m_pNeeds_keepalive = NULL; -#endif /* #ifdef MINIZ_NO_STDIO */ - } - else if (pState->m_pMem) - { - /* Archive lives in a memory block. Assume it's from the heap that we can resize using the realloc callback. */ - if (pZip->m_pIO_opaque != pZip) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - pState->m_mem_capacity = pState->m_mem_size; - pZip->m_pWrite = mz_zip_heap_write_func; - pZip->m_pNeeds_keepalive = NULL; - } - /* Archive is being read via a user provided read function - make sure the user has specified a write function too. */ - else if (!pZip->m_pWrite) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - /* Start writing new files at the archive's current central directory location. */ - /* TODO: We could add a flag that lets the user start writing immediately AFTER the existing central dir - this would be safer. */ - pZip->m_archive_size = pZip->m_central_directory_file_ofs; - pZip->m_central_directory_file_ofs = 0; - - /* Clear the sorted central dir offsets, they aren't useful or maintained now. */ - /* Even though we're now in write mode, files can still be extracted and verified, but file locates will be slow. */ - /* TODO: We could easily maintain the sorted central directory offsets. */ - mz_zip_array_clear(pZip, &pZip->m_pState->m_sorted_central_dir_offsets); - - pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; - - return MZ_TRUE; -} - -mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename) -{ - return mz_zip_writer_init_from_reader_v2(pZip, pFilename, 0); -} - -/* TODO: pArchive_name is a terrible name here! */ -mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags) -{ - return mz_zip_writer_add_mem_ex(pZip, pArchive_name, pBuf, buf_size, NULL, 0, level_and_flags, 0, 0); -} - -typedef struct -{ - mz_zip_archive *m_pZip; - mz_uint64 m_cur_archive_file_ofs; - mz_uint64 m_comp_size; -} mz_zip_writer_add_state; - -static mz_bool mz_zip_writer_add_put_buf_callback(const void *pBuf, int len, void *pUser) -{ - mz_zip_writer_add_state *pState = (mz_zip_writer_add_state *)pUser; - if ((int)pState->m_pZip->m_pWrite(pState->m_pZip->m_pIO_opaque, pState->m_cur_archive_file_ofs, pBuf, len) != len) - return MZ_FALSE; - - pState->m_cur_archive_file_ofs += len; - pState->m_comp_size += len; - return MZ_TRUE; -} - -#define MZ_ZIP64_MAX_LOCAL_EXTRA_FIELD_SIZE (sizeof(mz_uint16) * 2 + sizeof(mz_uint64) * 2) -#define MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE (sizeof(mz_uint16) * 2 + sizeof(mz_uint64) * 3) -static mz_uint32 mz_zip_writer_create_zip64_extra_data(mz_uint8 *pBuf, mz_uint64 *pUncomp_size, mz_uint64 *pComp_size, mz_uint64 *pLocal_header_ofs) -{ - mz_uint8 *pDst = pBuf; - mz_uint32 field_size = 0; - - MZ_WRITE_LE16(pDst + 0, MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID); - MZ_WRITE_LE16(pDst + 2, 0); - pDst += sizeof(mz_uint16) * 2; - - if (pUncomp_size) - { - MZ_WRITE_LE64(pDst, *pUncomp_size); - pDst += sizeof(mz_uint64); - field_size += sizeof(mz_uint64); - } - - if (pComp_size) - { - MZ_WRITE_LE64(pDst, *pComp_size); - pDst += sizeof(mz_uint64); - field_size += sizeof(mz_uint64); - } - - if (pLocal_header_ofs) - { - MZ_WRITE_LE64(pDst, *pLocal_header_ofs); - pDst += sizeof(mz_uint64); - field_size += sizeof(mz_uint64); - } - - MZ_WRITE_LE16(pBuf + 2, field_size); - - return (mz_uint32)(pDst - pBuf); -} - -static mz_bool mz_zip_writer_create_local_dir_header(mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, mz_uint16 extra_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date) -{ - (void)pZip; - memset(pDst, 0, MZ_ZIP_LOCAL_DIR_HEADER_SIZE); - MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_SIG_OFS, MZ_ZIP_LOCAL_DIR_HEADER_SIG); - MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_VERSION_NEEDED_OFS, method ? 20 : 0); - MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_BIT_FLAG_OFS, bit_flags); - MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_METHOD_OFS, method); - MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_TIME_OFS, dos_time); - MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_DATE_OFS, dos_date); - MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_CRC32_OFS, uncomp_crc32); - MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS, MZ_MIN(comp_size, MZ_UINT32_MAX)); - MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS, MZ_MIN(uncomp_size, MZ_UINT32_MAX)); - MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILENAME_LEN_OFS, filename_size); - MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_EXTRA_LEN_OFS, extra_size); - return MZ_TRUE; -} - -static mz_bool mz_zip_writer_create_central_dir_header(mz_zip_archive *pZip, mz_uint8 *pDst, - mz_uint16 filename_size, mz_uint16 extra_size, mz_uint16 comment_size, - mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, - mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, - mz_uint64 local_header_ofs, mz_uint32 ext_attributes) -{ - (void)pZip; - memset(pDst, 0, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); - MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_SIG_OFS, MZ_ZIP_CENTRAL_DIR_HEADER_SIG); - MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_VERSION_NEEDED_OFS, method ? 20 : 0); - MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_BIT_FLAG_OFS, bit_flags); - MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_METHOD_OFS, method); - MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_TIME_OFS, dos_time); - MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_DATE_OFS, dos_date); - MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_CRC32_OFS, uncomp_crc32); - MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS, MZ_MIN(comp_size, MZ_UINT32_MAX)); - MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS, MZ_MIN(uncomp_size, MZ_UINT32_MAX)); - MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILENAME_LEN_OFS, filename_size); - MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_EXTRA_LEN_OFS, extra_size); - MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_COMMENT_LEN_OFS, comment_size); - MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS, ext_attributes); - MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_LOCAL_HEADER_OFS, MZ_MIN(local_header_ofs, MZ_UINT32_MAX)); - return MZ_TRUE; -} - -static mz_bool mz_zip_writer_add_to_central_dir(mz_zip_archive *pZip, const char *pFilename, mz_uint16 filename_size, - const void *pExtra, mz_uint16 extra_size, const void *pComment, mz_uint16 comment_size, - mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, - mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, - mz_uint64 local_header_ofs, mz_uint32 ext_attributes, - const char *user_extra_data, mz_uint user_extra_data_len) -{ - mz_zip_internal_state *pState = pZip->m_pState; - mz_uint32 central_dir_ofs = (mz_uint32)pState->m_central_dir.m_size; - size_t orig_central_dir_size = pState->m_central_dir.m_size; - mz_uint8 central_dir_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; - - if (!pZip->m_pState->m_zip64) - { - if (local_header_ofs > 0xFFFFFFFF) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_TOO_LARGE); - } - - /* miniz doesn't support central dirs >= MZ_UINT32_MAX bytes yet */ - if (((mz_uint64)pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + extra_size + user_extra_data_len + comment_size) >= MZ_UINT32_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); - - if (!mz_zip_writer_create_central_dir_header(pZip, central_dir_header, filename_size, extra_size + user_extra_data_len, comment_size, uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time, dos_date, local_header_ofs, ext_attributes)) - return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); - - if ((!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_dir_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) || - (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pFilename, filename_size)) || - (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pExtra, extra_size)) || - (!mz_zip_array_push_back(pZip, &pState->m_central_dir, user_extra_data, user_extra_data_len)) || - (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pComment, comment_size)) || - (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, ¢ral_dir_ofs, 1))) - { - /* Try to resize the central directory array back into its original state. */ - mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); - return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - } - - return MZ_TRUE; -} - -static mz_bool mz_zip_writer_validate_archive_name(const char *pArchive_name) -{ - /* Basic ZIP archive filename validity checks: Valid filenames cannot start with a forward slash, cannot contain a drive letter, and cannot use DOS-style backward slashes. */ - if (*pArchive_name == '/') - return MZ_FALSE; - - while (*pArchive_name) - { - if ((*pArchive_name == '\\') || (*pArchive_name == ':')) - return MZ_FALSE; - - pArchive_name++; - } - - return MZ_TRUE; -} - -static mz_uint mz_zip_writer_compute_padding_needed_for_file_alignment(mz_zip_archive *pZip) -{ - mz_uint32 n; - if (!pZip->m_file_offset_alignment) - return 0; - n = (mz_uint32)(pZip->m_archive_size & (pZip->m_file_offset_alignment - 1)); - return (mz_uint)((pZip->m_file_offset_alignment - n) & (pZip->m_file_offset_alignment - 1)); -} - -static mz_bool mz_zip_writer_write_zeros(mz_zip_archive *pZip, mz_uint64 cur_file_ofs, mz_uint32 n) -{ - char buf[4096]; - memset(buf, 0, MZ_MIN(sizeof(buf), n)); - while (n) - { - mz_uint32 s = MZ_MIN(sizeof(buf), n); - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_file_ofs, buf, s) != s) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); - - cur_file_ofs += s; - n -= s; - } - return MZ_TRUE; -} - -mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, - mz_uint64 uncomp_size, mz_uint32 uncomp_crc32) -{ - return mz_zip_writer_add_mem_ex_v2(pZip, pArchive_name, pBuf, buf_size, pComment, comment_size, level_and_flags, uncomp_size, uncomp_crc32, NULL, NULL, 0, NULL, 0); -} - -mz_bool mz_zip_writer_add_mem_ex_v2(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, - mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32, MZ_TIME_T *last_modified, - const char *user_extra_data, mz_uint user_extra_data_len, const char *user_extra_data_central, mz_uint user_extra_data_central_len) -{ - mz_uint16 method = 0, dos_time = 0, dos_date = 0; - mz_uint level, ext_attributes = 0, num_alignment_padding_bytes; - mz_uint64 local_dir_header_ofs = pZip->m_archive_size, cur_archive_file_ofs = pZip->m_archive_size, comp_size = 0; - size_t archive_name_size; - mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; - tdefl_compressor *pComp = NULL; - mz_bool store_data_uncompressed; - mz_zip_internal_state *pState; - mz_uint8 *pExtra_data = NULL; - mz_uint32 extra_size = 0; - mz_uint8 extra_data[MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE]; - mz_uint16 bit_flags = 0; - - if (uncomp_size || (buf_size && !(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) - bit_flags |= MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR; - - if (!(level_and_flags & MZ_ZIP_FLAG_ASCII_FILENAME)) - bit_flags |= MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_UTF8; - - if ((int)level_and_flags < 0) - level_and_flags = MZ_DEFAULT_LEVEL; - level = level_and_flags & 0xF; - store_data_uncompressed = ((!level) || (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)); - - if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || ((buf_size) && (!pBuf)) || (!pArchive_name) || ((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - pState = pZip->m_pState; - - if (pState->m_zip64) - { - if (pZip->m_total_files == MZ_UINT32_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); - } - else - { - if (pZip->m_total_files == MZ_UINT16_MAX) - { - pState->m_zip64 = MZ_TRUE; - /*return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); */ - } - if ((buf_size > 0xFFFFFFFF) || (uncomp_size > 0xFFFFFFFF)) - { - pState->m_zip64 = MZ_TRUE; - /*return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); */ - } - } - - if ((!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (uncomp_size)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - if (!mz_zip_writer_validate_archive_name(pArchive_name)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_FILENAME); - -#ifndef MINIZ_NO_TIME - if (last_modified != NULL) - { - mz_zip_time_t_to_dos_time(*last_modified, &dos_time, &dos_date); - } - else - { - MZ_TIME_T cur_time; - time(&cur_time); - mz_zip_time_t_to_dos_time(cur_time, &dos_time, &dos_date); - } -#endif /* #ifndef MINIZ_NO_TIME */ - - archive_name_size = strlen(pArchive_name); - if (archive_name_size > MZ_UINT16_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_FILENAME); - - num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); - - /* miniz doesn't support central dirs >= MZ_UINT32_MAX bytes yet */ - if (((mz_uint64)pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE + comment_size) >= MZ_UINT32_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); - - if (!pState->m_zip64) - { - /* Bail early if the archive would obviously become too large */ - if ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + archive_name_size - + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size + user_extra_data_len + - pState->m_central_dir.m_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE + user_extra_data_central_len - + MZ_ZIP_DATA_DESCRIPTER_SIZE32) > 0xFFFFFFFF) - { - pState->m_zip64 = MZ_TRUE; - /*return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); */ - } - } - - if ((archive_name_size) && (pArchive_name[archive_name_size - 1] == '/')) - { - /* Set DOS Subdirectory attribute bit. */ - ext_attributes |= MZ_ZIP_DOS_DIR_ATTRIBUTE_BITFLAG; - - /* Subdirectories cannot contain data. */ - if ((buf_size) || (uncomp_size)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - } - - /* Try to do any allocations before writing to the archive, so if an allocation fails the file remains unmodified. (A good idea if we're doing an in-place modification.) */ - if ((!mz_zip_array_ensure_room(pZip, &pState->m_central_dir, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size + (pState->m_zip64 ? MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE : 0))) || (!mz_zip_array_ensure_room(pZip, &pState->m_central_dir_offsets, 1))) - return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - - if ((!store_data_uncompressed) && (buf_size)) - { - if (NULL == (pComp = (tdefl_compressor *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)))) - return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - } - - if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, num_alignment_padding_bytes)) - { - pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); - return MZ_FALSE; - } - - local_dir_header_ofs += num_alignment_padding_bytes; - if (pZip->m_file_offset_alignment) - { - MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); - } - cur_archive_file_ofs += num_alignment_padding_bytes; - - MZ_CLEAR_OBJ(local_dir_header); - - if (!store_data_uncompressed || (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) - { - method = MZ_DEFLATED; - } - - if (pState->m_zip64) - { - if (uncomp_size >= MZ_UINT32_MAX || local_dir_header_ofs >= MZ_UINT32_MAX) - { - pExtra_data = extra_data; - extra_size = mz_zip_writer_create_zip64_extra_data(extra_data, (uncomp_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL, - (uncomp_size >= MZ_UINT32_MAX) ? &comp_size : NULL, (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL); - } - - if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, extra_size + user_extra_data_len, 0, 0, 0, method, bit_flags, dos_time, dos_date)) - return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); - - if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); - - cur_archive_file_ofs += sizeof(local_dir_header); - - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) - { - pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); - return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); - } - cur_archive_file_ofs += archive_name_size; - - if (pExtra_data != NULL) - { - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, extra_data, extra_size) != extra_size) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); - - cur_archive_file_ofs += extra_size; - } - } - else - { - if ((comp_size > MZ_UINT32_MAX) || (cur_archive_file_ofs > MZ_UINT32_MAX)) - return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); - if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, user_extra_data_len, 0, 0, 0, method, bit_flags, dos_time, dos_date)) - return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); - - if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); - - cur_archive_file_ofs += sizeof(local_dir_header); - - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) - { - pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); - return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); - } - cur_archive_file_ofs += archive_name_size; - } - - if (user_extra_data_len > 0) - { - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, user_extra_data, user_extra_data_len) != user_extra_data_len) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); - - cur_archive_file_ofs += user_extra_data_len; - } - - if (!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) - { - uncomp_crc32 = (mz_uint32)mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, buf_size); - uncomp_size = buf_size; - if (uncomp_size <= 3) - { - level = 0; - store_data_uncompressed = MZ_TRUE; - } - } - - if (store_data_uncompressed) - { - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pBuf, buf_size) != buf_size) - { - pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); - return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); - } - - cur_archive_file_ofs += buf_size; - comp_size = buf_size; - } - else if (buf_size) - { - mz_zip_writer_add_state state; - - state.m_pZip = pZip; - state.m_cur_archive_file_ofs = cur_archive_file_ofs; - state.m_comp_size = 0; - - if ((tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params(level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) || - (tdefl_compress_buffer(pComp, pBuf, buf_size, TDEFL_FINISH) != TDEFL_STATUS_DONE)) - { - pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); - return mz_zip_set_error(pZip, MZ_ZIP_COMPRESSION_FAILED); - } - - comp_size = state.m_comp_size; - cur_archive_file_ofs = state.m_cur_archive_file_ofs; - } - - pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); - pComp = NULL; - - if (uncomp_size) - { - mz_uint8 local_dir_footer[MZ_ZIP_DATA_DESCRIPTER_SIZE64]; - mz_uint32 local_dir_footer_size = MZ_ZIP_DATA_DESCRIPTER_SIZE32; - - MZ_ASSERT(bit_flags & MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR); - - MZ_WRITE_LE32(local_dir_footer + 0, MZ_ZIP_DATA_DESCRIPTOR_ID); - MZ_WRITE_LE32(local_dir_footer + 4, uncomp_crc32); - if (pExtra_data == NULL) - { - if (comp_size > MZ_UINT32_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); - - MZ_WRITE_LE32(local_dir_footer + 8, comp_size); - MZ_WRITE_LE32(local_dir_footer + 12, uncomp_size); - } - else - { - MZ_WRITE_LE64(local_dir_footer + 8, comp_size); - MZ_WRITE_LE64(local_dir_footer + 16, uncomp_size); - local_dir_footer_size = MZ_ZIP_DATA_DESCRIPTER_SIZE64; - } - - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, local_dir_footer, local_dir_footer_size) != local_dir_footer_size) - return MZ_FALSE; - - cur_archive_file_ofs += local_dir_footer_size; - } - - if (pExtra_data != NULL) - { - extra_size = mz_zip_writer_create_zip64_extra_data(extra_data, (uncomp_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL, - (uncomp_size >= MZ_UINT32_MAX) ? &comp_size : NULL, (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL); - } - - if (!mz_zip_writer_add_to_central_dir(pZip, pArchive_name, (mz_uint16)archive_name_size, pExtra_data, extra_size, pComment, - comment_size, uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time, dos_date, local_dir_header_ofs, ext_attributes, - user_extra_data_central, user_extra_data_central_len)) - return MZ_FALSE; - - pZip->m_total_files++; - pZip->m_archive_size = cur_archive_file_ofs; - - return MZ_TRUE; -} - -#ifndef MINIZ_NO_STDIO -mz_bool mz_zip_writer_add_cfile(mz_zip_archive *pZip, const char *pArchive_name, MZ_FILE *pSrc_file, mz_uint64 size_to_add, const MZ_TIME_T *pFile_time, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, - const char *user_extra_data, mz_uint user_extra_data_len, const char *user_extra_data_central, mz_uint user_extra_data_central_len) -{ - mz_uint16 gen_flags = MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR; - mz_uint uncomp_crc32 = MZ_CRC32_INIT, level, num_alignment_padding_bytes; - mz_uint16 method = 0, dos_time = 0, dos_date = 0, ext_attributes = 0; - mz_uint64 local_dir_header_ofs, cur_archive_file_ofs = pZip->m_archive_size, uncomp_size = size_to_add, comp_size = 0; - size_t archive_name_size; - mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; - mz_uint8 *pExtra_data = NULL; - mz_uint32 extra_size = 0; - mz_uint8 extra_data[MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE]; - mz_zip_internal_state *pState; - - if (!(level_and_flags & MZ_ZIP_FLAG_ASCII_FILENAME)) - gen_flags |= MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_UTF8; - - if ((int)level_and_flags < 0) - level_and_flags = MZ_DEFAULT_LEVEL; - level = level_and_flags & 0xF; - - /* Sanity checks */ - if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pArchive_name) || ((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - pState = pZip->m_pState; - - if ((!pState->m_zip64) && (uncomp_size > MZ_UINT32_MAX)) - { - /* Source file is too large for non-zip64 */ - /*return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); */ - pState->m_zip64 = MZ_TRUE; - } - - /* We could support this, but why? */ - if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - if (!mz_zip_writer_validate_archive_name(pArchive_name)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_FILENAME); - - if (pState->m_zip64) - { - if (pZip->m_total_files == MZ_UINT32_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); - } - else - { - if (pZip->m_total_files == MZ_UINT16_MAX) - { - pState->m_zip64 = MZ_TRUE; - /*return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); */ - } - } - - archive_name_size = strlen(pArchive_name); - if (archive_name_size > MZ_UINT16_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_FILENAME); - - num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); - - /* miniz doesn't support central dirs >= MZ_UINT32_MAX bytes yet */ - if (((mz_uint64)pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE + comment_size) >= MZ_UINT32_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); - - if (!pState->m_zip64) - { - /* Bail early if the archive would obviously become too large */ - if ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + archive_name_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE - + archive_name_size + comment_size + user_extra_data_len + pState->m_central_dir.m_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE + 1024 - + MZ_ZIP_DATA_DESCRIPTER_SIZE32 + user_extra_data_central_len) > 0xFFFFFFFF) - { - pState->m_zip64 = MZ_TRUE; - /*return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); */ - } - } - -#ifndef MINIZ_NO_TIME - if (pFile_time) - { - mz_zip_time_t_to_dos_time(*pFile_time, &dos_time, &dos_date); - } -#endif - - if (uncomp_size <= 3) - level = 0; - - if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, num_alignment_padding_bytes)) - { - return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); - } - - cur_archive_file_ofs += num_alignment_padding_bytes; - local_dir_header_ofs = cur_archive_file_ofs; - - if (pZip->m_file_offset_alignment) - { - MZ_ASSERT((cur_archive_file_ofs & (pZip->m_file_offset_alignment - 1)) == 0); - } - - if (uncomp_size && level) - { - method = MZ_DEFLATED; - } - - MZ_CLEAR_OBJ(local_dir_header); - if (pState->m_zip64) - { - if (uncomp_size >= MZ_UINT32_MAX || local_dir_header_ofs >= MZ_UINT32_MAX) - { - pExtra_data = extra_data; - extra_size = mz_zip_writer_create_zip64_extra_data(extra_data, (uncomp_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL, - (uncomp_size >= MZ_UINT32_MAX) ? &comp_size : NULL, (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL); - } - - if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, extra_size + user_extra_data_len, 0, 0, 0, method, gen_flags, dos_time, dos_date)) - return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); - - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); - - cur_archive_file_ofs += sizeof(local_dir_header); - - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) - { - return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); - } - - cur_archive_file_ofs += archive_name_size; - - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, extra_data, extra_size) != extra_size) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); - - cur_archive_file_ofs += extra_size; - } - else - { - if ((comp_size > MZ_UINT32_MAX) || (cur_archive_file_ofs > MZ_UINT32_MAX)) - return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); - if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, user_extra_data_len, 0, 0, 0, method, gen_flags, dos_time, dos_date)) - return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); - - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); - - cur_archive_file_ofs += sizeof(local_dir_header); - - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) - { - return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); - } - - cur_archive_file_ofs += archive_name_size; - } - - if (user_extra_data_len > 0) - { - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, user_extra_data, user_extra_data_len) != user_extra_data_len) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); - - cur_archive_file_ofs += user_extra_data_len; - } - - if (uncomp_size) - { - mz_uint64 uncomp_remaining = uncomp_size; - void *pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, MZ_ZIP_MAX_IO_BUF_SIZE); - if (!pRead_buf) - { - return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - } - - if (!level) - { - while (uncomp_remaining) - { - mz_uint n = (mz_uint)MZ_MIN((mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE, uncomp_remaining); - if ((MZ_FREAD(pRead_buf, 1, n, pSrc_file) != n) || (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pRead_buf, n) != n)) - { - pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); - return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); - } - uncomp_crc32 = (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, n); - uncomp_remaining -= n; - cur_archive_file_ofs += n; - } - comp_size = uncomp_size; - } - else - { - mz_bool result = MZ_FALSE; - mz_zip_writer_add_state state; - tdefl_compressor *pComp = (tdefl_compressor *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)); - if (!pComp) - { - pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); - return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - } - - state.m_pZip = pZip; - state.m_cur_archive_file_ofs = cur_archive_file_ofs; - state.m_comp_size = 0; - - if (tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params(level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) - { - pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); - pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); - return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); - } - - for (;;) - { - size_t in_buf_size = (mz_uint32)MZ_MIN(uncomp_remaining, (mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE); - tdefl_status status; - tdefl_flush flush = TDEFL_NO_FLUSH; - - if (MZ_FREAD(pRead_buf, 1, in_buf_size, pSrc_file) != in_buf_size) - { - mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); - break; - } - - uncomp_crc32 = (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, in_buf_size); - uncomp_remaining -= in_buf_size; - - if (pZip->m_pNeeds_keepalive != NULL && pZip->m_pNeeds_keepalive(pZip->m_pIO_opaque)) - flush = TDEFL_FULL_FLUSH; - - status = tdefl_compress_buffer(pComp, pRead_buf, in_buf_size, uncomp_remaining ? flush : TDEFL_FINISH); - if (status == TDEFL_STATUS_DONE) - { - result = MZ_TRUE; - break; - } - else if (status != TDEFL_STATUS_OKAY) - { - mz_zip_set_error(pZip, MZ_ZIP_COMPRESSION_FAILED); - break; - } - } - - pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); - - if (!result) - { - pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); - return MZ_FALSE; - } - - comp_size = state.m_comp_size; - cur_archive_file_ofs = state.m_cur_archive_file_ofs; - } - - pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); - } - - { - mz_uint8 local_dir_footer[MZ_ZIP_DATA_DESCRIPTER_SIZE64]; - mz_uint32 local_dir_footer_size = MZ_ZIP_DATA_DESCRIPTER_SIZE32; - - MZ_WRITE_LE32(local_dir_footer + 0, MZ_ZIP_DATA_DESCRIPTOR_ID); - MZ_WRITE_LE32(local_dir_footer + 4, uncomp_crc32); - if (pExtra_data == NULL) - { - if (comp_size > MZ_UINT32_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); - - MZ_WRITE_LE32(local_dir_footer + 8, comp_size); - MZ_WRITE_LE32(local_dir_footer + 12, uncomp_size); - } - else - { - MZ_WRITE_LE64(local_dir_footer + 8, comp_size); - MZ_WRITE_LE64(local_dir_footer + 16, uncomp_size); - local_dir_footer_size = MZ_ZIP_DATA_DESCRIPTER_SIZE64; - } - - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, local_dir_footer, local_dir_footer_size) != local_dir_footer_size) - return MZ_FALSE; - - cur_archive_file_ofs += local_dir_footer_size; - } - - if (pExtra_data != NULL) - { - extra_size = mz_zip_writer_create_zip64_extra_data(extra_data, (uncomp_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL, - (uncomp_size >= MZ_UINT32_MAX) ? &comp_size : NULL, (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL); - } - - if (!mz_zip_writer_add_to_central_dir(pZip, pArchive_name, (mz_uint16)archive_name_size, pExtra_data, extra_size, pComment, comment_size, - uncomp_size, comp_size, uncomp_crc32, method, gen_flags, dos_time, dos_date, local_dir_header_ofs, ext_attributes, - user_extra_data_central, user_extra_data_central_len)) - return MZ_FALSE; - - pZip->m_total_files++; - pZip->m_archive_size = cur_archive_file_ofs; - - return MZ_TRUE; -} - -mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags) -{ - MZ_FILE *pSrc_file = NULL; - mz_uint64 uncomp_size = 0; - MZ_TIME_T file_modified_time; - MZ_TIME_T *pFile_time = NULL; - mz_bool status; - - memset(&file_modified_time, 0, sizeof(file_modified_time)); - -#if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_STDIO) - pFile_time = &file_modified_time; - if (!mz_zip_get_file_modified_time(pSrc_filename, &file_modified_time)) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_STAT_FAILED); -#endif - - pSrc_file = MZ_FOPEN(pSrc_filename, "rb"); - if (!pSrc_file) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); - - MZ_FSEEK64(pSrc_file, 0, SEEK_END); - uncomp_size = MZ_FTELL64(pSrc_file); - MZ_FSEEK64(pSrc_file, 0, SEEK_SET); - - status = mz_zip_writer_add_cfile(pZip, pArchive_name, pSrc_file, uncomp_size, pFile_time, pComment, comment_size, level_and_flags, NULL, 0, NULL, 0); - - MZ_FCLOSE(pSrc_file); - - return status; -} -#endif /* #ifndef MINIZ_NO_STDIO */ - -static mz_bool mz_zip_writer_update_zip64_extension_block(mz_zip_array *pNew_ext, mz_zip_archive *pZip, const mz_uint8 *pExt, uint32_t ext_len, mz_uint64 *pComp_size, mz_uint64 *pUncomp_size, mz_uint64 *pLocal_header_ofs, mz_uint32 *pDisk_start) -{ - /* + 64 should be enough for any new zip64 data */ - if (!mz_zip_array_reserve(pZip, pNew_ext, ext_len + 64, MZ_FALSE)) - return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - - mz_zip_array_resize(pZip, pNew_ext, 0, MZ_FALSE); - - if ((pUncomp_size) || (pComp_size) || (pLocal_header_ofs) || (pDisk_start)) - { - mz_uint8 new_ext_block[64]; - mz_uint8 *pDst = new_ext_block; - mz_write_le16(pDst, MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID); - mz_write_le16(pDst + sizeof(mz_uint16), 0); - pDst += sizeof(mz_uint16) * 2; - - if (pUncomp_size) - { - mz_write_le64(pDst, *pUncomp_size); - pDst += sizeof(mz_uint64); - } - - if (pComp_size) - { - mz_write_le64(pDst, *pComp_size); - pDst += sizeof(mz_uint64); - } - - if (pLocal_header_ofs) - { - mz_write_le64(pDst, *pLocal_header_ofs); - pDst += sizeof(mz_uint64); - } - - if (pDisk_start) - { - mz_write_le32(pDst, *pDisk_start); - pDst += sizeof(mz_uint32); - } - - mz_write_le16(new_ext_block + sizeof(mz_uint16), (mz_uint16)((pDst - new_ext_block) - sizeof(mz_uint16) * 2)); - - if (!mz_zip_array_push_back(pZip, pNew_ext, new_ext_block, pDst - new_ext_block)) - return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - } - - if ((pExt) && (ext_len)) - { - mz_uint32 extra_size_remaining = ext_len; - const mz_uint8 *pExtra_data = pExt; - - do - { - mz_uint32 field_id, field_data_size, field_total_size; - - if (extra_size_remaining < (sizeof(mz_uint16) * 2)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - - field_id = MZ_READ_LE16(pExtra_data); - field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); - field_total_size = field_data_size + sizeof(mz_uint16) * 2; - - if (field_total_size > extra_size_remaining) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - - if (field_id != MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) - { - if (!mz_zip_array_push_back(pZip, pNew_ext, pExtra_data, field_total_size)) - return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - } - - pExtra_data += field_total_size; - extra_size_remaining -= field_total_size; - } while (extra_size_remaining); - } - - return MZ_TRUE; -} - -/* TODO: This func is now pretty freakin complex due to zip64, split it up? */ -mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint src_file_index) -{ - mz_uint n, bit_flags, num_alignment_padding_bytes, src_central_dir_following_data_size; - mz_uint64 src_archive_bytes_remaining, local_dir_header_ofs; - mz_uint64 cur_src_file_ofs, cur_dst_file_ofs; - mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; - mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; - mz_uint8 new_central_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; - size_t orig_central_dir_size; - mz_zip_internal_state *pState; - void *pBuf; - const mz_uint8 *pSrc_central_header; - mz_zip_archive_file_stat src_file_stat; - mz_uint32 src_filename_len, src_comment_len, src_ext_len; - mz_uint32 local_header_filename_size, local_header_extra_len; - mz_uint64 local_header_comp_size, local_header_uncomp_size; - mz_bool found_zip64_ext_data_in_ldir = MZ_FALSE; - - /* Sanity checks */ - if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pSource_zip->m_pRead)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - pState = pZip->m_pState; - - /* Don't support copying files from zip64 archives to non-zip64, even though in some cases this is possible */ - if ((pSource_zip->m_pState->m_zip64) && (!pZip->m_pState->m_zip64)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - /* Get pointer to the source central dir header and crack it */ - if (NULL == (pSrc_central_header = mz_zip_get_cdh(pSource_zip, src_file_index))) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - if (MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_SIG_OFS) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - - src_filename_len = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_FILENAME_LEN_OFS); - src_comment_len = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_COMMENT_LEN_OFS); - src_ext_len = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS); - src_central_dir_following_data_size = src_filename_len + src_ext_len + src_comment_len; - - /* TODO: We don't support central dir's >= MZ_UINT32_MAX bytes right now (+32 fudge factor in case we need to add more extra data) */ - if ((pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + src_central_dir_following_data_size + 32) >= MZ_UINT32_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); - - num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); - - if (!pState->m_zip64) - { - if (pZip->m_total_files == MZ_UINT16_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); - } - else - { - /* TODO: Our zip64 support still has some 32-bit limits that may not be worth fixing. */ - if (pZip->m_total_files == MZ_UINT32_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); - } - - if (!mz_zip_file_stat_internal(pSource_zip, src_file_index, pSrc_central_header, &src_file_stat, NULL)) - return MZ_FALSE; - - cur_src_file_ofs = src_file_stat.m_local_header_ofs; - cur_dst_file_ofs = pZip->m_archive_size; - - /* Read the source archive's local dir header */ - if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); - - if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - - cur_src_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; - - /* Compute the total size we need to copy (filename+extra data+compressed data) */ - local_header_filename_size = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS); - local_header_extra_len = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); - local_header_comp_size = MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS); - local_header_uncomp_size = MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS); - src_archive_bytes_remaining = local_header_filename_size + local_header_extra_len + src_file_stat.m_comp_size; - - /* Try to find a zip64 extended information field */ - if ((local_header_extra_len) && ((local_header_comp_size == MZ_UINT32_MAX) || (local_header_uncomp_size == MZ_UINT32_MAX))) - { - mz_zip_array file_data_array; - const mz_uint8 *pExtra_data; - mz_uint32 extra_size_remaining = local_header_extra_len; - - mz_zip_array_init(&file_data_array, 1); - if (!mz_zip_array_resize(pZip, &file_data_array, local_header_extra_len, MZ_FALSE)) - { - return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - } - - if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, src_file_stat.m_local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + local_header_filename_size, file_data_array.m_p, local_header_extra_len) != local_header_extra_len) - { - mz_zip_array_clear(pZip, &file_data_array); - return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); - } - - pExtra_data = (const mz_uint8 *)file_data_array.m_p; - - do - { - mz_uint32 field_id, field_data_size, field_total_size; - - if (extra_size_remaining < (sizeof(mz_uint16) * 2)) - { - mz_zip_array_clear(pZip, &file_data_array); - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - } - - field_id = MZ_READ_LE16(pExtra_data); - field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); - field_total_size = field_data_size + sizeof(mz_uint16) * 2; - - if (field_total_size > extra_size_remaining) - { - mz_zip_array_clear(pZip, &file_data_array); - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - } - - if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) - { - const mz_uint8 *pSrc_field_data = pExtra_data + sizeof(mz_uint32); - - if (field_data_size < sizeof(mz_uint64) * 2) - { - mz_zip_array_clear(pZip, &file_data_array); - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - } - - local_header_uncomp_size = MZ_READ_LE64(pSrc_field_data); - local_header_comp_size = MZ_READ_LE64(pSrc_field_data + sizeof(mz_uint64)); /* may be 0 if there's a descriptor */ - - found_zip64_ext_data_in_ldir = MZ_TRUE; - break; - } - - pExtra_data += field_total_size; - extra_size_remaining -= field_total_size; - } while (extra_size_remaining); - - mz_zip_array_clear(pZip, &file_data_array); - } - - if (!pState->m_zip64) - { - /* Try to detect if the new archive will most likely wind up too big and bail early (+(sizeof(mz_uint32) * 4) is for the optional descriptor which could be present, +64 is a fudge factor). */ - /* We also check when the archive is finalized so this doesn't need to be perfect. */ - mz_uint64 approx_new_archive_size = cur_dst_file_ofs + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + src_archive_bytes_remaining + (sizeof(mz_uint32) * 4) + - pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + src_central_dir_following_data_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE + 64; - - if (approx_new_archive_size >= MZ_UINT32_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); - } - - /* Write dest archive padding */ - if (!mz_zip_writer_write_zeros(pZip, cur_dst_file_ofs, num_alignment_padding_bytes)) - return MZ_FALSE; - - cur_dst_file_ofs += num_alignment_padding_bytes; - - local_dir_header_ofs = cur_dst_file_ofs; - if (pZip->m_file_offset_alignment) - { - MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); - } - - /* The original zip's local header+ext block doesn't change, even with zip64, so we can just copy it over to the dest zip */ - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); - - cur_dst_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; - - /* Copy over the source archive bytes to the dest archive, also ensure we have enough buf space to handle optional data descriptor */ - if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)MZ_MAX(32U, MZ_MIN((mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE, src_archive_bytes_remaining))))) - return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - - while (src_archive_bytes_remaining) - { - n = (mz_uint)MZ_MIN((mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE, src_archive_bytes_remaining); - if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, n) != n) - { - pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); - return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); - } - cur_src_file_ofs += n; - - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) - { - pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); - return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); - } - cur_dst_file_ofs += n; - - src_archive_bytes_remaining -= n; - } - - /* Now deal with the optional data descriptor */ - bit_flags = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS); - if (bit_flags & 8) - { - /* Copy data descriptor */ - if ((pSource_zip->m_pState->m_zip64) || (found_zip64_ext_data_in_ldir)) - { - /* src is zip64, dest must be zip64 */ - - /* name uint32_t's */ - /* id 1 (optional in zip64?) */ - /* crc 1 */ - /* comp_size 2 */ - /* uncomp_size 2 */ - if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, (sizeof(mz_uint32) * 6)) != (sizeof(mz_uint32) * 6)) - { - pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); - return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); - } - - n = sizeof(mz_uint32) * ((MZ_READ_LE32(pBuf) == MZ_ZIP_DATA_DESCRIPTOR_ID) ? 6 : 5); - } - else - { - /* src is NOT zip64 */ - mz_bool has_id; - - if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, sizeof(mz_uint32) * 4) != sizeof(mz_uint32) * 4) - { - pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); - return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); - } - - has_id = (MZ_READ_LE32(pBuf) == MZ_ZIP_DATA_DESCRIPTOR_ID); - - if (pZip->m_pState->m_zip64) - { - /* dest is zip64, so upgrade the data descriptor */ - const mz_uint32 *pSrc_descriptor = (const mz_uint32 *)((const mz_uint8 *)pBuf + (has_id ? sizeof(mz_uint32) : 0)); - const mz_uint32 src_crc32 = pSrc_descriptor[0]; - const mz_uint64 src_comp_size = pSrc_descriptor[1]; - const mz_uint64 src_uncomp_size = pSrc_descriptor[2]; - - mz_write_le32((mz_uint8 *)pBuf, MZ_ZIP_DATA_DESCRIPTOR_ID); - mz_write_le32((mz_uint8 *)pBuf + sizeof(mz_uint32) * 1, src_crc32); - mz_write_le64((mz_uint8 *)pBuf + sizeof(mz_uint32) * 2, src_comp_size); - mz_write_le64((mz_uint8 *)pBuf + sizeof(mz_uint32) * 4, src_uncomp_size); - - n = sizeof(mz_uint32) * 6; - } - else - { - /* dest is NOT zip64, just copy it as-is */ - n = sizeof(mz_uint32) * (has_id ? 4 : 3); - } - } - - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) - { - pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); - return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); - } - - cur_src_file_ofs += n; - cur_dst_file_ofs += n; - } - pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); - - /* Finally, add the new central dir header */ - orig_central_dir_size = pState->m_central_dir.m_size; - - memcpy(new_central_header, pSrc_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); - - if (pState->m_zip64) - { - /* This is the painful part: We need to write a new central dir header + ext block with updated zip64 fields, and ensure the old fields (if any) are not included. */ - const mz_uint8 *pSrc_ext = pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + src_filename_len; - mz_zip_array new_ext_block; - - mz_zip_array_init(&new_ext_block, sizeof(mz_uint8)); - - MZ_WRITE_LE32(new_central_header + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS, MZ_UINT32_MAX); - MZ_WRITE_LE32(new_central_header + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS, MZ_UINT32_MAX); - MZ_WRITE_LE32(new_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS, MZ_UINT32_MAX); - - if (!mz_zip_writer_update_zip64_extension_block(&new_ext_block, pZip, pSrc_ext, src_ext_len, &src_file_stat.m_comp_size, &src_file_stat.m_uncomp_size, &local_dir_header_ofs, NULL)) - { - mz_zip_array_clear(pZip, &new_ext_block); - return MZ_FALSE; - } - - MZ_WRITE_LE16(new_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS, new_ext_block.m_size); - - if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, new_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) - { - mz_zip_array_clear(pZip, &new_ext_block); - return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - } - - if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, src_filename_len)) - { - mz_zip_array_clear(pZip, &new_ext_block); - mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); - return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - } - - if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, new_ext_block.m_p, new_ext_block.m_size)) - { - mz_zip_array_clear(pZip, &new_ext_block); - mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); - return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - } - - if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + src_filename_len + src_ext_len, src_comment_len)) - { - mz_zip_array_clear(pZip, &new_ext_block); - mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); - return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - } - - mz_zip_array_clear(pZip, &new_ext_block); - } - else - { - /* sanity checks */ - if (cur_dst_file_ofs > MZ_UINT32_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); - - if (local_dir_header_ofs >= MZ_UINT32_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); - - MZ_WRITE_LE32(new_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_dir_header_ofs); - - if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, new_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) - return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - - if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, src_central_dir_following_data_size)) - { - mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); - return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - } - } - - /* This shouldn't trigger unless we screwed up during the initial sanity checks */ - if (pState->m_central_dir.m_size >= MZ_UINT32_MAX) - { - /* TODO: Support central dirs >= 32-bits in size */ - mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); - return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); - } - - n = (mz_uint32)orig_central_dir_size; - if (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &n, 1)) - { - mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); - return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - } - - pZip->m_total_files++; - pZip->m_archive_size = cur_dst_file_ofs; - - return MZ_TRUE; -} - -mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip) -{ - mz_zip_internal_state *pState; - mz_uint64 central_dir_ofs, central_dir_size; - mz_uint8 hdr[256]; - - if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - pState = pZip->m_pState; - - if (pState->m_zip64) - { - if ((pZip->m_total_files > MZ_UINT32_MAX) || (pState->m_central_dir.m_size >= MZ_UINT32_MAX)) - return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); - } - else - { - if ((pZip->m_total_files > MZ_UINT16_MAX) || ((pZip->m_archive_size + pState->m_central_dir.m_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) > MZ_UINT32_MAX)) - return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); - } - - central_dir_ofs = 0; - central_dir_size = 0; - if (pZip->m_total_files) - { - /* Write central directory */ - central_dir_ofs = pZip->m_archive_size; - central_dir_size = pState->m_central_dir.m_size; - pZip->m_central_directory_file_ofs = central_dir_ofs; - if (pZip->m_pWrite(pZip->m_pIO_opaque, central_dir_ofs, pState->m_central_dir.m_p, (size_t)central_dir_size) != central_dir_size) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); - - pZip->m_archive_size += central_dir_size; - } - - if (pState->m_zip64) - { - /* Write zip64 end of central directory header */ - mz_uint64 rel_ofs_to_zip64_ecdr = pZip->m_archive_size; - - MZ_CLEAR_OBJ(hdr); - MZ_WRITE_LE32(hdr + MZ_ZIP64_ECDH_SIG_OFS, MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIG); - MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_SIZE_OF_RECORD_OFS, MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE - sizeof(mz_uint32) - sizeof(mz_uint64)); - MZ_WRITE_LE16(hdr + MZ_ZIP64_ECDH_VERSION_MADE_BY_OFS, 0x031E); /* TODO: always Unix */ - MZ_WRITE_LE16(hdr + MZ_ZIP64_ECDH_VERSION_NEEDED_OFS, 0x002D); - MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS, pZip->m_total_files); - MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_CDIR_TOTAL_ENTRIES_OFS, pZip->m_total_files); - MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_CDIR_SIZE_OFS, central_dir_size); - MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_CDIR_OFS_OFS, central_dir_ofs); - if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); - - pZip->m_archive_size += MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE; - - /* Write zip64 end of central directory locator */ - MZ_CLEAR_OBJ(hdr); - MZ_WRITE_LE32(hdr + MZ_ZIP64_ECDL_SIG_OFS, MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIG); - MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDL_REL_OFS_TO_ZIP64_ECDR_OFS, rel_ofs_to_zip64_ecdr); - MZ_WRITE_LE32(hdr + MZ_ZIP64_ECDL_TOTAL_NUMBER_OF_DISKS_OFS, 1); - if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) != MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); - - pZip->m_archive_size += MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE; - } - - /* Write end of central directory record */ - MZ_CLEAR_OBJ(hdr); - MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_SIG_OFS, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG); - MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS, MZ_MIN(MZ_UINT16_MAX, pZip->m_total_files)); - MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS, MZ_MIN(MZ_UINT16_MAX, pZip->m_total_files)); - MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_SIZE_OFS, MZ_MIN(MZ_UINT32_MAX, central_dir_size)); - MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_OFS_OFS, MZ_MIN(MZ_UINT32_MAX, central_dir_ofs)); - - if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); - -#ifndef MINIZ_NO_STDIO - if ((pState->m_pFile) && (MZ_FFLUSH(pState->m_pFile) == EOF)) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_CLOSE_FAILED); -#endif /* #ifndef MINIZ_NO_STDIO */ - - pZip->m_archive_size += MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE; - - pZip->m_zip_mode = MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED; - return MZ_TRUE; -} - -mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **ppBuf, size_t *pSize) -{ - if ((!ppBuf) || (!pSize)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - *ppBuf = NULL; - *pSize = 0; - - if ((!pZip) || (!pZip->m_pState)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - if (pZip->m_pWrite != mz_zip_heap_write_func) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - if (!mz_zip_writer_finalize_archive(pZip)) - return MZ_FALSE; - - *ppBuf = pZip->m_pState->m_pMem; - *pSize = pZip->m_pState->m_mem_size; - pZip->m_pState->m_pMem = NULL; - pZip->m_pState->m_mem_size = pZip->m_pState->m_mem_capacity = 0; - - return MZ_TRUE; -} - -mz_bool mz_zip_writer_end(mz_zip_archive *pZip) -{ - return mz_zip_writer_end_internal(pZip, MZ_TRUE); -} - -#ifndef MINIZ_NO_STDIO -mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags) -{ - return mz_zip_add_mem_to_archive_file_in_place_v2(pZip_filename, pArchive_name, pBuf, buf_size, pComment, comment_size, level_and_flags, NULL); -} - -mz_bool mz_zip_add_mem_to_archive_file_in_place_v2(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_zip_error *pErr) -{ - mz_bool status, created_new_archive = MZ_FALSE; - mz_zip_archive zip_archive; - struct MZ_FILE_STAT_STRUCT file_stat; - mz_zip_error actual_err = MZ_ZIP_NO_ERROR; - - mz_zip_zero_struct(&zip_archive); - if ((int)level_and_flags < 0) - level_and_flags = MZ_DEFAULT_LEVEL; - - if ((!pZip_filename) || (!pArchive_name) || ((buf_size) && (!pBuf)) || ((comment_size) && (!pComment)) || ((level_and_flags & 0xF) > MZ_UBER_COMPRESSION)) - { - if (pErr) - *pErr = MZ_ZIP_INVALID_PARAMETER; - return MZ_FALSE; - } - - if (!mz_zip_writer_validate_archive_name(pArchive_name)) - { - if (pErr) - *pErr = MZ_ZIP_INVALID_FILENAME; - return MZ_FALSE; - } - - /* Important: The regular non-64 bit version of stat() can fail here if the file is very large, which could cause the archive to be overwritten. */ - /* So be sure to compile with _LARGEFILE64_SOURCE 1 */ - if (MZ_FILE_STAT(pZip_filename, &file_stat) != 0) - { - /* Create a new archive. */ - if (!mz_zip_writer_init_file_v2(&zip_archive, pZip_filename, 0, level_and_flags)) - { - if (pErr) - *pErr = zip_archive.m_last_error; - return MZ_FALSE; - } - - created_new_archive = MZ_TRUE; - } - else - { - /* Append to an existing archive. */ - if (!mz_zip_reader_init_file_v2(&zip_archive, pZip_filename, level_and_flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY, 0, 0)) - { - if (pErr) - *pErr = zip_archive.m_last_error; - return MZ_FALSE; - } - - if (!mz_zip_writer_init_from_reader_v2(&zip_archive, pZip_filename, level_and_flags)) - { - if (pErr) - *pErr = zip_archive.m_last_error; - - mz_zip_reader_end_internal(&zip_archive, MZ_FALSE); - - return MZ_FALSE; - } - } - - status = mz_zip_writer_add_mem_ex(&zip_archive, pArchive_name, pBuf, buf_size, pComment, comment_size, level_and_flags, 0, 0); - actual_err = zip_archive.m_last_error; - - /* Always finalize, even if adding failed for some reason, so we have a valid central directory. (This may not always succeed, but we can try.) */ - if (!mz_zip_writer_finalize_archive(&zip_archive)) - { - if (!actual_err) - actual_err = zip_archive.m_last_error; - - status = MZ_FALSE; - } - - if (!mz_zip_writer_end_internal(&zip_archive, status)) - { - if (!actual_err) - actual_err = zip_archive.m_last_error; - - status = MZ_FALSE; - } - - if ((!status) && (created_new_archive)) - { - /* It's a new archive and something went wrong, so just delete it. */ - int ignoredStatus = MZ_DELETE_FILE(pZip_filename); - (void)ignoredStatus; - } - - if (pErr) - *pErr = actual_err; - - return status; -} - -void *mz_zip_extract_archive_file_to_heap_v2(const char *pZip_filename, const char *pArchive_name, const char *pComment, size_t *pSize, mz_uint flags, mz_zip_error *pErr) -{ - mz_uint32 file_index; - mz_zip_archive zip_archive; - void *p = NULL; - - if (pSize) - *pSize = 0; - - if ((!pZip_filename) || (!pArchive_name)) - { - if (pErr) - *pErr = MZ_ZIP_INVALID_PARAMETER; - - return NULL; - } - - mz_zip_zero_struct(&zip_archive); - if (!mz_zip_reader_init_file_v2(&zip_archive, pZip_filename, flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY, 0, 0)) - { - if (pErr) - *pErr = zip_archive.m_last_error; - - return NULL; - } - - if (mz_zip_reader_locate_file_v2(&zip_archive, pArchive_name, pComment, flags, &file_index)) - { - p = mz_zip_reader_extract_to_heap(&zip_archive, file_index, pSize, flags); - } - - mz_zip_reader_end_internal(&zip_archive, p != NULL); - - if (pErr) - *pErr = zip_archive.m_last_error; - - return p; -} - -void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint flags) -{ - return mz_zip_extract_archive_file_to_heap_v2(pZip_filename, pArchive_name, NULL, pSize, flags, NULL); -} - -#endif /* #ifndef MINIZ_NO_STDIO */ - -#endif /* #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS */ - -/* ------------------- Misc utils */ - -mz_zip_mode mz_zip_get_mode(mz_zip_archive *pZip) -{ - return pZip ? pZip->m_zip_mode : MZ_ZIP_MODE_INVALID; -} - -mz_zip_type mz_zip_get_type(mz_zip_archive *pZip) -{ - return pZip ? pZip->m_zip_type : MZ_ZIP_TYPE_INVALID; -} - -mz_zip_error mz_zip_set_last_error(mz_zip_archive *pZip, mz_zip_error err_num) -{ - mz_zip_error prev_err; - - if (!pZip) - return MZ_ZIP_INVALID_PARAMETER; - - prev_err = pZip->m_last_error; - - pZip->m_last_error = err_num; - return prev_err; -} - -mz_zip_error mz_zip_peek_last_error(mz_zip_archive *pZip) -{ - if (!pZip) - return MZ_ZIP_INVALID_PARAMETER; - - return pZip->m_last_error; -} - -mz_zip_error mz_zip_clear_last_error(mz_zip_archive *pZip) -{ - return mz_zip_set_last_error(pZip, MZ_ZIP_NO_ERROR); -} - -mz_zip_error mz_zip_get_last_error(mz_zip_archive *pZip) -{ - mz_zip_error prev_err; - - if (!pZip) - return MZ_ZIP_INVALID_PARAMETER; - - prev_err = pZip->m_last_error; - - pZip->m_last_error = MZ_ZIP_NO_ERROR; - return prev_err; -} - -const char *mz_zip_get_error_string(mz_zip_error mz_err) -{ - switch (mz_err) - { - case MZ_ZIP_NO_ERROR: - return "no error"; - case MZ_ZIP_UNDEFINED_ERROR: - return "undefined error"; - case MZ_ZIP_TOO_MANY_FILES: - return "too many files"; - case MZ_ZIP_FILE_TOO_LARGE: - return "file too large"; - case MZ_ZIP_UNSUPPORTED_METHOD: - return "unsupported method"; - case MZ_ZIP_UNSUPPORTED_ENCRYPTION: - return "unsupported encryption"; - case MZ_ZIP_UNSUPPORTED_FEATURE: - return "unsupported feature"; - case MZ_ZIP_FAILED_FINDING_CENTRAL_DIR: - return "failed finding central directory"; - case MZ_ZIP_NOT_AN_ARCHIVE: - return "not a ZIP archive"; - case MZ_ZIP_INVALID_HEADER_OR_CORRUPTED: - return "invalid header or archive is corrupted"; - case MZ_ZIP_UNSUPPORTED_MULTIDISK: - return "unsupported multidisk archive"; - case MZ_ZIP_DECOMPRESSION_FAILED: - return "decompression failed or archive is corrupted"; - case MZ_ZIP_COMPRESSION_FAILED: - return "compression failed"; - case MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE: - return "unexpected decompressed size"; - case MZ_ZIP_CRC_CHECK_FAILED: - return "CRC-32 check failed"; - case MZ_ZIP_UNSUPPORTED_CDIR_SIZE: - return "unsupported central directory size"; - case MZ_ZIP_ALLOC_FAILED: - return "allocation failed"; - case MZ_ZIP_FILE_OPEN_FAILED: - return "file open failed"; - case MZ_ZIP_FILE_CREATE_FAILED: - return "file create failed"; - case MZ_ZIP_FILE_WRITE_FAILED: - return "file write failed"; - case MZ_ZIP_FILE_READ_FAILED: - return "file read failed"; - case MZ_ZIP_FILE_CLOSE_FAILED: - return "file close failed"; - case MZ_ZIP_FILE_SEEK_FAILED: - return "file seek failed"; - case MZ_ZIP_FILE_STAT_FAILED: - return "file stat failed"; - case MZ_ZIP_INVALID_PARAMETER: - return "invalid parameter"; - case MZ_ZIP_INVALID_FILENAME: - return "invalid filename"; - case MZ_ZIP_BUF_TOO_SMALL: - return "buffer too small"; - case MZ_ZIP_INTERNAL_ERROR: - return "internal error"; - case MZ_ZIP_FILE_NOT_FOUND: - return "file not found"; - case MZ_ZIP_ARCHIVE_TOO_LARGE: - return "archive is too large"; - case MZ_ZIP_VALIDATION_FAILED: - return "validation failed"; - case MZ_ZIP_WRITE_CALLBACK_FAILED: - return "write calledback failed"; - default: - break; - } - - return "unknown error"; -} - -/* Note: Just because the archive is not zip64 doesn't necessarily mean it doesn't have Zip64 extended information extra field, argh. */ -mz_bool mz_zip_is_zip64(mz_zip_archive *pZip) -{ - if ((!pZip) || (!pZip->m_pState)) - return MZ_FALSE; - - return pZip->m_pState->m_zip64; -} - -size_t mz_zip_get_central_dir_size(mz_zip_archive *pZip) -{ - if ((!pZip) || (!pZip->m_pState)) - return 0; - - return pZip->m_pState->m_central_dir.m_size; -} - -mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip) -{ - return pZip ? pZip->m_total_files : 0; -} - -mz_uint64 mz_zip_get_archive_size(mz_zip_archive *pZip) -{ - if (!pZip) - return 0; - return pZip->m_archive_size; -} - -mz_uint64 mz_zip_get_archive_file_start_offset(mz_zip_archive *pZip) -{ - if ((!pZip) || (!pZip->m_pState)) - return 0; - return pZip->m_pState->m_file_archive_start_ofs; -} - -MZ_FILE *mz_zip_get_cfile(mz_zip_archive *pZip) -{ - if ((!pZip) || (!pZip->m_pState)) - return 0; - return pZip->m_pState->m_pFile; -} - -size_t mz_zip_read_archive_data(mz_zip_archive *pZip, mz_uint64 file_ofs, void *pBuf, size_t n) -{ - if ((!pZip) || (!pZip->m_pState) || (!pBuf) || (!pZip->m_pRead)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - return pZip->m_pRead(pZip->m_pIO_opaque, file_ofs, pBuf, n); -} - -mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size) -{ - mz_uint n; - const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index); - if (!p) - { - if (filename_buf_size) - pFilename[0] = '\0'; - mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - return 0; - } - n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); - if (filename_buf_size) - { - n = MZ_MIN(n, filename_buf_size - 1); - memcpy(pFilename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); - pFilename[n] = '\0'; - } - return n + 1; -} - -mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat) -{ - return mz_zip_file_stat_internal(pZip, file_index, mz_zip_get_cdh(pZip, file_index), pStat, NULL); -} - -mz_bool mz_zip_end(mz_zip_archive *pZip) -{ - if (!pZip) - return MZ_FALSE; - - if (pZip->m_zip_mode == MZ_ZIP_MODE_READING) - return mz_zip_reader_end(pZip); -#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS - else if ((pZip->m_zip_mode == MZ_ZIP_MODE_WRITING) || (pZip->m_zip_mode == MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED)) - return mz_zip_writer_end(pZip); -#endif - - return MZ_FALSE; -} - -#ifdef __cplusplus -} -#endif - -#endif /*#ifndef MINIZ_NO_ARCHIVE_APIS*/ -/* end of file miniz-sgb.c */ -#endif -/* ^^^ S2_INTERNAL_MINIZ */ -/* start of file /home/stephan/fossil/cwal/cwal_amalgamation.c */ -#include "string.h" /*memset()*/ -#include "assert.h" -/* start of file cwal_internal.h */ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=4 et sw=2 tw=80: */ -#if !defined(WANDERINGHORSE_NET_CWAL_INTERNAL_H_INCLUDED) -#define WANDERINGHORSE_NET_CWAL_INTERNAL_H_INCLUDED 1 -/** - This file documents the internal/private API of libcwal. It's - strictly internal parts are only in the main implementation file, - but the parts in this file are thought to potentially be useful in - future sub-systems which live somewhere between the private API and - public API (not quite public, not quite core). -*/ - -#if defined(__cplusplus) -extern "C" { -#endif - -/** @internal - - CWAL_UNUSED_VAR exists only to squelch, in non-debug builds, - warnings about the existence of vars and function parameters which - are only used in assert() expressions (and thus get filtered out in - non-debug builds). -*/ -#define CWAL_UNUSED_VAR __attribute__((__unused__)) /* avoiding unused var in non-debug build */ - -/** - A callback type for use with cwal_ptr_table_visit(). The elem - argument is the entry being visited over. The state argument is - whatever state the caller passed to cwal_ptr_table_visit(). - - If a visitor function returns non-0, iteration ceases and that - result code is returned to the caller of cwal_ptr_table_visit(). - - Hypothetically, it is legal for a visitor to overwrite *elem, but - that feature is not used in cwal's internals and might or might not - work (or be semantically legal) in any other context. -*/ -typedef int (*cwal_ptr_table_visitor_f)( cwal_value ** elem, void * state ); - -/** @internal - Operation values for cwal_ptr_table_op(). -*/ -enum cwal_ptr_table_ops { - /** Indicates that cwal_ptr_table_op() should remove the requested - item. */ - CWAL_PTR_TABLE_OP_REMOVE = -1, - /** Indicates that cwal_ptr_table_op() should search for the - requested item. */ - CWAL_PTR_TABLE_OP_SEARCH = 0, - /** Indicates that cwal_ptr_table_op() should insert the requested - item. */ - CWAL_PTR_TABLE_OP_INSERT = 1 -}; -typedef enum cwal_ptr_table_ops cwal_ptr_table_ops; - -/** @internal - - Initializes a new pointer table. *T may be NULL, in which case this - function allocates a new cwal_ptr_table. If *T is not NULL then it is - assumed to be a freshly-allocated, non-initialized pointer table - and is initialized as-is. - - Returns 0 on error. On success *T is set to the ptr table (possibly - freshly allocated) and ownership is transfered to the caller, who - must eventually call cwal_ptr_table_destroy() to free its resources. -*/ -int cwal_ptr_table_create( cwal_engine * e, cwal_ptr_table ** T, uint16_t hashSize, uint16_t step ); - -/** @internal - - Frees all resources owned by t. t must have been initialized by - cwal_ptr_table_create(), and if that function allocated t, then t - will also be free()'d, otherwise the caller must free t using the - method which complements its allocation technique (e.g. do nothing - for stack-allocated values). - - Returns 0 on success. -*/ -int cwal_ptr_table_destroy( cwal_engine * e, cwal_ptr_table * t ); - -/** @internal - - Performs a search/remove/insert operation (specified by the op - parameter) on the given ptr table. Returns 0 on success. - - The valid operations are: - - CWAL_PTR_TABLE_OP_REMOVE: remove the given key from the table. - Returns CWAL_RC_NOT_FOUND, and has no side effects, if no matching - entry is found. - - CWAL_PTR_TABLE_OP_SEARCH: If a match is found returns 0, else - returns CWAL_RC_NOT_FOUND. - - CWAL_PTR_TABLE_OP_INSERT: insert the given key into the - table. Returns CWAL_RC_ALREADY_EXISTS, and has no side effects, if - key is already in the table. -*/ -int cwal_ptr_table_op( cwal_engine * e, cwal_ptr_table * t, void * key, cwal_ptr_table_ops op ); - -/** @internal - Equivalent to cwal_ptr_table_op(), passing it (e,t,key,CWAL_PTR_TABLE_OP_SEARCH). -*/ -int cwal_ptr_table_search( cwal_engine * e, cwal_ptr_table * t, cwal_value * key ); - -/** @internal - Equivalent to cwal_ptr_table_op(), passing it (e,t,key,CWAL_PTR_TABLE_OP_REMOVE). -*/ -int cwal_ptr_table_remove( cwal_engine * e, cwal_ptr_table * t, cwal_value * key ); - -/** @internal - Equivalent to cwal_ptr_table_op(), passing it (e,t,key,CWAL_PTR_TABLE_OP_INSERT). -*/ -int cwal_ptr_table_insert( cwal_engine * e, cwal_ptr_table * t, cwal_value * key ); - -/** @internal - - Calculates the amount of memory allocated for use with the given - table. The results are stored in *mallocs (the total number of - memory allocation calls) and *memory (the total number of bytes - allocated for use with t). Either of mallocs or memory may be - NULL. This is an O(N) operation, where N is the number of pages - currently managed by t. - */ -int cwal_ptr_table_mem_cost( cwal_ptr_table const * t, uint32_t * mallocs, uint32_t * memory ); - -/** @internal - - "Visits" each entry in t, calling the given callback for each one - (NULL entries in the table are skipped - only "live" entries are - iterated over). The callback is passed a pointer to a pointer to - the original entry, and if that pointer is re-assigned, that - change is written back to the table when the visitor - returns. (Why? i'm not sure why it was done that way - it is a - dangerous feature and should not be used.) - - Returns 0 on success. if the visitor returns non-0, that code is - returned to the caller of this function. -*/ -int cwal_ptr_table_visit( cwal_ptr_table * t, cwal_ptr_table_visitor_f f, void * state ); - - -/** @internal - - Strings are allocated as an instances of this class with N+1 - trailing bytes, where N is the length, in bytes, of the string - being allocated. To convert a cwal_string to c-string we simply - increment the cwal_string pointer. To do the opposite we use (cstr - - sizeof(cwal_string)). Zero-length strings are a special case - handled by a couple of the cwal_string functions. - - The top-most 3 bits of the length field are reserved for - flags. This is how we mark "x-strings" (external strings, held in - memory allocated elsewhere (e.g. static globals or client-interned - strings), z-strings (whose memory comes from cwal_malloc() but is - allocated separately from the string instance (we use this for - "taking" memory from buffer instances), and (as a performance - optimization in some algorithms) ASCII-only strings. -*/ -struct cwal_string { - cwal_size_t length; -}; - -/** @internal - - Internal state flags. Keep these at 16 bits (and use only the - bottom 8 unless you know a given type supports it!) or adjust - various flags types accordingly! Note that some flags apply only - to particular types, and thus certain flags might have the same - values to conserve bit-space. -*/ -enum cwal_internal_flags { -/** - Sentinel value for empty flags. - */ - CWAL_F_NONE = 0, - /** - Used by cwal_value_vtab::flags to indicate that the type contains - a cwal_obase as its first struct member and therefore qualifies - as an "obase" (object base) sub-type. This is a casting-related - optimization. - - "OBases" must meet these requirements: - - - It is allocated using the library-conventional single-malloc - method of (cwal_value,concrete_type) in a single block. See - cwal_value_new() for the many examples. - - - Its concrete value type has a cwal_obase struct as its first - member. This, in combination with the first requirement, allows - us (due to an interesting C rule) to efficiently/safely cast - directly between a cwal_value, its "object type," and a - convenience base type (cwal_obase) which is used in many internal - algorithms to consolidate code for container handling. And... we - don't hold an extra pointer (or two) for this - it comes for free - as a side-effect of these first 2 requirements. - - See cwal_object and cwal_array for examples of using the obase - flag. - - Reminder to self: we can re-use this slot for flags on - cwal_engine, cwal_obase, and cwal_scope :). - */ - CWAL_F_ISA_OBASE = 0x01, - - /** - Set on cwal_engine instances during init if their memcap config - is enabled, to speed up some if/else checking in the allocator. - */ - CWAL_F_TRACK_MEM_SIZE = 0x02, - - /** - Is used as an extra safety mechanism to avoid a double-delete if - the refcounts-with-cycles-counting mechanism breaks. This only - means that we convert a double free() into a leak (or an assert() - in debug builds). - - Used in cwal_engine::flags and cwal_scope::flags. Values use a - different flag with similar semantics. - */ - CWAL_F_IS_DESTRUCTING = 0x04, - - /** - Used for marking cwal_scope::props (via its cwal_obase::flags) to - avoid some weird corner cases involving the vacuum-safe flag - when/if the variable storage Objects are exposed to - clients/scripts. It's needed to be able to differentiate this - case from vacuum-safe in order to avoid a corner case if the - client explicitly sets/unsets the vacuum-safe flag on a prop - storage container. - */ - CWAL_F_IS_PROP_STORAGE = 0x10, - - /** - A flag to briefly note that a value is temporarily locked, e.g. - currently being sorted, and must not be traversed or modified. - As of this writing (20191211), only arrays are/need to be locked - in a way distinct from the is-visiting flag, so we we "could" - re-use this flag's value with other semantics for non-array - types, if needed. - */ - CWAL_F_LOCKED = 0x20 -}; - -/** @internal - Convenience typedef. */ -typedef struct cwal_htable cwal_htable; -/** @internal - An internal helper class for building hashtables of cwal_kvp - entries. -*/ -struct cwal_htable { - /** - Array (hash table) of (cwal_kvp*) values. Its .count property - holds the current total number of entries (noting that they won't - typically be in contiguous list slots). Its .alloced property - holds the length (in entries) of the table. Its .list member is - the raw array storage. - */ - cwal_list list; - /** - Side effect of the chunk recycler: we need to be able to - differentiate between the hashtable size and the amount of memory - allocated for it (which might be larger). This value be less than - or equal to this->list.alloced. - */ - cwal_midsize_t hashSize; -}; -/** A clean cwal_htable instance for cost-copy initialization. */ -#define cwal_htable_empty_m {cwal_list_empty_m,0} - -/** @internal - Convenience typedef. */ -typedef struct cwal_obase cwal_obase; - -/** @internal - "Base" type for types which contain other values (which means they - are subject to cycles). An instance of this struct must be embedded - at the FIRST MEMBER of any such class, and any type-specific - members must come after that. See cwal_array and cwal_object for - examples. - */ -struct cwal_obase { -#if CWAL_OBASE_ISA_HASH - /** - Hashtable of object-level properties. - */ - cwal_htable hprops; -#else - /** - Linked list of key/value pairs held by this object. - */ - cwal_kvp * kvp; -#endif - /** - The "prototype" (analog to a parent class). - */ - cwal_value * prototype; - /** - Internal flags. - - Maintenance note: due to struct padding, this can be either 16 - or 32-bits with no real change in struct size on 64-bit, but - increasing either flags field on 32-bit increases the sizeof - (4 bytes if we increase both fields to 32 bits). Internally we - currently need 16 bits for flags. - - As of 20141205, we are using the top few bits of these via - cwal_container_flags, exposing/modifying the upper byte of - these flags via cwal_container_flags_set() and - cwal_container_flags_get(). - - As of 20191212, we desperately need more room for flags, but - cannot do so without increasing the sizeof by up to 4 on 32-bit - builds, from 12 to 16. We may just have to eat that cost :/. - On 64-bit builds that change wouldn't change the sizeof(). - */ - cwal_flags16_t flags; - /** - Engine-internal flags specifically for container-type-specific - behaviour. - */ - cwal_flags16_t containerFlags; - - /** - Holds client-specified flags. - */ - cwal_flags16_t clientFlags; - - cwal_flags16_t reservedPadding; -}; - -/** @internal - Empty-initialized cwal_obase object. -*/ -#if CWAL_OBASE_ISA_HASH -# define cwal_obase_empty_m {\ - cwal_htable_empty_m/*hprops*/, NULL/*prototype*/,CWAL_F_NONE/*flags*/,\ - 0/*containerFlags*/, 0/*clientFlags*/, 0/*reservedPadding*/\ - } -#else -# define cwal_obase_empty_m { \ - NULL/*kvp*/, NULL/*prototype*/, CWAL_F_NONE/*flags*/,\ - 0/*containerFlags*/, 0/*clientFlags*/, 0/*reservedPadding*/\ - } -#endif - -/** @internal - - Concrete value type for Arrays (type CWAL_TYPE_ARRAY). -*/ -struct cwal_array { - /** - base MUST be the first member for casting reasons. - */ - cwal_obase base; - /** - Holds (cwal_value*). NULL entries ARE semantically legal. - */ - cwal_list list; -}; -/** - Empty-initialized cwal_array object. -*/ -#define cwal_array_empty_m { cwal_obase_empty_m, cwal_list_empty_m } -/** - Empty-initialized cwal_array object. -*/ -extern const cwal_array cwal_array_empty; - -/** @internal - - The metadata for concrete Object values (type CWAL_TYPE_OBJECT). - */ -struct cwal_object { - /** - base MUST be the first member for casting reasons. - */ - cwal_obase base; -}; -/** - Empty-initialized cwal_object object. -*/ -#define cwal_object_empty_m { cwal_obase_empty_m } -/** - Empty-initialized cwal_object object. -*/ -extern const cwal_object cwal_object_empty; - -/** - Information for binding a native function to the script engine in - the form of a Function value (type CWAL_TYPE_FUNCTION). -*/ -struct cwal_function { - /** - base MUST be the first member for casting reasons. - */ - cwal_obase base; - /** - Client-defined state for the function. - */ - cwal_state state; - - /** - The concrete callback implementation. - */ - cwal_callback_f callback; - - /** - "Rescoper" for the function. Can be set via - cwal_function_set_rescoper(), and gives the client a way to - rescope any function-private data (stored in this struct's - state member) if needed. - - Use case: s2's s2_func_state wants to hold/manage "static" - script state at the function level without using a hidden - property. i.e. we don't want cwal_props_clear() to be able to - nuke that state. - */ - cwal_value_rescoper_f rescoper; -}; - -/** - Empty-initialized cwal_function object. -*/ -#define cwal_function_empty_m { cwal_obase_empty_m, cwal_state_empty_m, NULL, NULL } -/** - Empty-initialized cwal_function object. -*/ -extern const cwal_function cwal_function_empty; - -/** - Concrete type for generic error/exception values. -*/ -struct cwal_exception { - /** - base MUST be the first member for casting reasons. - */ - cwal_obase base; - int code; -}; -/** - Empty-initialized cwal_exception object. -*/ -#define cwal_exception_empty_m { cwal_obase_empty_m, -1 } -/** - Empty-initialized cwal_exception object. -*/ -extern const cwal_exception cwal_exception_empty; - -/** - A key/value pair of cwal_values. While key can be an arbitrary - cwal_value, the engine requires that the key be of a type with a - stable hash code AND stable comparison semantics (as of 201811, - cwal_tuple and cwal_buffer are the only types which are "most - definitely not recommended) for use as keys because modification of - their contents changes how they compare to other values, which - means that they can get "out of place" within a sorted property - list (e.g. cwal_obase::kvp). - - Each of these objects owns its key/value pointers, and they - are cleaned up by cwal_kvp_clean(). A KVP holds a reference - to each of its parts. -*/ -struct cwal_kvp{ - /** - The key. Keys are compared using cwal_value_vtab::compare(). - */ - cwal_value * key; - /** - Arbitrary value. Objects do not have NULL values - a literal - NULL means to "unset" a property. cwal_value_null() can be - used as a value, of course. - */ - cwal_value * value; - /** - Right-hand member in a linked list. cwal_obase and cwal_hash - use this. Nobody else should. - */ - cwal_kvp * right; - /** - We need this for intepreter-level flags like "const" and - "hidden/non-iterable." This was increased from 16 to 32 bits on - 20191210, which does not change the sizeof(), because of - padding, but the public APIs were left as-is (exposing only - cwal_flags16_t). We can still, on 64-bit builds, stuff another - 4(?) bytes in here without increasing the sizeof(), which would - allow us to add a refcount to KVPs, though that wouldn't be as - useful as it may initially sound because we'd need to implement - Copy-on-Write for shared KVPs, which has some backfire cases - for how we use these objects. - - It might be interesting to expose the top 16 of these bits for - use by clients, but a concrete use case for such flags (which - isn't covered by existing cwal-level flags) eludes me - */ - cwal_flags16_t flags; -}; - -/** - Empty-initialized cwal_kvp object. -*/ -#define cwal_kvp_empty_m {NULL,NULL,NULL,0U/*flags*/} -/** - Empty-initialized cwal_kvp object. -*/ -extern const cwal_kvp cwal_kvp_empty; - -/** @internal - - Semantically allocates a new cwal_kvp object, owned by e, though it - may pull a recycled kvp from e's internal recycler. Returns NULL on - error. On success the returned value is empty-initialized. -*/ -cwal_kvp * cwal_kvp_alloc(cwal_engine *e); - -/** @internal - Unrefs kvp->key and kvp->value and sets them to NULL, but does not - free kvp. If !kvp then this is a no-op. -*/ -void cwal_kvp_clean( cwal_engine * e, cwal_kvp * kvp ); - -/** @internal - - Calls cwal_kvp_clean(e,kvp) and then either adds kvp to e's recycle - bin or frees it, depending on the value of allowRecycle and the - capacity/size of the associated recycler list. - - Callers must treat this call as if kvp is free()d by it, whether or - not this function actually does so. -*/ -void cwal_kvp_free( cwal_engine * e, cwal_kvp * kvp, char allowRecycle ); - -/** - Typedef for cwal_value hashing functions. Must return a hash value - for the given value. -*/ -typedef cwal_hash_t (*cwal_value_hash_f)( cwal_value const * v ); - -/** - Returns v's hash value, as computed by v's vtab. - Returns 0 if !v. -*/ -cwal_hash_t cwal_value_hash( cwal_value const * const v ); - -/** - Typedef for cwal_value comparison functions. Has memcmp() - semantics. Ordering of mismatched types (e.g. comparing an array to - an object) is type-dependent, possibly undefined. Implementations - of this function are type-specific and require that the lhs - (left-hand-side) argument be of their specific type (and are - permitted to assert that that is so). When performing conversions, - they should treat the LHS as the primary type for - conversion/precision purposes. e.g. comparison of (int 42) and - (double 42.24) might be different depending on which one is the LHS - because of changes in precision. - - Beware that these comparisons are primarily intended for - cwal-internal use (e.g. in the context of property lists and - hashtables), and are not strictly required to follow the semantics - of any given scripting environment or specificiation. (That said, - the public cwal_value_compare() interface uses these, so the - behaviour must remain stable.) - - Where (lhs,rhs) do not have any sort of natural ordering, - implementations should return any value other than 0, implementing - ECMAScript-like semantics if feasible. - - Implementations are encouraged to do cross-type comparisons where - feasible (e.g. "123"==123 is true), and to delegate to the converse - comparison (swapping lhs/rhs and the return value) when the logic - for the comparison is non-trivial and already implemented for the - other type. Strict-equality comparisons (e.g. "123"===123 is false) - are handled at a higher level which compares type IDs and/or - pointers before passing the values on to this function. Comparisons - are prohibited (by convention) from allocating any memory, and the - API is not set up to be able to report an OOM error to the caller. -*/ -typedef int (*cwal_value_compare_f)( cwal_value const * lhs, cwal_value const * rhs ); - -/** - This type holds the "vtbl" for type-specific operations when - working with cwal_value objects. - - All cwal_values of a given logical type share a pointer to a single - library-internal instance of this class. -*/ -struct cwal_value_vtab -{ - /** - The logical data type associated with this object. - */ - const cwal_type_id typeID; - - /** - A descriptive type name intented primarily for debuggering, and - not (necessarily) as a type's name as a client script language - might see/name it (though, in fact, they are in used that way). - */ - char const * typeName; - - /** - Internal flags. - */ - cwal_flags16_t flags; - - /** - Must free any memory owned by the second argument, which will - be a cwal_value of the concrete type associated with this - instance of this class, but not free the second argument (it is - owned by the engine and may be recycled). The API shall never - pass a NULL value to this function. - - The API guarantees that the scope member of the passed-in value - will be set to the value's pre-cleanup owning scope, but also - that the value is not in the scope value list at that time. The - scope member is, however, needed for proper unreferencing of - child values (which still live in a scope somewhere, very - possibly the same one). Implementations must not do anything - with child values other than unref them, as they may very well - already be dead and in the gc-queue (or recycler) by the time - this is called. The engine delays (via the gc-queue) any - free()ing of those children while a cleanup pass is running, so - handling the memory of a child value is legal, but any usage - other than an unref is semantically strictly illegal. - */ - cwal_finalizer_f cleanup; - - /** - Must return a hash value for this value. Hashes are used only as - a quick comparison, with the compare() method being used for - a more detailed comparison. - */ - cwal_value_hash_f hash; - - /** - Must perform a comparison on its values. The cwal engine - guarantees that the left-hand argument will be of the type - managed by the instance of the cwal_value_tab on which this is - called, but the right-hand argument may be of an arbitrary - type. - - This function checks for equivalence, not identity, and uses - memcmp() semantics: less than 0 means that the left-hand - argument is "less than" the right, 0 means they are equivalent, - and 1 means the the lhs is "greater than" the right. It is - understood, of course, that not all comparisons have meaningful - results, and implementations should always return non-0 for - meaningless comparisons. They are not required to return a - specific value but should behave consistently (e.g. not - swapping the order on every call or some such sillynesss). - - For many non-POD types, 0 can only be returned when both - pointers have the same address (that said, the framework should - short-circuit any such comparison itself). - */ - cwal_value_compare_f compare; - - /** - Called by the framework when it determines that v needs to be - "upscoped." The framework will upscope v but cannot generically - know if v contains any other values which also need to be - upscoped, so this function has the following responsibilities: - - For any child values which are "unmanaged" (e.g. they're not - stored in cwal_object properties), this function must call - cwal_value_rescope( v->scope->e, v->scope, child ). That, in - turn, will trigger the recursive rescoping of any children of - that value. Note that the rescoping problem is not subject to - "cyclic misbehaviours" - the worst that will happen is a cycle - gets visited multiple times, but those after the first will be - no-ops because no re-scoping is necessary: the API only calls - this when upscoping is necessary. - - The framework guarantees the following: - - Before this is called on a value, the following preconditions - exist: - - - v is of the value type represented by this vtab instance. - - - v->scope has been set to the "proper" scope by e. This - function will never be called when v->scope is 0. - - - v->scope->e points to the active engine. - - - This is only called when/if v is actually upscoped. Re-scope - requests which do not require a rescope will not trigger a call - to this function. - - If v owns any "unmanaged" child values (e.g. not kept in the - cwal_obase base class container or as part of a cwal_array) - then those must be rescoped by this function (the framework - does not know about them). They likely also need to be made - vacuum-proof (see cwal_value_make_vacuum_proof()). - - Classes which do not contain other values may set this member - to 0. It is only called if it is not NULL. Classes which do - hold other values _must_ implement it (properly!). - - Must return 0 on success and "truly shouldn't fail" because all - it does it pass each child on to cwal_value_rescope(), which - cannot fail if all arguments are in order and the internal - state of the values seems okay (the engine does a good deal of - extra checking and assert()ing). However, if it fails it should - return an appropriate value from the cwal_rc_e enum. Returning - non-0 will be treated as fatal, possibly assert()ing in debug - builds. - */ - int (*rescope_children)( cwal_value * v ); - - /** - TODOs???: - - // Using JS semantics for true/value - char (*bool_value)( cwal_value const * self ); - - // To-string ops... - unsigned char const * to_byte_array( cwal_value const * self, cwal_size_t * len ); - // which is an optimized form of ... - int to_string( cwal_value const * self, cwal_engine * e, cwal_buffer * dest ); - // with the former being used for (Buffer, String, builtins) - // and the latter for everything else. Either function may be 0 - // to indicate that the operation is not supported - // (e.g. Object, Array, Hashtable, Function...). - - // The problem with adding an allocator is... - int (*allocate)( cwal_engine *, ??? ); - // If we split it into allocation and initialization, might - // that solve it? Or cause more problems? - // cwal_value * (*allocate)( cwal_engine * e ); - // int (*initialize)( cwal_engine * e, cwal_value * v, ... ) - - // Deep copy. - int (*clone)( cwal_engine *e, cwal_value const * self, cwal_value ** tgt ); - - // Property interceptors: - int (*get)( cwal_engine *e, cwal_value const * self, - cwal_value const * key, cwal_value **rv ); - - int (*set)( cwal_engine *e, cwal_value * self, - cwal_value * key, cwal_value *v ); - - But for convenience the get() op also needs a variant taking a - c-string key (otherwise the client has to create values when - searching, more often than not) - */ -}; - -typedef struct cwal_value_vtab cwal_value_vtab; -/** - Empty-initialized cwal_value_vtab object. -*/ -#define cwal_value_vtab_empty_m { \ - CWAL_TYPE_UNDEF/*typeID*/, \ - ""/*typeName*/, \ - 0U/*flags*/, \ - NULL/*cleanup()*/, \ - NULL/*hash()*/, \ - NULL/*compare()*/, \ - NULL/*rescope_children()*/ \ - } -/** - Empty-initialized cwal_value_vtab object. -*/ -extern const cwal_value_vtab cwal_value_vtab_empty; - -/** - cwal_value represents an opaque Value handle within the cwal - framework. Values are all represented by this basic type but they - have certain polymorphic behaviours (via cwal_value_vtab) and many - concrete types have high-level handle representations - (e.g. cwal_object and cwal_array). - - @see cwal_new_VALUE() - @see cwal_value_vtab -*/ -struct cwal_value { - /** - The "vtbl" of type-specific operations. All instances of a - given logical value type share a single vtab instance. - - Results are undefined if this value is NULL or points to the - incorrect vtab instance. - */ - cwal_value_vtab const * vtab; - - /** - The "current owner" scope of this value. Its definition is - as follows: - - When a value is initially allocated its owner is the - currently-active scope. If a value is referenced by a - higher-level (older) scope, it is migrated into that scope - (recursively for containers) so that we can keep cleanup of - cycles working (because all values in a given graph need to be - in the same scope for cleanup to work). It is, on rare - occasion, necessary for code (sometimes even client-side) to - cwal cwal_value_rescope() to re-parent a value. - */ - cwal_scope * scope; - - /** - The left-hand-link for a linked list. Who exactly owns a value, - and which values they own, are largely handled via this - list. Each manager (e.g. scope, recycle bin, or gc queue) holds - the head of a list and adds/removes the entries as needed. - - Note that we require two links because if we only have a single - link then cleanup of a member in a list can lead traversal - through that list into places it must not go (like into the - recycler's memory). - - Design notes: in the original design each value-list manager - had a separate array-style list to manage its values. Switching - to this form (where the values can act as a list) actually - (perhaps non-intuitively) cuts both the number of overall - allocations and memory cost, converts many of the previous - operations from O(N) to O(1), and _also_ removes some - unrecoverable error cases caused by OOM during manipulation of - the owner's list of values. So it's an overall win despite the - cost of having 2 pointers per value. Just remember that it's - not strictly Value-specific overhead... it's overhead Scopes - and other Value owners would have if this class didn't. - */ - cwal_value * left; - - /** - Right-hand link of a linked list. - */ - cwal_value * right; - - /** - We use this to allow us to store a refcount and certain flags. - - Notes about the rc implementation: - - - Instances start out with a refcount of 0 (not 1). Adding them - to a container will increase the refcount. Cleaning up the container - will decrement the count. cwal_value_ref() can be used to obtain - a reference when no container is handy. - - - cwal_value_unref() decrements the refcount (if it is not - already 0) and cleans/frees the value only when the refcount is - 0 (and then it _might_ not destroy the value immediately, - depending on which scope owns it and where (from which scope) - its refcount goes to 0). - - - cwal_value_unhand() decrements the refcount (if it is not - already 0) but does not destroy the value if it reaches 0. If - it reaches 0, "unhanding" re-sets the value into a so-called - "probationary" state, making it subject to being swept up if no - reference is taken before the next cwal_engine_sweep() (or - similar). - - - This number HAS FLAGS ENCODED IN IT, so don't use this value - as-is. How many flags, where they are, and what they mean, are - internal details. Search cwal.c for RCFLAGS for the gory - details. - */ - cwal_refcount_t rcflags; - - /* - Historical notes, no longer entirely relevant but perhaps - interesting: - - ======== - - Potential TODO: if we _need_ flags in this class, we can use the - high byte (or half-byte) of refcount and restrict refcount to - the lower bytes (possibly only 3 resp. 3.5). We need to make - sure refcount uses a 32-bit type in that case, as opposed to - cwal_size_t (which can be changed to uint16_t, which only gives - us a range of up to 4k if we reserve 4 bits!). While 4k might - initially sound like a reasonable upper limit for refcounts, - practice has shown that value prototypes tend to accumulate lots - and lots of references (one for each value which has it as a - prototype), so 4kb quickly becomes a real limit. - - 16 bits (64k) of refcount might be a feasible upper limit, even - for large apps. And nobody will ever need more than 640kb of - RAM, either. - - We could... use a 32-bit type, reserve the bottom 24 bits (16M) - for the refcount, and the top 8 bits for client-side flags. - - Class-level flags are set in the associated cwal_value_vtab - instance. Container classes may have their own instance-specific - flags. - - Reminder to self: interpreters are going to need flags for - marking special values like constants/non-removable. Oh, but - that's going to not like built-in constants. So we'll need to - tag these at the cwal_kvp level (which costs us less, actually, - because we have one set of flags per key/value pair, instead of - per Value instance). - - Ideas of what clients could use flags for: - - - tagging values which want special handling. e.g. if scripts - can override get/set operations, that may be too costly if - performed on all values. A flag could indicate whether a given - value has such an override. Tagging constructor/factory - functions for special handling with the 'new' keyword is - something we could possibly use in s2. - - - in s2, we could use this to tag Classes and instances of classes, - such that we could change property lookup on them (and potentially - reject the addition of new properties to classes). - - Problems: - - - Built in constant values cannot be flagged. The use of the - numeric (-1, 0, 1) values as built-in constants saves up to 50% - of numeric-type allocations in many test scripts, so i don't - want to drop those. If we allow flags only on container types - (plus buffers), we can move the cost/handling there (and maybe - get more flag space). Or we add a way for clients to create - mutable instances of builtin values, such that they can be - tagged. That would require some fixes/changes in other bits - which make assumptions about the uniqueness of, e.g. boolean - values. - - */ -}; - - -/** - Empty-initialized cwal_value object. -*/ -#define cwal_value_empty_m { \ - &cwal_value_vtab_empty/*api*/,\ - 0/*scope*/,\ - 0/*left*/,\ - 0/*right*/, \ - 0/*rcflags*/ \ -} -/** - Empty-initialized cwal_value object. -*/ -extern const cwal_value cwal_value_empty; - - -struct cwal_native { - /** - base MUST be the first member for casting reasons. - */ - cwal_obase base; - void * native; - void const * typeID; - cwal_finalizer_f finalize; - /** - If this member is non-NULL then it is called to allow - the native to rescope properties not visible via its property - list. - */ - cwal_value_rescoper_f rescoper; -}; -#define cwal_native_empty_m {\ - cwal_obase_empty_m, \ - 0/*native*/,\ - 0/*typeID*/,\ - 0/*finalize*/, \ - 0/*rescoper*/ \ - } -extern const cwal_native cwal_native_empty; - -/** @internal - Hash table Value type. -*/ -struct cwal_hash { - /** - base MUST be the first member for casting reasons. - */ - cwal_obase base; - /** - The actual hashtable. Note that if (CWAL_OBASE_ISA_HASH) then - this hashtable is a separate one: that one is the object-level - properties and this one is the "plain" hashtable. The main - difference is that the latter does not participate in prototype - property lookup. - */ - cwal_htable htable; -}; -#define cwal_hash_empty_m { \ - cwal_obase_empty_m/*base*/, \ - cwal_htable_empty_m/*htable*/ \ - } -extern const cwal_hash cwal_hash_empty; - - -/** @internal - - An object-style representation for cwal_buffer. This type is - strictly internal, not exposed to clients. -*/ -struct cwal_buffer_obj { - /** - base MUST be the first member for casting reasons. - */ - cwal_obase base; - /** - The buffer owned/tracked by this object. - */ - cwal_buffer buf; -}; -typedef struct cwal_buffer_obj cwal_buffer_obj; -#define cwal_buffer_obj_empty_m {\ - cwal_obase_empty_m/*base*/, \ - cwal_buffer_empty_m/*buf*/ \ -} -extern const cwal_buffer_obj cwal_buffer_obj_empty; - -/** - Internal state for CWAL_TYPE_TUPLE-typed cwal_values. - -*/ -struct cwal_tuple { - /** - Number of entries in the list (set at init-time and - never changes). - */ - uint16_t n; - /** - Not yet used. Note that removing this does not shrink this - type's sizeof(), due to padding. - */ - uint16_t flags; - /** - List of this->n entries. - */ - cwal_value ** list; -}; -#define cwal_tuple_empty_m {0U,0U,NULL} - -/** @internal - - Internal impl of the weak reference class. -*/ -struct cwal_weak_ref { - void * value; - cwal_type_id typeID; - cwal_refcount_t refcount; - struct cwal_weak_ref * next; -}; - -/** @internal - - Initialized-with-defaults cwal_weak_ref instance. -*/ -#define cwal_weak_ref_empty_m {NULL, CWAL_TYPE_UNDEF, 0U, NULL} - -/** @internal - - Initialized-with-defaults cwal_weak_ref instance. -*/ -extern const cwal_weak_ref cwal_weak_ref_empty; - -/** @internal - - If v is-a obase then its obase part is returned, else NULL is - returned. -*/ -cwal_obase * cwal_value_obase( cwal_value * const v ); - - -/** @internal - - Internal debuggering function which MIGHT dump some useful info - about v (not recursively) to some of the standard streams. - - Do not rely on this function from client code. - - The File/Line params are expected to be the __FILE__/__LINE__ - macros. - - If msg is not NULL then it is included in the output (the exact - placement, beginning or end, is unspecified). - */ -void cwal_dump_value( char const * File, int Line, - cwal_value const * v, char const * msg ); - -/** @def cwal_dump_v(V,M) - - Internal debuggering macro which calls cwal_dump_value() with the - current file/line/function info. -*/ -#if 1 -# define cwal_dump_v(V,M) cwal_dump_value(__func__,__LINE__,(V),(M)) -#else -# define cwal_dump_v(V,M) assert(1) -#endif - - -/** - Searches e for an internalized string matching (zKey,nKey). If - found, it returns 0 and sets any of the output parameters which are - not NULL. - - On success, *out (if out is not NULL) be set to the value matching - the key. Note that only String values can compare equal here, even - if the key would normally compare as equivalent to a value of - another type. e.g. 1=="1" when using cwal_value_compare(), but - using that comparison here would not be possible unless we - allocated a temporary string to compare against. - - It sets *itemIndex (if not NULL) to the index in the strings table - for the given key, regardless of success of failure. The other - output params are only set on success. - - *out (if not NULL) is set to the value in the table. pageIndex (if - *not NULL) is set to the page in which the entry was found. - - Reminder to self: we might be able to stack-allocate an x-string - around zKey and do a cwal_value-keyed search on that. That would - work around the (1!="1") inconsistency. -*/ -int cwal_interned_search( cwal_engine * e, char const * zKey, cwal_size_t nKey, - cwal_value ** out, cwal_ptr_page ** pageIndex, uint16_t * itemIndex ); - -/** - Equivalent to cwal_interned_search() except that it takes a - cwal_value parameter and uses cwal_value_compare() for the hashing - comparisons. A cwal String value inserted this way _will_ compare -*/ -int cwal_interned_search_val( cwal_engine * e, cwal_value const * v, - cwal_value ** out, cwal_ptr_page ** pageIndex, - uint16_t * itemIndex ); -/** - Removes the string matching (zKey,nKey) from e's interned - strings table. If an entry is found 0 is returned and - *out (if not NULL) is set to the entry. - - Returns CWAL_RC_NOT_FOUND if no entry is found. -*/ -int cwal_interned_remove( cwal_engine * e, cwal_value const * v, cwal_value ** out ); - -/** - Inserts the given value, which must be-a String, into - e's in interned strings list. Returns 0 on success. - Returns CWAL_RC_ALREADY_EXISTS if the entry's string - value is already in the table. - -*/ -int cwal_interned_insert( cwal_engine * e, cwal_value * v ); - -/** - Pushes the given cwal_value into e->gc for later destruction. We do - this to avoid prematurely stepping on a being-destroyed Value when - visiting cycles. - - If insertion of p into the gc list fails then this function frees - it immediately. We "could" try to stuff it in the recycle bin, but - that would only potentially delay the problem (of stepping on a - freed value while cycling). - - This function asserts that e->gcInitiator is not 0. -*/ -int cwal_gc_push( cwal_engine * e, cwal_value * p ); - -/** - Passes all entries in e->gc to cwal_value_recycle() for recycling - or freeing. -*/ -int cwal_gc_flush( cwal_engine * e ); - -/** - If v->vtab->typeID (T) is of a recyclable type and e->recycler entry - number cwal_recycler_index(T) has space, v is put there, otherwise - it is cwal_free()'d. This is ONLY to be called when v->refcount - drops to 0 (in place of calling cwal_free()), or results are - undefined. - - If e->gcLevel is not 0 AND v is-a obase then v is placed in e->gc - instead of being recycled so that the destruction process can - finish to completion without getting tangled up in the recycle bin - (been there, debugged that). That is a bit of a shame, actually, - but the good news is that cwal_gc_flush() will try to stick it back - in the recycle bin. Note that non-Objects do not need to be - delayed-destroyed because they cannot contribute to cycles. - - Returns 0 if the value is freed immediately, 1 if it is recycled, - and -1 if v is placed in e->gc. If insertion into e->gc is called - for fails, v is freed immediately (and 0 is returned). (But since - e-gc is now a linked list, insertion cannot fail except on internal - mis-use of the GC bits.) -*/ -int cwal_value_recycle( cwal_engine * e, cwal_value * v ); - -/** - Tracing macros. - */ -#if CWAL_ENABLE_TRACE -#define CWAL_ETR(E) (E)->trace -#define CWAL_TR_SRC(E) CWAL_ETR(E).cFile=__FILE__; CWAL_ETR(E).cLine=__LINE__; CWAL_ETR(E).cFunc=__func__ -#define CWAL_TR_MSG(E,MSG) CWAL_ETR(E).msg = MSG; if((MSG) && *(MSG)) CWAL_ETR(E).msgLen = strlen(MSG) -#define CWAL_TR_EV(E,EV) CWAL_ETR(E).event = (EV); -/*if(!(CWAL_ETR(E).msg)) { CWAL_TR_MSG(E,#EV); }*/ - -#define CWAL_TR_RC(E,RC) CWAL_ETR(E).code = (RC) -#define CWAL_TR_V(E,V) CWAL_ETR(E).value = (V); -#define CWAL_TR_MEM(E,M,SZ) CWAL_ETR(E).memory = (M); CWAL_ETR(E).memorySize = (SZ) -#define CWAL_TR_S(E,S) CWAL_ETR(E).scope = (S) -#define CWAL_TR_SV(E,S,V) CWAL_TR_V(E,V); CWAL_TR_S(E,S) -#define CWAL_TR_VCS(E,V) CWAL_TR_V(E,V); CWAL_TR_S(E,(E)->current) -#define CWAL_TR3(E,EV,MSG) \ - if(MSG && *MSG) { CWAL_TR_MSG(E,MSG); } \ - CWAL_TR_EV(E,EV); \ - if(!(CWAL_ETR(E).scope)) { \ - if(CWAL_ETR(E).value) CWAL_ETR(E).scope = CWAL_ETR(E).value->scope; \ - if(!(CWAL_ETR(E).scope)) CWAL_ETR(E).scope=(E)->current; \ - } \ - CWAL_TR_SRC(E); \ - cwal_trace(E) -#define CWAL_TR2(E,EV) CWAL_TR3(E,EV,"") -#else -#define CWAL_ETR(E) -#define CWAL_TR_SRC(E) -#define CWAL_TR_MSG(E,MSG) -#define CWAL_TR_EV(E,EV) -#define CWAL_TR_RC(E,RC) -#define CWAL_TR_V(E,V) -#define CWAL_TR_S(E,S) -#define CWAL_TR_MEM(E,M,SZ) -#define CWAL_TR_SV(E,S,V) -#define CWAL_TR_VCS(E,V) -#define CWAL_TR3(E,EV,MSG) -#define CWAL_TR2(E,EV) -#endif - -/** @internal - - If the library is built with tracing enabled and tracing is enabled - for e, this function outputs the state of e->trace and then clears - that state. The intention is that various macros initialize the - trace state, then call this to output it. -*/ -void cwal_trace( cwal_engine * e ); - -/** @internal - - cwal_value_take() "takes" a value away from its owning scope, - transfering the scope's reference count point to the caller, - removing the value from any list it is currently in, and settings - its scope to NULL. - - On error non-0 is returned and ownership is not modified. - - This function works only on "managed" values (with an owning - scope), and there is no API for creating/managing non-scope-managed - values from client code. - - Each allocated value is owned by exactly one scope, and this - function effectively steals the value from the owning scope. This - function must not be passed the same value instance more than once - unless the value has been re-scoped since calling this (it will - fail on subsequent calls, and may assert() that v's is in the - expected state). - - In all cases, if this function returns 0 the caller effectively - takes over ownership of v and its memory, and the value IS NOT - VALID for use with most of the API because, after calling this, it - has no owning scope, and many APIs assert() that a value has an - owning scope. - - For built-in values this is a harmless no-op. - - Error conditions: - - CWAL_RC_MISUE: either e or v are NULL. - - CWAL_RC_RANGE: means that v has no owning scope. This - constellation is highly unlikely but "could happen" if the API ever - evolves to allow "unscoped" values (not sure how GC could work - without the scopes, though). - - @see cwal_value_unref() -*/ -int cwal_value_take( cwal_engine * e, cwal_value * v ); - -/** @internal - - An internal helper for routines (specifically JSON) - to traverse an object tree and detect cycles. - - Passed the object which is about to be traversed and a pointer - to an opaque state value. - - If this function returns 0, the value is either not capable of - participating in acyclic traversal (cannot form cyles) or it is - and was flagged as not being in an acyclic traversal. If non-0 is - returned, the value was already flagged as being in an acylic - traversal and was traversed again (by this function), indicating a - cyclic case (i.e. an error). - - If it returns CWAL_RC_CYCLES_DETECTED: the value is already in the - process of acyclic traversal. The caller should fail the operation - with the result code returned by this function - (CWAL_RC_CYCLES_DETECTED) or a semantic equivalent for the given - operation. - - If, and only if, the return code is 0, the caller is obligated to - call cwal_visit_acyclic_end(), passing it the same second - argument. The caller MAY call cwal_visit_acyclic_end() if this - function returns non-0, but is not obligated to. - - @see cwal_visit_props_begin() - @see cwal_visit_list_begin() - @see cwal_visit_acyclic_end() -*/ -int cwal_visit_acyclic_begin( cwal_value * const v, int * const opaque ); - -/** @internal - - MUST be called if, and only if, the previous call to - cwal_visit_acyclic_begin() returned 0. MAY be called if the - previous call to cwal_visit_acyclic_begin() returned non-0, but it - is not required. - - The 2nd argument must be the same value which was passed to - cwal_visit_acyclic_begin(), as it contains state relevant to the - cycle-checking process. - - @see cwal_visit_acyclic_begin() -*/ -void cwal_visit_acyclic_end( cwal_value * const v, int opaque ); - -/** @internal - - Internal helper to flag property visitation/traversal. If this is - called, the value stored in *opaque MUST be passed to - cwal_visit_props_end() in the same logical code block. - - v MUST be a type capable of property iteration (and not a - builtin). - - Calling this obliges the caller to pass the value of *opaque - to cwal_visit_props_end() when visitation is complete. - - The API guarantees that this routine will set *opaque to a non-0 - value, so that callers may use 0 for their own purposes (e.g. - determining whether or not they need to call - cwal_visit_props_end()). - - This function may set the CWAL_RCF_IS_VISITING flag on v, and - records in the 2nd argument whether or not it did so. When - cwal_visit_props_end() is called, if its second argument records - that it set the flag then that call unsets that flag. This allows - properties to be visited multiple times concurrently, with only - the top-most visitation toggling that flag. That flag, in turn, is - checked by routines which would invalidate such iteration, causing - such routines to return an error code rather than invalidating the - in-progress iteration. e.g. trying to set a property value while - the properties are being iterated over will trigger such a case - because the underlying data model does not support modification - during traversal. - - @see cwal_visit_props_end() - @see cwal_visit_acyclic_begin() -*/ -void cwal_visit_props_begin( cwal_value * const v, int * const opaque ); - -/** @internal - - If, and only if, cwal_visit_props_begin() was passed v, the - resulting integer value from that call MUST be passed to this - function when property traversal is complete. - - @see cwal_visit_props_begin() -*/ -void cwal_visit_props_end( cwal_value * const v, int opaque ); - -/** @internal - - Internal helper to flag property visitation. If this is called, - the value stored in *opaque MUST be passed to - cwal_visit_list_end() in the same logical code block. - - v MUST be a type capable of list iteration (and not a builtin). - - Calling this obliges the caller to pass the value of *opaque - to cwal_visit_list_end() when visitation is complete. - - The API guarantees that this routine will set *opaque to a non-0 - value, so that callers may use 0 for their own purposes (e.g. - determining whether or not they need to call - cwal_visit_props_end()). - - If called recursively, only the top-most call will modify the - visitation flag. - - @see cwal_visit_list_end() -*/ -void cwal_visit_list_begin( cwal_value * const v, int * const opaque ); - -/** @internal - - If, and only if, cwal_visit_list_begin() was passed v, the - resulting integer value from that call MUST be passed to this - function when property traversal is complete. - - @see cwal_visit_list_begin() -*/ -void cwal_visit_list_end( cwal_value * const v, int opaque ); - -/** - Internal helper for iterating over cwal_obase properties. -*/ -struct cwal_obase_kvp_iter { - cwal_value * v; - cwal_kvp const * current; -#if CWAL_OBASE_ISA_HASH - cwal_obase * base; - cwal_list const * li; - cwal_midsize_t ndx; -#endif -}; -typedef struct cwal_obase_kvp_iter cwal_obase_kvp_iter; - -/** @internal - - Initializes oks for iteration over v's properties and returns the - first property. Returns NULL if v has no properties. - - This routine may assert that v is currently marked as is-visiting - or is-list-visiting. - - Use cwal_obase_kvp_iter_next() to iterate over subsequent entries. -*/ -cwal_kvp const * cwal_obase_kvp_iter_init( cwal_value * const v, - cwal_obase_kvp_iter * const oks ); - -/** @internal - - Returns the next property in oks's state, or NULL once the end of - the property list has been reached. - - This routine may assert that v is currently marked as is-visiting - or is-list-visiting. - - Results are undefined if oks has has previously been passed to - cwal_obase_kvp_iter_init(). -*/ -cwal_kvp const * cwal_obase_kvp_iter_next( cwal_obase_kvp_iter * const oks ); - - - -/* LICENSE - -This software's source code, including accompanying documentation and -demonstration applications, are licensed under the following -conditions... - -Certain files are imported from external projects and have their own -licensing terms. Namely, the JSON_parser.* files. See their files for -their official licenses, but the summary is "do what you want [with -them] but leave the license text and copyright in place." - -The author (Stephan G. Beal [http://wanderinghorse.net/home/stephan/]) -explicitly disclaims copyright in all jurisdictions which recognize -such a disclaimer. In such jurisdictions, this software is released -into the Public Domain. - -In jurisdictions which do not recognize Public Domain property -(e.g. Germany as of 2011), this software is Copyright (c) 2011-2018 by -Stephan G. Beal, and is released under the terms of the MIT License -(see below). - -In jurisdictions which recognize Public Domain property, the user of -this software may choose to accept it either as 1) Public Domain, 2) -under the conditions of the MIT License (see below), or 3) under the -terms of dual Public Domain/MIT License conditions described here, as -they choose. - -The MIT License is about as close to Public Domain as a license can -get, and is described in clear, concise terms at: - - http://en.wikipedia.org/wiki/MIT_License - -The full text of the MIT License follows: - --- - -Copyright (c) 2011-2021 Stephan G. Beal -(https://wanderinghorse.net/home/stephan/) - -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. - ---END OF MIT LICENSE-- - -For purposes of the above license, the term "Software" includes -documentation and demonstration source code which accompanies -this software. ("Accompanies" = is contained in the Software's -primary public source code repository.) - -*/ - -#if defined(__cplusplus) -} /*extern "C"*/ -#endif - -#endif /* WANDERINGHORSE_NET_CWAL_INTERNAL_H_INCLUDED */ -/* end of file cwal_internal.h */ -/* start of file cwal.c */ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=4 et sw=2 tw=80: */ -#include -#include /* malloc(), free(), qsort() */ -#include -#include -#include - -/** - Tells the internals whether to keep Object properties sorted or - not. Sorting speeds up searches. It is/should be enabled as of - 20170320. - - 202107: this has no effect when CWAL_OBASE_ISA_HASH is true. -*/ -#define CWAL_KVP_TRY_SORTING 1 - -#if 1 -#include -#define MARKER(pfexp) \ - do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__); \ - printf pfexp; \ - } while(0) -#else -#define MARKER(exp) if(0) printf -#endif - -#if defined(__cplusplus) -extern "C" { -#endif - -/** Convenience typedef. - typedef enum cwal_e_options cwal_e_options; */ - - -/* - Public-API constant/shared objects. -*/ -const cwal_array cwal_array_empty = cwal_array_empty_m; -const cwal_buffer cwal_buffer_empty = cwal_buffer_empty_m; -const cwal_callback_args cwal_callback_args_empty = cwal_callback_args_empty_m; -const cwal_callback_hook cwal_callback_hook_empty = cwal_callback_hook_empty_m; -const cwal_engine cwal_engine_empty = cwal_engine_empty_m; -const cwal_engine_tracer cwal_engine_tracer_empty = cwal_engine_tracer_empty_m; -const cwal_engine_vtab cwal_engine_vtab_empty = cwal_engine_vtab_empty_m; -const cwal_error cwal_error_empty = cwal_error_empty_m; -const cwal_exception cwal_exception_empty = cwal_exception_empty_m; -const cwal_exception_info cwal_exception_info_empty = cwal_exception_info_empty_m; -const cwal_function cwal_function_empty = cwal_function_empty_m; -const cwal_hash cwal_hash_empty = cwal_hash_empty_m; -const cwal_kvp cwal_kvp_empty = cwal_kvp_empty_m; -const cwal_list cwal_list_empty = cwal_list_empty_m; -const cwal_native cwal_native_empty = cwal_native_empty_m; -const cwal_object cwal_object_empty = cwal_object_empty_m; -const cwal_output_buffer_state cwal_output_buffer_state_empty = {NULL/*e*/, NULL/*b*/}; -const cwal_ptr_table cwal_ptr_table_empty = cwal_ptr_table_empty_m; -const cwal_recycler cwal_recycler_empty = cwal_recycler_empty_m; -const cwal_scope cwal_scope_empty = cwal_scope_empty_m; -const cwal_state cwal_state_empty = cwal_state_empty_m; -const cwal_trace_state cwal_trace_state_empty = cwal_trace_state_empty_m; -const cwal_value_vtab cwal_value_vtab_empty = cwal_value_vtab_empty_m; -const cwal_memchunk_config cwal_memchunk_config_empty = cwal_memchunk_config_empty_m; -static const cwal_memchunk_overlay cwal_memchunk_overlay_empty = {0,0}; -const cwal_memcap_config cwal_memcap_config_empty = cwal_memcap_config_empty_m; -const cwal_buffer_obj cwal_buffer_obj_empty = cwal_buffer_obj_empty_m; -const cwal_tuple cwal_tuple_empty = cwal_tuple_empty_m; - -#define E_IS_DEAD(E) ((E)->fatalCode) - -/** - An experiment in padding all allocations up to a pointer size so - that the recycler (which might (or might not)) can optimize a - bit. Similar to the string padding, but it's not clear whether we - will get as much benefit here. - - Initial tests show padding to take up notably more memory (~2k in - s2's amalgamated unit tests) and not saving any (or trivially few) - allocations. - - 20160206: enabling this gives, in the s2 unit tests, a microscopic - reduction (<500b) in peak mem (via list and buffer memory) but - shows promise in chunk recycling hits (roughly 4% - improvement). This depends entirely on other options, though: if - value/chunk recycling and string interning are enabled, plus - cwal_memcap_config::forceAllocSizeTracking is enabled, alloc counts - are completely unaffected and the byte difference between using - this and not is in the 2-digit range. -*/ -#define CWAL_ALLOC_DO_PAD 1 -#if 0 -/* Round N to next ptr size, even if it is on a ptr size boundary. */ -/* ==> valgrind errors (uninvestigated) */ -#define CWAL_MEMSZ_PAD(N) \ - ((CWAL_ALLOC_DO_PAD) \ - ? ((N) + sizeof(void*) - ((N) % sizeof(void*))) \ - : (N)) -#else -/* Round to next ptr size if N is not on a ptr size boundary. */ -#define CWAL_MEMSZ_PAD(N) \ - ((CWAL_ALLOC_DO_PAD) \ - ? (((N)%sizeof(void*)) \ - ? ((N) + sizeof(void*) - ((N) % sizeof(void*))) \ - : (N)) \ - : (N)) -#endif - -/** - CWAL_RCFLAGS_BITS = Number of bits to steal from - cwal_value::refcount for use in per-value-instance flags. - - i could possibly be convinced to go up to 8 bits (16M on 32-bit, - noting that cwal_config.h uses 32-bit int for cwal_refcount_t on - 16-bit builds). If we go any higher than 10 bits (~4M refcount max - on 32-bit) it would make sense to switch to 64-bit - cwal_value::refcount on 32-bit platforms, in which case we can - comfortably use as many of these flags as we need (at the cost of - bit-flipping performance on 32-bit platforms). -*/ -#define CWAL_RCFLAGS_BITS 8 -/** CWAL_RCFLAGS_BITS_MASK = lower-byte mask of CWAL_RCFLAGS_BITS bits. */ -#define CWAL_RCFLAGS_BITS_MASK 0xFF - -/** - CWAL_RCFLAG_MAXRC is a mask of bits of cwal_value::refcount - which are usable for reference counting. We actually use the bottom - bits for flags, not the top, just to help provoke any internal - misuse faster. This mask is used to check for overflow when - incrementing the refcount. -*/ -#define CWAL_RCFLAG_MAXRC (((cwal_refcount_t)-1)>>CWAL_RCFLAGS_BITS) - -/** - CWAL_REFCOUNT(V) requires V to be a non-null - (cwal_value*). Evaluates to the (V)->rcflags normalized as a - refcount counter, stripped of the mask bits. - - Warning: the compiler likes to complain about expressions with no - effect, and it's easy to use this macro in such a context (when - combined with other macros from its family). It's also easy to - reformulate such uses so that they don't cause that. -*/ -#define CWAL_REFCOUNT(V) ((V)->rcflags >> CWAL_RCFLAGS_BITS) - -/** - CWAL_REFCOUNT_SHIFTED(V) requires V to be a non-null - (cwal_value*). Evaluates to the (V)->rcflags, shifted and/or masked - into position so that it can be masked with flags. - - e.g. if the reference count is currently 1, then this will be (1 - <rcflags & ~CWAL_RCFLAGS_BITS_MASK) - -/** - CWAL_RCFLAGS(V) requires V to be a non-null (cwal_value*). Evaluates to the - flag bits of (V)->rcflags, stripped of the refcount part. -*/ -#define CWAL_RCFLAGS(V) ((V)->rcflags & CWAL_RCFLAGS_BITS_MASK) - -/** Adjusts (cwal_value*) V's refcount by N, retaining flags stashed there. Evals - to the new refcount, INCLUDING the flags bits. */ -#define CWAL_RCADJ(V,N) ((V)->rcflags = CWAL_RCFLAGS(V) | ((CWAL_REFCOUNT(V)+(N)) << CWAL_RCFLAGS_BITS)) - -/** Decrements (cwal_value*) V's refcount by 1, retaining flags stashed there. Evals to - the new refcount value, sans flags. */ -#define CWAL_RCDECR(V) (CWAL_RCADJ(V,-1), CWAL_REFCOUNT(V)) - -/** Increments (cwal_value*) V's refcount by 1, retaining flags stashed there. Evals to - the new refcount value, sans flags. */ -#define CWAL_RCINCR(V) (CWAL_RCADJ(V,1), CWAL_REFCOUNT(V)) - -/*#define CWAL_RCFLAGS_SET(V,F) ((V)->rcflags = CWAL_REFCOUNT_SHIFTED(V) | (CWAL_RCFLAGS_BITS_MASK & (F)))*/ -#define CWAL_RCFLAG_ON(V,F) ((V)->rcflags = CWAL_REFCOUNT_SHIFTED(V) | (CWAL_RCFLAGS_BITS_MASK & (CWAL_RCFLAGS(V) | (F)))) - -/*Disable the given flag in the given (cwal_value*). */ -#define CWAL_RCFLAG_OFF(V,F) ((V)->rcflags = CWAL_REFCOUNT_SHIFTED(V) | (CWAL_RCFLAGS_BITS_MASK & (CWAL_RCFLAGS(V) & ~(F)))) - -/*True if the given flag is on in the given (cwal_value*), else false. */ -#define CWAL_RCFLAG_HAS(V,F) ((CWAL_RCFLAGS(V) & (F)) ? 1 : 0) - -/*True if the (cwal_value*) V is not NULL and has any rc-flags - set which indicate that it is in the process of being cleaned - up, e.g. during its own destruction or its scope's cleanup. */ -#define CWAL_V_IS_IN_CLEANUP(V) \ - ((V) && (CWAL_RCFLAG_HAS((V),CWAL_RCF_IS_DESTRUCTING) \ - || CWAL_RCFLAG_HAS((V), CWAL_RCF_IS_GC_QUEUED) \ - /* || CWAL_RCFLAG_HAS((V), CWAL_RCF_IS_RECYCLED)) */)) - -#define CWAL_V_IS_RESCOPING(V) \ - ((V) && CWAL_RCFLAG_HAS((V),CWAL_RCF_IS_RESCOPING)) - -/** - Evaluates to true if the non-NULL (cwal_value*) V is suitable for storage - in cwal_scope::mine::headObj (else it goes in headPod, which has finalization - repercussions). -*/ -#if 0 -#define CWAL_V_GOES_IN_HEADOBJ(V) (CWAL_VOBASE(V) \ - || CWAL_TYPE_TUPLE==(V)->vtab->typeID \ - || CWAL_TYPE_UNIQUE==(V)->vtab->typeID) -#else -# define CWAL_V_GOES_IN_HEADOBJ(V) (!!CWAL_VOBASE(V)) -#endif - -/** - Flags for use with CWAL_REFCOUNT() and friends. Reminder: every bit - we steal halves the maximum refcount value! - - See also: CWAL_RCFLAGS_BITS -*/ - enum { - CWAL_RCF_NONE = 0x0, - /** - Set on values which are being destroyed, so that finalization can - DTRT when encounting it multiple times along the way (cycles). - */ - CWAL_RCF_IS_DESTRUCTING = 0x1, - /** - Sanity-checking flag which tells us that a given Value is in the - delayed-gc queue. - */ - CWAL_RCF_IS_GC_QUEUED = 0x2, - /** - Sanity-checking flag which tells us that a given Value is in a - recycling bin. - */ - CWAL_RCF_IS_RECYCLED = 0x4, - /** - Flag set only when a value is in the process of rescoping, so that - cyclic rescoping can break cycles. - */ - CWAL_RCF_IS_RESCOPING = 0x8, - /** - Flags an object that its properties are being iterated over or are - otherwise locked from being modified. - */ - CWAL_RCF_IS_VISITING = 0x10, - /** - Flags an object that one of the following parts is being iterated - over or is otherwise locked from being modified: array list, tuple - list, hashtable (also a list). - */ - CWAL_RCF_IS_VISITING_LIST = 0x20, - - /** - A variant of the visiting-related flags intended to be able to - restrict recursion by catching cycles. Specifically added to - re-enable cycle detection in the JSON bits. This flag is - specifically not intended to be used recursively (it's intended to - catch recursion) and it explicitly is not specific to iteration - over either object-level properties or list entries: it's intended - to be used for both. In the contexts it's used for (JSON), those - two uses are never combined in the same operation, so there is no - semantic ambiguity. - */ - CWAL_RCF_IS_VISITING_ACYCLIC = 0x40, - - /** - This flag tells the engine whether or not a given value is - "vacuum-proof" (immune to cwal_engine_vacuum()). This has to be in - cwal_value::rcflags instead of cwal_obase::flags so that - CWAL_TYPE_UNIQUE and CWAL_TYPE_TUPLE (and similar - not-full-fledged-container types) can be made vacuum-proof. - */ - CWAL_RCF_IS_VACUUM_PROOF = 0x80 - /* CWAL_RCF_IS_LOCKED = 0x100 - we'll need this if we want to lock - tuples the same way as arrays and hashtables, but we can also - justify not giving tuples full-fledged superpowers. */ - }; - -#define cwal_string_empty_m {0U/*length*/} -static const cwal_string cwal_string_empty = cwal_string_empty_m; - -#if 0 -const cwal_var cwal_var_empty = cwal_var_empty_m; -#endif -const cwal_engine_tracer cwal_engine_tracer_FILE = { -cwal_engine_tracer_f_FILE, -cwal_engine_tracer_close_FILE, -0 -}; -const cwal_allocator cwal_allocator_empty = - cwal_allocator_empty_m; -const cwal_allocator cwal_allocator_std = { -cwal_realloc_f_std, -cwal_state_empty_m -}; -const cwal_outputer cwal_outputer_empty = - cwal_outputer_empty_m; -const cwal_outputer cwal_outputer_FILE = { -cwal_output_f_FILE, -cwal_output_flush_f_FILE, -cwal_state_empty_m -}; -#if 0 -const cwal_outputer cwal_outputer_buffer = { -cwal_output_f_buffer, -NULL, -cwal_state_empty_m -}; -#endif - -const cwal_engine_vtab cwal_engine_vtab_basic = { -{ /*allocator*/ -cwal_realloc_f_std, -cwal_state_empty_m -}, -{/* outputer */ -cwal_output_f_FILE, -cwal_output_flush_f_FILE, -{/*state (cwal_state) */ -NULL/*data*/, -NULL/*typeID*/, -cwal_finalizer_f_fclose/*finalize*/ -} -}, -cwal_engine_tracer_empty_m, -cwal_state_empty_m/*state*/, -{/*hook*/ -NULL/*on_init()*/, -NULL/*init_state*/, -NULL/*scope_push()*/, -NULL/*scope_pop()*/, -NULL/*scope_state*/ -}, -{/*interning*/ -cwal_cstr_internable_predicate_f_default/*is_internable()*/, -NULL/*state*/ -}, -cwal_memcap_config_empty_m -}; - -/** - CwalConsts holds some library-level constants and default values - which have no better home. -*/ -static const struct { - /** The minimum/default hash size used by cwal_ptr_table. */ - const uint16_t MinimumHashSize; - /** The minimum step/span used by cwal_ptr_table. */ - const uint16_t MinimumStep; - /** Default length of some arrays on the first memory reservation - op. - */ - const uint16_t InitialArrayLength; - /** - Used as the "allocStamp" value for values which the library - allocates, in order to differentiate them from those allocated - via stack or being embedded in another object. Should point to - some library-internal static/constant pointer (any one will - do). - */ - void const * const AllocStamp; - /** - Largest allowable size for cwal_size_t values in certain - contexts (e.g. cwal_value::refcount). If it gets this high - then something is probably very wrong or the client is trying - too hard to push the boundaries. - */ - const cwal_size_t MaxSizeTCounter; - /** - If true then newly-create cwal_string instances will be - auto-interned. All strings with the same bytes will be shared - across a single cwal_string instance. - */ - char AutoInternStrings; - /** - Property name used to store the message part of an Exception - value. - */ - char const * ExceptionMessageKey; - - /** - Property name used to store the code part of an Exception - value. - */ - char const * ExceptionCodeKey; - - /** - If >0, this sets the maximum size for interning strings. Larger - strings will not be interned. - */ - cwal_size_t MaxInternedStringSize; - - /** - The maximum length of string to recycle. Should be relatively - small unless we implement a close-fit strategy for - recycling. Currently we only recycle strings for use with - "close" size matches (within 1 increment of - CwalConsts.StringPadSize). - */ - cwal_size_t MaxRecycledStringLen; - - /** - If StringPadSize is not 0... - - When strings are allocated, their sizes are padded to be evenly - divisible by this many bytes. When recycling strings, we use - this padding to allow the strings to be re-used for any similar - length which is within 1 of these increments. - - Expected to be an even value, relatively small (under 32, in any - case). - - Tests have shown 4-8 to be good values, saving anywhere from a - few percent to 36%(!!!) of the total allocations in the th1ish - test scripts (compared to a value of 0). Switching from 0 to 4 - gives a notable improvement on the current test scripts. 8 or - 12 don't reduce allocations all that much compared to 4, and - _normally_ (not always) cost more total memory. - */ - cwal_size_t StringPadSize; - - /** - Initial size for cwal_scope::props hashtables. - */ - cwal_size_t DefaultHashtableSize; - /** - "Preferred" load for hashtables before they'll automatically - resize. - */ - double PreferredHashLoad; -} CwalConsts = { -13 /* MinimumHashSize. Chosen almost arbitrarily, weighted towards - small memory footprint per table. */, -sizeof(void*) /* MinimumStep. */, -6 /* InitialArrayLength, starting length of various arrays. */, -&cwal_engine_vtab_empty/*AllocStamp - any internal ptr will do.*/, -#if 16 == CWAL_SIZE_T_BITS -(cwal_size_t)0xCFFF/*MaxSizeTCounter*/, -#else -(cwal_size_t)0xCFFFFFFF/*MaxSizeTCounter*/, -#endif -0/*AutoInternStrings*/, -"message"/*ExceptionMessageKey*/, -"code"/*ExceptionCodeKey*/, -32/*MaxInternedStringSize*/, -#if 0 -32/*MaxRecycledStringLen*/, -#elif 16 == CWAL_SIZE_T_BITS -32/*MaxRecycledStringLen*/, -#elif 1 -64/*MaxRecycledStringLen*/, -#elif 32==CWAL_SIZE_T_BITS || 16==CWAL_SIZE_T_BITS -2*CWAL_SIZE_T_BITS/*MaxRecycledStringLen*/, -/* In basic tests using s2, 64 gives overall better results (tiny - bit of peak, marginal number of mallocs saved), than 32 or 48. -*/ -#else -CWAL_SIZE_T_BITS/*MaxRecycledStringLen*/, -#endif -8/*StringPadSize*/, -11/*DefaultHashtableSize*/, -0.75/*PreferredHashLoad*/ -}; - -const cwal_weak_ref cwal_weak_ref_empty = cwal_weak_ref_empty_m; - -/** - CWAL_BUILTIN_INT_FIRST is the lowest-numbered built-in integer - value, and it must have a value of 0 or - lower. CWAL_BUILTIN_INT_LAST is the highest, and it must have a - value of 0 or higher. CWAL_BUILTIN_INT_COUNT is how many of those - values there are. - - The library currently won't build if CWAL_BUILTIN_INT_COUNT is 0, - but both FIRST and LAST may be 0, in which case the COUNT will be 1 - (the number 0 will be built in). - - The real limit to how many values we "could" build in is the - sizeof(CWAL_BUILTIN_VALS): we don't want it to be 64k+. 100 - built-in integers take up approximately 4k of space on 64-bit. - - Historical tests showed the single biggest gains to be had (in - terms of malloc saving) when then inclusive range [-1,1] is built - in. A range of [-1,10] provides marginally higher results. Above - that tends to make little difference, at least in generic test - scripts. The values lower than -1 are not used nearly as often, and - thus don't benefit as much from building them in. -*/ -#define CWAL_BUILTIN_INT_FIRST (-10) -#define CWAL_BUILTIN_INT_LAST (20) -#define CWAL_BUILTIN_INT_COUNT (CWAL_BUILTIN_INT_LAST + -(CWAL_BUILTIN_INT_FIRST) + 1/*zero*/) - -char const * cwal_version_string(cwal_size_t * length){ - if(length) *length = (cwal_size_t)(sizeof(CWAL_VERSION_STRING) - -sizeof(CWAL_VERSION_STRING[0] - /*NUL byte*/)); - return CWAL_VERSION_STRING; -} - -char const * cwal_cppflags(cwal_size_t * length){ - if(length) *length = (cwal_size_t)(sizeof(CWAL_CPPFLAGS) - -sizeof(CWAL_CPPFLAGS[0] - /*NUL byte*/)); - return CWAL_CPPFLAGS; -} - -char const * cwal_cflags(cwal_size_t * length){ - if(length) *length = (cwal_size_t)(sizeof(CWAL_CFLAGS) - -sizeof(CWAL_CFLAGS[0] - /*NUL byte*/)); - return CWAL_CFLAGS; -} - -char const * cwal_cxxflags(cwal_size_t * length){ - if(length) *length = (cwal_size_t)(sizeof(CWAL_CXXFLAGS) - -sizeof(CWAL_CXXFLAGS[0] - /*NUL byte*/)); - return CWAL_CXXFLAGS; -} - -/** - Internal impl for cwal_value_unref(). Neither e nor v may be NULL - (may trigger an assert()). This is a no-op if v is a builtin. -*/ -static int cwal_value_unref2(cwal_engine * e, cwal_value *v ); - -/** - Was intended to be an internal impl for cwal_value_ref(), but it - didn't quite work out that way. -*/ -static int cwal_value_ref2( cwal_engine *e, cwal_value * cv ); - -/** - Does nothing. Intended as a cwal_value_vtab::cleanup handler - for types which need not cleanup. - - TODO: re-add the zeroing of such values (lost in porting from - cson). -*/ -static void cwal_value_cleanup_noop( cwal_engine * e, void * self ); -/** - Requires that self is-a CWAL_TYPE_INTEGER cwal_value. This function - zeros its numeric value but goes not free() self. -*/ -static void cwal_value_cleanup_integer( cwal_engine * e, void * self ); -/** - Requires that self is-a CWAL_TYPE_DOUBLE cwal_value. This function - zeros its numeric value but goes not free() self. -*/ -static void cwal_value_cleanup_double( cwal_engine * e, void * self ); -/** - Requires that self is-a cwal_array. This function destroys its - contents but goes not free() self. -*/ -static void cwal_value_cleanup_array( cwal_engine * e, void * self ); -/** - Requires that self is-a cwal_object. This function destroys its - contents but goes not free() self. -*/ -static void cwal_value_cleanup_object( cwal_engine * e, void * self ); -/** - Requires that self is-a cwal_native. This function destroys its - contents but goes not free() self. -*/ -static void cwal_value_cleanup_native( cwal_engine * e, void * self ); -/** - Requires that self is-a cwal_string. This function removes the - string from e's intering table. -*/ -static void cwal_value_cleanup_string( cwal_engine * e, void * self ); - -/** - Requires that self is-a cwal_buffer. This function calls - cwal_buffer_reserve() to clear the memory owned by the buffer. -*/ -static void cwal_value_cleanup_buffer( cwal_engine * e, void * self ); -/** - Requires that self is-a cwal_function. This function destroys its - contents but goes not free() self. -*/ -static void cwal_value_cleanup_function( cwal_engine * e, void * self ); -/** - Requires that self is-a cwal_exception. This function destroys its - contents but goes not free() self. -*/ -static void cwal_value_cleanup_exception( cwal_engine * e, void * self ); - -/** - Requires that self is-a cwal_hash. This function destroys its - contents but goes not free() self. -*/ -static void cwal_value_cleanup_hash( cwal_engine * e, void * V ); - -/** - Requires that self is-a cwal_unique. This function destroys its - contents but goes not free() self. -*/ -static void cwal_value_cleanup_unique( cwal_engine * e, void * V ); - -/** - Requires that self is-a cwal_tuple. This function destroys its - contents but goes not free() self. -*/ -static void cwal_value_cleanup_tuple( cwal_engine * e, void * V ); - -/** - Fetches v's string value as a non-const string. - - cwal_strings are supposed to be immutable, but this form provides - access to the immutable bits, which are v->length bytes long. A - length-0 string is returned as NULL from here, as opposed to - "". (This is a side-effect of the string allocation mechanism.) - Returns NULL if !v or if v is the internal empty-string singleton. -*/ -static char * cwal_string_str_rw(cwal_string *v); - -/* - Hash/compare routines for cwal_value_vtab. -*/ -static cwal_hash_t cwal_value_hash_null_undef( cwal_value const * v ); -static cwal_hash_t cwal_value_hash_bool( cwal_value const * v ); -static cwal_hash_t cwal_value_hash_int( cwal_value const * v ); -static cwal_hash_t cwal_value_hash_double( cwal_value const * v ); -static cwal_hash_t cwal_value_hash_string( cwal_value const * v ); -static cwal_hash_t cwal_value_hash_ptr( cwal_value const * v ); -static cwal_hash_t cwal_value_hash_tuple( cwal_value const * v ); -static int cwal_value_cmp_bool( cwal_value const * lhs, cwal_value const * rhs ); -static int cwal_value_cmp_int( cwal_value const * lhs, cwal_value const * rhs ); -static int cwal_value_cmp_double( cwal_value const * lhs, cwal_value const * rhs ); -static int cwal_value_cmp_string( cwal_value const * lhs, cwal_value const * rhs ); -/* static int cwal_value_cmp_type_only( cwal_value const * lhs, cwal_value const * rhs ); */ -static int cwal_value_cmp_ptr_only( cwal_value const * lhs, cwal_value const * rhs ); -static int cwal_value_cmp_nullundef( cwal_value const * lhs, cwal_value const * rhs ); -static int cwal_value_cmp_func( cwal_value const * lhs, cwal_value const * rhs ); -static int cwal_value_cmp_buffer( cwal_value const * lhs, cwal_value const * rhs ); -static int cwal_value_cmp_tuple( cwal_value const * lhs, cwal_value const * rhs ); - -/* - Rescope-children routines for container types. -*/ -static int cwal_rescope_children_obase( cwal_value * v ); -static int cwal_rescope_children_array( cwal_value * v ); -static int cwal_rescope_children_function( cwal_value * v ); -static int cwal_rescope_children_native( cwal_value * v ); -static int cwal_rescope_children_hash( cwal_value * v ); -static int cwal_rescope_children_unique( cwal_value * v ); -static int cwal_rescope_children_tuple( cwal_value * v ); - -/* - Internal "API" (a.k.a. "VTab") instances. One per core type. -*/ -static const cwal_value_vtab cwal_value_vtab_null = - { CWAL_TYPE_NULL, "null", - CWAL_F_NONE, - cwal_value_cleanup_noop, - cwal_value_hash_null_undef, - cwal_value_cmp_nullundef, - NULL/*rescope_children()*/ - }; -static const cwal_value_vtab cwal_value_vtab_undef = - { CWAL_TYPE_UNDEF, "undefined", - CWAL_F_NONE, - cwal_value_cleanup_noop, - cwal_value_hash_null_undef, - cwal_value_cmp_nullundef, - NULL/*rescope_children()*/ - }; -static const cwal_value_vtab cwal_value_vtab_bool = - { CWAL_TYPE_BOOL, "bool", - CWAL_F_NONE, - cwal_value_cleanup_noop, - cwal_value_hash_bool, - cwal_value_cmp_bool, - NULL/*rescope_children()*/ - }; -static const cwal_value_vtab cwal_value_vtab_integer = - { CWAL_TYPE_INTEGER, "integer", - CWAL_F_NONE, - cwal_value_cleanup_integer, - cwal_value_hash_int, - cwal_value_cmp_int, - NULL/*rescope_children()*/ - }; -static const cwal_value_vtab cwal_value_vtab_double = - { CWAL_TYPE_DOUBLE, "double", - CWAL_F_NONE, - cwal_value_cleanup_double, - cwal_value_hash_double, - cwal_value_cmp_double, - NULL/*rescope_children()*/ - }; -static const cwal_value_vtab cwal_value_vtab_string = - { CWAL_TYPE_STRING, "string", - CWAL_F_NONE, - cwal_value_cleanup_string, - cwal_value_hash_string, - cwal_value_cmp_string, - NULL/*rescope_children()*/ - }; -static const cwal_value_vtab cwal_value_vtab_array = - { CWAL_TYPE_ARRAY, "array", - CWAL_F_ISA_OBASE, - cwal_value_cleanup_array, - cwal_value_hash_ptr, - cwal_value_cmp_ptr_only, - cwal_rescope_children_array - }; -static const cwal_value_vtab cwal_value_vtab_object = - { CWAL_TYPE_OBJECT, "object", - CWAL_F_ISA_OBASE, - cwal_value_cleanup_object, - cwal_value_hash_ptr, - cwal_value_cmp_ptr_only, - cwal_rescope_children_obase - }; -static const cwal_value_vtab cwal_value_vtab_native = - { CWAL_TYPE_NATIVE, "native", - CWAL_F_ISA_OBASE, - cwal_value_cleanup_native, - cwal_value_hash_ptr, - cwal_value_cmp_ptr_only, - cwal_rescope_children_native - }; -static const cwal_value_vtab cwal_value_vtab_hash = - { CWAL_TYPE_HASH, "hash", - CWAL_F_ISA_OBASE, - cwal_value_cleanup_hash, - cwal_value_hash_ptr, - cwal_value_cmp_ptr_only, - cwal_rescope_children_hash - }; -static const cwal_value_vtab cwal_value_vtab_buffer = - { CWAL_TYPE_BUFFER, "buffer", - CWAL_F_ISA_OBASE, - cwal_value_cleanup_buffer, - cwal_value_hash_ptr, - cwal_value_cmp_buffer, - cwal_rescope_children_obase - }; -static const cwal_value_vtab cwal_value_vtab_function = - { CWAL_TYPE_FUNCTION, "function", - CWAL_F_ISA_OBASE, - cwal_value_cleanup_function, - cwal_value_hash_ptr, - cwal_value_cmp_func, - cwal_rescope_children_function - }; -static const cwal_value_vtab cwal_value_vtab_exception = - { CWAL_TYPE_EXCEPTION, "exception", - CWAL_F_ISA_OBASE, - cwal_value_cleanup_exception, - cwal_value_hash_ptr, - cwal_value_cmp_ptr_only, - cwal_rescope_children_obase - }; -static const cwal_value_vtab cwal_value_vtab_unique = - { CWAL_TYPE_UNIQUE, "unique", - CWAL_F_NONE, - cwal_value_cleanup_unique, - cwal_value_hash_ptr, - cwal_value_cmp_ptr_only, - cwal_rescope_children_unique - }; -static const cwal_value_vtab cwal_value_vtab_tuple = - { CWAL_TYPE_TUPLE, "tuple", - CWAL_F_NONE, - cwal_value_cleanup_tuple, - cwal_value_hash_tuple, - cwal_value_cmp_tuple, - cwal_rescope_children_tuple - }; - -/** - Internal constant cwal_values, used for copy-initialization of new - Value instances. -*/ -static const cwal_value cwal_value_undef = { &cwal_value_vtab_undef, NULL, NULL, NULL, 0 }; -/* static const cwal_value cwal_value_null_empty = { &cwal_value_vtab_null, NULL, NULL, NULL, 0 }; */ -/* static const cwal_value cwal_value_bool_empty = { &cwal_value_vtab_bool, NULL, NULL, NULL, 0 }; */ -static const cwal_value cwal_value_integer_empty = { &cwal_value_vtab_integer, NULL, NULL, NULL, 0 }; -static const cwal_value cwal_value_double_empty = { &cwal_value_vtab_double, NULL, NULL, NULL, 0 }; -static const cwal_value cwal_value_string_empty = { &cwal_value_vtab_string, NULL, NULL, NULL, 0 }; -static const cwal_value cwal_value_array_empty = { &cwal_value_vtab_array, NULL, NULL, NULL, 0 }; -static const cwal_value cwal_value_object_empty = { &cwal_value_vtab_object, NULL, NULL, NULL, 0 }; -static const cwal_value cwal_value_native_empty = { &cwal_value_vtab_native, NULL, NULL, NULL, 0 }; -static const cwal_value cwal_value_hash_empty = { &cwal_value_vtab_hash, NULL, NULL, NULL, 0 }; -static const cwal_value cwal_value_buffer_empty = { &cwal_value_vtab_buffer, NULL, NULL, NULL, 0 }; -static const cwal_value cwal_value_function_empty = { &cwal_value_vtab_function, NULL, NULL, NULL, 0 }; -static const cwal_value cwal_value_exception_empty = { &cwal_value_vtab_exception, NULL, NULL, NULL, 0 }; -static const cwal_value cwal_value_unique_empty = { &cwal_value_vtab_unique, NULL, NULL, NULL, 0 }; -static const cwal_value cwal_tuple_value_empty = { &cwal_value_vtab_tuple, NULL, NULL, NULL, 0 }; - -/* - Internal convenience macros... -*/ - -/** - Cast ((cwal_value*)V) to (T*). It assumes the caller knows WTF he - is doing. Evaluates to 0 if !(V). - - This op relies on the fact that memory (V+1) contains a (T) - value. i.e. it relies on the allocation mechanism used by - cwal_value_new() and that V was allocated by that function, is a - builtin/shared value instance, or is NULL. -*/ -#define CWAL_VVPCAST(T,V) ((T*)((V) ? ((T*)((V)+1)) : (T*)0)) - -/** - CWAL_VALPART(CONCRETE) - - Cast (concrete_value_type*) CONCRETE to a - (cwal_value*). CWAL_VALPART() relies on the fact that ALL cwal_value - types which use it are allocated in a single memory chunk with - (cwal_value,concrete_type), in that order. Do not use this macro - for types which are not allocated that way. - - AFAIK, it is also legal for CONCRETE to be (cwal_obase*), provided - that pointer was allocated as part of one of the container types - (object, array, etc.). This relies on them having their (cwal_obase - base) member as the first member of the struct. - - e.g. assuming an Object value: - - cwal_obase * base = CWAL_VOBASE(val); - cwal_object * obj = cwal_value_get_object(val); - assert( CWAL_VALPART(base) == val ); - assert( base == &obj->base ); -*/ - -#if 1 -#define CWAL_VALPART(CONCRETE) ((CONCRETE) ? ((cwal_value *)(((unsigned char *)(CONCRETE))-sizeof(cwal_value))) : 0) -#else -/* i'm not convinced that this one is standards-conformant. - But it looks nicer. -*/ -#define CWAL_VALPART(CONCRETE) ((CONCRETE) ? (((cwal_value *)(CONCRETE))-1) : 0) -#endif - -/** - CWAL_INT(V) casts CWAL_TYPE_INTEGER (cwal_value*) V to a - (cwal_int_t*). -*/ -#define CWAL_INT(V) (CWAL_VVPCAST(cwal_int_t,(V))) - -/** - Requires that V be one of the special cwal_values TRUE or FALSE. - Evaluates to 1 if it is the TRUE value, else false. -*/ -#define CWAL_BOOL(V) ((&CWAL_BUILTIN_VALS.vTrue==(V)) ? 1 : 0) - -/** - CWAL_DBL(V) casts CWAL_TYPE_DOUBLE (cwal_value*) V to a (cwal_double_t*). -*/ -#define CWAL_DBL(V) CWAL_VVPCAST(cwal_double_t,(V)) - -/* - workarounds for false gcc warning: - - https://gcc.gnu.org/bugzilla/show_bug.cgi?id=47214 - - Summary: gcc's nonnull warning triggers incorrectly - for cases like somefunc( X ? Y : NULL ) because it cannot - know that X will never be false in that context. - - The _NONULL variants work like the non-_NONULL variants - but MUST NOT be passed a NULL value. -*/ -#define CWAL_VVPCAST_NONULL(T,V) ((T*)((V)+1)) -#define CWAL_DBL_NONULL(V) CWAL_VVPCAST_NONULL(cwal_double_t,(V)) -#define CWAL_INT_NONULL(V) (CWAL_VVPCAST_NONULL(cwal_int_t,(V))) - -/** - For cwal_string we store flags in the cwal_string::length member, - rather than add a flag to them (for memory reasons). We reserve the - top three bits and encode the length in the remaining ones. So the - maximum length of a given String value is 2^(CWAL_SIZE_T_BITS-3). -*/ -#if 16 == CWAL_SIZE_T_BITS -/* Max string length: 8k */ -# define CWAL_STRLEN_MASK ((cwal_size_t)0x1FFFU) -# define CWAL_STR_XMASK ((cwal_size_t)0x8000U) -# define CWAL_STR_ZMASK ((cwal_size_t)0x4000U) -# define CWAL_STR_ASCII_MASK ((cwal_size_t)0x2000U) -#elif 32 == CWAL_SIZE_T_BITS -/* Max string length: 0.5GB */ -# define CWAL_STRLEN_MASK ((cwal_size_t)0x1FFFFFFFU) -# define CWAL_STR_XMASK ((cwal_size_t)0x80000000U) -# define CWAL_STR_ZMASK ((cwal_size_t)0x40000000U) -# define CWAL_STR_ASCII_MASK ((cwal_size_t)0x20000000U) -#elif 64 == CWAL_SIZE_T_BITS -#if 0 -/* Portability: stick with 32-bit lengths. */ -# define CWAL_STRLEN_MASK ((cwal_size_t)0x1FFFFFFFU) -# define CWAL_STR_XMASK ((cwal_size_t)0x80000000U) -# define CWAL_STR_ZMASK ((cwal_size_t)0x40000000U) -# define CWAL_STR_ASCII_MASK ((cwal_size_t)0x20000000U) -#else -/* Max string length: 32-bits so that we can use cwal_midsize_t - for all string lengths. */ -# define CWAL_STRLEN_MASK ((cwal_size_t)0x1FFFFFFFU) -# define CWAL_STR_XMASK ((cwal_size_t)0x8000000000000000U) -# define CWAL_STR_ZMASK ((cwal_size_t)0x4000000000000000U) -# define CWAL_STR_ASCII_MASK ((cwal_size_t)0x2000000000000000U) -#endif -#endif - -/* - CWAL_STR_ASCII_MASK is a tag for strings which are pure ASCII (all - bytes are in the inclusive range [0,127]), in which case we can - speed up many operations which currently always have to read UTF8 - char-by-char. To disable this feature, set CWAL_STR_ASCII_MASK to 0 - and make sure all test code which assert()s that a given string is - ASCII is disabled. -*/ - -/* #define CWAL_STRLEN_MASK ((cwal_size_t)~(CWAL_STR_XMASK \ - | CWAL_STR_ZMASK | CWAL_STR_ASCII_MASK)) */ - - -/** - CWAL_STR(V) casts CWAL_TYPE_STRING (cwal_value*) V to a (cwal_string*). - If V is NULL or not-a String it evals to 0. -*/ -#define CWAL_STR(V) (((V) && (V)->vtab && (CWAL_TYPE_STRING==(V)->vtab->typeID)) ? CWAL_VVPCAST(cwal_string,(V)) : 0) - -/** - Evaluates to true if S (which must be a valid (cwal_string*)) is an - x-string, else false. -*/ -#define CWAL_STR_ISX(S) ((CWAL_STR_XMASK & (S)->length) ? 1 : 0) -/** - Evaluates to true if S (which must be a valid (cwal_string*)) is a - z-string, else false. -*/ -#define CWAL_STR_ISZ(S) ((CWAL_STR_ZMASK & (S)->length) ? 1 : 0) -/** - Evaluates to true if S (which must be a valid (cwal_string*)) is a - either an x-string or z-string, else false. -*/ -#define CWAL_STR_ISXZ(S) (CWAL_STR_ISX(S) || CWAL_STR_ISZ(S)) - -/** - Evaluates to true if S (which must be a valid (cwal_string*)) has been - marked as being ASCII. -*/ -#define CWAL_STR_ISASCII(S) ((CWAL_STR_ASCII_MASK & (S)->length) ? 1 : 0) - -/** - Evaluates to the absolute value of S->length, in bytes, where S - must be a non-NULL (cwal_string [const]*). This is required instead - direct access to S->length because we encode non-size info in the - length field for X- and Z-strings, plus the is-ASCII flag. -*/ -#define CWAL_STRLEN(S) ((cwal_midsize_t)((S)->length & CWAL_STRLEN_MASK)) - -/** Evaluates to non-0 if the cwal_size_t value LEN is too long for a string length. */ -#define CWAL_STRLEN_TOO_LONG(LEN) (((cwal_size_t)(LEN)) & ~CWAL_STRLEN_MASK) - -/** - CWAL_OBJ(V) casts CWAL_TYPE_OBJECT (cwal_value*) V to a (cwal_object*). -*/ -#define CWAL_OBJ(V) (((V) && (V)->vtab && (CWAL_TYPE_OBJECT==(V)->vtab->typeID)) ? CWAL_VVPCAST(cwal_object,(V)) : 0) - -/** - CWAL_ARRAY(V) casts CWAL_TYPE_ARRAY (cwal_value*) V to a (cwal_array*). -*/ -#define CWAL_ARRAY(V) (((V) && (V)->vtab && (CWAL_TYPE_ARRAY==(V)->vtab->typeID)) ? CWAL_VVPCAST(cwal_array,(V)) : 0) - -/** - CWAL_HASH(V) casts CWAL_TYPE_HASH (cwal_value*) V to a (cwal_hash*). -*/ -#define CWAL_HASH(V) (((V) && (V)->vtab && (CWAL_TYPE_HASH==(V)->vtab->typeID)) ? CWAL_VVPCAST(cwal_hash,(V)) : 0) - -/** - CWAL_OBASE(O) casts the OBase-type pointer OB to a (cwal_obase*). - This relies on OB being an obase-compliant type, with a cwal_obase - member being the first struct member of OB. -*/ -#define CWAL_OBASE(OB) ((cwal_obase*)(OB)) - -/** - Evaluates to true if ((cwal_value*) V)->vtab is not 0 and has the - CWAL_F_ISA_OBASE flag, else false. -*/ -#define CWAL_V_IS_OBASE(V) (((V) && (V)->vtab && (CWAL_F_ISA_OBASE & (V)->vtab->flags)) ? 1 : 0) - -/** - If CWAL_V_IS_OBASE(V), evaluates to V's (cwal_obase*) part, else it - evaluates to 0. For this to work all "object base" types must have - a cwal_obase member named 'base' as their VERY FIRST structure - member because we rely on a C's rule/allowance that a struct can be - cast to a pointer to its first member. -*/ -#define CWAL_VOBASE(V) (CWAL_V_IS_OBASE(V) ? CWAL_VVPCAST(cwal_obase,(V)) : 0) - -/** - Casts CWAL_TYPE_NATIVE value V to (cwal_native*). -*/ -#define CWAL_V2NATIVE(V) CWAL_VVPCAST(cwal_native,(V)) -/** - CWAL_BUFOBJ(V) casts CWAL_TYPE_BUFFER (cwal_value*) V to a (cwal_buffer_obj*). -*/ -#define CWAL_BUFOBJ(V) (((V) && (V)->vtab && (CWAL_TYPE_BUFFER==(V)->vtab->typeID)) ? CWAL_VVPCAST(cwal_buffer_obj,(V)) : 0) - -/** - CWAL_UNIQUE_VALPP(V) casts gets the wrapped (cwal_value**) part of - CWAL_TYPE_UNIQUE (cwal_value*) V. If V is-not-a Unique, it evals - to 0. -*/ -#define CWAL_UNIQUE_VALPP(V) (((V) && (V)->vtab && (CWAL_TYPE_UNIQUE==(V)->vtab->typeID)) ? (CWAL_VVPCAST(cwal_value*,(V))) : 0) - -/** - CWAL_TUPLE(V) casts (cwal_value*) V to (cwal_tuple*). - If V is-not-a Tuple, it evals to 0. -*/ -#define CWAL_TUPLE(V) (((V) && (V)->vtab && (CWAL_TYPE_TUPLE==(V)->vtab->typeID)) ? (CWAL_VVPCAST(cwal_tuple,(V))) : 0) - -/** - If (cwal_value*) V is not NULL and has a scope, this evaluates to - its (cwal_engine*), else to 0. Note that built-in values have no - scope and are not specific to a cwal_engine instance. -*/ -#define CWAL_VENGINE(V) ((V) ? ((V)->scope ? (V)->scope->e : 0) : 0) - -/** - Evaluates to true if (cwal_value [const] *)V is currently flagged - as being visited (object-level properties). -*/ -#define CWAL_V_IS_VISITING(V) CWAL_RCFLAG_HAS((V),CWAL_RCF_IS_VISITING) -/** - Evaluates to true if (cwal_value [const] *)V is currently flagged - as being list-visited (arrays and hashtable entries). -*/ -#define CWAL_V_IS_VISITING_LIST(V) CWAL_RCFLAG_HAS((V),CWAL_RCF_IS_VISITING_LIST) - -/** - CWAL_OB_xxx(OBTYPE) all require OBTYPE to be a pointer to a - cwal_obase-deriving type, typically an array or hashtable. - - Semantic ambiguity here: this flag is currently only used to lock - array/list parts. If we also want to lock properties, this flag - becomes ambiguous for list-using types. It would be conceivable to - have the list part locked while the properties are not, and vice - versa. -*/ -#define CWAL_OB_LOCK(OBTYPE) (OBTYPE)->base.flags |= CWAL_F_LOCKED -#define CWAL_OB_UNLOCK(OBTYPE) (OBTYPE)->base.flags &= ~CWAL_F_LOCKED -#define CWAL_OB_IS_LOCKED(OBTYPE) (CWAL_F_LOCKED & (OBTYPE)->base.flags) - -#define METRICS_REQ_INCR(E,TYPE) ++(E)->metrics.requested[TYPE] - -#define CWAL_V_IS_VACUUM_SAFE(V) \ - (CWAL_RCFLAG_HAS((V), CWAL_RCF_IS_VACUUM_PROOF)) - -/** - Must only be used when (cwal_engine::flags & - CWAL_F_TRACK_MEM_SIZE). This returns an address sizeof(void*) - bytes before void pointer M, cast to a (cwal_memsize_t*). -*/ -#define MEMSZ_PTR_FROM_MEM(M) (cwal_memsize_t*)((unsigned char *)(M) - sizeof(void*)) - -/** - Returns a (cwal_value*) to the given index from - CWAL_BUILTIN_VALS.memInt. -*/ -#define CWAL_BUILTIN_INT_VAL(NDX) ((cwal_value*)&CWAL_BUILTIN_VALS.memInt[NDX]) - -/** - Some "special" shared cwal_value instances. - - Note that they are not const because they are used as - shared-allocation objects in non-const contexts. However, the public - API provides no way of modifying them, and clients who modify values - directly are subject to The Wrath of Undefined Behaviour. -*/ -static struct CWAL_BUILTIN_VALS_ { - /** - Gets set to a true value when this struct gets initialized by - cwal_init_builtin_values(), to ensure that we only initialize - this once. Pedantic side-note: it's potentially possible that - two engine instances in different threads, being initialized at - the same time, try to initialize this data concurrently. That's - okay, as each initialization will set the data to the exact - same state and same addresses, so there's no real harm done. We - intentionally don't update the 'inited' member until the end up - of the init process, as its harmless if it's inited multiple - times concurrently but not harmless if we update this flag at - the start of the process and another thread tries to use this - data before it's completely initialized by the thread which set - that flag. - */ - int inited; - /** - Each of the memXXX entries holds the raw block of memory - intended for (cwal_value + concrete_type). These are - initialized by cwal_init_builtin_values(). - */ -#define sz_int sizeof(cwal_value)+sizeof(cwal_int_t) - unsigned char memInt[CWAL_BUILTIN_INT_COUNT - ? CWAL_BUILTIN_INT_COUNT - : 1/*dummy build placeholder*/][sz_int]; - unsigned char memDblM1[sizeof(cwal_value)+sizeof(cwal_double_t)]; - unsigned char memDbl0[sizeof(cwal_value)+sizeof(cwal_double_t)]; - unsigned char memDbl1[sizeof(cwal_value)+sizeof(cwal_double_t)]; - unsigned char memEmptyString[sizeof(cwal_value)+sizeof(cwal_string)+1/*NUL byte*/]; -#if CWAL_ENABLE_BUILTIN_LEN1_ASCII_STRINGS - unsigned char memAsciiPrintable[128/* one entry each for ASCII [0,127] */] - [(sizeof(cwal_value)+sizeof(cwal_string)+2) - /* ==> "X\0", where X is an ASCII char 0..127. */]; -#else - unsigned char memAsciiPrintable[1][1/*dummy placeholder*/]; -#endif - unsigned char memTuple0[sizeof(cwal_value)+sizeof(cwal_tuple)]; -#undef sz_int - /** - Each of the vXXX pointers points to memory held in the - similarly-named memXXX member. - */ - cwal_value * vDblM1 /* TODO: eliminate these, as was done for integers. */; - cwal_value * vDbl0; - cwal_value * vDbl1; - cwal_value * vEmptyString; - - /** - Points to the cwal_string part of this->memEmptyString. - */ - cwal_string * sEmptyString; - cwal_value * vTuple0; - cwal_value vTrue; - cwal_value vFalse; - cwal_value vNull; - cwal_value vUndef; - - /** - Double values -1.0, 0.0, and 1.0. - */ - struct { - cwal_double_t mOne; - cwal_double_t zero; - cwal_double_t one; - } dbls; - - /** - Each of the wref.wXXX entries is a shared cwal_weak_ref - instance pointing to a similarly-named vXXX entry. We do not - allocate new cwal_weak_ref instances if they wrap a Value which - itself is a built-in value. It's hard to imagine a use case for - someone trying to weak-ref a boolean value, but the generic - nature of the Value system makes it conceivably possible, so - here it is... - */ - struct { - cwal_weak_ref wTrue; - cwal_weak_ref wFalse; - cwal_weak_ref wNull; - cwal_weak_ref wUndef; - cwal_weak_ref wStrEmpty - /* Reminder to self: we don't currently have entries here for - the built-in length-1 strings (memAsciiPrintable). Nor the - length-0 Tuple, it seems. Oh, well. We removed the integer - weak refs on 20171202 when that numeric range was made - built-time configurable. */; - cwal_weak_ref wDblM1; - cwal_weak_ref wDbl0; - cwal_weak_ref wDbl1; - } wref; - -} CWAL_BUILTIN_VALS = { -0/*inited*/, -{/*memInt*/ {0}}, -{/*memDblM1*/ 0}, -{/*memDbl0*/ 0}, -{/*memDbl1*/ 0}, -{/*memEmptyString*/ 0}, -{/*memAsciiPrintable*/{0}}, -{/*memTuple0*/0}, -NULL/*vDblM1*/, -NULL/*vDbl0*/, -NULL/*vDbl1*/, -NULL/*vEmptyString*/, -NULL/*sEmptyString*/, -NULL/*vTuple0*/, -{/*vTrue*/ &cwal_value_vtab_bool, NULL, NULL, NULL, 0 }, -{/*vFalse*/ &cwal_value_vtab_bool, NULL, NULL, NULL, 0 }, -{/*vNull*/ &cwal_value_vtab_null, NULL, NULL, NULL, 0 }, -{/*vUndef*/ &cwal_value_vtab_undef, NULL, NULL, NULL, 0 }, -#if CWAL_DISABLE_FLOATING_POINT -{/*dbls*/-1,0,1}, -#else -{/*dbls*/-1.0,0.0,1.0}, -#endif -{/*wref*/ -cwal_weak_ref_empty_m/* wTrue */, -cwal_weak_ref_empty_m/* wFalse */, -cwal_weak_ref_empty_m/* wNull */, -cwal_weak_ref_empty_m/* wUndef */, -cwal_weak_ref_empty_m/* wStrEmpty */, -cwal_weak_ref_empty_m/* wDblM1 */, -cwal_weak_ref_empty_m/* wDbl0 */, -cwal_weak_ref_empty_m/* wDbl1 */ -} -}; - -static void cwal_init_builtin_values(){ - struct CWAL_BUILTIN_VALS_ * h = &CWAL_BUILTIN_VALS; - cwal_value * v; - - {/* Set up empty string */ - memset(h->memEmptyString, 0, sizeof(h->memEmptyString)) - /* ensure that the NUL terminator is set */; - v = h->vEmptyString = (cwal_value*)h->memEmptyString; - *v = cwal_value_string_empty; - h->sEmptyString = CWAL_STR(v); - assert(h->sEmptyString); - assert(0==CWAL_STRLEN(h->sEmptyString)); - assert(0==*cwal_string_cstr(h->sEmptyString)); - } - -#if CWAL_ENABLE_BUILTIN_LEN1_ASCII_STRINGS - {/* set up length-1 ASCII strings */ - int i = 0; - cwal_string * s; - char * cp; - memset(h->memAsciiPrintable, 0, sizeof(h->memAsciiPrintable)); - for( ; i <= 127; ++i ){ - v = (cwal_value *)(h->memAsciiPrintable[i]); - *v = cwal_value_string_empty; - s = CWAL_STR(v); - *s = cwal_string_empty; - s->length = CWAL_STR_ASCII_MASK | 1; - assert(1 == CWAL_STRLEN(s)); - cp = cwal_string_str_rw(s); - cp[0] = (char)i; - cp[1] = 0; - assert(1 == CWAL_STRLEN(s)); - assert(cp == cwal_string_cstr(s)); - } - v = 0; - } -#endif - - { - /* Set up integers [CWAL_BUILTIN_INT_FIRST .. CWAL_BUILTIN_INT_LAST]. - Maintenance reminder: the memcpy() is needed, rather than direct - copy, to avoid a "type punning" error in certain compilation - environments. */ - cwal_int_t v = CWAL_BUILTIN_INT_FIRST, ndx = 0; - cwal_int_t const last = CWAL_BUILTIN_INT_LAST; - assert(CWAL_BUILTIN_INT_FIRST <= 0); - assert(CWAL_BUILTIN_INT_LAST >= 0); - assert(CWAL_BUILTIN_INT_COUNT > 0); - assert(sizeof(h->memInt)/sizeof(h->memInt[0]) == - (CWAL_BUILTIN_INT_COUNT ? CWAL_BUILTIN_INT_COUNT : 1)); - for( ; v <= last; ++v, ++ndx ){ - cwal_value * cv = CWAL_BUILTIN_INT_VAL(ndx); - *cv = cwal_value_integer_empty; - memcpy(CWAL_INT_NONULL(cv), &v, sizeof(cwal_int_t)); - assert( v == cwal_value_get_integer(cv) ); - } - } - - /* Set up doubles (-1, 0, 1) */ -#if CWAL_DISABLE_FLOATING_POINT -#define dbl_m1 -1 -#define dbl_0 0 -#define dbl_1 1 -#else -#define dbl_m1 -1.0 -#define dbl_0 0.0 -#define dbl_1 1.0 -#endif -#define NUM(N,V) { \ - const cwal_double_t dv = V; \ - h->vDbl##N = v = (cwal_value*)h->memDbl##N; \ - *v = cwal_value_double_empty; \ - memcpy(CWAL_DBL_NONULL(v), &dv, sizeof(cwal_double_t)); \ - } (void)0 - NUM(M1,dbl_m1); - NUM(0,dbl_0); - NUM(1,dbl_1); -#undef NUM -#undef dbl_m1 -#undef dbl_0 -#undef dbl_1 - - { - /** Sets up shared weak refs */ - cwal_weak_ref * r; -#define REF(N,V) r = &h->wref.N; *r = cwal_weak_ref_empty; \ - r->value = V; r->typeID = (V)->vtab->typeID - REF(wTrue,&h->vTrue); - REF(wFalse,&h->vFalse); - REF(wNull,&h->vNull); - REF(wUndef,&h->vUndef); - REF(wStrEmpty,h->vEmptyString); - REF(wDblM1,h->vDblM1); - REF(wDbl0,h->vDbl0); - REF(wDbl1,h->vDbl1); - } - - { /* Empty Tuple... */ - memset(h->memTuple0, 0, sizeof(h->memTuple0)); - v = h->vTuple0 = (cwal_value*)h->memTuple0; - *v = cwal_tuple_value_empty; - assert(CWAL_TUPLE(v)); - assert(0==CWAL_TUPLE(h->vTuple0)->n); - } - - h->inited = 1 - /* We do this at the end, instead of the start, to cover a - specific threading corner case: If two (or more) threads - end up triggering this routine concurrently, we let all of - them modify the memory. Because they all set it to the - same values, we really don't care which one finishes - first. Once any of them have set h->inited=1, - CWAL_BUILTIN_VALS contains the memory we want. Even if a - slower thread is still re-initializing it after a faster - thread has returned, it is overwriting the contents with - the same values, so writing them while the faster thread is - (potentially) using them "should" be harmless. - - Note that this race can only potentially happen once during - the life of the application, during the initialization of - the first cwal_engine instance(s), and only if they are - initialized in concurrent threads. - */; - -} - -/** - CWAL_MEM_IS_BUILTIN(V) determines if the (void const *) V is one of - the special built-in/constant values. It does so by simply checking - if its address lies within range of the stack-allocated - special-value holders, so it's about as fast as it can be. - - - Maintenance reminders: - - - Profiling shows that cwal_value_is_builtin() is by far the - most-called routine in the library and accounts for about 1% of the - total calls in my test app. That is the only reason it has become a - macro. Client-side code never uses (never really has a need for, - other than basic curiosity) cwal_value_is_builtin(). -*/ -#define CWAL_MEM_IS_BUILTIN(V) \ - ((((void const *)(V) >= (void const *)&CWAL_BUILTIN_VALS) \ - && ( (void const *)(V) < (void const *)(&CWAL_BUILTIN_VALS+1)) \ - ) ? 1 : 0) - - -/** - Intended for use in assertions to ensure that (cwal_value const *) - V is either a builtin value or has an owning scope. -*/ -#define V_SEEMS_OK(V) ((V)->scope || CWAL_MEM_IS_BUILTIN(V)) - -/** - Type used for counting memory chunk sizes. -*/ -typedef uint32_t cwal_memsize_t; - - -bool cwal_value_is_builtin( void const * m ){ - return CWAL_MEM_IS_BUILTIN(m); -} - -/** - Static state for the recycling mechanism. Here we only - store some calculated values which apply to all engines. - - Gets populated by cwal_setup_recycler_indexes(). -*/ -static struct { - /** - A map of cwal_type_id to integer array indexes - for cwal_engine::recycler[]. It gets populated - once during engine initialization and holds values - valid for all engine instances. - */ - int indexes[CWAL_TYPE_end]; - /** - The total number of recycling bins calculated by - cwal_setup_recycler_indexes(). cwal_engine::recycler - must have at least this many elements. - */ - cwal_size_t recyclerCount; -} cwalRecyclerInfo = { -{-1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1 }, -0 -}; - -/** - Calculates an optimized value recycling bin layout for - cwal_engine::recycler and stores the result in cwalRecyclerInfo.indexes. - All non-recyclable types get a -1 put in - cwalRecyclerInfo.indexes[thatTypeId]. All others get a value - representing an index into cwal_engine::recycler. All types with - the same base Value size are grouped together in the same index. -*/ -static void cwal_setup_recycler_indexes(){ - if(cwalRecyclerInfo.recyclerCount) return; - else{ - static const cwal_type_id tlist[] = { - /* - Reminders to self: only set up VALUE TYPES this way because - we cannot mix Value and non-Value types in one recycler - because usage of their linked list members - breaks. CWAL_TYPE_STRING must not be in this list, but - CWAL_TYPE_XSTRING and ZSTRING must be (both have the same - size and will be grouped together). - */ - CWAL_TYPE_INTEGER, - CWAL_TYPE_DOUBLE, - CWAL_TYPE_ARRAY, - CWAL_TYPE_OBJECT, - CWAL_TYPE_NATIVE, - CWAL_TYPE_BUFFER, - CWAL_TYPE_FUNCTION, - CWAL_TYPE_EXCEPTION, - CWAL_TYPE_HASH, - CWAL_TYPE_XSTRING, - CWAL_TYPE_ZSTRING, - CWAL_TYPE_UNIQUE, - CWAL_TYPE_TUPLE, - CWAL_TYPE_UNDEF /* list sentinel - gets excluded below */ - }; -#define ASIZE(A) (sizeof(A)/sizeof(A[0])) - cwal_size_t xlist[ASIZE(tlist)]; - cwal_size_t zlist[ASIZE(tlist)]; - cwal_size_t i, x, zCount = 0; - memset(zlist, 0, sizeof(zlist)); -#ifdef DEBUG - /* Make sure the inlined intialization is as expected... */ - for(i = 0; i < CWAL_TYPE_end; ++i){ - assert(-1==cwalRecyclerInfo.indexes[i]); - /* cwalRecyclerInfo.indexes[i] = -1; */ - /* cwalRecyclerSizes[i] = cwal_type_id_sizeof(i); */ - } -#endif - /* Collect the sizes of each type... */ - for(i = 0; CWAL_TYPE_UNDEF != tlist[i] ; ++i){ - xlist[i] = cwal_type_id_sizeof(tlist[i]); - assert(xlist[i]); - /*MARKER(("xlist[%s] = %d\n", - cwal_type_id_name(tlist[i]), (int)xlist[i]));*/ - }; - xlist[i] = 0; - /* Bubblesort the sizes... */ - for(i = 0; i < ASIZE(xlist)-1; ++i){ - for( x = 1; x < ASIZE(xlist)-1; ++x){ - if(xlist[x] < xlist[x-1]){ - cwal_size_t const tmp = xlist[x-1]; - xlist[x-1] = xlist[x]; - xlist[x] = tmp; - } - } - } -#if 0 - for(i = 0; xlist[i] && i < CWAL_TYPE_end; ++i){ - MARKER(("Sorted index %d %d\n", - (int)i, (int)xlist[i])); - } -#endif - /* Remove dupes... */ - for( x = 0; x < ASIZE(xlist)-1; ++x ){ - int gotIt = 0; - for(i = 0; zlist[i] && i < ASIZE(zlist)-1; ++i){ - if( zlist[i] == xlist[x] ){ - gotIt = 1; - break; - } - } - if(!gotIt) zlist[zCount++] = xlist[x]; - } -#if 0 - for(i = 0; i < CWAL_TYPE_end && zlist[i]; ++i){ - MARKER(("Index #%d sizeof=%d\n", - (int)i, (int)zlist[i])); - } -#endif - /* Match up sizes to types, to group recycle bins... */ - for(i = 0; zlist[i]; ++i){ - /* MARKER(("#%d = %d\n", (int)i, (int)zlist[i])); */ - for(x = 0; CWAL_TYPE_UNDEF != tlist[x]; ++x){ - cwal_size_t const sz = cwal_type_id_sizeof(tlist[x]); - if(sz == zlist[i]){ - /*MARKER(("Size match (%d): %s\n", (int)sz, - cwal_type_id_name(tlist[x])));*/ - cwalRecyclerInfo.indexes[tlist[x]] = (int)i; - } - } - } - assert(cwalRecyclerInfo.indexes[CWAL_TYPE_XSTRING] - ==cwalRecyclerInfo.indexes[CWAL_TYPE_ZSTRING]); - /* assert(cwalRecyclerSizes[CWAL_TYPE_OBJECT]); */ - - cwalRecyclerInfo.indexes[CWAL_TYPE_KVP] = zCount++; - cwalRecyclerInfo.indexes[CWAL_TYPE_WEAK_REF] = zCount++; - cwalRecyclerInfo.indexes[CWAL_TYPE_SCOPE] = zCount++; - - cwalRecyclerInfo.recyclerCount = zCount; -#ifdef DEBUG - { - /* Make sure cwal_engine::recycler is sized big enough. */ - cwal_engine * e = 0; - assert(zCount <= sizeof(e->recycler)/sizeof(e->recycler[0])); - } -#endif -#if 0 - for(i = 0; i < CWAL_TYPE_end; ++i){ - MARKER(("Recycler: %d %s index=%d\n", - (int)i, - cwal_type_id_name((cwal_type_id)i), - (int)cwalRecyclerInfo.indexes[i] - )); - } -#endif - } -#undef ASIZE -} - -/** - Returns the index in cwal_engine::recycler[] for the given - type ID, or -1 if there is no recycler for that type. - - Special case: for CWAL_TYPE_STRING it returns the x-/z-string - index. Cases which refer to the real string recycler need to be - careful NOT to use this routine, but cwal_recycler_get() - instead. -*/ -static int cwal_recycler_index( cwal_type_id typeID ){ - static int once = 0; - if(!once){ - cwal_setup_recycler_indexes(); - once=1; - /* - Pedantic side note: if two threads init two cwal_engine - instances at the same time, they will both init the recycler - indexes, but will set the same memory to the same values, so - it makes no difference. We set once=1 last to allow two - threads to do that, rather than to have the second thread - continue before the first is filling up cwalRecyclerInfo. - */ - } - switch( typeID ){ - case CWAL_TYPE_STRING: - return cwalRecyclerInfo.indexes[CWAL_TYPE_XSTRING] - /* Special case because x/z-strings get tagged - with this type after construction. */ - ; - case CWAL_TYPE_INTEGER: - case CWAL_TYPE_DOUBLE: - case CWAL_TYPE_XSTRING: - case CWAL_TYPE_ZSTRING: - /* we only handle x/z-strings via e->recycler, - and STRING via e->reString. */ - case CWAL_TYPE_ARRAY: - case CWAL_TYPE_OBJECT: - case CWAL_TYPE_HASH: - case CWAL_TYPE_NATIVE: - case CWAL_TYPE_BUFFER: - case CWAL_TYPE_FUNCTION: - case CWAL_TYPE_EXCEPTION: - case CWAL_TYPE_UNIQUE: - case CWAL_TYPE_TUPLE: - - case CWAL_TYPE_KVP: - case CWAL_TYPE_SCOPE: - case CWAL_TYPE_WEAK_REF: - - assert(cwalRecyclerInfo.indexes[typeID]>=0); - return cwalRecyclerInfo.indexes[typeID]; - default: - return -1; - } -} - -/** - Overwrites all state in buf with defaults (zeroes) but - retains the buf->self member. -*/ -static void cwal_buffer_wipe_keep_self( cwal_buffer * buf ){ - void * self = buf->self; - *buf = cwal_buffer_empty; - buf->self = self; -} - -int cwal_is_dead(cwal_engine const * e){ - return e ? e->fatalCode : CWAL_RC_MISUSE; -} - -/** @internal - - Checks whether child refers to a newer scope than parent, and if - it does then it moves child to par. If par is 0 this function - sets *res (if not NULL) to 1 and returns. - - Returns 0 on success and the only error case is if popping child - from its parent or pushing to its new parent fails (which since the - transition from arrays to linked lists for child values, has no - failure cases other than memory corruption or similar internal - mismanagement of cwal's bits). It sets res (if not NULL) to one of: - - -1: means that par takes over child, adding it to its list setting - child->scope to par. - - 0: no action is necessary. Child already belongs to par. - - 1: child is a built-in, belongs to par, or belongs to a scope with - a lower scope->level (in which case that scope is its owner). In any - such case, this function does not modify child's scope. - - Note that this does NOT change child's reference count in any case. -*/ -static int cwal_value_xscope( cwal_engine * e, cwal_scope * par, cwal_value * child, int * res ); - - -/** - Internal debuggering routine which dumps out info about the value v - (which must not be NULL) to stdout or stderr. If msg is provided it - is appended to the output. -*/ -void cwal_dump_value( char const * File, int Line, cwal_value const * v, - char const * msg ){ - FILE * out = stdout; - cwal_obase const * b = CWAL_VOBASE(v); - if(File && *File && (Line>0)){ - fprintf(out, "%s():%d: ", File, Line ); - } - fprintf(out, "%s@%p (scope=#%d) refCount=%u", - v->vtab->typeName, - (void*)v, - v->scope - ? (int)v->scope->level - : (int)(CWAL_MEM_IS_BUILTIN(v) ? 0 : -666), - (unsigned)CWAL_REFCOUNT(v)); - if(b){ - fprintf( out, " flags=%02x", b->flags ); - } - if( cwal_value_is_string(v) ){ - cwal_string const * s = cwal_value_get_string(v); - if(s && CWAL_STRLEN(s)){ - const cwal_size_t len = CWAL_STRLEN(s); - fprintf( out, " strlen=%u", (unsigned)len); - if( len <= 30 ){ - fprintf( out, " bytes=[%.*s]", (int)len, cwal_string_cstr(s) ); - } - }else{ - fprintf( out, " (STILL INITIALIZING?)" ); - } - } - else if(cwal_value_is_integer(v)){ - fprintf( out, " int=%"CWAL_INT_T_PFMT, - cwal_value_get_integer(v)); - } - else if(cwal_value_is_double(v)){ - fprintf( out, " double=%"CWAL_DOUBLE_T_PFMT, - cwal_value_get_double(v)); - } - else if(cwal_value_is_bool(v)){ - fprintf( out, " bool=%s", - cwal_value_get_double(v) ? "true" : "false"); - }else if(cwal_value_is_tuple(v)){ - cwal_tuple const * p = CWAL_TUPLE(v); - assert(p); - fprintf( out, " n=%d", (int)p->n ); - } - if(msg && *msg) fprintf( out, "\t%s\n", msg ); - else fputc( '\n', out ); - fflush(out); -} - -#define dump_val(V,M) cwal_dump_value(__FILE__,__LINE__,(V),(M)) - -/** - Returns the recycler for the given type, distinguishing between - CWAL_TYPE_STRING (==>e->reString) and CWAL_TYPE_XSTRING/ZSTRING - (==>e->recycler[something]). BE CAREFUL: do not put x/z-strings - in the other string bin, or vice versa! -*/ -static cwal_recycler * cwal_recycler_get( cwal_engine * e, cwal_type_id t ){ - if(CWAL_TYPE_STRING == t){ - return &e->reString; - } - else { - const int ndx = cwal_recycler_index(t); - /* assert(ndx>=0); */ - return (ndx >= 0) ? &e->recycler[ndx] : 0; - } -} - - -/** - Either adds mem to e->reChunk or (if recycling is disabled or capacity/quota - is reached) frees mem using cwal_free(). -*/ -static void cwal_memchunk_add(cwal_engine * e, void * mem, cwal_size_t size ){ - cwal_memchunk_recycler * re = &e->reChunk; - assert(mem); - assert(size>0); - assert((cwal_size_t)-1 != size); - size = CWAL_MEMSZ_PAD(size); - if(CWAL_F_TRACK_MEM_SIZE & e->flags){ - /* If we have the size info in the memory block then use that. - This allows us to make up for list and string allocations truncating - sizes, effectively "losing" bytes (making them unusable, but still - part of a tracked block) each time they do that. */ - cwal_memsize_t * sz = MEMSZ_PTR_FROM_MEM(mem); - /* static int counter1 = 0; ++counter1; */ - if(*sz != size+sizeof(void*)){ - /* static int counter2 = 0; */ - assert(*sz); - assert(e->memcap.currentMem >= *sz); - assert(size < *sz-sizeof(void*)); - /*MARKER(("#%d of %d Replacing size %d with %d from memory stamp.\n", - ++counter2, counter1, (int)size, (int)(*sz - sizeof(void*))));*/ - e->metrics.recoveredSlackBytes += *sz - size - sizeof(void*); - ++e->metrics.recoveredSlackCount; - size = *sz - sizeof(void*) - /* -sizeof is needed to avoid a semantic conflict in - cwal_memchunk_overlay::size - vs. *MEMSZ_PTR_FROM_MEM(mem). If we don't account - for it here, we end up corrupting malloc()-internal - state! - */; - } - } - if(!re->config.maxChunkCount - || !e->current /* i.e. during finalization */ - || size < sizeof(cwal_memchunk_overlay) - || (re->config.maxTotalSize < (size + re->currentTotal)) - || (re->config.maxChunkSize < size) - || (re->headCount >= re->config.maxChunkCount) - ){ - /* MARKER(("Freeing chunk @%p of size %d\n", mem, (int)size)); */ - cwal_free(e,mem); - }else{ - cwal_memchunk_overlay * ovl; - /* MARKER(("Adding mem chunk @%p of size %d\n", mem, (int)size)); */ - assert(re->headCount < re->config.maxChunkCount); - /* memset(mem, 0, size); */ - ovl = (cwal_memchunk_overlay *)mem; - *ovl = cwal_memchunk_overlay_empty; - ovl->size = size; - if(!re->metrics.smallestChunkSize - || (size < re->metrics.smallestChunkSize)){ - re->metrics.smallestChunkSize = size; - } - if(size > re->metrics.largestChunkSize){ - re->metrics.largestChunkSize = size; - } - if( (re->currentTotal += size) > - re->metrics.peakTotalSize ){ - re->metrics.peakTotalSize = re->currentTotal; - } - if( ++re->headCount > re->metrics.peakChunkCount ){ - re->metrics.peakChunkCount = re->headCount; - } - re->metrics.runningAverageSize = (re->metrics.runningAverageSize + size)/2; - /* Insert ovl into the linked list, sorted by size... */ - if(!re->head){ - assert(1==re->headCount) /* 1 b/c we increment it above */; - re->head = ovl; - }else{ - cwal_memchunk_overlay * h = re->head; - cwal_memchunk_overlay * prev = 0; - char gotIt = 0; - for( ; h; prev = h, h = h->next ){ - if(h->size>=ovl->size){ - gotIt = 1; - if(prev){ - prev->next = ovl; - }else{ - assert(h==re->head); - re->head = ovl; - } - ovl->next = h; - break; - } - } - if(!gotIt){ - /* End of list: ovl is biggest */ - assert(prev); - assert(!prev->next); - assert(prev->size < ovl->size); - prev->next = ovl; - } - } - /* MARKER(("Added mem chunk @%p #%d of size %d\n", mem, (int)re->headCount, (int)size)); */ - } - return; -} - -/** - Requests a chunk of memory from the memchunk cache. *size must be - the size of the block we would "like" to have. A value of zero - means to give back the first chunk (an O(1) op). - - deltaPolicy specifies a size tolerance. Legal values are: - - 0: no tolerance - only an exact size match qualifies. - - N>100: a percent larger the buffer may be. If a larger buffer is - found within that that size, it is returned. It is ignored if - !*size. If deltaPolicy>999 then any chunk at least as large as *size - will be accepted. - - N<100: at least *size, but no bigger than *size+N. - - N<0: the first buffer in the list will match, the same as if - *size==0. - - If non-NULL is returned, *size is updated to the size of the chunk. - - Potential TODO: change sig to include a param which specifies how - to interpret deltaPolicy (e.g. absolute vs percent vs - smaller-or-larger). - - Potential TODO: if !*size, interpret deltaPolicy as a preferred value -*/ -static void * cwal_memchunk_request(cwal_engine * e, cwal_size_t * size, - int deltaPolicy, - char const * debugDescription){ - cwal_memchunk_recycler * re = &e->reChunk; - cwal_memchunk_overlay * ovl = 0; - cwal_memchunk_overlay * left = 0; - void * rc = 0; - ++re->metrics.requests; - for( ovl = re->head; ovl; left = ovl, ovl = ovl->next ){ - ++re->metrics.searchComparisons; - if(deltaPolicy<0 - || !*size - || *size == ovl->size) break; - else if( deltaPolicy>100 ){ - /* Chunk size within (*size, *size+(deltaPolicy/100)) */ - cwal_size_t const max = (*size * (cwal_size_t)(deltaPolicy/100.0)); - assert(ovl->size!=*size && "Is caught above."); - if( ovl->size>*size - && (deltaPolicy>999 || ovl->size <= max) - ){ - break; - }else if(ovl->size > max){ - /* We won't find a match above this point */ - ovl = 0; - break; - } - }else if(deltaPolicy>0){ - /* Interpret as absolute byte count */ - if(ovl->size>*size - && ovl->size <= *size + deltaPolicy ){ - break; - }else if(ovl->size > *size * deltaPolicy){ - /* We won't find a match above this point */ - ovl = 0; - break; - } - } - } - if(!ovl) ++re->metrics.searchMisses; - else{ - /*MARKER(("Donating chunk of size %d for request of size %d. Context=%s\n", - (int)ch->size, (int)*size, debugDescription));*/ - if(debugDescription){/*avoid unused param warning*/} - assert(re->headCount>0); - if(left){ - assert(re->headCount>1); - assert(left->next == ovl); - left->next = ovl->next; - } - if(ovl->next){ - assert(re->headCount > (left ? 2 : 1)); - } - if(re->head == ovl){ - re->head = ovl->next; - } - *size = ovl->size; - memset(ovl, 0, *size); - rc = ovl; - assert(re->currentTotal >= *size); - re->currentTotal -= *size; - --re->headCount; - if(!re->headCount){ - assert(!re->head); - } - ++re->metrics.totalChunksServed; - re->metrics.totalBytesServed += *size; - re->metrics.runningAverageResponseSize = - (re->metrics.runningAverageResponseSize + *size)/2; - } - return rc; -} - - -static void cwal_memchunk_freeit( cwal_engine * e, cwal_memchunk_overlay * ovl ){ - cwal_memchunk_recycler * re = &e->reChunk; - assert(!ovl->next); - assert(re->headCount>0); - assert(re->currentTotal >= ovl->size); - --re->headCount; - re->currentTotal -= ovl->size; - *ovl = cwal_memchunk_overlay_empty; - cwal_free(e, ovl); -} - -/** - Frees up all entries in e->reChunk. -*/ -static void cwal_memchunks_free( cwal_engine * e ){ - cwal_memchunk_recycler * re = &e->reChunk; - cwal_memchunk_overlay * ovl; - for( ; (ovl = re->head); ){ - re->head = ovl->next; - ovl->next = 0; - cwal_memchunk_freeit(e, ovl); - } - assert(0==re->headCount); - assert(0==re->currentTotal); - re->head = 0; -} - - -int cwal_engine_memchunk_config( cwal_engine * e, - cwal_memchunk_config const * conf){ - if(!e || !conf) return CWAL_RC_MISUSE; - else{ - /* Adjust size... */ - cwal_memchunk_recycler * re = &e->reChunk; - cwal_memchunk_overlay * ovl; - if(!conf->maxChunkCount - || !conf->maxTotalSize - || !conf->maxChunkSize){ - /* The simplest case: disable the recycler. */ - cwal_memchunks_free( e ); - re->config = *conf; - return 0; - } - - if(re->config.maxChunkSize > conf->maxChunkSize){ - /* Trim now-too-large chunks. */ - cwal_memchunk_overlay * prev = 0; - cwal_memchunk_overlay * next = 0; - ovl = re->head; - assert(ovl); - for( ; ovl; ovl = next){ - next = ovl->next; - if(ovl->size > conf->maxChunkSize){ - if(prev) prev->next = next; - ovl->next = 0; - cwal_memchunk_freeit(e, ovl); - }else{ - prev = ovl; - } - } - } - - if(re->currentTotal > conf->maxTotalSize){ - /* Trim chunks until we're under the limit. */ - cwal_memchunk_overlay * prev = 0; - cwal_memchunk_overlay * next = 0; - ovl = re->head; - assert(ovl); - for( ; ovl && (re->currentTotal > conf->maxTotalSize); - ovl = next ){ - next = ovl->next; - if(ovl->size > conf->maxChunkSize){ - if(prev) prev->next = next; - ovl->next = 0; - cwal_memchunk_freeit(e, ovl); - }else{ - prev = ovl; - } - } - } - while(conf->maxChunkCount - ? (re->headCount > conf->maxChunkCount) - : !!re->headCount){ - /* Too many chunks. Lop off the smallest ones. */ - assert(re->head); - ovl = re->head; - re->head = ovl->next; - ovl->next = 0; - cwal_memchunk_freeit(e, ovl); - } - re->config = *conf; - return 0; - } -} - -cwal_kvp * cwal_kvp_alloc(cwal_engine *e){ - cwal_kvp * kvp; - cwal_recycler * re; - ++e->metrics.requested[CWAL_TYPE_KVP]; - re = cwal_recycler_get(e, CWAL_TYPE_KVP); - assert(re); - if(re->list){ - ++re->hits; - ++e->metrics.valuesRecycled; - kvp = (cwal_kvp*)re->list; - re->list = kvp->right; - kvp->right = 0; - --re->count; - } - else{ - ++re->misses; - ++e->metrics.valuesRecycleMisses; - kvp = (cwal_kvp*)cwal_malloc(e, sizeof(cwal_kvp)); - if(kvp){ - ++e->metrics.allocated[CWAL_TYPE_KVP]; - e->metrics.bytes[CWAL_TYPE_KVP] += sizeof(cwal_kvp); - } - } - if( kvp ) { - *kvp = cwal_kvp_empty; - } - return kvp; -} - -void cwal_kvp_clean( cwal_engine * e, /* cwal_scope * fromScope, */ - cwal_kvp * kvp ){ - if( kvp ){ - cwal_value * key = kvp->key; - cwal_value * value = kvp->value; - *kvp = cwal_kvp_empty; - if(key) cwal_value_unref2(e, key); - if(value) cwal_value_unref2(e, value); - } -} - -void cwal_kvp_free( cwal_engine * e, /* cwal_scope * fromScope, */ - cwal_kvp * kvp, char allowRecycle ){ - if( kvp ){ - cwal_kvp_clean(e/* , fromScope */, kvp); - if(allowRecycle){ - cwal_recycler * re = cwal_recycler_get(e, CWAL_TYPE_KVP); - assert(re); - if(re->count < re->maxLength){ - assert(!kvp->right); - kvp->right = (cwal_kvp*)re->list; - re->list = kvp; - ++re->count; - }else{ - cwal_free(e, kvp); - } - } - else{ - cwal_free(e, kvp); - } - } -} - -cwal_value * cwal_kvp_key( cwal_kvp const * kvp ){ - return kvp ? kvp->key : NULL; -} - -cwal_value * cwal_kvp_value( cwal_kvp const * kvp ){ - return kvp ? kvp->value : NULL; -} - -int cwal_kvp_value_set( cwal_kvp * const kvp, - cwal_value * const v ){ - if(!kvp || !v) return CWAL_RC_MISUSE; - else{ - assert(kvp->key); - assert(kvp->value); - cwal_value_ref(v); - cwal_value_unref(kvp->value); - kvp->value = v; - return 0; - } -} - -int cwal_kvp_value_set2( cwal_kvp * const kvp, - cwal_value * const v ){ - if(!kvp || !v) return CWAL_RC_MISUSE; - else if(CWAL_VAR_F_CONST & kvp->flags){ - return CWAL_RC_CONST_VIOLATION; - } - return cwal_kvp_value_set(kvp, v); -} - -cwal_flags16_t cwal_kvp_flags( cwal_kvp const * kvp ){ - return kvp ? (cwal_flags16_t)(CWAL_VAR_F_PRESERVE & kvp->flags) : 0; -} - -cwal_flags16_t cwal_kvp_flags_set( cwal_kvp * kvp, cwal_flags16_t flags ){ - cwal_flags16_t const rc = (cwal_flags16_t)(CWAL_VAR_F_PRESERVE & kvp->flags); - if(CWAL_VAR_F_PRESERVE != flags){ - kvp->flags = flags; - } - return rc; -} - -#if !CWAL_OBASE_ISA_HASH -/** @internal - - Searches for the given key in the given kvp list. - - Returns the found item if a match is found, NULL if not. If prev is - not NULL then *prev is set to the returned value's left-hand-side - kvp from the linked list (or the end of the list, if no match is - found). A *prev value of NULL and return value of non-NULL - indicates that the result kvp was found at the head of the list. -*/ -static cwal_kvp * cwal_kvp_search( cwal_kvp * kvp, char const * key, - cwal_midsize_t keyLen, cwal_kvp ** prev){ - if(!kvp || !key ) return NULL; - else{ - cwal_kvp * left = 0; - char const * cKey; - cwal_size_t cLen; - int cmp; - for( left = 0; kvp; left = kvp, kvp = kvp->right ){ - assert( kvp->key ); - assert(kvp->right != kvp); - cKey = cwal_value_get_cstr(kvp->key, &cLen); - if(prev) *prev=left; - if(!cKey) continue /* we don't know where non-strings sort in this world! */; - else if(0 == (cmp = cwal_compare_cstr( key, keyLen, cKey, cLen ))){ - return kvp; - } -#if CWAL_KVP_TRY_SORTING - if(cmp<0) break; -#endif - } - if(prev) *prev = CWAL_KVP_TRY_SORTING ? left : 0; - return 0; - } -} - -/** - Variant of cwal_kvp_search() which takes a cwal_value key and uses - key->vtab->compare() to check for equivalence. -*/ -static cwal_kvp * cwal_kvp_search_v( cwal_kvp * kvp, - cwal_value const * key, - cwal_kvp ** prev){ - if(!kvp || !key ) return NULL; - else{ - cwal_kvp * left; - int cmp; - const int keyIsBool = CWAL_TYPE_BOOL==key->vtab->typeID; - for( left = 0; kvp; left = kvp, kvp = kvp->right ){ - const int kvpIsBool = CWAL_TYPE_BOOL==kvp->key->vtab->typeID; - assert(kvp->key); - assert(kvp->right != kvp); - if(key==kvp->key){ - cmp = 0; - }else if(keyIsBool || kvpIsBool){ - /* - 20190706: it was *finally* discovered (by accident) - that: - - var o = {}; - o[true]; - - Matches the first truthy property key! In our case, - it was the s2 object prototype's constructor method. - - Likewise: - - o[true] = 3; // bool-typed property key - o['x']; // ==> 3 - - Because this lookup explicitly does type-loose - comparisons and most things are equivalent to true - in that context. So... now we special-case a - type-strict lookup if either of key or kvp->key is-a - boolean. - */ - if(keyIsBool && kvpIsBool){ - cmp = key->vtab->compare(key, kvp->key); - /* And fall through. */ - }else{ - /* Do not allow a match if either key is a bool - but the other one is not. */ - continue; - } - }else{ - cmp = key->vtab->compare(key, kvp->key); - } - if(prev) *prev=left; - if(0==cmp) return kvp; -#if CWAL_KVP_TRY_SORTING - else if(cmp<0) break; -#endif - } - if(prev) *prev = CWAL_KVP_TRY_SORTING ? left : 0; - return 0; - } -} - -/** - Functionally identical to cwal_kvp_unset_v() but takes - its key in C-string form. -*/ -static int cwal_kvp_unset( cwal_engine * e, /* cwal_scope * fromScope, */ - cwal_kvp ** list, - char const * key, cwal_midsize_t keyLen ) { - /* assert(fromScope); */ - assert(e); - assert(key); - if( !e || !key || !list ) return CWAL_RC_MISUSE; - else if(!*list) return CWAL_RC_NOT_FOUND; - else { - cwal_kvp * left = 0; - cwal_kvp * kvp; - kvp = cwal_kvp_search( *list, key, keyLen, &left ); - if( !kvp ) return CWAL_RC_NOT_FOUND; - else if(left) left->right = kvp->right; - else { - assert(*list == kvp); - *list = kvp->right; - } - kvp->right = NULL; - cwal_kvp_free( e/* , fromScope */, kvp, 1 ); - return 0; - } -} - -/** - Unsets a the given key in the given kvp list. list must point to - the head of a cwal_kvp list, and if the head is the unset kvp then - *list is updated to point to kvp->right. - - Returns 0 on successs, CWAL_RC_NOT_FOUND if - no match is found. -*/ -static int cwal_kvp_unset_v( cwal_engine * e, cwal_kvp ** list, - cwal_value * key ) { - assert(e); - assert(key); - if( !e || !key || !list ) return CWAL_RC_MISUSE; - else if(!*list) return CWAL_RC_NOT_FOUND; - else { - cwal_kvp * left = 0; - cwal_kvp * kvp; - kvp = cwal_kvp_search_v( *list, key, &left ); - if( ! kvp ) return CWAL_RC_NOT_FOUND; - if(left) left->right = kvp->right; - else { - assert(*list==kvp); - *list = kvp->right; - } - kvp->right = NULL; - cwal_kvp_free( e, kvp, 1 ); - return 0; - } -} -#endif /* !CWAL_OBASE_ISA_HASH */ - -/** - Returns the client-supplied hash table size "trimmed" to some - "convenient" prime number (more or less arbitrarily chosen by this - developer - feel free to change/extend this range). -*/ -static uint16_t cwal_trim_hash_size( uint16_t hashSize ){ - if(hashSize < CwalConsts.MinimumHashSize) return CwalConsts.MinimumHashSize; -#define P(N) else if( hashSize <= N ) return N - /* TODO? add more granularity here. */ - P(17); P(37); P(53); P(71); - P(151); P(211); P(281); P(311); - P(379); P(433); P(503); P(547); - P(587); P(613); P(683); P(719); - P(751); P(1033); - P(1549); P(2153); - else return 3163; -#undef P -} - -/** - Returns the cwal_ptr_table step size "trimmed" to some "acceptable" - range. -*/ -static uint16_t cwal_trim_step( uint16_t step ){ - if(step < CwalConsts.MinimumStep) step = CwalConsts.MinimumStep; - return step; -} - - -/** - Allocates a new cwal_ptr_page object, owned by e. Returned NULL on - error. On success the returned value is empty-initialized. - - The page has n entries (hash table size) and the given step size. - - n MUST currently be the same as the owning table's hash size, but - there are plans to potentially change that, allowing new page sizes - to grow if collision counts become too high. -*/ -static cwal_ptr_page * cwal_ptr_page_create( cwal_engine * e, uint16_t n ){ - const uint32_t asz = (sizeof(void*) * n); - const uint32_t psz = asz + sizeof(cwal_ptr_page); - cwal_ptr_page * p = (cwal_ptr_page*)cwal_malloc(e, psz); - if(p){ - memset( p, 0, psz ); - p->list = (void**)(p+1); - p->entryCount = 0; - } - return p; -} - -/** - Allocates a new page for the given table. - - Returns CWAL_RC_OK on success. The only conceivable non-bug error - case here is CWAL_RC_OOM. -*/ -static int cwal_ptr_table_add_page( cwal_engine * e, cwal_ptr_table * t ){ - cwal_ptr_page * p = cwal_ptr_page_create( e, t->hashSize ); - if(!p) return CWAL_RC_OOM; - else { - cwal_ptr_page * tail = t->pg.tail; - if(!tail){ - assert(!t->pg.head); - t->pg.head = t->pg.tail = p; - }else{ - assert(t->pg.head); - assert(!tail->next); - t->pg.tail = tail->next = p; - } - assert(t->pg.tail->next != t->pg.head); - return 0; - } -} - -int cwal_ptr_table_create( cwal_engine * e, cwal_ptr_table ** T, - uint16_t hashSize, - uint16_t step){ - int rc; - cwal_ptr_table * t; - if(!e || !T) return CWAL_RC_MISUSE; - hashSize = cwal_trim_hash_size(hashSize); - step = cwal_trim_step(step); - t = *T; - if(t){ - *t = cwal_ptr_table_empty; - }else { - cwal_size_t reqSize = sizeof(cwal_ptr_table); - t = (cwal_ptr_table*)cwal_memchunk_request(e, &reqSize, 0, - "cwal_ptr_table_create()"); - if(!t){ - t = (cwal_ptr_table*)cwal_malloc(e, reqSize); - }else{ - assert(reqSize==sizeof(cwal_ptr_table)); - } - if(!t) { - rc = CWAL_RC_OOM; - goto error; - } - *t = cwal_ptr_table_empty; - t->allocStamp = CwalConsts.AllocStamp; - } - - t->hashSize = hashSize; - t->step = step; - rc = cwal_ptr_table_add_page( e, t ); - if(rc) goto error; - assert( t->pg.head ); - if(!*T) *T = t; - return CWAL_RC_OK; - - error: - assert(0 != rc && "You seem to have failed to set an error code!"); - if(t && (t!=*T)){ - cwal_memchunk_add(e, t, sizeof(cwal_ptr_table)); - /* cwal_free(e, t); */ - } - return rc; -} - -int cwal_ptr_table_destroy( cwal_engine * e, cwal_ptr_table * t ){ - if(!e || !t) return CWAL_RC_MISUSE; - else{ - cwal_size_t const psz = sizeof(cwal_ptr_page) + - (sizeof(void*) * t->hashSize); - void const * stamp = t->allocStamp; - cwal_ptr_page * p = t->pg.head; - assert(t->hashSize || !p); - t->pg.head = t->pg.tail = NULL; - while( p ){ - cwal_ptr_page * n = p->next; - /* cwal_free(e, p); */ - cwal_memchunk_add(e, p, psz); - p = n; - } - *t = cwal_ptr_table_empty; - if( CwalConsts.AllocStamp == stamp ){ - cwal_free( e, t ); - /* cwal_memchunk_add(e, t, sizeof(cwal_ptr_table)); */ - }else{ - /* Assume t was stack allocated or is part of another - object.*/ - t->allocStamp = stamp; - } - return CWAL_RC_OK; - } -} - -int cwal_ptr_table_visit( cwal_ptr_table * t, cwal_ptr_table_visitor_f f, void * state ){ - if(!t || !f) return CWAL_RC_MISUSE; - else{ - cwal_size_t i; - cwal_ptr_page * page = t->pg.head; - cwal_value ** val; - cwal_size_t seen; - int rc = 0; - for( ; page; page = page->next ){ - seen = 0; - for( i = 0; - (0==rc) - && (i < t->hashSize) - && (seen < page->entryCount); ++i ){ - val = (cwal_value**)&page->list[i]; - if(!*val) continue; - ++seen; - rc = f( val, state ); - page->list[i] = *val; - } - - } - return rc; - } -} - - -int cwal_ptr_table_mem_cost( cwal_ptr_table const * t, - uint32_t * mallocs, - uint32_t * memory ){ - enum { SV = sizeof(void*) }; - uint32_t a = 1; - uint32_t m = sizeof(cwal_ptr_table); - if(!t) return CWAL_RC_MISUSE; - else{ - cwal_ptr_page const * p = t->pg.head; - for( ; p; p = p->next ){ - ++a; - m += sizeof(cwal_ptr_page) - + (t->hashSize*SV); - } - } - if(mallocs) *mallocs = a; - if(memory) *memory = m; - return CWAL_RC_OK; -} - -static uint16_t cwal_ptr_table_hash( void const * key, - uint16_t step, - uint16_t hashSize){ -#if CWAL_VOID_PTR_IS_BIG - /* IF THE DEBUGGER LEADS YOU NEAR HERE... - try changing ptr_int_t back to uint64_t. - */ - typedef uint64_t ptr_int_t; -#else - typedef uint32_t ptr_int_t; -#endif -#if 1 - const ptr_int_t k = ((ptr_int_t)key); - const uint32_t v1 = (uint32_t)(k / step); - const uint16_t v2 = v1 % hashSize; - /* - MARKER("key=%p step=%u hashSize=%u k=%lu v1=%u v2=%u\n", - key, step, hashSize, k, v1, v2); - */ - return v2; -#else - return ((ptr_int_t)key) / step % hashSize; -#endif -} - - -int cwal_ptr_table_op( cwal_engine * e, - cwal_ptr_table * t, - void * key, - cwal_ptr_table_ops op ){ - cwal_ptr_page * pPage; - void * pRet = NULL; - uint16_t iKey; - int rc = 0; - if(!e || !t || !key) return CWAL_RC_MISUSE; - iKey = cwal_ptr_table_hash( key, t->step, t->hashSize ); - assert( iKey < t->hashSize ); - assert( t->pg.head ); - /* - TODO?: honor page-specific hashSize values, re-calculating the - hash value. if the step value changes while iterating. - */ - switch( op ){ - /* FIXME: refactor the 3 loops below into one loop at the start. - */ - case CWAL_PTR_TABLE_OP_SEARCH: - rc = CWAL_RC_NOT_FOUND; - for(pPage = t->pg.head; pPage; pPage = pPage->next ){ - pRet = pPage->list[iKey]; - if(!pRet) break; - else if(pRet == key){ - rc = CWAL_RC_OK; - break; - } - } - break; - case CWAL_PTR_TABLE_OP_INSERT:{ - assert(t->pg.head); - rc = CWAL_RC_OK; - for(pPage = t->pg.head; pPage; pPage = pPage->next ){ - pRet = pPage->list[iKey]; -#if 0 - MARKER("COMPARING STASHED %p AGAINST KEY %p\n", (void*)pRet, (void*)key); -#endif - if(!pRet) goto insert; - else if(pRet == key){ - rc = CWAL_RC_ALREADY_EXISTS; - break; - } - } -#if 0 - MARKER("INSERT NO AVAILABLE SLOT CONTAINS %p. " - "ADDING PAGE for hash %u rc=%d=%s\n", - (void *)key, iKey, rc, cwal_rc_cstr(rc)); -#endif - if(rc) break; - /* We reached the end of the tables and found - no empty slot. Add a page and insert it there. */ - rc = cwal_ptr_table_add_page( e, t ); - if(rc) break; - pPage = t->pg.tail; - insert: -#if 0 - MARKER("INSERTING %p (hash=%u) in list %p\n", (void*)key, iKey, (void *)pPage); -#endif - rc = CWAL_RC_OK; - assert(NULL != pPage); - pPage->list[iKey] = key; - ++pPage->entryCount; - } break; - case CWAL_PTR_TABLE_OP_REMOVE: - rc = CWAL_RC_NOT_FOUND; - for(pPage = t->pg.head; pPage; pPage = pPage->next ){ - pRet = pPage->list[iKey]; - if(!pRet) break; - else if(pRet == key){ - cwal_ptr_page * prevPage = pPage; - assert(pPage->entryCount>0); - /* hijack the loop to shift all other entries - down... */ - pPage->list[iKey] = NULL; - if(!pPage->next){ - --pPage->entryCount; - }else{ - /* Potential TODO: move empty pages - to the back of the list. */ - for( pPage = pPage->next; pPage; - prevPage = pPage, pPage = pPage->next ){ - if(!(prevPage->list[iKey] = pPage->list[iKey])){ - --prevPage->entryCount; - break; - } - else if(!pPage->next){ - pPage->list[iKey] = 0; - --pPage->entryCount; - } - } - } - rc = CWAL_RC_OK; -#if 0 - MARKER("REMOVING ENTRY %p for hash %u FROM PAGE #%u\n", (void*)pRet, iKey, x+1); -#endif - break; - } - } - break; - } - - return rc; -} - -int cwal_ptr_table_search( cwal_engine * e, - cwal_ptr_table * t, - cwal_value * key ){ - return cwal_ptr_table_op( e, t, key, CWAL_PTR_TABLE_OP_SEARCH ); -} -int cwal_ptr_table_insert( cwal_engine * e, - cwal_ptr_table * t, - cwal_value * key ){ - return cwal_ptr_table_op( e, t, key, CWAL_PTR_TABLE_OP_INSERT ); -} -int cwal_ptr_table_remove( cwal_engine * e, - cwal_ptr_table * t, - cwal_value * key ){ - return cwal_ptr_table_op( e, t, key, CWAL_PTR_TABLE_OP_REMOVE ); -} - -/** - Adds an entry in e->weakp for p, initializing e->weakp - if needed. -*/ -static int cwal_weak_annotate( cwal_engine * e, void * p ){ - int rc; - cwal_ptr_table * pt = &e->weakp; - if(!pt->pg.head){ - cwal_size_t const hashSize = 151 - /* We don't expect many weak refs, so we'll try - a relatively small hash size. */; - rc = cwal_ptr_table_create(e, &pt, hashSize, sizeof(void *) ); - if(rc) return rc; - assert(pt->pg.head); - } - rc = cwal_ptr_table_op( e, pt, p, CWAL_PTR_TABLE_OP_INSERT ); - /* MARKER(("Annotating %s weak ptr @%p insert rc=%d\n",cwal_type_id_name(tid),p,rc)); */ - switch(rc){ - case 0: - case CWAL_RC_ALREADY_EXISTS: - return 0; - default: - return rc; - } -} - -/** - If p is found in e->weakr[tid] then its (shared) cwal_weak_ref is - returned, otherwise 0 is returned. -*/ -static cwal_weak_ref * cwal_weak_ref_search( cwal_engine * e, void *p, cwal_type_id tid ){ - cwal_weak_ref * r; - assert(e && p && (tid>=CWAL_TYPE_UNDEF && tidweakr[tid]; - for( ; r && (r->value != p); r = r->next ){} - return r; -} - -/** - Removes the entry for p added by cwal_weak_annotate() and - unsets the value field of each cwal_weak_ref in - e->weakr[t] where value==p. -*/ -static int cwal_weak_unregister( cwal_engine * e, void * p, - cwal_type_id t ){ - assert(p); - assert(t>=CWAL_TYPE_UNDEF && tweakp.pg.head) return 0; - else{ - - int const rc = cwal_ptr_table_op( e, &e->weakp, p, - CWAL_PTR_TABLE_OP_REMOVE ); - switch(rc){ - case 0:{ - /* MARKER(("Invalidating %s weak ptr to %p\n",cwal_type_id_name(t),p)); */ - cwal_weak_ref * r = cwal_weak_ref_search( e, p, t ); - if(r) r->value = NULL - /* because we share instances for any given (p,t) - combination, there can be no more matches in the - list. */ - ; - return 0; - } - case CWAL_RC_NOT_FOUND: - return 0; - default: - return rc; - } - } -} - -bool cwal_is_weak_referenced( cwal_engine * e, void * p ){ - return (e && p) - ? (0==cwal_ptr_table_op( e, &e->weakp, p, - CWAL_PTR_TABLE_OP_SEARCH )) - : 0; -} - -/** - Makes wr the head of the cwal_weak_ref chain starting at - e->weakr[wr->typeID]. Returns 0 on success, and the only non-bug - error cases are CWAL_RC_OOM. -*/ -static int cwal_weak_ref_insert( cwal_engine * e, cwal_weak_ref * wr ){ - int rc; - assert(wr && (wr->typeID>=CWAL_TYPE_UNDEF && wr->typeIDvalue); - if(rc) return rc; - else{ - cwal_weak_ref * list; - assert(!wr->next); - list = e->weakr[wr->typeID]; - wr->next = list; - e->weakr[wr->typeID] = wr; - return 0; - } -} - -/** - Removes wr from e->weakr[wr->typeID] but does not free wr. -*/ -static void cwal_weak_ref_remove( cwal_engine * e, cwal_weak_ref * wr ){ - cwal_weak_ref * list; - cwal_weak_ref * prev = NULL; - assert(wr && (wr->typeID>=CWAL_TYPE_UNDEF && wr->typeIDweakr[wr->typeID]; - for( ; list; prev = list, list = list->next ){ - if(wr != list) continue; - else if(prev) prev->next = wr->next; - else e->weakr[wr->typeID] = wr->next; - wr->next = NULL; - break; - } - assert(wr == list); -} - -/** - Zeroes out r and either adds r to e->recycler (if there is space) or - frees it (if no recycling space is available). - - Preconditions: - - - neither argument may be 0. - - r->next must be 0. - - Postconditions: r must be treated as if this function freed it - (because semantically it does). - -*/ -static void cwal_weak_ref_free2( cwal_engine * e, cwal_weak_ref * r ){ - cwal_recycler * re = cwal_recycler_get(e, CWAL_TYPE_WEAK_REF); - assert(e && r && !r->next); - assert(!CWAL_MEM_IS_BUILTIN(r)); - if(re->maxLength>0 - && re->count < re->maxLength){ - *r = cwal_weak_ref_empty; - r->next = (cwal_weak_ref*)re->list; - re->list = r; - ++re->count; - } - else { - *r = cwal_weak_ref_empty; - cwal_free2( e, r, sizeof(cwal_weak_ref) ); - /* cwal_memchunk_add(e, r, sizeof(cwal_weak_ref)); */ - } -} - -void cwal_weak_ref_free( cwal_engine * e, cwal_weak_ref * r ){ - assert(e && r); - if(!e || !r || CWAL_MEM_IS_BUILTIN(r)) return; - else if(0==r->refcount || 0==--r->refcount){ - cwal_weak_ref_remove( e, r ); - cwal_weak_ref_free2(e, r); - } -} - -cwal_value * cwal_weak_ref_value( cwal_weak_ref * r ){ - if(!r||!r->value) return NULL; - else switch(r->typeID){ - case CWAL_TYPE_BOOL: - case CWAL_TYPE_NULL: - case CWAL_TYPE_UNDEF: - assert(r->value) - /* Because of how we allocate/share these, this will - always be true if r was validly allocated. */; - case CWAL_TYPE_ARRAY: - case CWAL_TYPE_BUFFER: - case CWAL_TYPE_DOUBLE: - case CWAL_TYPE_EXCEPTION: - case CWAL_TYPE_FUNCTION: - case CWAL_TYPE_HASH: - case CWAL_TYPE_INTEGER: - case CWAL_TYPE_NATIVE: - case CWAL_TYPE_OBJECT: - case CWAL_TYPE_STRING: - case CWAL_TYPE_UNIQUE: - case CWAL_TYPE_TUPLE: - return (cwal_value*)r->value; - case CWAL_TYPE_KVP: - case CWAL_TYPE_SCOPE: - case CWAL_TYPE_WEAK_REF: - return NULL; - case CWAL_TYPE_XSTRING: - case CWAL_TYPE_ZSTRING: - assert(!"Not possible"); - default: - assert(!"Unhandled type!"); - return NULL; - } -} - - -/** - Allocates a new cwal_weak_ref. If possible, it takes the head of - the recycler list, else is cwal_malloc()s it. The returned value must - eventually be passed to cwal_weak_ref_free() or - cwal_weak_ref_free2(), depending on its state at cleanup time. - - If cwal_weak_ref_search(e,ptr,tid) returns a value then this - function returns the same one. - - It is up to the caller to increment the return'd object's refcount. -*/ -static cwal_weak_ref * cwal_weak_ref_alloc( cwal_engine * e, void * ptr, - cwal_type_id tid ){ - cwal_weak_ref * r; - ++e->metrics.requested[CWAL_TYPE_WEAK_REF]; - r = cwal_weak_ref_search(e, ptr, tid); - if(!r){ - cwal_recycler * re = cwal_recycler_get(e, CWAL_TYPE_WEAK_REF); - r = (cwal_weak_ref *)re->list; - if(r){ - assert(re->count); - ++re->hits; - re->list = r->next; - --re->count; - }else{ - ++re->misses; - r = cwal_malloc2(e, sizeof(cwal_weak_ref)); - if(r){ - ++e->metrics.allocated[CWAL_TYPE_WEAK_REF]; - e->metrics.bytes[CWAL_TYPE_WEAK_REF] += sizeof(cwal_weak_ref); - } - } - if(r){ - *r = cwal_weak_ref_empty; - r->value = ptr; - r->typeID = tid; - } - if(cwal_weak_ref_insert(e, r)){ - cwal_weak_ref_free2(e, r); - r = NULL; - } - } - return r; -} - -cwal_weak_ref * cwal_weak_ref_new( cwal_value * v ){ - cwal_engine * e = v ? ((v && v->scope) ? v->scope->e : NULL) : NULL; - if(!e && !CWAL_MEM_IS_BUILTIN(v)) return NULL; - else{ - cwal_type_id const tid = v->vtab->typeID; - cwal_weak_ref * r = NULL; - switch(tid){ - case CWAL_TYPE_UNDEF: - r = &CWAL_BUILTIN_VALS.wref.wUndef; - break; - case CWAL_TYPE_NULL: - r = &CWAL_BUILTIN_VALS.wref.wNull; - break; - case CWAL_TYPE_BOOL: - r = (&CWAL_BUILTIN_VALS.vTrue == v) - ? &CWAL_BUILTIN_VALS.wref.wTrue - : &CWAL_BUILTIN_VALS.wref.wFalse; - break; - case CWAL_TYPE_STRING: - if(CWAL_BUILTIN_VALS.vEmptyString==v) r = &CWAL_BUILTIN_VALS.wref.wStrEmpty; - else{/* It's one of the length-1 strings */} - break; - case CWAL_TYPE_INTEGER:{ - /* - Shared weak-ref-to-int removed 20171202 because (A) - the built-in int range is now variable, (B) adding - static weak refs to all of them would be a huge waste - (weak refs to ints are NEVER used), and (C) ... i - forgot (C) while reformatting this comment :/. - */ - break; - } - case CWAL_TYPE_DOUBLE: - if(CWAL_MEM_IS_BUILTIN(v)){ - if(CWAL_BUILTIN_VALS.vDblM1==v) r = &CWAL_BUILTIN_VALS.wref.wDblM1; - else if(CWAL_BUILTIN_VALS.vDbl0==v) r = &CWAL_BUILTIN_VALS.wref.wDbl0; - else if(CWAL_BUILTIN_VALS.vDbl1==v) r = &CWAL_BUILTIN_VALS.wref.wDbl1; - else{assert(!"Impossible!");} - } - break; - default: - break; - } - if(!r){ - r = cwal_weak_ref_alloc(e, v, v->vtab->typeID); - if(r){ - assert(r->value == v); - assert(r->typeID == v->vtab->typeID); - ++r->refcount; - } - } - return r; - } -} - -cwal_weak_ref * cwal_weak_ref_custom_new( cwal_engine * e, void * p ){ - if(!e || CWAL_MEM_IS_BUILTIN(p)) return NULL; - else{ - cwal_weak_ref * r = cwal_weak_ref_alloc(e, p, CWAL_TYPE_WEAK_REF); - if(r){ - assert(r->value == p); - assert(r->typeID == CWAL_TYPE_WEAK_REF); - ++r->refcount; - } - return r; - } -} - -void * cwal_weak_ref_custom_ptr( cwal_weak_ref * r ){ - return (r && (CWAL_TYPE_WEAK_REF==r->typeID)) - ? r->value - : NULL; -} - -void * cwal_weak_ref_custom_check( cwal_engine * e, void * p ){ - if(!e || !p) return NULL; - else{ - cwal_weak_ref * r = cwal_weak_ref_search(e, p, CWAL_TYPE_WEAK_REF); - if(r){ - assert(r->value==p); - } - return r ? r->value : NULL; - } -} - -bool cwal_weak_ref_custom_invalidate( cwal_engine * e, void * p ){ - if(!e || !p) return 0; - else{ - cwal_weak_ref * r = cwal_weak_ref_search(e, p, CWAL_TYPE_WEAK_REF); - if(r) r->value = NULL; - return r ? 1 : 0; - } -} - - -static int cwal_engine_init_interning(cwal_engine * e){ - cwal_ptr_table * t = &e->interned; - /* notes to self regarding table size... - - The following gives me a really good fill rate for - the low page (over 90%) for 500 random strings: - - entries= 3*1024/(2*sizeof(void*)) - - hashSize= trim_hash(entriesPerPage*33/50) - - But lots of tables (9 on average, it seems) - - */ - uint16_t const entriesPerPage = -#if 0 - /* testing a leak of interned strings. */ - 3 -#elif 0 - 1024 * 4 / sizeof(void*) -#elif 0 - 281 /* mediocre */ -#elif 1 - 379 /* reasonable */ -#elif 0 - 503 -#else - /*cwal_trim_hash_size(200)*/ - /* not bad 240 */ - /* 281 seems to give a good size for 500-string tests. */ - 512 * 5 / (sizeof(void*)) /* also not too bad, about 2.5kb/page (64-bit), low page count. */ - /* One test: with a table size of 3163 we got - over 90% in the first hit and 99% in the - second hit with 478 strings. - - With 433 entries/page we got about 58% - in the 1st hit, 85 in the 2nd hit. - - After much experimentation, a starting page size of about - 550 seems to provide a good basis here. Increasing the size - by 8 (later: 8 what?) doesn't give us many fewer tables and - does cost a lot more memory. - */ -#endif - ; - uint16_t const hashSize = - cwal_trim_hash_size(entriesPerPage); - uint16_t const stepSize = 0 /* not actually used by this particular table */; - /*MARKER("INTERNED STRING TABLE hashSize=%u stepSize=%u\n", hashSize, stepSize);*/ - return cwal_ptr_table_create(e, &t, hashSize, stepSize ); -} - - - -cwal_hash_t cwal_hash_bytes( void const * _zKey, cwal_size_t nKey ){ - unsigned char const * zKey = (unsigned char const *)_zKey; -#if 0 - /* - FNV-xx. These both well for our typical inputs. Marginally more - collisions when using the 32-bit seeds on 64-bit arch. - */ -# if CWAL_SIZE_T_BITS < 64 - cwal_hash_t const prime = 16777619U; - cwal_hash_t const offset = 2166136261U; -# else - cwal_hash_t const prime = 1099511628211U; - cwal_hash_t const offset = 14695981039346656037U; -# endif - cwal_size_t i; - cwal_hash_t hash = offset; - for( i = 0; i < nKey; ++i ){ -# if 0 - /* FNV-1 */ - hash = hash * prime; - hash = hash ^ zKey[i]; -# else - /* FNV-1a */ - /* Works a tick better than FNV-1 in my tests */ - hash = hash ^ zKey[i]; - hash = hash * prime; -# endif - } - return hash; - /* end FNV-1/1a */ -#elif 0 - /* - CRC32a: http://www.hackersdelight.org/hdcodetxt/crc.c.txt - */ -# define reverse(x) \ - x = ((x & 0x55555555) << 1) | ((x >> 1) & 0x55555555); \ - x = ((x & 0x33333333) << 2) | ((x >> 2) & 0x33333333); \ - x = ((x & 0x0F0F0F0F) << 4) | ((x >> 4) & 0x0F0F0F0F); \ - x = (x << 24) | ((x & 0xFF00) << 8) | \ - ((x >> 8) & 0xFF00) | (x >> 24) - int i, j; - cwal_hash_t byte, crc; - cwal_size_t n; - i = 0; - crc = 0xFFFFFFFF; - for( n = 0; n < nKey; ++n ){ - byte = (unsigned char)zKey[i]; - reverse(byte); - for (j = 0; j <= 7; j++) { - if ((int)(crc ^ byte) < 0) - crc = (crc << 1) ^ 0x04C11DB7; - else crc = crc << 1; - byte = byte << 1; - } - i = i + 1; - } - crc = ~crc; - reverse(crc); - return crc; -# undef reverse -#elif 0 - /* - CRC32b: http://www.hackersdelight.org/hdcodetxt/crc.c.txt - */ - int j; - unsigned char byte; - cwal_hash_t crc, mask; - cwal_size_t n = 0; - crc = 0xFFFFFFFF; - for ( ; n < nKey; ++n) { - byte = (unsigned char)zKey[n]; - crc = crc ^ byte; - for (j = 7; j >= 0; j--) { - mask = -(crc & 1); - crc = (crc >> 1) ^ (0xEDB88320 & mask); - } - } - return ~crc; -#elif 0 - /* - CRC32e: http://www.hackersdelight.org/hdcodetxt/crc.c.txt - - HOLY COW: this collides about every 2nd string! - - Worst. Hash. Ever. - - Seriously, in the s2 unit tests: interning tables with space for - 379 entries each, holdling a total of 264 strings: 32 tables are - needed with this hash! - */ - int j; - cwal_hash_t byte, c; - cwal_int_t crc; - cwal_size_t i; - const unsigned int g0 = 0xEDB88320, g1 = g0 >> 1, - g2 = g0 >> 2, g3 = g0 >> 3; -# if CWAL_SIZE_T_BITS < 64 - crc = 0xFFFFFFFF; -# else - crc = 0xFFFFFFFFFFFFFFFF; -# endif - for(i = 0; i < nKey; ++i ){ - byte = (unsigned char)zKey[i]; - crc = crc ^ byte; - for (j = 1; j >= 0; j--) { - c = ((crc<<31>>31) & g3) ^ ((crc<<30>>31) & g2) ^ - ((crc<<29>>31) & g1) ^ ((crc<<28>>31) & g0); - crc = ((unsigned)crc >> 4) ^ c; - } - i = i + 1; - } - return (cwal_hash_t)~crc; -#elif 1 - /* another experiment... */ - /* 20181122: this one seems to perform the best for the s2 unit - test suite, measured in terms of how many string interning - tables get allocated and how tightly packed they get. */ - cwal_hash_t h = 0; - unsigned char const * p = (unsigned char const *)zKey; - cwal_size_t i = 0; - /* This one performs a tick better than FNV-1a in my brief tests */ - for( ; i> shift)) & mask; - } -# elif 0 - /* This one seems to perform (hash-wise) pretty well, by just a tick, - based on simple tests with the string interning table. - It's just a tiny tick slower than option #1. - - This hash in combination with a table size of 547 performs - quite well for my pseudo-scientific random-strings tests. - - Longer-term tests show it not to perform as well as FNV - for s2's unit tests. - */ - /* "djb2" algo code taken from: http://www.cse.yorku.ca/~oz/hash.html */ - static const cwal_hash_t seed = 5381; - char const * vstr = (char const *)zKey; - cwal_hash_t hash = seed; - cwal_size_t i = 0; - for( ; iinterned; - if( !t->pg.head ) return CWAL_RC_NOT_FOUND; - iKey = (uint16_t)(cwal_hash_bytes( zKey, nKey ) % t->hashSize); - if(itemIndex) *itemIndex = iKey; - for(pPage = t->pg.head; pPage; pPage = pPage->next ){ - pRet = (cwal_value*)pPage->list[iKey]; - if(!pRet) break /* end of the table list */; - else if(pRet){ - cwal_string const * sRet = CWAL_STR(pRet); - assert(sRet); - if(sRet && - (CWAL_STRLEN(sRet) == nKey) - && (0 == memcmp( cwal_string_cstr(sRet), - zKey, nKey ))){ - if(out) *out = pRet; - if(pageIndex) *pageIndex = pPage; - return CWAL_RC_OK; - } - } - } - return CWAL_RC_NOT_FOUND; -} - -int cwal_interned_search_val( cwal_engine * e, - cwal_value const * v, - cwal_value ** out, - cwal_ptr_page ** pageIndex, - uint16_t * itemIndex ){ - cwal_ptr_page * pPage = NULL; - cwal_value * pRet = NULL; - uint16_t iKey = 0; - cwal_ptr_table *t; - if(!e || !v) return CWAL_RC_MISUSE; - t = &e->interned; - if( !t->pg.head ) return CWAL_RC_NOT_FOUND; - iKey = (uint16_t)(v->vtab->hash(v) % t->hashSize); - if(itemIndex) *itemIndex = iKey; - for(pPage = t->pg.head; pPage; pPage = pPage->next ){ - pRet = (cwal_value*)pPage->list[iKey]; - if(!pRet) break /* end of the table list for this hash */; - else if(pRet){ - if((v==pRet) - || ((v->vtab == pRet->vtab /* enforce strict type comparisons */) - && (0 == v->vtab->compare(v, pRet)))){ - if(out) *out = pRet; - if(pageIndex) *pageIndex = pPage; - return CWAL_RC_OK; - } - } - } - return CWAL_RC_NOT_FOUND; -} - - -int cwal_interned_insert( cwal_engine * e, cwal_value * v ){ - cwal_ptr_page * pPage = NULL; - cwal_ptr_page * pageIndex = NULL; - cwal_value * pRet = NULL; - uint16_t iKey = 0; - int rc; - cwal_ptr_table * t; - if(!(CWAL_FEATURE_INTERN_STRINGS & e->flags)) return CWAL_RC_UNSUPPORTED; - else if(!e || !v) return CWAL_RC_MISUSE; - t = &e->interned; - if(!t->pg.head){ - rc = cwal_engine_init_interning( e ); - if(rc) return rc; - assert(t->pg.head); - } - - rc = cwal_interned_search_val( e, v, &pRet, &pageIndex, &iKey ); - if( pRet ) { - assert(pageIndex); - assert( (pRet == v) && "i'm fairly sure this holds with the current code."); - return CWAL_RC_ALREADY_EXISTS; - } - assert(!pageIndex); - - /** - Search just failed, so we need to add an entry. Check if one - of our existing pages has a slot... - */ - for(pPage = t->pg.head; pPage; pPage = pPage->next ){ - pRet = pPage->list[iKey]; - if(!pRet) goto insert; - } - if(!pPage){ - /* We reached the end of the table and found no empty slot - (maybe had a collision). Add a page and insert the value - there. */ - rc = cwal_ptr_table_add_page( e, t ); - if(rc) return rc; - pPage = t->pg.tail; - } - insert: - rc = CWAL_RC_OK; - assert(NULL != pPage); - assert(!pPage->list[iKey]); - pPage->list[iKey] = v; - CWAL_TR_VCS(e,v); - CWAL_TR2(e,CWAL_TRACE_VALUE_INTERNED); - ++pPage->entryCount; - return rc; -} - -int cwal_interned_remove( cwal_engine * e, - cwal_value const * v, - cwal_value ** out ){ - cwal_ptr_page * pPage = 0; - cwal_value * pRet = NULL; - cwal_ptr_table * t; - uint16_t iKey = 0; - cwal_ptr_page * pageIndex = NULL; - int rc; - if(!e || !v) return CWAL_RC_MISUSE; - t = &e->interned; - if(!t->pg.head) return CWAL_RC_NOT_FOUND; - - rc = cwal_interned_search_val( e, v, &pRet, &pageIndex, &iKey ); - if( !pRet ) { - assert( CWAL_RC_NOT_FOUND == rc ); - return rc; - } - else if(rc){ - assert(!"Cannot happen"); - return rc; - } - if( out ) *out = pRet; - CWAL_TR_VCS(e,pRet); - CWAL_TR2(e,CWAL_TRACE_VALUE_UNINTERNED); - assert( pageIndex ); - for( pPage = pageIndex; pPage; pPage = pPage->next ){ - /* Remove the entry. If any higher-level pages contain that - key, move it into this page (up through to the top-most - page which has a matching key). - */ - pPage->list[iKey] = pPage->next - ? pPage->next->list[iKey] - : 0; - if( !pPage->list[iKey] ) { - --pPage->entryCount; - break; - } - } - assert( pPage && (0 == pPage->list[iKey]) ); - return CWAL_RC_OK; -} - -cwal_obase * cwal_value_obase( cwal_value * const v ){ - return CWAL_VOBASE(v); -} - - -void cwal_value_cleanup_noop( cwal_engine * e, void * v ){ - if(e || v){/*avoid unused param warning*/} -} - -void cwal_value_cleanup_integer( cwal_engine * e, void * self ){ -#if 1 - /* Only disable this block when chasing bugs. */ - cwal_value * v = (cwal_value *)self; - *CWAL_INT(v) = 0; -#endif - if(e){/*avoid unused param warning*/} -} - -void cwal_value_cleanup_double( cwal_engine * e, void * self ){ - static const cwal_double_t zero = 0.0; - cwal_value * v = (cwal_value *)self; - memcpy(CWAL_DBL_NONULL(v), &zero, sizeof(cwal_double_t)); - if(e){/*avoid unused param warning*/} -} - - -void cwal_value_cleanup_unique( cwal_engine * e, void * self ){ - cwal_value * v = (cwal_value *)self; - cwal_value ** wrapped = CWAL_UNIQUE_VALPP(v); - if(e){/*avoid unused param warning*/} - assert(wrapped); - if(*wrapped){ - cwal_value * w = *wrapped; - *wrapped = 0; - if(!CWAL_V_IS_IN_CLEANUP(w)){ - /* - Without this is-in-cleanup check, code like the - following (s2) crashes here during scope cleanup: - - var e = enum {a:{x:1},b:{x:2}}; - e.a.value.b = e.b; - e.b.value.a = e.a; - - 20180105: a string key and its Unique-type wrapper were - being cleaned up during scope cleanup and the string got - recycled (as one does) during that process before the - Unique wrapper did. That ended up triggering the - assert() below. As of 20180105, the cleanup process - gc-queues all values, not just containers, which - resolves this case. It's just amazing that it didn't - trigger sooner. - - Addenda: the root cause, it turns out, is that Uniques - and Tuples live in the cwal_scope::mine::headPod list, - not headObj, and can therefore be destroyed after their - values are. - */ - assert( CWAL_REFCOUNT(w) || CWAL_MEM_IS_BUILTIN(w) ); - cwal_value_unref(w); - } - } -} - -void cwal_value_cleanup_tuple( cwal_engine * e, void * self ){ - cwal_value * v = (cwal_value *)self; - cwal_tuple * p = CWAL_TUPLE(v); - cwal_size_t i; - assert(p && p->n); - for( i = 0; i < p->n; ++i ){ - /* hashtag CWAL_V_GOES_IN_HEADOBJ */ - if(!CWAL_V_IS_IN_CLEANUP(p->list[i])){ - /* ^^^ cleanup check is hypothetically needed for certain - constellations because Tuples are managed via the - cwal_scope::headPod list, not headObj. That said, it's - never been seen to trigger a problem before (probably - because tuples are seldom used?).*/ - cwal_value_unref(p->list[i]); - } - p->list[i] = 0; - } - cwal_free2(e, p->list, sizeof(cwal_value*) * p->n); - *p = cwal_tuple_empty; -} - -cwal_type_id cwal_value_type_id( cwal_value const * v ){ - return (v && v->vtab) ? v->vtab->typeID : CWAL_TYPE_UNDEF; -} - -cwal_value_type_name_proxy_f cwal_engine_type_name_proxy( cwal_engine * e, - cwal_value_type_name_proxy_f f ){ - cwal_value_type_name_proxy_f rc = e ? e->type_name_proxy : 0; - if(e) e->type_name_proxy = f; - return rc; -} - -char const * cwal_value_type_name2( cwal_value const * v, - cwal_size_t * len){ - if(!v || !v->vtab) return NULL; - else{ - cwal_engine const * e = v->scope ? v->scope->e : NULL; - char const * rc = NULL; - if(e && e->type_name_proxy){ - rc = e->type_name_proxy(v, len); - } - if(!rc){ - rc = v->vtab->typeName; - if(rc && len) *len = cwal_strlen(rc); - } - return rc; - } -} - -char const * cwal_value_type_name( cwal_value const * v ){ - return v ? cwal_value_type_name2(v, NULL) : NULL; -} - -char const * cwal_type_id_name( cwal_type_id id ){ - cwal_value_vtab const * t = 0; - switch(id){ - case CWAL_TYPE_BOOL: t = &cwal_value_vtab_bool; break; - case CWAL_TYPE_UNDEF: t = &cwal_value_vtab_undef; break; - case CWAL_TYPE_NULL: t = &cwal_value_vtab_null; break; - case CWAL_TYPE_STRING: t = &cwal_value_vtab_string; break; - case CWAL_TYPE_INTEGER: t = &cwal_value_vtab_integer; break; - case CWAL_TYPE_DOUBLE: t = &cwal_value_vtab_double; break; - case CWAL_TYPE_ARRAY: t = &cwal_value_vtab_array; break; - case CWAL_TYPE_OBJECT: t = &cwal_value_vtab_object; break; - case CWAL_TYPE_NATIVE: t = &cwal_value_vtab_native; break; - case CWAL_TYPE_BUFFER: t = &cwal_value_vtab_buffer; break; - case CWAL_TYPE_FUNCTION: t = &cwal_value_vtab_function; break; - case CWAL_TYPE_EXCEPTION: t = &cwal_value_vtab_exception; break; - case CWAL_TYPE_HASH: t = &cwal_value_vtab_hash; break; - case CWAL_TYPE_UNIQUE: t = &cwal_value_vtab_unique; break; - case CWAL_TYPE_TUPLE: t = &cwal_value_vtab_tuple; break; - case CWAL_TYPE_SCOPE: return "cwal_scope"; - case CWAL_TYPE_KVP: return "cwal_kvp"; - case CWAL_TYPE_WEAK_REF: return "cwal_weak_ref"; - case CWAL_TYPE_XSTRING: return "x-string"; - case CWAL_TYPE_ZSTRING: return "z-string"; - case CWAL_TYPE_LISTMEM: return "cwal_list"; - default: break; - } - return t ? t->typeName : NULL; -} - -bool cwal_value_is_undef( cwal_value const * v ){ - return ( !v || !v->vtab || (v->vtab==&cwal_value_vtab_undef)) - ? 1 : 0; -} - -#define ISA(T,TID) bool cwal_value_is_##T( cwal_value const * v ) { \ - /*return (v && v->vtab) ? cwal_value_is_a(v,CWAL_TYPE_##TID) : 0;*/ \ - return (v && (v->vtab == &cwal_value_vtab_##T)) ? 1 : 0; \ - } - -ISA(null,NULL) - ISA(bool,BOOL) - ISA(integer,INTEGER) - ISA(double,DOUBLE) - ISA(string,STRING) - ISA(array,ARRAY) - ISA(object,OBJECT) - ISA(native,NATIVE) -/* ISA(buffer,BUFFER) */ - ISA(function,FUNCTION) - ISA(exception,EXCEPTION) - ISA(hash,HASH) - ISA(unique,UNIQUE) - ISA(tuple,TUPLE) -#undef ISA - - - bool cwal_value_is_buffer( cwal_value const * v ){ - cwal_buffer_obj const * bo = CWAL_BUFOBJ(v); - assert(bo ? (bo==bo->buf.self) : 1); - return (bo && bo == bo->buf.self) ? 1 : 0; -} - -bool cwal_value_is_number( cwal_value const * v ){ - if(!v) return 0; - else switch(v->vtab->typeID){ - case CWAL_TYPE_INTEGER: - case CWAL_TYPE_DOUBLE: - case CWAL_TYPE_BOOL: - return 1; - default: - return 0; - } -} - - -void cwal_finalizer_f_fclose( cwal_engine * e, void * m ){ - if(e){/*avoid unused param warning*/} - if(m && (m != stdout) && (m != stderr) && (m != stdin)){ - fclose( (FILE*)m ); - } -} - -void * cwal_realloc_f_std( void * state, void * m, cwal_size_t n ){ - if( 0 == n ){ - free( m ); - return NULL; - }else if( !m ){ - return malloc( n ); - }else{ - if(state){/*avoid unused param warning*/} - return realloc( m, n ); - } -} - -int cwal_output_f_FILE( void * state, void const * src, cwal_size_t n ){ - if( !state || !src || !n ) return 0; - return (1 == fwrite( src, n, 1, state ? (FILE*)state : stdout )) - ? CWAL_RC_OK - : CWAL_RC_IO; -} - -int cwal_output_flush_f_FILE( void * f ){ - return fflush(f ? (FILE*)f : stdout) - ? CWAL_RC_IO - : 0 - ; -} - -int cwal_output_f_buffer( void * state, void const * src, cwal_size_t n ){ - cwal_output_buffer_state * ob = (cwal_output_buffer_state*) state; -#if 1 - return cwal_buffer_append(ob->e, ob->b, src, n); -#else - int rc = 0; - cwal_output_buffer_state * ob = (cwal_output_buffer_state *)state_; - cwal_size_t sz = ob->b->used+n+1; - if(sz > ob->b->capacity){ - /* TODO? expand by some factor */ - /* sz = sz * 13 / 10; */ - rc = cwal_buffer_reserve(ob->e, ob->b, sz); - } - if(!rc){ - rc = cwal_buffer_append( ob->e, ob->b, n ); - } - return rc; -#endif -} - -void cwal_output_buffer_finalizer( cwal_engine * e, void * m ){ - cwal_output_buffer_state * ob = (cwal_output_buffer_state *)m; - assert(ob->e == e); - cwal_buffer_reserve(e, ob->b, 0); - ob->e = NULL; - *ob = cwal_output_buffer_state_empty; -} - -void * cwal_malloc( cwal_engine * e, cwal_size_t n ){ - unsigned char * rc = 0; - cwal_size_t const origN = n; - if(!e || !n || !e->vtab) return 0; - n = CWAL_MEMSZ_PAD(n); - if(CWAL_F_TRACK_MEM_SIZE & e->flags){ - n += sizeof(void*) - /* To store the size in. Must be generically aligned, thus - we don't use sizeof(uint32_t). */; -#if 64==CWAL_SIZE_T_BITS - if(n > 0xFFFFFFFF){ - /* b/c our size marker is explicitly uint32_t. */ - return NULL; - } -#endif - } - CWAL_TR_MEM(e,rc,n); - if(n < origN) return NULL /* overflow after adjustment */; - else if(/* Check cap constraints... */ - /* too-large single alloc */ - (e->vtab->memcap.maxSingleAllocSize - && (n > e->vtab->memcap.maxSingleAllocSize)) - || /* too many concurrent allocs */ - (e->vtab->memcap.maxConcurrentAllocCount - && (e->memcap.currentAllocCount - >= e->vtab->memcap.maxConcurrentAllocCount)) - || /* too much concurrent memory */ - (e->vtab->memcap.maxConcurrentMem - && (e->memcap.currentMem + n - > e->vtab->memcap.maxConcurrentMem)) - || /* too many total allocs */ - (e->vtab->memcap.maxTotalAllocCount - && (e->memcap.totalAllocCount - >= e->vtab->memcap.maxTotalAllocCount)) - || /* Too much total memory... */ - (e->vtab->memcap.maxTotalMem - && (e->memcap.currentMem + n - > e->vtab->memcap.maxTotalMem)) - ){ - return 0; - } - rc = (unsigned char *) - e->vtab->allocator.realloc( e->vtab->allocator.state.data, NULL, n ); - if(rc){ - if( ++e->memcap.currentAllocCount > e->memcap.peakAllocCount ){ - e->memcap.peakAllocCount = - e->memcap.currentAllocCount; - } - e->memcap.totalMem += n; - ++e->memcap.totalAllocCount; - if(CWAL_F_TRACK_MEM_SIZE & e->flags){ - /* Stamp the size and adjust rc. */ - cwal_memsize_t * sz = (cwal_memsize_t*)rc; - *sz = (cwal_memsize_t)n; - rc += sizeof(void*); - e->memcap.currentMem += n - /* We can only decrement this if overallocating, so - only increment if we overallocate. */; - if(e->memcap.peakMem < e->memcap.currentMem){ - e->memcap.peakMem = e->memcap.currentMem; - } - } - } - CWAL_TR2(e,CWAL_TRACE_MEM_MALLOC); - return rc; -} - -void * cwal_malloc2( cwal_engine * e, cwal_size_t n ){ - cwal_size_t newN = n; - void * rc = cwal_memchunk_request(e, &newN, - (CWAL_F_TRACK_MEM_SIZE & e->flags) - ? 150 : 125 - /* If over-allocation/tracking - is on, we can recover all - slack bytes when the mem is - passed to cwal_free2(), so - allow more leeway in the size - of the recycled chunk. */, - "cwal_malloc2()"); - if(!rc){ - rc = cwal_malloc(e, n); - } - return rc; -} - - -void cwal_free( cwal_engine * e, void * m ){ - if(e && m){ - assert(e != m /* check for this corner case: e is allocated - before cwal_malloc() and friends are - configured, so e was allocated on the stack or - before CWAL_F_TRACK_MEM_SIZE could take - effect. */); - if(CWAL_F_TRACK_MEM_SIZE & e->flags){ - cwal_memsize_t * sz = MEMSZ_PTR_FROM_MEM(m); - assert(e->memcap.currentMem >= *sz); - e->memcap.currentMem -= *sz; - m = sz; - } - CWAL_TR_MEM(e,m,0); - CWAL_TR2(e,CWAL_TRACE_MEM_FREE); - e->vtab->allocator.realloc( e->vtab->allocator.state.data, m, 0 ); - --e->memcap.currentAllocCount; - } -} - -void cwal_free2(cwal_engine * e, void * mem, cwal_size_t size ){ - assert(e); - if(mem){ - assert(e != mem /* check for this corner case: e is allocated - before cwal_malloc() and friends are - configured, so e was allocated on the stack or - before CWAL_F_TRACK_MEM_SIZE could take - effect. */); - if(size) cwal_memchunk_add(e, mem, size); - else cwal_free(e, mem); - } -} - -void * cwal_realloc( cwal_engine * e, void * m, cwal_size_t n ){ - if(!e || !e->vtab) return 0; - else if( 0 == n ){ - cwal_free( e, m ); - return NULL; - }else if( !m ){ - return cwal_malloc( e, n ); - }else{ - unsigned char * rc; - uint32_t oldSize = 0; - cwal_size_t const origN = n; - n = CWAL_MEMSZ_PAD(n); - if(CWAL_F_TRACK_MEM_SIZE & e->flags){ - cwal_memsize_t * sz = MEMSZ_PTR_FROM_MEM(m); - oldSize = *sz; - assert(oldSize>0); - assert(e->memcap.currentMem >= oldSize); - m = sz; - n += sizeof(void*); -#if 64==CWAL_SIZE_T_BITS - if(n > 0xFFFFFFFF){ - /* b/c our size marker is explicitly uint32_t. */ - return NULL; - } -#endif - } - CWAL_TR_MEM(e,m,n); - CWAL_TR2(e,CWAL_TRACE_MEM_REALLOC); - if(n < origN) return NULL /* overflow after adjustment */; - else if(/* Allocation is too big... */ - (e->vtab->memcap.maxSingleAllocSize - && (n > e->vtab->memcap.maxSingleAllocSize)) - || /* Too much concurrent memory... */ - (e->vtab->memcap.maxConcurrentMem - && (e->memcap.currentMem - oldSize + n - > e->vtab->memcap.maxConcurrentMem)) - || /* Too much total memory... */ - (e->vtab->memcap.maxTotalMem - && (e->memcap.currentMem + n - > e->vtab->memcap.maxTotalMem)) - ){ - rc = NULL; - }else{ - rc = (unsigned char*) - e->vtab->allocator.realloc( e->vtab->allocator.state.data, - m, n ); - if(rc && (CWAL_F_TRACK_MEM_SIZE & e->flags)){ - /* update e->memcap, re-stamp memory size */ - cwal_memsize_t * sz = (cwal_memsize_t*)rc; - *sz = n; - rc += sizeof(void*); - e->memcap.currentMem -= oldSize; - e->memcap.currentMem += n; - } - } - return rc; - } -} - -static cwal_size_t cwal_scope_sweep_r0( cwal_scope * s ){ - cwal_engine * e = s->e; - cwal_value * v; - cwal_value * n; - cwal_size_t rc = 0; - cwal_value * r0 = s->mine.r0; - assert(e); - CWAL_TR_MSG(e,"s->mine.r0:"); - CWAL_TR_SV(e,s,s->mine.r0); - CWAL_TR2(e,CWAL_TRACE_SCOPE_MASK); - s->mine.r0 = NULL; - for(v = r0; v; v = n ){ - n = v->right; - if(v->scope!=s) { - dump_val(v,"Check for scope mismatch"); - assert(!v->left); - if(v->right) dump_val(v->right,"v->right"); - } - assert(v->scope==s); - v->left = v->right = 0; - if(n){ - assert(n->scope==s); - n->left = 0; - } - /* The "special" propagating values always get a reference, - and therefore cannot be in the r0 list. */ - assert(e->values.exception != v); - assert(e->values.propagating != v); - cwal_value_unref2(e,v); - ++rc; - } - return rc; -} - -cwal_size_t cwal_engine_sweep2( cwal_engine * e, char allScopes ){ - if(!e) return 0; - else if(!allScopes){ - return cwal_scope_sweep_r0(e->current); - } - else { - cwal_scope * s = e->current; - cwal_size_t rc = 0; - for( ; s; s = s->parent ){ - rc += cwal_scope_sweep_r0(s); - } - return rc; - } -} - -cwal_size_t cwal_engine_sweep( cwal_engine * e ){ - return (e && e->current) - ? cwal_scope_sweep_r0(e->current) - : 0; -} - -cwal_size_t cwal_scope_sweep( cwal_scope * s ){ - return (s && s->e) - ? cwal_scope_sweep_r0(s) - : 0; -} - -/** - calls cwal_value_snip() to snip v from any chain and moves v to the - head of one of s->mine's members (depending on a couple of - factors). Does not modify refcount. - - Reminder to self: this is also used to move v around within - s->mine's various lists, so v->scope may be s. - - It only returns non-0 if it sets s->e->fatalCode. -*/ -static int cwal_scope_insert( cwal_scope * s, cwal_value * v ); - -/** - Removes v from its owning scope and places it in s->mine.r0, - putting it back in the probationary state. v MUST have a refcount - of 0 and CWAL_MEM_IS_BUILTIN(v) MUST be false. s MUST be the scope to - reprobate v to. -*/ -static void cwal_value_reprobate( cwal_scope * s, cwal_value * v){ - /* int rc; */ - assert(v); - assert(!CWAL_REFCOUNT(v)); - assert(!CWAL_MEM_IS_BUILTIN(v)); - assert(s); - assert(s->e); - /* dump_val(v,"Re-probating value"); */ - cwal_scope_insert(s, v); - /* dump_val(v,"Re-probated value"); */ -} - -/** - "Snips" v from its left/right neighbors. If v->scope and v is the - head of one of v->scope->mine's ownership lists then the list is - adjusted to point to v->left (if set) or v->right. Also sets - v->scope to 0. - - Returns the right-hand neighbor of v, or 0 if it has no neighbor. -*/ -static cwal_value * cwal_value_snip( cwal_value * v ); - -/** - Internal helper to move a refcount==0 value from the r0 list to one - of the "longer-lived" lists. Returns 0 on success. - - CWAL_REFCOUNT(v) must be 1 (not 0) when this is called, and must have - just gone from 0 to 1, as opposed to going from 2 to 1. -*/ -static int cwal_scope_from_r0( cwal_value * v ){ - cwal_scope * s = v->scope; - assert(1==CWAL_REFCOUNT(v)); - if(!s->mine.r0) return CWAL_RC_NOT_FOUND; - else if(1!=CWAL_REFCOUNT(v)) return CWAL_RC_RANGE - /* Only to ensure that caller ++'s it before calling this, so - that the cwal_scope_insert() call below can DTRT. */ - ; - cwal_scope_insert( s, v ) /* does the list shuffling */; - if(E_IS_DEAD(s->e)) return s->e->fatalCode; - assert(v->scope == s); - return 0; -} - -/** - Returns the number of values in s->mine's various lists. An O(N) - operation, N being the number returned (not incidentally). -*/ -static cwal_size_t cwal_scope_value_count( cwal_scope const * s ){ - cwal_size_t n = 0; - cwal_value const * v; -# define VCOUNT(WHO) v = WHO; while(v){++n; v=v->right;} (void)0 - VCOUNT(s->mine.headPod); - VCOUNT(s->mine.headObj); - VCOUNT(s->mine.headSafe); - VCOUNT(s->mine.r0); -#undef VCOUNT - return n; -} - -/** - This function frees the internal state of s but does not free s. - If any of the specially-propagating values live in s, they are - re-scoped/moved to s's parent unless s is the top-most scope. in - which case they get cleaned up. -*/ -int cwal_scope_clean( cwal_engine * e, cwal_scope * s ){ - int rc = 0; - cwal_value * v; - char iInitedGc = 0; - if(!e->gcInitiator) { - iInitedGc = 1; - e->gcInitiator = s; - CWAL_TR_S(e,s); - CWAL_TR3(e,CWAL_TRACE_MESSAGE,"Initializing gc capture."); - } - - CWAL_TR_S(e,s); - CWAL_TR3(e,CWAL_TRACE_SCOPE_CLEAN_START,"Scope cleanup starting."); - /* prohibits vacuum: assert(e->current != s); */ - /* Special treatment of e->values.exception and e->values.propagating. */ - { - cwal_value * vPropagate; - int phase = 1; - propagate_next: - vPropagate = (1==phase ? e->values.exception : e->values.propagating); - if(vPropagate && vPropagate->scope == s){ - cwal_scope * parent = (s==e->current /* vacuum op */) ? s->parent : e->current; - CWAL_TR_SV(e,s,vPropagate); - CWAL_TR3(e,CWAL_TRACE_SCOPE_MASK,"Relocating vPropagate..."); - if(!parent){ - if(1==phase) cwal_exception_set(e, 0); - else cwal_propagating_set(e, 0); - assert((1==phase) ? 0==e->values.exception : 0==e->values.propagating); - }else{ - rc = cwal_value_xscope( e, parent, vPropagate, NULL ); -#if 0 - /* we really should soldier on and clean up, but - we'd be doing so on possibly corrupt memory! - - 20200111: that said, this operation has never - failed in practice. */ - if(rc){ - assert(rc == e->fatalCode); - return e->fatalCode; - } -#endif - assert(!rc && "Cannot fail anymore?"); - assert(vPropagate && (vPropagate->scope!=s)); - CWAL_TR_SV(e,vPropagate->scope,vPropagate); - CWAL_TR3(e,CWAL_TRACE_SCOPE_MASK,"Moved EXCEPTION/PROPAGATING to next scope up."); - } - } - if(2==++phase) goto propagate_next; - } - - if(s->props){ - cwal_value * const pv = s->props; - cwal_obase * const obase = CWAL_VOBASE(pv); - assert(pv); - assert(obase); - assert(pv->scope && "It's not possible to have no scope at this point."); - assert((pv->scope==s || (pv->scope->levellevel)) - && "Scoping/lifetime precondition violation."); - assert((CWAL_REFCOUNT(pv)>0) && "Who stole my properties ref?"); - /* - If CWAL_REFCOUNT(pv)>1 then we know that "someone" still - holds a reference. During/after scope cleanup, using such a - reference is illegal, so we don't really care about - that. What we do care about is if... - - If we set the vacuum-safe flag on pv, we also need to turn - off the flag, but... If a client gets a handle to pv and - explicitely sets it to vacuum-safe then we can no longer - know (without a new flag) that we are the ones who set the - vacuum-proofing flag, so unsetting it here "could be bad." - One solution would be to use another flag bit in cwal_obase - to mark property storage objects as being so, and unmark - them if they are ever removed from their initial scope. It - is possible/legal that an older scope holds a reference to - pv, and in that case pv->scope!=s. So we can use that info - to determine whether this scope really owns pv or not, which - may help us do... something or other useful... - - So CWAL_F_IS_PROP_STORAGE is born... - */ - assert(obase->flags & CWAL_F_IS_PROP_STORAGE); - obase->flags &= ~CWAL_F_IS_PROP_STORAGE; - s->props = 0 /* if pv->scope==s, pv is in s->mine, - otherwise pv is in pv->scope->mine. Either way, - it's where it needs to be right now. */; - cwal_value_unref(pv); - } - - if(e->values.prototypes && (s == CWAL_VALPART(e->values.prototypes)->scope)){ - /* cwal_value_unhand(CWAL_VALPART(e->values.prototypes)); */ - e->values.prototypes = 0 /* it's in s->mine somewhere, - and will be cleaned up - momentarily. */; - } - - cwal_scope_sweep_r0( s ); - - /** - Reminder: we HAVE to clean up the containers first to ensure - that cleanup of PODs during container cleanup does not step - on dead POD refs we already cleaned. We could get around this - ordering if we included PODs in the gc queue, but we do not - need to, so we don't. (20180105: we gc-queue PODs now.) - - Algorith: keep reducing each value's refcount by 1 until it's - dead. This weeds out cycles one step at a time. - - Notes: - - For PODs we REALLY want to unref them only once here, BUT - internalized strings screw that up for us (but are too cool to - outright give up, yet i also don't want to special-case them). - - The destruction order is not QUITE what i want (i would prefer - reverse-allocation order, but we cannot guaranty that ordering - once objects move between scopes, anyway). What we're doing - here is unref'ing the head (last-added) item. If that item - still has references (it was not destroyed) then we proceed to - unref subsequent items in the list until one is destroyed. - Value destruction modifies the list we are traversing, forcing - a re-start of the traversal if any item is actually finalized - by the unref. As values are cleaned up they remove themselves - from s->mine, so we can simply walk the list until it's - empty. For "normal use" the destruction order will be the - referse of allocation, but once references are held that - doesn't... well, hold. - - Remember that this ONLY works because of our scoping rules: - - - All values in a scope when it is cleaned up must not (cannot) - reference values in higher (newer) scopes because performing - such a reference transfers the being-referenced value - (recursively for containers) into the referencing value's - owning scope. - */ - while((v = s->mine.headObj - ? s->mine.headObj - : (s->mine.headSafe - ? s->mine.headSafe - : s->mine.headPod) - )){ - CWAL_TR_SV(e,s,v); - CWAL_TR_MSG(e,"Scope is about to unref value"); - CWAL_TR2(e,CWAL_TRACE_SCOPE_MASK); - assert(!CWAL_MEM_IS_BUILTIN(v)); - assert(v->scope); - assert(v->scope==s); - assert(v->right ? v->right->scope==s : 1); - while(v){ - cwal_value * n = v->right; - assert(n != v); - assert(!n || CWAL_REFCOUNT(n)>0); - assert(!n || n->scope == s); - if( CWAL_RC_HAS_REFERENCES == cwal_value_unref2(e, v) ) { - /* - It still has references. Let's try again. - - This is part of the reason the gc queue is so - important/helpful. Consider what happens when we - clean up a Prototype value (which may have hundreds - or thousands of references to it). We may clean it - up before some of the objects which reference it - because of this "repeat if it survives" behaviour. - */ - assert(CWAL_REFCOUNT(v)>0); - v = n; - assert((!n || s == n->scope) && "unexpected. Quite."); - continue; - /* break; */ - } - else if(n && n->scope){ - assert((s == n->scope) && "This is still true in a vacuum, right?"); - /* n is still in THIS list, else n is in the gc - queue and we need to re-start traversal. - - The destruction of v can only affect n if v is a - container. a POD cannot form a reference to anyone - else, so if we're here then we know that either: - - - v was a POD before unref'ing it. - - - OR v was a container which did not (even - indirectly) reference n. Had it cleaned up n, - n->scope would be 0. - */ - v = n; - continue; - } - else{ - /* - Need to restart traversal due to either: - - - v being finalized (which modifies this list). - - - n being in the gc queue or recycle bin (having - been put there when we unref'd v, which held the - only reference(s) (possibly indirectly) to n). - We detect this case by checking whether n has a scope. - If it has no scope, it's in the gc queue. Because - PODs don't gc-queue (they don't have to because they - cannot reference anything) all this funkiness only - applies to containers. - */ - break; - } - } - } - - assert(0 == s->mine.headPod); - assert(0 == s->mine.headObj); - assert(0 == s->mine.headSafe); - assert(0 == s->mine.r0); - CWAL_TR3(e,CWAL_TRACE_SCOPE_CLEAN_END,"Scope cleanup finished."); - /*MARKER("ALLOCS LIST SIZES: compound=%u simple=%u\n", s->mine.compound.count, s->mine.simple.count );*/ - - if(iInitedGc){ - assert(s == e->gcInitiator); - if(s == e->gcInitiator) { - e->gcInitiator = 0; - cwal_gc_flush( e ); - } - } - return rc; -} - -static void cwal_scope_free( cwal_engine * e, cwal_scope * s, char allowRecycle ){ - void const * stamp; - assert( e && s ); - stamp = s->allocStamp; - s->flags |= CWAL_F_IS_DESTRUCTING; - cwal_scope_clean(e, s); - *s = cwal_scope_empty; - if(CwalConsts.AllocStamp == stamp){ - /* This API allocated the scope - recycle or free it. */ - cwal_recycler * re = cwal_recycler_get(e, CWAL_TYPE_SCOPE); - assert(re); - if( allowRecycle && (re->count < re->maxLength) ){ - s->parent = (cwal_scope*)re->list; - re->list = s; - ++re->count; - } - else cwal_free(e, s); - }else{ - /* it was allocated elsewhere */ - s->allocStamp = stamp; - } -} - -int cwal_exception_info_clear( cwal_engine * e, cwal_exception_info * err ){ - if(!e || !err) return CWAL_RC_MISUSE; - else{ - int rc = CWAL_RC_OK; - if( err->zMsg ) cwal_free( e, err->zMsg ); - if( err->value ) rc = cwal_value_unref2( e, err->value ); - if(CWAL_RC_DESTRUCTION_RUNNING == rc) { - assert( 0 && "i don't _think_ this can happen." ); - rc = 0; - } - assert(0 == rc); - *err = cwal_exception_info_empty; - return CWAL_RC_OK; - } -} - -/** - Passes all values in the given linked value list to cwal_free(). - The values MUST have been properly cleaned up via the - cwal_unref() mechanism. -*/ -static void cwal_value_list_free( cwal_engine * e, cwal_value * list){ - cwal_value * v, * next; - for( v = list; v; v = next ){ - assert(0==v->scope); - assert(0==CWAL_REFCOUNT(v)); - next = v->right; - cwal_free(e, v); - } -} - - -/** - If s->finalize is not NULL then s->finalize(e, s->state) is called - (if finalize is not 0) and s's state is cleared, else this is a - no-op. -*/ -static void cwal_state_cleanup( cwal_engine * e, cwal_state * s ); - -static int cwal_engine_destroy_impl( cwal_engine * e, cwal_engine_vtab * vtab ){ - if(!e || !vtab) return CWAL_RC_MISUSE; - else{ - void const * stamp = e->allocStamp; - cwal_state_cleanup( e, &e->client ); - if(!e->vtab ) e->vtab = vtab /* only happens during on-init errors. */ ; - e->gcInitiator = 0; - e->flags |= CWAL_F_IS_DESTRUCTING; - CWAL_TR2(e,CWAL_TRACE_ENGINE_SHUTDOWN_START); - - /* - Maintenance reminder: if we ever have an Values to clean up, - they need to be cleaned up first (right after e->client). - */ - - cwal_recycler_get(e, CWAL_TYPE_WEAK_REF)->maxLength = 0; - - e->values.exception = 0 /* its scope will clean it up */; - e->values.propagating = 0 /* its scope will clean it up */; - e->values.prototypes = 0 /* its scope will clean it up */; - while( e->current ){ - cwal_scope_pop(e); - } - - {/* Cleanup recyclers (AFTER scopes have been popped)... */ - cwal_size_t i; - cwal_kvp * kvp, * next; - cwal_recycler * re; - cwal_scope * s, * snext; - /* This "should" be a loop, but our use of mixed types - screws that up. - */ -#define RE(T) re = cwal_recycler_get(e, T); assert(re && #T) -#define UNCYCLE(T) RE(T); cwal_value_list_free(e, (cwal_value*)re->list); \ - re->list = 0; re->count = 0 - UNCYCLE(CWAL_TYPE_INTEGER); - UNCYCLE(CWAL_TYPE_DOUBLE); - UNCYCLE(CWAL_TYPE_OBJECT); - UNCYCLE(CWAL_TYPE_HASH); - UNCYCLE(CWAL_TYPE_ARRAY); - UNCYCLE(CWAL_TYPE_NATIVE); - UNCYCLE(CWAL_TYPE_BUFFER); - UNCYCLE(CWAL_TYPE_FUNCTION); - UNCYCLE(CWAL_TYPE_EXCEPTION); - UNCYCLE(CWAL_TYPE_XSTRING /* actually x/z-strings! */); - UNCYCLE(CWAL_TYPE_UNIQUE); - UNCYCLE(CWAL_TYPE_TUPLE); - /* WEAK_REF, KVP and SCOPE are handled below... */ -#undef UNCYCLE - cwal_value_list_free(e, e->reString.list); - e->reString.list = 0; - e->reString.count = 0; - - RE(CWAL_TYPE_KVP); - kvp = (cwal_kvp*) re->list; - re->list = 0; - for( ; kvp; kvp = next ){ - next = kvp->right; - assert(!kvp->key); - assert(!kvp->value); - kvp->right = NULL; - cwal_kvp_free( e/* , NULL */, kvp, 0 ); - --re->count; - } - assert(0==re->count); - - RE(CWAL_TYPE_SCOPE); - s = (cwal_scope*) re->list; - re->list = 0; - for( ; s; s = snext ){ - snext = s->parent; - s->parent = 0; - cwal_free( e, s ); - --re->count; - } - assert(0==re->count); - - { /* Clean up weak ref recycler... */ - cwal_weak_ref * wr; - cwal_weak_ref * wnext; - RE(CWAL_TYPE_WEAK_REF); - wr = (cwal_weak_ref*) re->list; - re->list = 0; - for( ; wr; wr = wnext ){ - wnext = wr->next; - assert(!wr->value); - wr->next = NULL; - cwal_free(e, wr); - --re->count; - } - assert(0==re->count); - } -#undef RE - - /* sanity-check to make sure we didn't leave any - new additions out of the e-recycler cleanup... - - This has saved me grief twice now. - */ - for( i = 0; i < (sizeof(e->recycler)/sizeof(e->recycler[0])); ++i ){ - re = &e->recycler[i]; - if(re->list){ - MARKER(("Recycler index #%d has a list? count=%d\n", (int)i, (int)re->count)); - } -#if 0 - assert(0==re->list && "Steve seems to have forgotten " - "to account for cwal_engine::recycler-related changes."); - assert(0==re->count); -#endif - } - } - - { /* Clean up any dangling cwal_weak_refs if the client - failed to do so... */ - cwal_size_t i = 0; - for( i = 0; i < sizeof(e->weakr)/sizeof(e->weakr[0]); ++i ){ - cwal_weak_ref * list = e->weakr[i]; - e->weakr[i] = NULL; - while( list ){ - cwal_weak_ref * next = list->next; - list->next = NULL; - cwal_weak_ref_free2(e, list); - list = next; - } - } - } - cwal_ptr_table_destroy(e, &e->weakp); - cwal_ptr_table_destroy( e, &e->interned ); - cwal_buffer_reserve(e, &e->buffer, 0); - cwal_gc_flush( e ); - - if(vtab->tracer.close){ - vtab->tracer.close( vtab->tracer.state ); - vtab->tracer.state = 0; - } - if(vtab->outputer.state.finalize){ - vtab->outputer.state.finalize( e, vtab->outputer.state.data ); - vtab->outputer.state.data = 0; - } - - cwal_memchunks_free(e); - cwal_error_clear(e, &e->err); - - CWAL_TR2(e,CWAL_TRACE_ENGINE_SHUTDOWN_END); - *e = cwal_engine_empty; - - if( stamp == CwalConsts.AllocStamp ){ - vtab->allocator.realloc( vtab->state.data, e, 0 ); - }else{ - /* client allocated it or it was part of another object. */ - e->allocStamp = stamp; - } - - if(vtab->state.finalize){ - vtab->state.finalize( NULL, vtab->state.data ); - } - - /** - TODO: call vtab->shutdown() once that's added to the - vtab interface. - */ - - return CWAL_RC_OK; - } -} - -/** - Lazily allocates and initializes e->values.prototypes, if it is not - 0, then returns it. Returns 0 only on OOM errors during initial - allocation/intialization. -*/ -static cwal_array * cwal_engine_prototypes(cwal_engine * e){ - if(!e->values.prototypes && (e->values.prototypes = cwal_new_array(e)) ){ - if(cwal_array_reserve(e->values.prototypes, (cwal_size_t)CWAL_TYPE_end-1)){ - cwal_value_unref(CWAL_VALPART(e->values.prototypes)); - e->values.prototypes = 0; - }else{ - cwal_value_ref2(e, CWAL_VALPART(e->values.prototypes)) - /* So that it cannot get sweep()'d up. */ - ; - cwal_value_make_vacuum_proof(CWAL_VALPART(e->values.prototypes),1); - } - } - return e->values.prototypes; -} - -int cwal_engine_destroy( cwal_engine * e ){ - if( NULL == e->vtab ) return 0 /* special case: assume not yet inited */; - return e ? cwal_engine_destroy_impl(e, e->vtab) : CWAL_RC_MISUSE; -} - -int cwal_engine_init( cwal_engine ** E, cwal_engine_vtab * vtab ){ - unsigned const sz = sizeof(cwal_engine); - cwal_engine * e; - int rc; - static int once = 0; - if(!once){ - /* Just making sure some assumptions are right... */ -#if CWAL_VOID_PTR_IS_BIG - assert(sizeof(void*)>4); -#else - assert(sizeof(void*)<8); -#endif - assert(sizeof(cwal_memsize_t) <= sizeof(void*)) - /* or we'll overwrite important stuff */; - once = 1; - } - - if(!E || !vtab){ - return CWAL_RC_MISUSE; - } - if(!CWAL_BUILTIN_VALS.inited) cwal_init_builtin_values(); - assert(CWAL_BUILTIN_VALS.inited); - e = *E; - if(!e){ - e = (cwal_engine*)vtab->allocator - .realloc( vtab->allocator.state.data, NULL, sz ) - /* reminder: this does not take into account memory - over-allocation. */; - if(!e){ - return CWAL_RC_OOM; - } - } - *e = cwal_engine_empty; - if(!*E){ - e->allocStamp = CwalConsts.AllocStamp - /* we use this later to recognize that we allocated (and - need to free()) e. */; - *E = e; - } - - e->vtab = vtab; - if(CwalConsts.AutoInternStrings){ - e->flags |= CWAL_FEATURE_INTERN_STRINGS; - } - if(e->vtab->memcap.forceAllocSizeTracking - || e->vtab->memcap.maxTotalMem - || e->vtab->memcap.maxConcurrentMem){ - e->flags |= CWAL_F_TRACK_MEM_SIZE; - } - - /* Tag e->recycler[*].id, just for sanity checking and to simplify - metrics reporting. We store the virtual size of the Value type(s!) - stored in that bin. - */ - { - int i = CWAL_TYPE_UNDEF; - for( ; i < CWAL_TYPE_end; ++i ){ - cwal_recycler * re = cwal_recycler_get(e, (cwal_type_id)i); - if(re){ - re->id = (int)cwal_type_id_sizeof((cwal_type_id)i); - } - } - e->reString.id = (int)cwal_type_id_sizeof(CWAL_TYPE_STRING); - } - -#if CWAL_ENABLE_TRACE - e->trace.e = e; -#endif - { - cwal_scope * sc = &e->topScope; - rc = cwal_scope_push( e, &sc ); - if(rc) goto end; - assert(sc->e == e); - } -#if 0 - /* defer interned strings init until needed. */ - if(CWAL_FEATURE_INTERN_STRINGS & e->flags) { - rc = cwal_engine_init_interning(e); - if(rc) goto end; - } -#endif - - if(! cwal_engine_prototypes(e) ){ - rc = CWAL_RC_OOM; - }else if(vtab->hook.on_init){ - rc = vtab->hook.on_init( e, vtab ); - } - end: - return rc; -} - - -/*static int cwal_list_visit_FreeFunction( void * S, void * E ){ - cwal_engine * e = (cwal_engine *)E; - cwal_function_info * f = (cwal_function_info *)S; - cwal_state_cleanup( e, &f->state ); - cwal_string_unref( e, f->name ); - cwal_free( e, S ); - return CWAL_RC_OK; - } -*/ - -void cwal_state_cleanup( cwal_engine * e, cwal_state * s ){ - if( s ){ - if( s->finalize ) s->finalize( e, s->data ); - *s = cwal_state_empty; - } -} - -int cwal_engine_client_state_set( cwal_engine * e, - void * state, void const * typeId, - cwal_finalizer_f dtor){ - if(!e || !state) return CWAL_RC_MISUSE; - else if(e->client.data) return CWAL_RC_ACCESS; - else{ - e->client.data = state; - e->client.typeID = typeId; - e->client.finalize = dtor; - return 0; - } -} - -void * cwal_engine_client_state_get( cwal_engine * e, void const * typeId ){ - return (e && (typeId == e->client.typeID)) - ? e->client.data - : 0; -} - - -int cwal_output( cwal_engine * e, void const * src, cwal_size_t n ){ - return (e && src && n) - ? (e->vtab->outputer.output - ? e->vtab->outputer.output( e->vtab->outputer.state.data, src, n ) - : CWAL_RC_OK) - : CWAL_RC_MISUSE; -} - -int cwal_output_flush( cwal_engine * e ){ - return (e && e->vtab) - ? (e->vtab->outputer.flush - ? e->vtab->outputer.flush( e->vtab->outputer.state.data ) - : CWAL_RC_OK) - : CWAL_RC_MISUSE; -} - -static int cwal_printfv_appender_cwal_output( void * S, char const * s, - unsigned n ){ - return cwal_output( (cwal_engine *)S, s, (cwal_size_t)n ); -} - -int cwal_outputfv( cwal_engine * e, char const * fmt, va_list args ){ - if(!e || !fmt) return CWAL_RC_MISUSE; - else{ - return cwal_printfv( cwal_printfv_appender_cwal_output, e, fmt, args ); - } -} - - -int cwal_outputf( cwal_engine * e, char const * fmt, ... ){ - if(!e || !fmt) return CWAL_RC_MISUSE; - else{ - int rc; - va_list args; - va_start(args,fmt); - rc = cwal_outputfv( e, fmt, args ); - va_end(args); - return rc; - } -} - -typedef struct BufferAppender { - cwal_engine * e; - cwal_buffer * b; - int rc; -} BufferAppender; - -static int cwal_printfv_appender_buffer( void * arg, char const * data, - unsigned n ){ - BufferAppender * const ba = (BufferAppender*)arg; - cwal_buffer * const sb = ba->b; - if( !sb ) return CWAL_RC_MISUSE; - else if( ! n ) return 0; - else{ - int rc; - unsigned N; - size_t npos = sb->used + n; - if( npos >= sb->capacity ){ - const size_t asz = npos ? ((3 * npos / 2) + 1) : 32; - if( asz < npos /* overflow */ ) { - return ba->rc = CWAL_RC_RANGE; - } else { - rc = cwal_buffer_reserve( ba->e, sb, asz ); - if(rc) { - return ba->rc = rc; - } - } - } - N = 0; - for( ; N < n; ++N, ++sb->used ) sb->mem[sb->used] = data[N]; - sb->mem[sb->used] = 0; - return 0; - } -} - -int cwal_buffer_append( cwal_engine * e, - cwal_buffer * b, - void const * data, - cwal_size_t len ){ - cwal_size_t sz; - int rc; - if(!b || !data) return CWAL_RC_MISUSE; - sz = b->used + len + 1/*NUL*/; - rc = cwal_buffer_reserve( e, b, sz ); - if(rc) return rc; - memcpy( b->mem+b->used, data, len ); - b->used += len; - b->mem[b->used] = 0; - return 0; -} - -int cwal_buffer_printfv( cwal_engine * e, cwal_buffer * b, char const * fmt, va_list args){ - if(!e || !b || !fmt) return CWAL_RC_MISUSE; - else{ - BufferAppender ba; - cwal_size_t const oldUsed = b->used; - ba.b = b; - ba.e = e; - ba.rc = 0; - cwal_printfv( cwal_printfv_appender_buffer, &ba, fmt, args ); - if(ba.rc){ - b->used = oldUsed; - if(b->capacity>oldUsed){ - b->mem[oldUsed] = 0; - } - } - return ba.rc; - } -} - -int cwal_buffer_printf( cwal_engine * e, cwal_buffer * b, char const * fmt, ... ){ - if(!e || !b || !fmt) return CWAL_RC_MISUSE; - else{ - int rc; - va_list args; - va_start(args,fmt); - rc = cwal_buffer_printfv( e, b, fmt, args ); - va_end(args); - return rc; - } -} - -static int cwal_scope_alloc( cwal_engine * e, cwal_scope ** S ){ - cwal_scope * s; - assert( S && "Invalid NULL ptr."); - s = *S; - ++e->metrics.requested[CWAL_TYPE_SCOPE]; - if(!s){ - cwal_recycler * re = cwal_recycler_get(e, CWAL_TYPE_SCOPE); - assert(re); - if(re->count){ - s = (cwal_scope*)re->list; - assert(s); - if(s->parent){ - re->list = s->parent; - s->parent = 0; - } - else re->list = 0; - --re->count; - } - else{ - s = (cwal_scope *)cwal_malloc( e, sizeof(cwal_scope) ); - if(s){ - ++e->metrics.allocated[CWAL_TYPE_SCOPE]; - e->metrics.bytes[CWAL_TYPE_SCOPE] += sizeof(cwal_scope); - } - } - } - if(s){ - *s = cwal_scope_empty; - s->e = e; - if(*S != s) { - s->allocStamp = CwalConsts.AllocStamp - /* we use this later to know whether or not we need to - free() s. */; - /* Potential TODO: use e as the allocStamp for any - resources e allocates. */ - *S = s; - } - } - return s ? CWAL_RC_OK : CWAL_RC_OOM; -} - -/** - Pops the e->current scope from the scope stack, cleaning it up and - possibly cwal_free()ing it. If callHook is true then the - cwal_engine_vtab::hook::scope_pop hook, if not NULL, will be called - before the scope state is changed. The only error conditions are - invalid arguments: - - !e = CWAL_RC_MISUSE - - !e->current = CWAL_RC_RANGE -*/ -static int cwal_scope_pop_impl( cwal_engine * e, char callHook ){ - if(!e) return CWAL_RC_MISUSE; - else if( 0 == e->current ) return CWAL_RC_RANGE; - else{ - cwal_scope * p; - cwal_scope * s = e->current; - assert(s->e == e); - if(callHook && e->vtab->hook.scope_pop){ - e->vtab->hook.scope_pop( s, e->vtab->hook.scope_state ); - } - p = s->parent; - assert(p || (e->top==s)); - e->current = p; - if(e->top==s) e->top = 0; - cwal_scope_free( e, s, 1 ); - return 0; - } -} - -int cwal_scope_pop( cwal_engine * e ){ - return cwal_scope_pop_impl(e, 1); -} - -int cwal_scope_push( cwal_engine * e, cwal_scope ** S ){ - cwal_scope * s = S ? *S : NULL; - int rc; - if(!e) return CWAL_RC_MISUSE; - rc = cwal_scope_alloc(e, &s); - if(rc){ - assert(NULL == s); - return rc; - } - assert(NULL != s); - s->level = e->current ? (1 + e->current->level) : 1; - s->parent = e->current; - if(!e->top){ - assert(NULL == e->current); - e->top = s; - } - e->current = s; - if(e->vtab->hook.scope_push){ - rc = e->vtab->hook.scope_push( s, e->vtab->hook.scope_state ); - if(rc) cwal_scope_pop_impl(e, 0); - } - if(!rc && S) *S = s; - return rc; -} - -int cwal_scope_push2( cwal_engine * e, cwal_scope * s ){ - return (!e || !s || memcmp(s, &cwal_scope_empty, sizeof(cwal_scope))) - ? CWAL_RC_MISUSE - : cwal_scope_push( e, &s ); -} - -int cwal_scope_pop2( cwal_engine * e, cwal_value * resultVal ){ - if(!e) return CWAL_RC_MISUSE; - else if(!e->current - || (resultVal && !e->current->parent)) return CWAL_RC_RANGE; - else{ - int rc = 0; - if(resultVal){ - cwal_value_ref(resultVal); - cwal_value_rescope(e->current->parent, resultVal); - } - rc = cwal_scope_pop_impl(e, 1); - if(resultVal){ - cwal_value_unhand(resultVal); - } - return rc; - } -} - -cwal_value * cwal_value_snip( cwal_value * v ){ - cwal_scope * p = v->scope; - cwal_value * l = v->left; - cwal_value * r = v->right; - v->scope = 0; - v->right = v->left = 0; - assert(r != v); - assert(l != v); - if(l) l->right = r; - if(r) r->left = l; - if(p){ - /* Adjust value lifetime lists if v is the head of one of them. - If it is not the head, then removal from its linked list - is sufficient. - */ - l = l ? l : r; - if(l){ - while(l->left){ - if(l == l->left){ - cwal_dump_value( "cwal.c", __LINE__, l, "Internal cwal_value list misuse."); - assert(l->left != l && "Internal cwal_value list misuse."); - E_IS_DEAD(p->e) = CWAL_RC_ASSERT; - return NULL; - /* abort(); */ - } - l=l->left; - } - } - if(p->mine.headObj==v){ - p->mine.headObj = l; - CWAL_TR_SV(p->e,p,l); - CWAL_TR3(p->e,CWAL_TRACE_SCOPE_MASK,"Scope replaced mine->headObj."); - if(p->mine.headObj) assert(0==p->mine.headObj->left); - }else if(p->mine.headPod==v){ - p->mine.headPod = l; - CWAL_TR_SV(p->e,p,l); - CWAL_TR3(p->e,CWAL_TRACE_SCOPE_MASK,"Scope replaced mine->headPod."); - if(p->mine.headPod) assert(0==p->mine.headPod->left); - }else if(p->mine.headSafe==v){ - p->mine.headSafe = l; - CWAL_TR_SV(p->e,p,l); - CWAL_TR3(p->e,CWAL_TRACE_SCOPE_MASK,"Scope replaced mine->headSafe."); - if(p->mine.headSafe) assert(0==p->mine.headSafe->left); - }else if(p->mine.r0==v){ - p->mine.r0 = l; - CWAL_TR_SV(p->e,p,l); - CWAL_TR3(p->e,CWAL_TRACE_SCOPE_MASK,"Scope replaced mine->r0."); - if(p->mine.r0) assert(0==p->mine.r0->left); - } - } - return r; -} - -/** - Inserts v so that v->right is now l, adjusting v and l as necessary. - v->right and v->left must be 0 before calling this (it assert()s so). -*/ -static void cwal_value_insert_before( cwal_value * l, cwal_value * v ){ - assert(0 == v->right); - assert(0 == v->left); - assert((l != v) && "Unexpected duplicate items for value list. " - "Possibly caused by an unwarranted unref."); - /* if(l != v){ */ - if( l->left ){ - l->left->right = v; - } - l->left = v; - v->right = l; - /* } */ -} - -cwal_value * cwal_string_from_recycler( cwal_engine * e, cwal_size_t len ){ - cwal_value * li = (cwal_value *)e->reString.list; - cwal_string * s; - cwal_value * prev = 0; - cwal_size_t slen; - cwal_size_t paddedLen; - for( ; li; prev = li, li = li->right ){ - s = CWAL_STR(li) /*cwal_value_get_string(li)*/; - assert(s); - assert(0 < CWAL_STRLEN(s)); - assert(!CWAL_STR_ISXZ(s)); - slen = CWAL_STRLEN(s); - if(!CwalConsts.StringPadSize){ - if(len!=slen) continue; - /* Else fall through */ - }else if(len!=slen){ - /** - If s's "padded length" is large enough for the request, - but not "too large" (within 1 increment of - CwalConsts.StringPadSize) then we will re-use it. - */ - cwal_size_t const mod = (slen % CwalConsts.StringPadSize); - paddedLen = mod - ? (slen + (CwalConsts.StringPadSize - mod)) - : slen; - if(paddedLen < len) continue; - else if(paddedLen > len){ - if((paddedLen - CwalConsts.StringPadSize) > len) continue; - } - } - if(prev){ - prev->right = li->right; - } - else { - assert(e->reString.list == li); - e->reString.list = li->right; - } - li->right = 0; - --e->reString.count; - if(CwalConsts.StringPadSize){ - s->length = CWAL_STRLEN_MASK & len; - } - /* MARKER("Pulling string of len %u from recycle bin.\n", (unsigned)len); */ - CWAL_TR_V(e,li); - CWAL_TR3(e,CWAL_TRACE_MEM_FROM_RECYCLER, - "Pulled string from recycle bin."); - ++e->metrics.valuesRecycled; - ++e->reString.hits; - return li; - } - ++e->reString.misses; - ++e->metrics.valuesRecycleMisses; -#if 0 - /* this is causing a valgrind warning via memset() via cwal_value_new() */ - if(e->reChunk.head - && !e->reString.list /* see comments below */){ - /* Look in the chunk recycler as a last resort. Testing with - the s2 amalgamation shows that this very rarely hits if - recycling is on (only once in the whole test suite from - 20141201). If recycling is off, it hits surprisingly often - (1224 times in the test suite). So we only do this O(N) - lookup when string recycling is off or its recycling bin is - empty. - - If both value recyling and string interning are off, this - block hits 3798 times in the above-mentioned test suite. - */ - cwal_size_t reqSize = sizeof(cwal_value) - + sizeof(cwal_string) - + len + 1 /*NUL*/; - cwal_value * v = (cwal_value *) - cwal_memchunk_request(e, &reqSize, - len up to 1.5x */ - : 125 /* ==> up to 1.25x. Wasting - memory? They should be glad - we're recycling it at - all! */, - "cwal_string_from_recycler()"); - if(v){ - /* MARKER(("Got string fallback!\n")); */ - *v = cwal_value_string_empty; - s = CWAL_STR(v); - assert(!(~CWAL_STRLEN_MASK & len)); - s->length = (cwal_size_t)(CWAL_STRLEN_MASK & len); - return v; - } - } -#endif - return NULL; -} - - -static bool cwal_string_recycle( cwal_engine * e, cwal_value * v ){ - cwal_string * s = cwal_value_get_string(v); - cwal_size_t const slen = CWAL_STRLEN(s); - char const * freeMsg = 0; - cwal_value * li; - assert(s); - if( slen > CwalConsts.MaxRecycledStringLen ){ - freeMsg = "String too long to recycle - freeing."; - goto freeit; - } - else if(CWAL_STR_ISXZ(s)){ - assert(!"Cannot happe anymore - x/z-string recycled elsewhere/elsehow."); - freeMsg = "Cannot recycle x/z-strings."; - goto freeit; - } - else if( 0 == e->reString.maxLength ){ - freeMsg = "String recycling disabled - freeing."; - goto freeit; - }else if(freeMsg){ - /* avoiding an unused var in non-debug build */ - assert(!"impossible"); - } - li = (cwal_value *)e->reString.list; - if(e->reString.count>=e->reString.maxLength){ - /* - Remove the oldest entries from the list. - They have not been recycled in a while, - and are not likely needed any more. - - To avoid unduly high N on the O(N) linked list traversal, - when trimming the list we trim some percentage of it, as - opposed to only the last (oldest) element. Otherwise this - algo is remarkably slow on large recycle lists or when - rapidly freeing many strings. - - TODO?: sort the strings by size(?) in order to optimize the - from-recycle-bin size lookup? - */ - cwal_size_t keep = e->reString.maxLength * 3 / 4; - cwal_size_t i; - cwal_value * x = li; - cwal_value * prev = 0; - cwal_value * cut = 0; - for( i = 0; x; - prev = x, x = x->right, ++i ){ - if(i==keep){ - assert(!x->left); - cut = x; - break; - } - } - if(prev) prev->right = 0; - else e->reString.list = 0; - -#if 0 - MARKER("Trimming list to %u of %u entries cut=%c.\n", - (unsigned)i, (unsigned) e->reString.maxLength, cut?'y':'n'); -#endif - - if(cut){ -#if 0 - e->reString.count = i; - CWAL_TR_V(e,x); - CWAL_TR3(e,CWAL_TRACE_MEM_TO_RECYCLER, - "Popping stale string(s) from recycler."); - cwal_value_list_free(e, cut); -#else - /* We "could" just use cwal_value_list_free(), - but i want more tracing info. */ - for( x = cut; x ; x = cut ){ - cut = x->right; - x->right = 0; - --e->reString.count; - CWAL_TR_V(e,x); - CWAL_TR3(e,CWAL_TRACE_MEM_TO_RECYCLER, - "Popping stale string from recycler."); - cwal_free(e,x); - } -#endif - } - assert(e->reString.count < e->reString.maxLength); - } - - /* MARKER("String to recyler...\n"); */ - assert(!v->right); - assert(!v->scope); - assert(!CWAL_REFCOUNT(v)); - assert(CWAL_TYPE_STRING==v->vtab->typeID); - li = (cwal_value*)e->reString.list; - assert(!li || (CWAL_TYPE_STRING==li->vtab->typeID)); - v->right = li; - e->reString.list = v; - ++e->reString.count; - CWAL_TR_V(e,v); - CWAL_TR3(e, CWAL_TRACE_MEM_TO_RECYCLER, - "Placed string in recycling bin."); - return 1; - freeit: -#if !CWAL_ENABLE_TRACE - if(0){ assert(freeMsg && "Avoid unused var warning in non-trace builds."); } -#endif - CWAL_TR_SV(e,e->current,v); - CWAL_TR3(e,CWAL_TRACE_MEM_TO_RECYCLER, freeMsg); -#if 1 - { - /** - Pushing this memory to the chunk recycler can lower both allocs - and peak marginally, but can also increase peak while lowering - allocs, depending on the usage. Compare s2's UNIT.s2 vs - UNIT-import.s2. They both run the same tests, but the former - loads them as a single script and the latter imports one script - at a time. - */ - cwal_size_t sz = sizeof(cwal_value)+sizeof(cwal_string) + slen + 1 /*NUL byte*/; - /* Account for string size padding */ - if(CwalConsts.StringPadSize){ - if(slenCwalConsts.StringPadSize){ - cwal_size_t const mod = (slen % CwalConsts.StringPadSize); - if(mod) sz = sz + (CwalConsts.StringPadSize - mod); - } - } - cwal_memchunk_add(e, v, sz); - } -#else - cwal_free( e, v ); -#endif - return 0; - -} - -int cwal_value_recycle( cwal_engine * e, cwal_value * v ){ - int ndx; - cwal_recycler * re; - cwal_size_t max; -#if CWAL_ENABLE_TRACE - char const * freeMsg = "==> CANNOT RECYCLE. FREEING."; -# define MSG(X) freeMsg = X -#else -# define MSG(X) -#endif - assert(e && v && v->vtab); - assert(0==CWAL_REFCOUNT(v)); - if(e->gcInitiator - /*&& (CWAL_V_IS_OBASE(v) - || (CWAL_TYPE_UNIQUE==v->vtab->typeID) - || (CWAL_TYPE_TUPLE==v->vtab->typeID) - //^^^^ We also need to put "not-quite-containers" here, - // namely CWAL_TYPE_UNIQUE and any potentially similar - // ones (CWAL_TYPE_TUPLE). - )*/){ - /** - 20180105: historically we only put certain types in the GC - queue, but we came across a situation where a Unique value - wrapping a string choked at destruction because its wrapped - string had already been sent to the string recycler - (strings, at the time, did not get gc-queued) - */ - /** - This means a scope cleanup is running and deallocation must - be delayed until the cleanup is finished. Move the value - into the GC queue. We hypothetically only need this for - types which can participate in cycles, as it's easy to step - on a destroyed value via a cycle during value - destruction. Practice has (finally, 20180105) shown that - certain non-cyclic relationships require that their values - (in particular code constellations) must also be gc-queued. - */ - CWAL_TR_V(e,v); - CWAL_TR3(e,CWAL_TRACE_MEM_TO_GC_QUEUE, - "Redirecting value to gc queue"); - ndx = cwal_gc_push( e, v ); - assert(0==ndx && "cwal_gc_push() can (now) only fail if !e->gcInitiator."); - return (0==ndx) - ? -1 - : 0; - } - else if(CWAL_TYPE_STRING == v->vtab->typeID - && !CWAL_STR_ISXZ(CWAL_STR(v))){ - return cwal_string_recycle( e, v ); - } - - assert( 0 == CWAL_REFCOUNT(v) ); - assert( 0 == v->right ); - assert( 0 == v->left ); - assert( 0 == v->scope ); - ndx = cwal_recycler_index( v->vtab->typeID ); - if( ndx < 0 ) { - /* Non-recylable type */ - MSG("==> Unrecyclable type. FREEING."); - goto freeit; - } - re = &e->recycler[ndx]; - max = re->maxLength; - if(!max) { - /* recycling disabled */ - MSG("==> Recyling disabled for this type. FREEING."); - goto freeit; - } - else if( re->count >= max ){ - /* bin is full */ - MSG("==> Recyling bin for this type is full. FREEING."); - goto freeit; - } - - assert(!CWAL_RCFLAG_HAS(v, CWAL_RCF_IS_RECYCLED)); - CWAL_RCFLAG_ON(v, CWAL_RCF_IS_RECYCLED); - assert(CWAL_RCFLAG_HAS(v, CWAL_RCF_IS_RECYCLED)); - if(re->list){ - cwal_value_insert_before( re->list, v ); - } - ++re->count; - re->list = v; - if(re->count > 1){ - assert(((cwal_value*)re->list)->right); - } - CWAL_TR_V(e,v); - CWAL_TR3(e, CWAL_TRACE_MEM_TO_RECYCLER, - "Placed in recycling bin."); - return 1; - freeit: - CWAL_TR_V(e,v); - CWAL_TR3(e,CWAL_TRACE_MEM_TO_RECYCLER,freeMsg); - *v = cwal_value_undef; - cwal_free(e, v); - return 0; -#undef MSG -} - - -int cwal_gc_push( cwal_engine * e, cwal_value * v ){ - assert( e->gcInitiator ); - assert(0 == v->scope); - assert(0 == v->right); - if(!e->gcInitiator) return CWAL_RC_MISUSE; - if(e->values.gcList){ - cwal_value_insert_before( e->values.gcList, v ); - } - assert(!CWAL_RCFLAG_HAS(v,CWAL_RCF_IS_GC_QUEUED)); - CWAL_RCFLAG_ON(v,CWAL_RCF_IS_GC_QUEUED); - assert(CWAL_RCFLAG_HAS(v,CWAL_RCF_IS_GC_QUEUED)); - e->values.gcList = v; - assert(0==e->values.gcList->left); - return CWAL_RC_OK; -} - -int cwal_gc_flush( cwal_engine * e ){ - int rc = 0; - cwal_value * v; - cwal_value * n; - assert( 0 == e->gcInitiator - && "Otherwise we might have a loop b/t this and cwal_value_recycle()"); - for( v = e->values.gcList; v; v = n ){ - n = v->right; - cwal_value_snip(v); - assert(!CWAL_REFCOUNT(v)); - assert(CWAL_RCFLAG_HAS(v,CWAL_RCF_IS_GC_QUEUED)); - CWAL_RCFLAG_OFF(v,CWAL_RCF_IS_GC_QUEUED); - assert(!CWAL_RCFLAG_HAS(v,CWAL_RCF_IS_GC_QUEUED)); - /* if( (base = CWAL_VOBASE(v)) ) base->flags &= ~CWAL_F_IS_GC_QUEUED; */ - /* dump_val(v,"refcount?"); */ - assert(!CWAL_REFCOUNT(v)); - rc = cwal_value_recycle(e, v); - assert(-1!=rc && "Impossible loop!"); - } - e->values.gcList = 0; - return rc; -} - -int cwal_scope_insert( cwal_scope * s, cwal_value * v ){ - /* cwal_scope * p = v->scope; */ - cwal_value * list; - cwal_value ** listpp = 0; - cwal_obase * const b = CWAL_VOBASE(v); - assert(s && v); - assert(!CWAL_MEM_IS_BUILTIN(v)); - /* - Reminder to self: v->scope == s when we're moving items - around from s->mine.{r0,headSafe}. - */ -#if 0 - /* 20191211: The intent: if we are moving a scope's properties - object into an older new scope, remove the is-prop-storage - flag, as it's now hypothetically moved beyond that role. It's - not yet certain that that's always correct, though, nor exactly - what the ramifications of doing this would be. - */ - if(b && (CWAL_F_IS_PROP_STORAGE & b->flags) && v->scope != s){ - b->flags &= ~CWAL_F_IS_PROP_STORAGE; - } -#endif - cwal_value_snip( v ); - assert(0==v->right); - assert(0==v->left); - assert(!CWAL_RCFLAG_HAS(v, CWAL_RCF_IS_RECYCLED)); - if(0==CWAL_REFCOUNT(v)){ - listpp = &s->mine.r0; - }else if(CWAL_V_IS_VACUUM_SAFE(v) - || (b && (b->flags & CWAL_F_IS_PROP_STORAGE))){ - listpp = &s->mine.headSafe; - }else if(CWAL_V_GOES_IN_HEADOBJ(v)){ - /* 20180105 reminder: this doesn't include Uniques and Tuples. - TODO?: add those types to headObj once we're certain that - doing so won't cause other Grief. We could undo the - special-case destruction checks in - cwal_value_cleanup_unique() and cwal_value_cleanup_tuple() - if we do that, and revert the GC queue to only holding - containers (plus Unique and Tuple). Initial tests in that - regard didn't alleviate them (or Unique, at least) needing - their extra cleanup checks :/. - */ - listpp = &s->mine.headObj; - }else { - listpp = &s->mine.headPod; - } - list = *listpp; - if(list == v){ - cwal_dump_value( __FILE__, __LINE__, v, - "FATAL: inserting item we already have! " - "String interning backfire?"); - assert(list != v && "Insertion failed: this item is " - "the head of one of the lists! String interning backfire?"); - E_IS_DEAD(s->e) = CWAL_RC_ASSERT; -#if 1 - return s->e->fatalCode; -#else - abort(/* this is the only solution, as this error is indicative - or memory corruption within cwal and we cannot report - it to the user from this level. */); -#endif - } - else if(list) { - v->right = list; - assert(0==list->left); - list->left = v; - } - *listpp = v; - v->scope = s; - assert(0==v->left); - CWAL_TR_SV(s->e,s,v); - CWAL_TR3(s->e,CWAL_TRACE_VALUE_SCOPED,"Value moved to scope."); - return 0; -} - - -int cwal_value_take( cwal_engine * e, cwal_value * v ){ - cwal_scope * s = v ? v->scope : 0; - if(!e || !v) return CWAL_RC_MISUSE; - else if( CWAL_MEM_IS_BUILTIN( v ) ) return CWAL_RC_OK; - else if(!s) return CWAL_RC_RANGE; - else{ - cwal_value_snip( v ); - CWAL_TR_SV(e,s,v); - CWAL_TR3(e,CWAL_TRACE_VALUE_UNSCOPED,"Removed from parent scope."); - assert(!v->scope); - assert(0==v->right); - assert(0==v->left); - assert(s->mine.headObj != v); - assert(s->mine.headPod != v); - assert(s->mine.headSafe != v); - assert(s->mine.r0 != v); - return CWAL_RC_OK; - } -} - -int cwal_value_unref(cwal_value *v ){ - if(!v) return CWAL_RC_MISUSE; - else if( CWAL_MEM_IS_BUILTIN( v ) ) return CWAL_RC_OK; - else if(!v->scope){ - if(CWAL_V_IS_IN_CLEANUP(v)) return CWAL_RC_DESTRUCTION_RUNNING; - assert(!"Cannot unref a Value with no scope: serious misuse or Value corruption."); - return CWAL_RC_MISUSE; - } - else return cwal_value_unref2(v->scope->e, v); -} - -int cwal_value_unref2(cwal_engine * e, cwal_value *v ){ - assert( e && v ); - if(NULL == e || NULL == v) return CWAL_RC_MISUSE; - CWAL_TR_SV(e,v->scope,v); - if(CWAL_MEM_IS_BUILTIN(v)) return 0; - else { - cwal_obase * b; - b = CWAL_VOBASE(v); - CWAL_TR3(e,CWAL_TRACE_VALUE_REFCOUNT,"Unref'ing"); - if(!CWAL_REFCOUNT(v) || !CWAL_RCDECR(v)){ - cwal_scope * const vScope = v->scope; - CWAL_TR_V(e,v); - if(CWAL_RCFLAG_HAS(v, CWAL_RCF_IS_GC_QUEUED)){ - assert(!v->scope); - CWAL_TR_S(e,vScope); - CWAL_TR3(e,CWAL_TRACE_VALUE_CYCLE, - "DESTRUCTION OF A GC-QUEUED OBJECT: SKIPPING"); - /* Possible again since starting refcount at 0: - assert(!"This is no longer possible."); */ - return CWAL_RC_DESTRUCTION_RUNNING; - } - else if(CWAL_RCFLAG_HAS(v, CWAL_RCF_IS_RECYCLED)){ - assert(!v->scope); - CWAL_TR_S(e,vScope); - CWAL_TR3(e,CWAL_TRACE_VALUE_CYCLE, - "DESTRUCTION OF A RECYCLED OBJECT: SKIPPING"); - /* Possible again since starting refcount at 0: - assert(!"This is no longer possible."); */ - return CWAL_RC_DESTRUCTION_RUNNING; - } - else if(CWAL_RCFLAG_HAS(v, CWAL_RCF_IS_DESTRUCTING)) { - CWAL_TR_S(e,vScope); - CWAL_TR3(e,CWAL_TRACE_VALUE_CYCLE, - "ENTERING DESTRUCTION A 2ND TIME (or more): SKIPPING"); - /* Possible again since starting refcount at 0: - assert(!"This is no longer possible."); */ - return CWAL_RC_DESTRUCTION_RUNNING; - } - CWAL_TR_S(e,vScope); - CWAL_TR3(e,CWAL_TRACE_VALUE_CLEAN_START, - "Starting finalization..."); - - if(e->values.exception == v){ - e->values.exception = 0; - } - if(e->values.propagating == v){ - e->values.propagating = 0; - } - - if(!v->scope){ - dump_val(v,"Value with NULL scope???"); - assert(v->scope && "this is always true now. " - "That was not always the case."); - return e->fatalCode = CWAL_RC_ASSERT; - } - cwal_value_take(e, v) - /*ignoring rc! take() cannot fail any more under these - conditions.*/; - if(b && (CWAL_F_IS_PROP_STORAGE & b->flags)){ - /* reminder to self: it's potentially possible for - clients to move this value into a place where - it's used for purposes other than property - storage, via cwal_scope_properties(). - */ - cwal_scope * sc = e->current; - assert(CWAL_TYPE_OBJECT==v->vtab->typeID - || CWAL_TYPE_HASH==v->vtab->typeID); - /* - Special case: if v is the cwal_scope::props handle - of a scope, we need to clear that to make sure it - doesn't get stale. This can hypothetically happen if - client code exposes cwal_scope_properties() to - script-space, causes it to get upscoped (for - ownership purposes) but still being pointed to by - cwal_scope::props, and then unrefs it. If that - happens, though... hmmm... the scope storage is - always treated as vacuum-safe, which means that they - could become impossible to vacuum up if clients - introduced cycles and then abandoned all - script-visible references. Oh, well. They shouldn't - be exposing these to script code, probably. - */ - for( ; sc ; sc = sc->parent ){ - if(sc->props == v){ - sc->props = 0; - break; - } - } - } - /* The left/right assertions help ensure we're not now - traversing through the recycle list, which is an easy thing - to do when memory has been mismanaged. - */ - if(v->left || v->right){ - /* - This is case checked above in a different manner. - If this check fails, then memory corruption is - what's going on and we need to stop that... the only - way we reasonably can. Alternately, we may at some - point add a flag to the engine telling it it's in an - unrecoverable/unusable state. That would require - adding that check to a great many routines, though. - */ - dump_val(v,"Item from recycler???"); - if(v->left) dump_val(v->left,"v->left"); - if(v->right) dump_val(v->right,"v->right"); - assert(!"Trying to clean up item from recycler(?)!"); - return e->fatalCode = CWAL_RC_ASSERT; - /* abort(); */ - } - - assert(!CWAL_RCFLAG_HAS(v, CWAL_RCF_IS_DESTRUCTING)); - CWAL_RCFLAG_ON(v, CWAL_RCF_IS_DESTRUCTING); - assert(CWAL_RCFLAG_HAS(v, CWAL_RCF_IS_DESTRUCTING)); - assert(0 == v->right); - assert(0 == v->left); - - cwal_weak_unregister( e, v, v->vtab->typeID ); - v->scope = vScope - /* Workaround to help support the ancient behaviour - which may or may not still be relevant. - */; - v->vtab->cleanup(e, v); - v->scope = 0 /* END KLUDGE! */; - assert(CWAL_RCFLAG_HAS(v, CWAL_RCF_IS_DESTRUCTING)); - CWAL_RCFLAG_OFF(v, CWAL_RCF_IS_DESTRUCTING); - assert(!CWAL_RCFLAG_HAS(v, CWAL_RCF_IS_DESTRUCTING)); - CWAL_TR_V(e,v); - CWAL_TR3(e,CWAL_TRACE_VALUE_CLEAN_END, - "Cleanup complete. Sending to recycler..."); - assert(0 == CWAL_REFCOUNT(v)); - cwal_value_recycle(e, v); - return CWAL_RC_FINALIZED; - } - else{ - CWAL_TR_V(e,v); - CWAL_TR3(e,CWAL_TRACE_VALUE_REFCOUNT, - "It continues to live"); - return CWAL_RC_HAS_REFERENCES; - } - } -} - -cwal_value * cwal_value_unhand( cwal_value * v ){ - if(!v || CWAL_MEM_IS_BUILTIN(v)) return v; - else if(!v->scope){ - /* should we do this check, like we do in cwal_value_unref()? - if(CWAL_V_IS_IN_CLEANUP(v)) return NULL; - */ - assert(!"Cannot unhand a Value with no scope: serious misuse or Value corruption."); - return NULL; - } - else if(CWAL_REFCOUNT(v) && 0==CWAL_RCDECR(v)){ - cwal_value_reprobate(v->scope, v); - } - return v; -} - -/** - Increments cv's reference count by 1. Asserts that !CWAL_MEM_IS_BUILTIN(v) - and (NULL!=cv). Code which might be dealing with those value should - call the public-API-equivalent of this, cwal_value_ref(). -*/ -static int cwal_refcount_incr( cwal_engine *e, cwal_value * cv ) -{ - assert( NULL != cv ); - /* assert(!CWAL_MEM_IS_BUILTIN(cv)); */ - assert(cv->scope) /* also catches builtins */; - if( CWAL_RCFLAG_MAXRC <= CWAL_REFCOUNT(cv) ){ - /* Overflow! */ - cwal_dump_value( __FILE__, __LINE__, cv, - "FATAL: refcount overflow! How?!?"); - assert(!"Refcount overflow! Undefined behaviour!"); - return e->fatalCode = CWAL_RC_RANGE; - } - else if(1 == CWAL_RCINCR(cv)){ - if(cwal_scope_from_r0(cv)){ - assert(!"If this is failing then internal " - "preconditions/assumptions have not been met."); -#ifdef DEBUG - abort(); -#endif - return e->fatalCode = CWAL_RC_ASSERT; - } - } - if(CWAL_REFCOUNT(cv) > e->metrics.highestRefcount){ - e->metrics.highestRefcount = CWAL_REFCOUNT(cv); - e->metrics.highestRefcountType = cv->vtab->typeID; - } - CWAL_TR_V(e,cv); - CWAL_TR3(e,CWAL_TRACE_VALUE_REFCOUNT,"++Refcount"); - return 0; -} - -int cwal_value_ref2( cwal_engine *e, cwal_value * cv ){ - assert(e && cv); - if( !e || !cv ) return CWAL_RC_MISUSE; - else if( CWAL_MEM_IS_BUILTIN(cv) ) return CWAL_RC_OK; - else if( !cv->scope ){ - assert(!"Apparent attempt to ref() an " - "invalid (cleaned up?) value."); - return CWAL_RC_MISUSE; - } - else return CWAL_RCFLAG_MAXRC <= CWAL_REFCOUNT(cv) - ? CWAL_RC_RANGE - : cwal_refcount_incr( e, cv ); -} - -int cwal_value_ref( cwal_value * cv ){ - if( NULL == cv ) return CWAL_RC_MISUSE; - else if( CWAL_MEM_IS_BUILTIN(cv) ) return CWAL_RC_OK; - else if( !cv->scope ){ - assert(!"Apparent attempt to ref() an " - "invalid (cleaned up?) value."); - return CWAL_RC_MISUSE; - } - else { - assert( cv->scope->e ); - return cwal_refcount_incr( cv->scope->e, cv ); - } -} - -#if 0 -int cwal_ref(cwal_value *v){ return cwal_value_ref(v); } -int cwal_unref(cwal_value *v){ return cwal_value_unref(v); } -cwal_value * cwal_unhand( cwal_value * v ){ - return cwal_value_unhand(v); -} -#endif - -bool cwal_refunref( cwal_value * v ){ - char rc = 0; - if(v && v->scope && !CWAL_REFCOUNT(v)){ - /* This is a temp. Or, it turns out, it's an interned string - which is used in 2+ places and our nuking it has disastrous - side-effects. So... there is no obvious internal workaround - because string interning does not count how many instances - are interned (which we could use to "fudge" the refcount - check). So we're going to call that a usage error and leave - it at that. i'm suddenly very glad i resisted, at the time, - the urge to intern integers/doubles as well. - - One potential workaround, but not a good one: - - if v is-a string AND (v->scope->level < - v->scope->e->current->level) then don't nuke it. - - That would only hide the problem some (most?) of the time, - though. - */ - cwal_value_unref(v); - rc = 1; - } - return rc; -} - -cwal_refcount_t cwal_value_refcount( cwal_value const * v ){ - return v ? CWAL_REFCOUNT(v) : 0; -} - - -int cwal_scope_current( cwal_engine * e, cwal_scope ** s ){ - if(!e || !s) return CWAL_RC_MISUSE; - else if(!e->current) return CWAL_RC_RANGE; - else{ - *s = e->current; - return CWAL_RC_OK; - } -} - -cwal_scope * cwal_scope_current_get( cwal_engine * e ){ - return e ? e->current : 0; -} - - - -cwal_size_t cwal_type_id_sizeof( cwal_type_id id ){ - switch(id){ - case CWAL_TYPE_BOOL: - case CWAL_TYPE_UNDEF: - case CWAL_TYPE_NULL: - return 0; - case CWAL_TYPE_STRING: return sizeof(cwal_value)+sizeof(cwal_string); - case CWAL_TYPE_UNIQUE: return sizeof(cwal_value)+sizeof(cwal_value*); - case CWAL_TYPE_TUPLE: return sizeof(cwal_value)+sizeof(cwal_tuple); - case CWAL_TYPE_INTEGER: return sizeof(cwal_value)+sizeof(cwal_int_t); - case CWAL_TYPE_DOUBLE: return sizeof(cwal_value)+sizeof(cwal_double_t); - case CWAL_TYPE_ARRAY: return sizeof(cwal_value)+sizeof(cwal_array); - case CWAL_TYPE_OBJECT: return sizeof(cwal_value)+sizeof(cwal_object); - case CWAL_TYPE_NATIVE: return sizeof(cwal_value)+sizeof(cwal_native); - case CWAL_TYPE_BUFFER: return sizeof(cwal_value)+sizeof(cwal_buffer_obj); - case CWAL_TYPE_FUNCTION: return sizeof(cwal_value)+sizeof(cwal_function); - case CWAL_TYPE_EXCEPTION: return sizeof(cwal_value)+sizeof(cwal_exception); - case CWAL_TYPE_HASH: return sizeof(cwal_value)+sizeof(cwal_hash); - case CWAL_TYPE_SCOPE: return sizeof(cwal_scope); - case CWAL_TYPE_KVP: return sizeof(cwal_kvp); - case CWAL_TYPE_WEAK_REF: return sizeof(cwal_weak_ref); - case CWAL_TYPE_XSTRING: - case CWAL_TYPE_ZSTRING: - return sizeof(cwal_value) - +sizeof(cwal_string) - + sizeof(char **); - case CWAL_TYPE_LISTMEM: return 0; - default: - return 0; - } -} - -/** - Allocates a new value of the specified type. The value is pushed - onto e->current, effectively transfering ownership to that scope. - - extra is a number of extra bytes to allocate after the "concrete - type part" of the allocation. It is only valid for type - CWAL_TYPE_STRING, and must be the length of the string to allocate - (NOT included the terminating NUL byte - this function adds that - byte itself). - - The returned value->vtab member will be set appropriately and. Use - the internal CWAL_VVPCAST() family of macros to convert the - cwal_values to their corresponding native representation. - - Returns NULL on allocation error or if adding the new value - to s fails. - - @see cwal_new_array() - @see cwal_new_object() - @see cwal_new_string() - @see cwal_new_integer() - @see cwal_new_double() - @see cwal_new_function() - @see cwal_new_native() - @see cwal_new_buffer() - @see cwal_new_hash() - @see cwal_new_unique() - @see cwal_new_tuple() - @see cwal_value_unref() -*/ -static cwal_value * cwal_value_new(cwal_engine * e, - cwal_scope * s, - cwal_type_id t, cwal_size_t extra){ - enum { vsz = sizeof(cwal_value) }; - const cwal_size_t sz = vsz + extra /* base amount of memory to allocate */; - cwal_size_t tx = 0 /* number of extra bytes to allocate for the - concrete value type */; - cwal_value def = cwal_value_undef /* prototype to stamp over the - newly-allocated value */; - cwal_value * v = NULL; - switch(t) - { - case CWAL_TYPE_DOUBLE: - assert( 0 == extra ); - def = cwal_value_double_empty; - tx = sizeof(cwal_double_t); - break; - case CWAL_TYPE_INTEGER: - assert( 0 == extra ); - def = cwal_value_integer_empty; - /* We might want to consider using double for integers on - 32-bit platforms, which would allow us to support - larger-precision integers in the public interface by - hiding the doubles behind them. With that we could - effectively declare cwal_int_t as guarantying, say 48 - bits of integer precision. But would break if we add - disable-doubles support (which i would like to eventually - add as an option). - */ - tx = sizeof(cwal_int_t); - break; - case CWAL_TYPE_STRING:{ - assert( (extra > 0) && "empty strings are handled elsewhere" ); - def = cwal_value_string_empty; - tx = sizeof(cwal_string) + 1 /*NUL byte*/; - if(CwalConsts.StringPadSize){ - int const pad = extra % CwalConsts.StringPadSize; - if(pad) tx += CwalConsts.StringPadSize - pad; - } - break; - } - case CWAL_TYPE_XSTRING: - case CWAL_TYPE_ZSTRING: - assert( !extra && "x/z-string length is handled elsewhere" ); - def = cwal_value_string_empty; - tx = sizeof(cwal_string) + sizeof(unsigned char **) - /* x/z-strings are stored like - (cwa_value+cwal_string+(cstring-ptr)), and we stuff - the external string pointer in the cstring-ptr part. - */; - break; - case CWAL_TYPE_ARRAY: - assert( 0 == extra ); - def = cwal_value_array_empty; - tx = sizeof(cwal_array); - break; - case CWAL_TYPE_OBJECT: - assert( 0 == extra ); - def = cwal_value_object_empty; - tx = sizeof(cwal_object); - break; - case CWAL_TYPE_FUNCTION: - assert( 0 == extra ); - def = cwal_value_function_empty; - tx = sizeof(cwal_function); - break; - case CWAL_TYPE_NATIVE: - assert( 0 == extra ); - def = cwal_value_native_empty; - tx = sizeof(cwal_native); - break; - case CWAL_TYPE_EXCEPTION: - assert( 0 == extra ); - def = cwal_value_exception_empty; - tx = sizeof(cwal_exception); - break; - case CWAL_TYPE_BUFFER: - assert( 0 == extra ); - def = cwal_value_buffer_empty; - tx = sizeof(cwal_buffer_obj); - break; - case CWAL_TYPE_HASH: - assert( 0 == extra ); - def = cwal_value_hash_empty; - tx = sizeof(cwal_hash); - break; - case CWAL_TYPE_UNIQUE: - assert( 0 == extra ); - def = cwal_value_unique_empty; - tx = sizeof(cwal_value*); - break; - case CWAL_TYPE_TUPLE: - assert( 0 == extra ); - def = cwal_tuple_value_empty; - tx = sizeof(cwal_tuple); - break; - default: - assert(0 && "Unhandled type in cwal_value_new()!"); - /* FIXME: set e error state here. */ - return NULL; - } - assert( def.vtab->typeID != CWAL_TYPE_UNDEF ); - /* See if one of the recycle bins can serve the request... */ - if(CWAL_TYPE_STRING == t){ - v = cwal_string_from_recycler( e, extra ); - } - else{ - cwal_recycler * re = - cwal_recycler_get( e, t /*def.vtab->typeID (wrong for x/z-strings) */ ); - /* MARKER(("BIN #%d(%s)\n", recycleListIndex, def.vtab->typeName)); */ - if(re){ - if(!re->count){ - ++e->metrics.valuesRecycleMisses; - ++re->misses; - }else{ - /* Recycle (take) the first entry from the list. */ - ++re->hits; - ++e->metrics.valuesRecycled; - /* MARKER(("BIN #%d(%s) LENGTH=%u\n", recycleListIndex, cwal_type_id_name(t), (unsigned)re->count)); */ - v = (cwal_value*)re->list; - assert(NULL != v); - re->list = cwal_value_snip( v ); - --re->count; - CWAL_TR_V(e,v); - CWAL_TR3(e,CWAL_TRACE_MEM_FROM_RECYCLER, - "RECYCLED FROM BIN."); - assert(CWAL_RCFLAG_HAS(v, CWAL_RCF_IS_RECYCLED)); - CWAL_RCFLAG_OFF(v,CWAL_RCF_IS_RECYCLED); - assert(!CWAL_RCFLAG_HAS(v, CWAL_RCF_IS_RECYCLED)); - *v = def /* needed for types which share a recycling pool */; - } - } - } - ++e->metrics.requested[t]; - if(!v){ - /* Check the memchunk for an exact-fit match. This saves a - small handful of allocs and total memory, but increases the - search/miss ratio notably, going from ~5% misses to ~20% misses - in the s2 amalgamated unit tests. - */ - cwal_size_t reqSize = sz+tx; - v = (e->reChunk.config.useForValues - && e->reChunk.head - && e->reChunk.head->size<=reqSize) - ? (cwal_value*)cwal_memchunk_request(e, &reqSize, 0, - "cwal_value_new()") - : 0; - if(v){ - assert(reqSize==sz+tx); - }else{ - v = (cwal_value *)cwal_malloc(e, sz+tx); - if(v){ - ++e->metrics.allocated[t]; - e->metrics.bytes[t] += sz+tx; - } - } - } - if( v ) { - int rc = 0; - *v = def; - if(tx || extra){ - memset(v+1, 0, tx + extra); - } - assert(0 == v->scope); - assert(0 == CWAL_REFCOUNT(v)); - - CWAL_TR_V(e, v); - CWAL_TR_S(e, s); - CWAL_TR2(e, CWAL_TRACE_VALUE_CREATED); - if(s) { - int check = 0; - rc = cwal_value_xscope( e, s, v, &check ) - /* reminder: xscope "cannot fail" in this case except - on inputs which are corrupt in "just the right way" - such that they appear valid by this point. */ - ; - assert(0 == CWAL_REFCOUNT(v)); - assert(s == v->scope); - assert(-1==check); - assert(0==rc); - } - if(rc){ - /* Reminder to self: since the port to linked lists for - values, this scenario essentially cannot happen for a - new value. - */ - v->vtab->cleanup( e, v ); - cwal_free(e, v); - v = NULL; - } - else if(e->values.prototypes - /* Will only be false once, while creating - e->values.prototypes! This also means e->values.prototypes will - not get the built-in prototype for arrays unless we - special-case that, but clients do not have access - to e->values.prototypes, anyway, so that shouldn't be a - problem/limitation. - */){ - cwal_obase const * base = CWAL_VOBASE(v); - if(base){ - cwal_value * proto = cwal_prototype_base_get(e, t); - if(proto){ - /*MARKER(("Setting %s prototype from base: @%p\n", - cwal_type_id_name(t), (void const*)proto));*/ - cwal_value_prototype_set(v, proto); - assert(proto == cwal_value_prototype_get(e, v)); - } - } - } -#ifdef DEBUG - if(v){ /* Sanity-check that the CWAL_VOBASE() and CWAL_VALPART() - can perform round-trip conversions. If not, much of cwal - is broken! - */ - cwal_obase const * baseCheck = CWAL_VOBASE(v); - if(baseCheck){ - /*MARKER("v=@%p, baseCheck=@%p\n", (void const *)v, (void const *)baseCheck);*/ - assert( CWAL_VALPART(baseCheck) == v ); - } - } -#endif - } - return v; -} - -cwal_value * cwal_new_bool( int v ){ - return v ? &CWAL_BUILTIN_VALS.vTrue : &CWAL_BUILTIN_VALS.vFalse; -} - -cwal_value * cwal_value_true(){ - return &CWAL_BUILTIN_VALS.vTrue; -} - -cwal_value * cwal_value_false(){ - return &CWAL_BUILTIN_VALS.vFalse; -} - -cwal_value * cwal_value_null(){ - return &CWAL_BUILTIN_VALS.vNull; -} - -cwal_value * cwal_value_undefined(){ - return &CWAL_BUILTIN_VALS.vUndef; -} - -cwal_value * cwal_new_integer( cwal_engine * e, cwal_int_t v ){ - if(!e) return NULL; - if(v>=CWAL_BUILTIN_INT_FIRST && - v<= CWAL_BUILTIN_INT_LAST){ - METRICS_REQ_INCR(e,CWAL_TYPE_INTEGER); - return (cwal_value*) &CWAL_BUILTIN_VALS.memInt[v + -CWAL_BUILTIN_INT_FIRST]; - } - else{ - cwal_value * c = cwal_value_new(e, e->current, CWAL_TYPE_INTEGER,0); - if( c ){ - *CWAL_INT(c) = v; - } - return c; - } -} - -cwal_value * cwal_new_double( cwal_engine * e, cwal_double_t v ) -{ - if( CWAL_BUILTIN_VALS.dbls.zero == v ){ - METRICS_REQ_INCR(e,CWAL_TYPE_DOUBLE); - return CWAL_BUILTIN_VALS.vDbl0; - } - else if( CWAL_BUILTIN_VALS.dbls.one == v ){ - METRICS_REQ_INCR(e,CWAL_TYPE_DOUBLE); - return CWAL_BUILTIN_VALS.vDbl1; - } - else if( CWAL_BUILTIN_VALS.dbls.mOne == v ){ - METRICS_REQ_INCR(e,CWAL_TYPE_DOUBLE); - return CWAL_BUILTIN_VALS.vDblM1; - }else{ - cwal_value * c = cwal_value_new(e, e->current, CWAL_TYPE_DOUBLE, 0); - if( c ){ - memcpy(CWAL_DBL_NONULL(c), &v, sizeof(cwal_double_t)); - } - return c; - } -} - -cwal_value * cwal_new_unique( cwal_engine * e, cwal_value * wrapped ){ - cwal_value * v = e ? cwal_value_new(e, e->current, CWAL_TYPE_UNIQUE, 0) : 0; - if(v){ - *CWAL_UNIQUE_VALPP(v) = wrapped; - if(wrapped){ - cwal_value_ref(wrapped); - cwal_value_rescope(v->scope, wrapped) - /* that's just me being overly pedantic. It's not - possible that wrapped->scope is newer if v->scope - resp. e->current is running. */; - } - } - return v; -} - -cwal_value * cwal_unique_wrapped_get( cwal_value const * v ){ - cwal_value ** rc = CWAL_UNIQUE_VALPP(v); - return rc ? *rc : 0; -} - -int cwal_unique_wrapped_set( cwal_value * v, cwal_value * w ){ - cwal_value ** ch = CWAL_UNIQUE_VALPP(v); - if(!ch) return CWAL_RC_TYPE; - else if(v == w) return CWAL_RC_CYCLES_DETECTED; - else{ - cwal_value * prev = *ch; - if(prev == w) return 0; - else{ - *ch = w; - if(w){ - cwal_value_ref(w); - cwal_value_rescope(v->scope, w); - } - if(prev){ - assert( CWAL_REFCOUNT(prev) || CWAL_MEM_IS_BUILTIN(prev) ); - cwal_value_unref(prev); - } - return 0; - } - } -} - -uint16_t cwal_tuple_length(cwal_tuple const * p){ - return p ? p->n : 0; -} - -int cwal_tuple_set(cwal_tuple * p, uint16_t n, cwal_value * v){ - cwal_value * self = CWAL_VALPART(p); - if(!self) return CWAL_RC_MISUSE; - else if(n>=p->n) return CWAL_RC_RANGE; - /* else if(self == v) return CWAL_RC_CYCLES_DETECTED; - Cycles are not a problem, are they? */ - else{ - cwal_value * ch = p->list[n]; - if(v) cwal_value_ref(v); - if(ch) cwal_value_unref(ch); - p->list[n] = v; - if(v) cwal_value_rescope(self->scope, v); - return 0; - } -} - -cwal_value * cwal_tuple_get(cwal_tuple const * p, uint16_t n){ - return (p && nn) ? p->list[n] : 0; -} - -cwal_tuple * cwal_new_tuple( cwal_engine * e, uint16_t n ){ - if(!n){ - assert(CWAL_MEM_IS_BUILTIN(CWAL_BUILTIN_VALS.vTuple0)); - return CWAL_TUPLE(CWAL_BUILTIN_VALS.vTuple0); - }else{ - cwal_tuple * p = 0; - cwal_value * v = e - ? cwal_value_new(e, e->current, CWAL_TYPE_TUPLE, 0) - : 0; - if(v){ - cwal_size_t const reqSize = sizeof(cwal_value*) * n; - p = CWAL_TUPLE(v); - assert(p); - p->list = (cwal_value**)cwal_malloc2(e, reqSize); - if(!p->list){ - cwal_value_unref(v); - p = 0; - }else{ - memset(p->list, 0, reqSize); - p->n = n; - } - } - return p; - } -} - -cwal_value * cwal_new_tuple_value( cwal_engine * e, uint16_t n ){ - cwal_tuple * p = cwal_new_tuple(e, n); - return CWAL_VALPART(p); -} - -cwal_value * cwal_tuple_value( cwal_tuple const * p ){ - return CWAL_VALPART(p); -} - -cwal_tuple * cwal_value_get_tuple( cwal_value * v ){ - return CWAL_TUPLE(v); -} - -#if 0 -/* Not needed because tuples cannot be prototypes. Maybe - someday. */ -cwal_tuple * cwal_tuple_part( cwal_engine * e, - cwal_value * v ){ - cwal_tuple * p; - do{ - if( (p = CWAL_TUPLE(v)) ) return p; - else v = cwal_value_prototype_get(e, v); - }while(v); - return NULL; -} -#endif - -int cwal_tuple_visit( cwal_tuple * o, cwal_value_visitor_f f, void * state ){ - cwal_value * const tv = CWAL_VALPART(o); - if(!tv || !f) return CWAL_RC_MISUSE; - /*else if(CWAL_OB_IS_LOCKED(o)) return CWAL_RC_LOCKED;*/ - else if(!o->n) return 0; - else { - uint16_t i; - cwal_value * v; - int rc = CWAL_RC_OK; - int opaque; - cwal_visit_list_begin(tv, &opaque); - cwal_value_ref(tv); - for( i = 0; i < o->n && !rc; ++i ){ - v = o->list[i]; - if(v) cwal_value_ref(v); - rc = f( v, state ); - if(v) cwal_value_unref(v); - } - cwal_value_unhand(tv); - cwal_visit_list_end(tv, opaque); - return rc; - } -} - -cwal_value * cwal_new_array_value(cwal_engine *e){ - cwal_value * v = (e && e->current) - ? cwal_value_new(e, e->current, CWAL_TYPE_ARRAY,0) - : 0; - if( NULL != v ){ - cwal_array * ar = CWAL_ARRAY(v); - cwal_value * proto = ar->base.prototype; - *ar = cwal_array_empty; - ar->base.prototype = proto; - } - return v; -} - -cwal_array * cwal_new_array(cwal_engine *e){ - return cwal_value_get_array(cwal_new_array_value(e)); -} - -cwal_value * cwal_new_object_value(cwal_engine *e){ - cwal_value * v = (e && e->current) - ? cwal_value_new(e, e->current, CWAL_TYPE_OBJECT,0) - : 0; - if( NULL != v ) - { - cwal_object * ar = CWAL_OBJ(v); - cwal_value * proto = ar->base.prototype; - *ar = cwal_object_empty; - ar->base.prototype = proto; - } - return v; -} - -cwal_object * cwal_new_object(cwal_engine *e){ - return cwal_value_get_object(cwal_new_object_value(e)); -} - -/** - If li->list is not 0 and e has space in its list memory recycler, - the contents of li are moved into the recycler and *li is reset to a - clean state. If li->list but the recycler has no slots, the memory - is freed instead. -*/ -static void cwal_list_to_recycler( cwal_engine * e, cwal_list * li ); - -/** - Frees all cwal_kvp entries in the given htable. If freeList - is true then it also frees up htable->list.list. -*/ -static void cwal_cleanup_htable( cwal_engine * const e, - cwal_htable * const htable, - bool freeList){ - cwal_kvp * kvp = 0; - cwal_kvp * next = 0; - for( cwal_midsize_t i = 0; - htable->list.count && (i < htable->hashSize); - ++i ){ - kvp = (cwal_kvp*)htable->list.list[i]; - htable->list.list[i] = next = NULL; - for(; kvp; kvp = next){ - assert(htable->list.count>0); - next = kvp->right; - kvp->right = 0; - cwal_kvp_free( e, kvp, 1 ); - --htable->list.count; - } - } - assert(0==htable->list.count); - if(freeList){ - cwal_list_to_recycler(e, &htable->list); - assert(0==htable->list.count); - assert(0==htable->list.alloced); - assert(0==htable->list.list); - } -} - -/** - Cleanup routine for the cwal_obase part of classes which use that. - Cleans up the contents of b->kvp and sets b->kvp to NULL. Also, if - unrefProto is true, clears the - CWAL_CONTAINER_DISALLOW_PROTOTYPE_SET flag from b->flags and - unrefs/NULLs b->prototype. -*/ -static void cwal_cleanup_obase( cwal_engine * e, cwal_obase * b, bool unrefProto ){ -#if CWAL_OBASE_ISA_HASH - cwal_cleanup_htable(e, &b->hprops, true); -#else - while(b->kvp){ - cwal_kvp * kvp = b->kvp; - cwal_kvp * next = 0; - b->kvp = 0; - /* In theory the is-visiting flag is not needed here because - b->kvp=0 means we cannot possibly traverse the property - list as a side-effect of this cleanup. Well, we cannot - travse THIS property list. We can only hope that cleanup - does not then add properties to b->kvp, but that's why we - while(b->kvp). - */ - /* b->flags |= CWAL_F_IS_VISITING; */ - for( ; kvp; kvp = next ){ - next = kvp->right; - kvp->right = 0; - /* if(kvp->key==bv) kvp->key = 0; */ - /* if(kvp->value==bv) kvp->value = 0; */ - cwal_kvp_free( e/* , bv->scope */, kvp, 1 ); - } - /* b->flags &= ~CWAL_F_IS_VISITING; */ - } -#endif - if( unrefProto ){ - b->flags &= ~CWAL_CONTAINER_DISALLOW_PROTOTYPE_SET; - if( b->prototype ){ - cwal_value_prototype_set( CWAL_VALPART(b), NULL ); - } - } -} - -/** - If table->hashSize is 0, initialize the table for hashSize - elements, or CwalConsts.ScopePropsHashSize if hashSize==0. Use this - only to initialize an empty table. Returns 0 on success, - CWAL_RC_OOM on error. -*/ -static int cwal_htable_alloc( cwal_engine * const e, cwal_htable * const table, - cwal_midsize_t hashSize ){ - if(table->hashSize && table->list.alloced){ - assert(table->list.alloced >= table->hashSize); - assert(table->hashSize >= hashSize); - return 0; - }else{ - assert(!table->list.alloced); - if(!hashSize) hashSize = CwalConsts.DefaultHashtableSize; - int rc = 0; - if(hashSize > cwal_list_reserve(e, &table->list, hashSize)){ - rc = CWAL_RC_OOM; - }else{ - table->hashSize = hashSize; - } - return rc; - } -} - -/** @internal - - Internal impl for cwal_list-of-(cwal_kvp*) hashtable search. If - tableIndex is not NULL then *tableIndex is assigned to the hash - table index for the given key, even on search failure. - - If a match is found then its kvp entry is returned and if left is - not NULL then *left will point to the kvp immediately to the left - of the returned kvp in the hash table (required for re-linking - collisions). - - This function is intollerant of NULLs for (table,key). -*/ -static cwal_kvp * cwal_htable_search_impl_v( cwal_htable const * htable, - cwal_value const * key, - cwal_midsize_t * tableIndex, - cwal_kvp ** left ){ - if(!htable->hashSize) return NULL; - cwal_midsize_t const ndx = cwal_value_hash( key ) % htable->hashSize; - if(!htable->list.count){ - if(left) *left = 0; - if(tableIndex) *tableIndex = ndx; - return NULL; - } - cwal_type_id const kType = key->vtab->typeID /*cwal_value_type_id(key)*/; - cwal_kvp * kvp = (cwal_kvp*)htable->list.list[ndx]; - //dump_val(key, "cwal_htable_search_impl_v() key"); - //MARKER(("ndx=%d, list->count=%d, kvp=%p\n", (int)ndx, (int)htable->list.count, (void const*)kvp)); - if(tableIndex) *tableIndex = ndx; - for( ; kvp; (left?(*left=kvp):NULL), kvp = kvp->right ){ - assert(kvp->key); -#if 0 - if(kvp){ - dump_val(kvp->key,"cwal_htable_search_impl_v() found key"); - dump_val(kvp->value,"cwal_htable_search_impl_v() found value"); - } -#endif - if(kvp->key==key) return kvp; - else if(kType != kvp->key->vtab->typeID - /*cwal_value_type_id(kvp->key)*/){ - //dump_val(kvp->key,"cwal_htable_search_impl_v() type mismatch. Skipping"); - continue; - } - else if(0==key->vtab->compare(key, kvp->key)){ - //MARKER(("returning ndx=%d, kvp=%p\n", (int)ndx, (void const*)kvp)); - return kvp; - } - } - return NULL; -} - -/** - C-string conterpart of cwal_htable_search_impl_v(). -*/ -static cwal_kvp * cwal_htable_search_impl_cstr( cwal_htable const * htable, - char const * key, - cwal_midsize_t keyLen, - cwal_midsize_t * tableIndex, - cwal_kvp ** left ){ - if(!htable->hashSize) return NULL; - cwal_hash_t const ndx = - cwal_hash_bytes( key, keyLen ) % htable->hashSize; - if(!htable->list.count){ - if(left) *left = 0; - if(tableIndex) *tableIndex = ndx; - return NULL; - } - cwal_kvp * kvp = (cwal_kvp*)htable->list.list[ndx]; - cwal_string const * sk; -#if 0 - MARKER(("%s() hash entries=%d, ndx=%d, key=%.*s, hash=%08x, kvp=%p\n", __func__, - (int)htable->list.count, (int)ndx, (int)keyLen, key, - (unsigned)cwal_hash_bytes( key, keyLen ), - (void *)kvp)); -#endif - if(tableIndex) *tableIndex = ndx; - for( ; kvp; (left?(*left=kvp):NULL), kvp = kvp->right ){ - assert(kvp->key); - //dump_val(kvp->key, "Comparing to this key."); - if(CWAL_TYPE_STRING != cwal_value_type_id(kvp->key)) continue; - sk = cwal_value_get_string(kvp->key); - if(keyLen != CWAL_STRLEN(sk)) continue; - else if(0==cwal_compare_str_cstr(sk, key, keyLen)){ - return kvp; - } - } - return NULL; -} - -/** - The cwal_htable counterpart of the public API's - cwal_hash_insert_with_flags_v(). The isResizing flag must only be - true when this insert is called during the course of - cwal_htable_resize(). That parameter is not strictly needed: it's - used as a sanity-checking measure for a case which could, if - internally used incorrectly, lead to infinite recursion (stack - overflow). -*/ -static int cwal_htable_insert_impl_v( cwal_value * const container, - cwal_htable * const table, - cwal_value * const key, cwal_value * const v, - bool allowOverwrite, uint16_t kvpFlags, - bool isResizing ); -/** - The cwal_htable counterpart of the public API's - cwal_hash_grow_if_loaded(). If load<=0 then - CwalConsts.PreferredHashLoad is used. htable is assumed to be - a component of the given container. -*/ -static int cwal_htable_grow_if_loaded( cwal_value * const container, - cwal_htable * htable, double load ); - -/** - Assumes table is used as a hashtable for the value hv. The table - is, if needed, resized to toSize. Returns 0 on success, CWAL_RC_OOM - on OOM. -*/ -static int cwal_htable_resize( cwal_value * const hv, - cwal_htable * const table, - cwal_midsize_t toSize ){ - if(!hv) return CWAL_RC_MISUSE; - else if(!toSize) return CWAL_RC_RANGE; - //else if(CWAL_V_IS_VISITING_LIST(hv)) return CWAL_RC_IS_VISITING_LIST; - else if(toSize==table->hashSize) return 0; - /* highly arguable: toSize = cwal_trim_hash_size( toSize ); */ - cwal_list li = cwal_list_empty; - int rc = 0; - cwal_engine * e = hv->scope->e; - cwal_midsize_t i; - //cwal_midsize_t const oldSize = table->hashSize; -#ifdef DEBUG - cwal_midsize_t const oldCount = table->list.count; -#endif - //MARKER(("Resizing htable @%p from %d to %d\n", (void *)table, (int)table->hashSize, (int)toSize)); - //dump_val(hv, "hv htable holder"); - if(toSize > cwal_list_reserve(e, &li, toSize)){ - assert(!li.list); - return CWAL_RC_OOM; - } - { - /* Swap the table memory */ - cwal_list const tmp = table->list; - table->list = li; - li = tmp; - } - /* Iterate over li.list and move all entries into table->list, - assigning them to a new index, as appropriate. */ - table->hashSize = toSize; - assert(toSize <= table->list.alloced); - assert(!table->list.count); - assert(li.alloced ? !!li.list : !li.list); - for( i = 0; li.count; ++i ){ - cwal_kvp * kvp = (cwal_kvp*)li.list[i]; - cwal_kvp * next = 0; - li.list[i] = 0; - for( ; !rc && kvp; kvp = next ){ - cwal_value * const k = kvp->key; - cwal_value * const v = kvp->value; - assert(V_SEEMS_OK(k)); - assert(V_SEEMS_OK(v)); - next = kvp->right; - /* kvp holds refs to k/v, but we're going to steal them... */ - kvp->right = 0; - kvp->key = 0; - kvp->value = 0; - /* *kvp = cwal_kvp_empty; must retain flags */ - e->values.hashXfer = kvp; -#if defined(DEBUG) - cwal_midsize_t const cCheck = table->list.count; -#endif - rc = cwal_htable_insert_impl_v( hv, table, k, v, false, kvp->flags, true ); - assert(!rc) /* cannot fail under these conditions - no allocation */; - assert(0==e->values.hashXfer); - assert(kvp->key == k); - assert(kvp->value == v); - assert(table->list.count==cCheck+1); - /* We got an extra ref on k/v up there, so... */ - assert(CWAL_REFCOUNT(k)>1 || CWAL_MEM_IS_BUILTIN(k)); - assert(CWAL_REFCOUNT(v)>1 || CWAL_MEM_IS_BUILTIN(v)); - cwal_value_unref(k); - cwal_value_unref(v); - assert(CWAL_MEM_IS_BUILTIN(k) || k->scope); - assert(CWAL_MEM_IS_BUILTIN(v) || v->scope); - assert(V_SEEMS_OK(k)); - assert(V_SEEMS_OK(v)); - --li.count; - } - } - assert(0==li.count); -#if defined(DEBUG) - assert(table->list.count == oldCount); -#endif - cwal_list_reserve(e, &li, 0); - return rc; -} - -static int cwal_htable_grow_if_loaded( cwal_value * const container, - cwal_htable * htable, double load ){ - if(!htable->list.count) return 0; - else if(load<=0) load = CwalConsts.PreferredHashLoad; - else if(load<0.5) load = 0.5/*kinda arbitrary*/; - double const hashSize = (double)htable->hashSize; - double const entryCount = (double)(htable->list.count - ? htable->list.count - : CwalConsts.DefaultHashtableSize); - int rc = 0; - assert(hashSize); -#if 0 - /* arguable. If someone wants loads of 5.0, let him. OTOH, values - approaching or surpassing 1.0 break an upcoming calculation... */ - if(load >= 0.95) load = 0.95; -#endif - if((entryCount / hashSize) > load){ - cwal_midsize_t const newSize = - (cwal_midsize_t)cwal_next_prime((cwal_midsize_t)(entryCount * 3 / 2)); - assert(newSize > entryCount); -#if 0 - MARKER(("Resizing hash: container@%p old size=%f, count=%f, Going for load %f, size=%d\n", - (void const *)container, - hashSize, entryCount, load, (int)newSize)); -#endif - rc = cwal_htable_resize(container, htable, newSize); - } - return rc; -} - -int cwal_htable_insert_impl_v( cwal_value * const container, - cwal_htable * const table, - cwal_value * const key, cwal_value * const v, - bool allowOverwrite, uint16_t kvpFlags, - bool isResizing ){ - cwal_midsize_t ndx = 0; - cwal_kvp * left = 0; - cwal_kvp * kvp; - cwal_obase * const base = CWAL_VOBASE(container); - cwal_scope * const sc = container->scope; - if(!key || !v) return CWAL_RC_MISUSE; - else if(CWAL_V_IS_IN_CLEANUP(container)) return CWAL_RC_DESTRUCTION_RUNNING; -#if 0 - // These need to be checked in the higher-level containers which - // call this - else if((h = CWAL_HASH(container)) && - table==&h->htable - && CWAL_V_IS_VISITING_LIST(container)){ - /* Genuine hashtable entries */ - return CWAL_RC_IS_VISITING_LIST; - } - else if(CWAL_V_IS_VISITING(container)){ - /* base->hprops properties */ - return CWAL_RC_IS_VISITING; - } -#endif - else if(!cwal_prop_key_can(key)) return CWAL_RC_TYPE; - assert(!(CWAL_CONTAINER_DISALLOW_PROP_SET & base->flags) - && "Expecting this to be checked before this is called."); - int rc = 0; - /* Maintenance reminder: we need to init/resize the table before - searching so that the calculated hash index is valid. There's a - potential corner case here where we'll grow even if the entry is - already in the hashtable (so no new space would have been - needed), but that's not too tragic. Working around that would - require(?) searching, then resizing if needed, then searching - _again_ so that we pick up the proper (new) kvp->right and ndx - values. Not worth it. */ - if(!table->list.alloced){ - assert(!isResizing && "Table must have already been allocated in this case."); - rc = cwal_htable_alloc(CWAL_VENGINE(container), table, 0); - }else if(!isResizing){ - rc = cwal_htable_grow_if_loaded(container, table, -1.0); - } - if(rc) return rc; - assert(table->list.alloced>=table->hashSize); - kvp = cwal_htable_search_impl_v( table, key, &ndx, &left ); - if(kvp){ - assert(!isResizing); - if(!allowOverwrite) return CWAL_RC_ALREADY_EXISTS; - else if(CWAL_VAR_F_CONST & kvp->flags){ - return CWAL_RC_CONST_VIOLATION; - }else if(kvp->key != key){ - cwal_value * const old = kvp->key; - cwal_value_xscope(sc->e, sc, key, 0); - if(E_IS_DEAD(sc->e)) return sc->e->fatalCode; - kvp->key = key; - cwal_value_ref(key); - cwal_value_unref(old); - } - if(kvp->value != v){ - cwal_value * const old = kvp->value; - cwal_value_xscope(sc->e, sc, v, 0); - if(E_IS_DEAD(sc->e)) return sc->e->fatalCode; - kvp->value = v; - cwal_value_ref(v); - cwal_value_unref(old); - } - if(CWAL_VAR_F_PRESERVE!=kvpFlags) kvp->flags = kvpFlags; - }else{/* Not found: add it. */ - if(CWAL_CONTAINER_DISALLOW_NEW_PROPERTIES & base->flags){ - return CWAL_RC_DISALLOW_NEW_PROPERTIES; - } - if(sc->e->values.hashXfer){ - kvp = sc->e->values.hashXfer; - sc->e->values.hashXfer = 0; - }else{ - kvp = cwal_kvp_alloc(sc->e); - if(!kvp) return CWAL_RC_OOM; - } - assert(!kvp->key); - assert(!kvp->value); - assert(!kvp->right); - if(left){ - kvp->right = left->right; - left->right = kvp; - }else{ - kvp->right = (cwal_kvp*)table->list.list[ndx]; - table->list.list[ndx] = kvp; - } - cwal_value_xscope(sc->e, sc, key, 0); - cwal_value_xscope(sc->e, sc, v, 0); - cwal_value_ref(key); - cwal_value_ref(v); - kvp->key = key; - kvp->value = v; - if(CWAL_VAR_F_PRESERVE!=kvpFlags) kvp->flags = kvpFlags; - assert(CWAL_MEM_IS_BUILTIN(key) || key->scope); - assert(CWAL_MEM_IS_BUILTIN(v) || v->scope); -#if 0 && CWAL_OBASE_ISA_HASH - dump_val(kvp->key,"inserted hash key"); - dump_val(kvp->value,"inserted hash value"); - dump_val(container,"inserted into container"); - MARKER(("hash ndx=%d, hashSize=%d\n", (int)ndx, (int)table->hashSize)); -#endif - ++table->list.count; - } - return 0; -} - -static int cwal_htable_remove_impl_v( cwal_value * const vSelf, - cwal_htable * const htable, - cwal_value * const key ){ - if(!htable || !key) return CWAL_RC_MISUSE; - else if(!htable->hashSize || !htable->list.count) return CWAL_RC_NOT_FOUND; - assert(!(CWAL_RCFLAG_HAS(vSelf,CWAL_RCF_IS_DESTRUCTING)) - && "Expecting this to be checked upstream."); -#if 0 - // To be checked by higher-level containers... - if(CWAL_RCFLAG_HAS(vSelf,CWAL_RCF_IS_DESTRUCTING)) return CWAL_RC_DESTRUCTION_RUNNING; - else if(CWAL_CONTAINER_DISALLOW_PROP_SET & CWAL_VOBASE(vSelf)->flags) return CWAL_RC_DISALLOW_PROP_SET; - else if(CWAL_V_IS_VISITING_LIST(vSelf)) return CWAL_RC_IS_VISITING_LIST; -#endif - cwal_midsize_t ndx = 0; - cwal_kvp * left = 0; - cwal_kvp * const kvp = - cwal_htable_search_impl_v( htable, key, &ndx, &left ); - cwal_engine * const e = vSelf->scope->e; - if(!kvp) return CWAL_RC_NOT_FOUND; - else{ - assert(htable->list.count>0); - if(left){ - left->right = kvp->right; - }else{ - htable->list.list[ndx] = kvp->right; - } - kvp->right = NULL; - --htable->list.count; - cwal_kvp_free(e, kvp, 1); - return 0; - } -} - -static int cwal_htable_remove_impl_cstr( cwal_value * const vSelf, - cwal_htable * const htable, - char const * const key, - cwal_midsize_t keyLen ){ - if(!vSelf || !key) return CWAL_RC_MISUSE; - else if(!htable->hashSize || !htable->list.count) return CWAL_RC_NOT_FOUND; - assert(!(CWAL_RCFLAG_HAS(vSelf,CWAL_RCF_IS_DESTRUCTING)) - && "Expecting this to be checked upstream."); -#if 0 - // To be checked by higher-level containers... - else if(CWAL_RCFLAG_HAS(vSelf,CWAL_RCF_IS_DESTRUCTING)) return CWAL_RC_DESTRUCTION_RUNNING; - else if(CWAL_CONTAINER_DISALLOW_PROP_SET & CWAL_VOBASE(vSelf)->flags) return CWAL_RC_DISALLOW_PROP_SET; - else if(CWAL_V_IS_VISITING_LIST(vSelf)) return CWAL_RC_IS_VISITING_LIST; -#endif - cwal_midsize_t ndx = 0; - cwal_kvp * left = 0; - cwal_kvp * kvp; - cwal_engine * const e = vSelf->scope->e; - kvp = cwal_htable_search_impl_cstr( htable, key, keyLen, &ndx, &left ); - if(!kvp) return CWAL_RC_NOT_FOUND; - else{ - assert(htable->list.count>0); - if(left){ - left->right = kvp->right; - }else{ - htable->list.list[ndx] = kvp->right; - } - kvp->right = NULL; - --htable->list.count; - cwal_kvp_free(e, kvp, 1); - return 0; - } -} - -void cwal_list_to_recycler( cwal_engine * e, cwal_list * li ){ - if(li->list){ - cwal_memchunk_add(e, li->list, li->alloced * sizeof(void*)); - *li = cwal_list_empty; - }else{ - assert(!li->count); - assert(!li->alloced); - li->isVisiting = false; - } -} - -/** - Cleans up various parts of an array: - - self must be a (ceal_value*). - - Cleans up all list entries Then... - - freeList: if true, frees all list memory - - freeProps: if true, clears all properties. - - unrefProto: if true, clears the - CWAL_CONTAINER_DISALLOW_PROTOTYPE_SET flag from the cwal_obase part - and unsets/unrefs the prototype. -*/ -static void cwal_value_cleanup_array_impl( cwal_engine * e, void * self, - char freeList, char freeProps, - char unrefProto ){ - cwal_value * const vSelf = (cwal_value *)self; - cwal_array * const ar = cwal_value_get_array(vSelf); - int opaque; - assert(NULL!=ar); - cwal_visit_list_begin(vSelf, &opaque); - if( ar->list.count ){ - cwal_value * v; - cwal_size_t i = 0, x = ar->list.count -1; - for( ; i < ar->list.count; ++i, --x ){ - v = (cwal_value*)ar->list.list[x]; - if(v){ - ar->list.list[x] = NULL; - if(!CWAL_V_IS_IN_CLEANUP(v)){ - cwal_value_unref(v); - } - } - } - ar->list.count = 0; - } - cwal_visit_list_end(vSelf, opaque); - if(freeList && ar->list.list){ - cwal_list_to_recycler(e, &ar->list); - } - if(freeProps) { - cwal_cleanup_obase( e, &ar->base, 0 ); - } - if(unrefProto){ - ar->base.flags &= ~CWAL_CONTAINER_DISALLOW_PROTOTYPE_SET; - if(ar->base.prototype){ - assert(vSelf->scope && "We can't have a prototype and yet have no scope."); - /* dump_val(vSelf,"Unref'ing this one's prototype"); */ - /* dump_val(ar->base.prototype,"Unref'ing prototype"); */ - cwal_value_prototype_set( vSelf, NULL ); - } - } -} - - -/** - cwal_value_vtab::cleanup() impl for Array values. Cleans up - self-owned memory, but does not free self. -*/ -void cwal_value_cleanup_array( cwal_engine * e, void * self ){ - cwal_value_cleanup_array_impl( e, self, 1, 1, 1 ); -} - -void cwal_array_clear( cwal_array * ar, char freeList, char freeProps ){ - cwal_scope * s = ar ? CWAL_VALPART(ar)->scope : 0; - cwal_engine * e = s ? s->e : 0; - if(e){ - cwal_value_cleanup_array_impl( e, CWAL_VALPART(ar), - freeList, freeProps, 0 ); - } -} - -void cwal_value_cleanup_object( cwal_engine * e, void * self ){ - cwal_value * vSelf = (cwal_value *)self; - cwal_object * ar = cwal_value_get_object(vSelf); - assert(vSelf && ar); - cwal_cleanup_obase( e, &ar->base, 1 ); - *ar = cwal_object_empty; -} - - -void cwal_value_cleanup_function( cwal_engine * e, void * self ){ - cwal_value * v = (cwal_value*)self; - cwal_function * f = CWAL_VVPCAST(cwal_function,v); - assert(v && f); - if(f->state.finalize){ - f->state.finalize( e, f->state.data ); - } - cwal_cleanup_obase( e, &f->base, 1 ); - *f = cwal_function_empty; -} - -int cwal_value_fetch_function( cwal_value const * val, cwal_function ** x){ - if( ! val ) return CWAL_RC_MISUSE; - else if( CWAL_TYPE_FUNCTION != val->vtab->typeID ) return CWAL_RC_TYPE; - else{ - if(x) *x = CWAL_VVPCAST(cwal_function,val); - return 0; - } -} - - -cwal_value * cwal_new_function_value(cwal_engine * e, - cwal_callback_f callback, - void * state, - cwal_finalizer_f stateDtor, - void const * stateTypeID ){ - if(!e || !callback) return NULL; - else{ - cwal_value * v = cwal_value_new(e, e->current, CWAL_TYPE_FUNCTION, 0); - if( NULL != v ) { - cwal_function * f = CWAL_VVPCAST(cwal_function,v); - cwal_value * proto = f->base.prototype; - *f = cwal_function_empty; - f->base.prototype = proto; - f->state.data = state; - f->state.finalize = stateDtor; - f->state.typeID = stateTypeID; - f->callback = callback; - } - return v; - } -} - -cwal_function * cwal_new_function(cwal_engine * e, - cwal_callback_f callback, - void * state, - cwal_finalizer_f stateDtor, - void const * stateTypeID ){ - cwal_value * v = cwal_new_function_value(e, callback, state, - stateDtor, stateTypeID); - return v ? cwal_value_get_function(v) : NULL; -} - -int cwal_function_unref(cwal_function *fv){ - cwal_value * v = CWAL_VALPART(fv); - if(!v){ - assert(!fv); - return CWAL_RC_MISUSE; - } - assert(v->scope); - assert(v->scope->e); - return cwal_value_unref2( v->scope->e, v ); -} - -cwal_engine * cwal_scope_engine(cwal_scope const * s){ - return s ? s->e : NULL; -} - - -int cwal_function_call_array( cwal_scope * s, - cwal_function * f, - cwal_value * self, - cwal_value ** rv, - cwal_array * args){ - cwal_value ** argv = args ? - (args->list.count ? (cwal_value **)args->list.list : 0) - : 0; - int const argc = argv ? (int)args->list.count : 0; - int rc; - cwal_value * vargs = argc ? CWAL_VALPART(args) : 0; - char const aWasVacSafe = vargs - ? CWAL_V_IS_VACUUM_SAFE(vargs) - : 1; - if(argc && !aWasVacSafe){ - cwal_value_make_vacuum_proof(vargs,1); - } - cwal_value_ref(vargs); - rc = s - ? cwal_function_call_in_scope( s, f, self, rv, argc, argv ) - : cwal_function_call( f, self, rv, argc, argv ); - cwal_value_unhand(vargs); - if(!aWasVacSafe){ - cwal_value_make_vacuum_proof(vargs,0); - } - return rc; -} - -int cwal_function_call_in_scope2( cwal_scope * s, - cwal_function * f, - cwal_value * propertyHolder, - cwal_value * self, - cwal_value ** _rv, - uint16_t argc, - cwal_value * const * argv){ - uint16_t cflags = 0; - if(!s ||!s->e || !f) return CWAL_RC_MISUSE; - else if((cflags = cwal_container_flags_get(CWAL_VALPART(f))) - && (CWAL_CONTAINER_INTERCEPTOR_RUNNING & cflags)){ - return CWAL_RC_CYCLES_DETECTED; - } - else { - cwal_engine * const e = s->e /* typing saver */; - cwal_scope * old = e->current /* previous scope */; - cwal_scope * check = 0 /* sanity check */; - int rc = 0; - cwal_callback_args args = cwal_callback_args_empty /* callback state */; - cwal_value * rv = 0 /* result value for f() */; - cwal_value * fv = CWAL_VALPART(f); - cwal_callback_hook const hook = e->cbHook /* why (again) do we take/need a copy? */; - char const fWasVacuumProof = CWAL_V_IS_VACUUM_SAFE(fv); - cwal_obase * selfBase = CWAL_VOBASE(self); - char const selfWasVacSafe = selfBase - ? CWAL_V_IS_VACUUM_SAFE(self) - : 0; - /* uint32_t const oldScopeFlags = s->flags; */ - assert(fv->scope); - args.engine = e; - args.scope = s; - args.self = self; - args.callee = f; - args.state = f->state.data; - args.stateTypeID = f->state.typeID; - args.argc = argc; - args.argv = argv; - args.propertyHolder = propertyHolder; - /* s->flags |= CWAL_F_IS_CALL_SCOPE; */ - - /* We can't just fiddle with the refcount here: - we have to make sure fv is removed from - fv->scope->mine.r0 so it's sweep-safe. */ - rc = cwal_refcount_incr(e, fv); - if(rc) return rc /* game over, man */; - - /* - We set the vacuum-proofing flag and an artificial - reference on f to proactively cover this hypothetical - case: - - function(){...}() - - where the anonymous function triggers a recursive sweep or - vacuum. - - Reminder to self: - - (proc(){...})() - - in th1ish, that can theoretically kill that proc before the - call op can be applied if auto-sweeping is running at an - interval of 1! In s2, the eval engine disables - sweeping/vacuuming during any given single expression, so - it's not a problem there unless/until we add recursive - sweeping/vacuuming. - */ - if(!fWasVacuumProof){ - cwal_value_make_vacuum_proof(fv, 1); - /* why does this trigger in th1ish? */ - assert(fv == (CWAL_REFCOUNT(fv) ? fv->scope->mine.headSafe : fv->scope->mine.r0)); - /* - Reminder: in th1ish we have refcount-0 funcs being - called. That's potentially unsafe (we've learned in the - meantime). - */ - } - if(self){ - cwal_value_ref(self); - if(selfBase && !selfWasVacSafe){ - cwal_value_make_vacuum_proof(self,1); - } - } - cwal_value_ref(propertyHolder); - if(hook.pre){ - rc = hook.pre(&args, hook.state); - } - if(!rc){ - uint16_t i; - for(i = 0; i < argc; ++i ) cwal_value_ref(argv[i]); - if(CWAL_CONTAINER_INTERCEPTOR & cflags){ - cwal_container_flags_set(fv,cflags | CWAL_CONTAINER_INTERCEPTOR_RUNNING); - assert(CWAL_CONTAINER_INTERCEPTOR & cwal_container_flags_get(fv)); - } - rc = f->callback( &args, &rv ); - if(CWAL_CONTAINER_INTERCEPTOR & cflags){ - cwal_container_flags_set(fv, cflags); - } - if(hook.post){ - /* ALWAYS call post() if pre() succeeds. */ - int const rc2 = hook.post(&args, hook.state, - rc, rc ? NULL : rv); - if(rc2 && !rc) rc = rc2; - } - for(i = 0; i < argc; ++i ) cwal_value_unhand(argv[i]); - } - /* assert(CWAL_REFCOUNT(fv)>0 && "Someone took my ref!"); */ - cwal_value_unhand(propertyHolder); - cwal_value_unhand(fv); - if(!fWasVacuumProof){ - cwal_value_make_vacuum_proof(fv, 0); - /*20181122: removed because this is triggering and i'm not 100% sure - whether this assertion is truly valid (i've been away from the - intricaces of this level too long :/) - - assert(fv == (CWAL_REFCOUNT(fv) - ? fv->scope->mine.headSafe : fv->scope->mine.r0)); - - For the time being we'll replace it with something less - intrusive... - */ - assert(fv->scope); - assert(!CWAL_RCFLAG_HAS(fv,CWAL_RCF_IS_GC_QUEUED)); - } - if(self){ - cwal_value_unhand(self); - if(selfBase && !selfWasVacSafe){ - cwal_value_make_vacuum_proof(self,0); - } - } - /* s->flags = oldScopeFlags; */ - check = e->current; - if(old != check){ - /* i've never seen this happen - it's intended as a - sanity check for higher-level implementors. */ - assert(!"The callback implementor or the engine " - "around it violated scope creation rules."); - MARKER(("WARNING: callback created scopes without popping them " - "(or popped too many!)." - " Cleaning them up now!\n")); - while(e->current && (e->current!=old)){ - cwal_scope_pop(e); - } - if(e->current!=old){ - assert(!"Serious scope mis-management during callback."); - rc = CWAL_RC_FATAL; - old = 0 /* assume it was lost along the way */; - } - } - e->current = old; - assert(e->current); - if(rc){ - if(rv) cwal_refunref(rv); - }else{ -#if 0 - /* Historical: disabled 20141124. The docs do not imply - that we do this, and no C code (aside from a stray - assertion) assumes it, either. And we need to leave - rv==0 in order to distinguish between "no return" and - "return undefined" (if we ever really want/need to). - FWIW, my callbacks almost always explicitly set it to - undefined, but that's more of a style thing than a - requirement. */ - if(!rv) rv = cwal_value_undefined(); -#endif - if(_rv) *_rv = rv; - else if(rv) cwal_refunref(rv); - } - return rc; - } -} - -int cwal_function_call_in_scope( cwal_scope * s, - cwal_function * f, - cwal_value * self, - cwal_value ** rv, - uint16_t argc, - cwal_value * const * argv){ - return cwal_function_call_in_scope2( s, f, 0, self, rv, argc, argv ); -} - -void * cwal_args_state( cwal_callback_args const * args, - void const * stateTypeID ){ - return (args && (args->stateTypeID==stateTypeID || !args->stateTypeID)) - ? args->state - : NULL; -} - -void * cwal_function_state_get( cwal_function * f, - void const * stateTypeID ){ - return (f && (f->state.typeID==stateTypeID || !stateTypeID)) - ? f->state.data - : NULL; - -} - -int cwal_function_set_rescoper( cwal_function * f, - cwal_value_rescoper_f rescoper){ - if(!f) return CWAL_RC_MISUSE; - else { - f->rescoper = rescoper; - return 0; - } -} - -int cwal_function_call_in_scopef( cwal_scope * s, - cwal_function * f, - cwal_value * self, - cwal_value ** rv, ... ){ - if(!s || !s->e || !f) return CWAL_RC_MISUSE; - else { - int rc = CWAL_RC_OK; - cwal_value * argv[CWAL_OPT_MAX_FUNC_CALL_ARGS+1] = {0,}; - cwal_value * v; - uint16_t argc = 0; - va_list args; - memset( argv, 0, sizeof(argv) ); - va_start(args, rv); - while( (v=va_arg(args,cwal_value*)) ){ - if(argc>CWAL_OPT_MAX_FUNC_CALL_ARGS){ - rc = CWAL_RC_RANGE; - break; - } - else argv[argc++] = v; - } - va_end(args); - if(CWAL_RC_OK==rc){ - argv[argc] = 0; - rc = cwal_function_call_in_scope( s, f, self, rv, argc, argv ); - } - return rc; - } -} - -int cwal_function_call2( cwal_function * f, - cwal_value * propertyHolder, - cwal_value * self, - cwal_value ** rv, - uint16_t argc, - cwal_value * const * argv ){ - cwal_value * fv = f ? cwal_function_value(f) : NULL; - cwal_engine * e = (fv && fv->scope) ? fv->scope->e : NULL; - if(!e) return CWAL_RC_MISUSE; - else{ - int rc, rc2 = 0; - cwal_scope _sub = cwal_scope_empty; - cwal_scope * s = &_sub; - rc = cwal_scope_push(e, &s); - if(!rc){ - rc = cwal_function_call_in_scope2( s, f, propertyHolder, - self, rv, argc, argv ); - rc2 = cwal_scope_pop2(e, rc ? 0 : (rv ? *rv : 0)); - } - return rc2 ? rc2 : rc; - } -} - -int cwal_function_call( cwal_function * f, - cwal_value * self, - cwal_value ** rv, - uint16_t argc, - cwal_value * const * argv ){ - return cwal_function_call2( f, 0, self, rv, argc, argv ); -} - -int cwal_function_callv( cwal_function * f, cwal_value * self, - cwal_value ** rv, va_list args ){ - cwal_value * fv = f ? cwal_function_value(f) : NULL; - cwal_engine * e = (fv && fv->scope) ? fv->scope->e : NULL; - if(!e) return CWAL_RC_MISUSE; - else { - cwal_value * argv[CWAL_OPT_MAX_FUNC_CALL_ARGS+1] = {0,}; - cwal_value * v; - uint16_t argc = 0; - int rc = 0; - memset( argv, 0, sizeof(argv) ); - while( (v=va_arg(args,cwal_value*)) ){ - if(argc>CWAL_OPT_MAX_FUNC_CALL_ARGS){ - rc = CWAL_RC_RANGE; - break; - } - else argv[argc++] = v; - } - if(rc) return rc; - else{ - argv[argc] = 0; - return cwal_function_call( f, self, rv, argc, argv ); - } - } -} - - -int cwal_function_callf( cwal_function * f, - cwal_value * self, - cwal_value ** rv, - ... ){ - int rc = 0; - va_list args; - va_start(args, rv); - rc = cwal_function_callv( f, self, rv, args ); - va_end(args); - return rc; -} - -cwal_function * cwal_value_get_function( cwal_value const * v ) { - cwal_function * ar = NULL; - cwal_value_fetch_function( v, &ar ); - return ar; -} - -cwal_value * cwal_function_value(cwal_function const * s){ - return CWAL_VALPART(s); -} - -cwal_value * cwal_new_buffer_value(cwal_engine *e, cwal_size_t startingSize){ - cwal_value * v = cwal_value_new(e, e->current, CWAL_TYPE_BUFFER,0); - if( NULL != v ) - { - cwal_buffer_obj * bo = CWAL_BUFOBJ(v); - cwal_buffer * b; - assert(NULL != bo); - b = &bo->buf; - b->self = bo; - cwal_buffer_wipe_keep_self(b); - assert(bo == b->self); - if(startingSize && - cwal_buffer_reserve(e, b, startingSize)){ - cwal_value_unref2(e, v); - v = NULL; - } - } - return v; -} - -int cwal_buffer_unref(cwal_engine *e, cwal_buffer *v){ - return (e&&v) - ? cwal_value_unref2( e, cwal_buffer_value(v) ) - : CWAL_RC_MISUSE; -} - -int cwal_value_fetch_buffer( cwal_value const * val, cwal_buffer ** x){ - cwal_buffer_obj * bo; - if( ! val ) return CWAL_RC_MISUSE; - else if( !(bo = CWAL_BUFOBJ(val)) ) return CWAL_RC_TYPE; - else{ - if(x) *x = &bo->buf; - return 0; - } -} - -cwal_buffer * cwal_value_get_buffer( cwal_value const * v ) { - cwal_buffer * b = NULL; - cwal_value_fetch_buffer( v, &b ); - return b; -} - -cwal_buffer * cwal_new_buffer(cwal_engine *e, cwal_size_t startingSize){ - return cwal_value_get_buffer(cwal_new_buffer_value(e, startingSize)); -} - -cwal_value * cwal_buffer_value(cwal_buffer const * s){ - if(!s || !s->self) return 0; - else{ - cwal_buffer_obj const * bo = (cwal_buffer_obj const *)s->self; - cwal_value * v = CWAL_VALPART(bo); - if(s->self != CWAL_BUFOBJ(v)){ - assert(!"It seems that that the 'self' member of a buffer got screwed up."); - return 0; - } - if(v && v->vtab && (CWAL_TYPE_BUFFER==v->vtab->typeID)){ - return v; - }else{ - assert(!"It seems that we were passed a non-Value cwal_buffer."); - return NULL; - } - } -} - -cwal_string * cwal_buffer_to_zstring(cwal_engine * e, cwal_buffer * b){ - if(!e || !e->current || !b) return 0; - else if((b->used+1) & ~((cwal_size_t)CWAL_STRLEN_MASK)) return 0 /* too big */; - else{ - cwal_string * s = cwal_new_zstring(e, (char *)b->mem, b->used) - /* reminder: that might cwal_free(e, b->mem) */; - if(!s) return NULL; - else if(s && !CWAL_MEM_IS_BUILTIN(s)){ - /* Re-tweak the metrics which the z-string ctor just - counted. Those bytes were already counted by wherever - buf->mem came from (it might have initially been from, - e.g. cwal_list::list). - - Because b->mem's source is unclear, we cannot subtract - the metric from its origin entry in e->metrics. The - best we can do here is _subtract_ the b->used+1 which - the z-string ctor just added to its metrics, to avoid - double-counting. - - Not perfect, but there it is. - */ - assert(e->metrics.bytes[CWAL_TYPE_ZSTRING] >= b->used+1); - e->metrics.bytes[CWAL_TYPE_ZSTRING] -= b->used+1; - } - cwal_buffer_wipe_keep_self(b); - return s; - } -} - -cwal_value * cwal_buffer_to_zstring_value(cwal_engine * e, cwal_buffer * b){ - return cwal_string_value(cwal_buffer_to_zstring(e,b)); -} - -/** - cwal_value_vtab::destroy_value() impl for Buffer - values. Cleans up self-owned memory, but does not - free self. -*/ -void cwal_value_cleanup_buffer( cwal_engine * e, void * self ){ - cwal_value * v = (cwal_value*)self; - cwal_buffer_obj * bo = CWAL_BUFOBJ(v); - cwal_buffer_reserve(e, &bo->buf, 0); - cwal_cleanup_obase(e, &bo->base, 1); - *bo = cwal_buffer_obj_empty; -} - -void cwal_value_cleanup_exception( cwal_engine * e, void * self ){ - cwal_value * v = (cwal_value*)self; - cwal_exception * f = CWAL_VVPCAST(cwal_exception,v); - cwal_cleanup_obase(e, &f->base, 1); - *f = cwal_exception_empty; -} - -cwal_value * cwal_new_exception_value( cwal_engine * e, int code, cwal_value * msg ){ - cwal_value * v = e - ? cwal_value_new(e, e->current, CWAL_TYPE_EXCEPTION, 0 ) - : NULL; - if(v){ - cwal_value * proto; - cwal_exception * r; - static cwal_size_t codeKeyLen = 0; - static cwal_size_t msgKeyLen = 0; - int rc; - if(!codeKeyLen){ - msgKeyLen = cwal_strlen(CwalConsts.ExceptionMessageKey); - codeKeyLen = cwal_strlen(CwalConsts.ExceptionCodeKey); - } - /* - Reminder: - - i would prefer to have a cwal_exception::message member, but - lifetime of it gets problematic. One solution would be to - move the xscope() operation into cwal_value_vtab, so that we - can generically xscope Exception values without having to - know that they have a free-floating member (not in a - cwal_obase::kvp list). - - (That feature has since been added, by the way.) - */ - r = cwal_value_get_exception(v); - assert(r); - proto = r->base.prototype; - *r = cwal_exception_empty; - r->base.prototype = proto; - r->code = code; - rc = cwal_prop_set(v, CwalConsts.ExceptionCodeKey, - codeKeyLen, - cwal_new_integer(e, (cwal_int_t)code)); - if(!rc && msg) rc = cwal_prop_set(v, - CwalConsts.ExceptionMessageKey, - msgKeyLen, - msg); - if(0!=rc){ - cwal_value_unref2(e, v); - v = 0; - } - } - return v; -} - -cwal_exception * cwal_new_exceptionfv(cwal_engine * e, int code, char const * fmt, va_list args ){ - if(!e) return 0; - else if(!fmt || !*fmt) return cwal_new_exception(e,code, NULL); - else{ - cwal_string * s = cwal_new_stringfv( e, fmt, args); - cwal_exception * x; - if(!s) return NULL; - x = cwal_new_exception(e, code, cwal_string_value(s)); - if(!x) cwal_string_unref(s); - return x; - } -} - -cwal_exception * cwal_new_exceptionf(cwal_engine * e, int code, char const * fmt, ...){ - if(!e) return 0; - else if(!fmt || !*fmt) return cwal_new_exception(e,code, NULL); - else{ - cwal_exception * x; - va_list args; - va_start(args,fmt); - x = cwal_new_exceptionfv(e, code, fmt, args); - va_end(args); - return x; - } -} - - - -int cwal_exception_unref(cwal_engine *e, cwal_exception *v){ - return (e&&v) - ? cwal_value_unref2( e, cwal_exception_value(v) ) - : CWAL_RC_MISUSE; -} - - -int cwal_value_fetch_exception( cwal_value const * val, cwal_exception ** x){ - if( ! val ) return CWAL_RC_MISUSE; - else if( !cwal_value_is_exception(val) ) return CWAL_RC_TYPE; - else{ - if(x) *x = CWAL_VVPCAST(cwal_exception,val); - return 0; - } -} - -cwal_exception * cwal_value_get_exception( cwal_value const * v ){ - cwal_exception * r = 0; - cwal_value_fetch_exception( v, &r ); - return r; -} - -cwal_exception * cwal_new_exception( cwal_engine * e, int code, cwal_value * msg ){ - cwal_value * v = cwal_new_exception_value(e, code, msg); - return v ? cwal_value_get_exception(v) : NULL; -} - -cwal_value * cwal_exception_value(cwal_exception const * s){ - return s - ? CWAL_VALPART(s) - : NULL; -} - -int cwal_exception_code_get( cwal_exception const * r ){ - return r ? r->code : cwal_exception_empty.code; -} -int cwal_exception_code_set( cwal_exception * r, int code ){ - return r - ? (r->code=code, 0) - : CWAL_RC_MISUSE; -} - -cwal_value * cwal_exception_message_get( cwal_exception const * r ){ - cwal_kvp * const kvp = - cwal_prop_get_kvp( CWAL_VALPART(r), CwalConsts.ExceptionMessageKey, - cwal_strlen(CwalConsts.ExceptionMessageKey), - false, NULL); - return kvp ? kvp->value : NULL; -} - -int cwal_exception_message_set( cwal_engine * e, cwal_exception * r, cwal_value * msg ){ - if(!e || !r) return CWAL_RC_MISUSE; - else return cwal_prop_set( cwal_exception_value(r), - CwalConsts.ExceptionMessageKey, - cwal_strlen(CwalConsts.ExceptionMessageKey), - msg ); -} - - -char * cwal_string_str_rw(cwal_string *v){ - /* - See http://groups.google.com/group/comp.lang.c.moderated/browse_thread/thread/2e0c0df5e8a0cd6a - */ - assert(v && - !CWAL_STR_ISX(v)/* not allowed for x-strings */); - return CWAL_STR_ISZ(v) - ? (char *)*((unsigned char **)(v+1)) - : (CWAL_STRLEN(v) - ? (char *)((unsigned char *)( v+1 )) - : NULL - ); -} - -/** - Intended to be called immediately after initialization of s and - assignment of its string content, and it assert()'s that the - is-ascii flag is no set on s. If the byte length of s equals its - UTF8 length, the is-ascii flag is encoded in s->length, else this - has no side effects. -*/ -static void cwal_string_check_for_ascii( cwal_string * s ){ - unsigned char const * c = (unsigned char const *) cwal_string_cstr(s); - unsigned char const * end = c + CWAL_STRLEN(s); - assert(!CWAL_STR_ISASCII(s)); - assert(c); - assert(c < end); - for( ; c < end; ++c ){ - if(*c & 0x80) return; - } - s->length |= CWAL_STR_ASCII_MASK; -} - -char const * cwal_string_cstr(cwal_string const *v){ -#if 1 - return (NULL == v) - ? NULL - : (CWAL_STR_ISXZ(v) - ? (char const *) *((unsigned char const **)(v+1)) - : (char const *) ((unsigned char const *)(v+1))) - ; -#else - /* - See https://groups.google.com/group/comp.lang.c.moderated/browse_thread/thread/2e0c0df5e8a0cd6a - */ - return (NULL == v) - ? NULL - : (CWAL_STRLEN(v) - ? (CWAL_STR_ISXZ(v) - ? (char const *) *((unsigned char const **)(v+1)) - : (char const *) ((unsigned char const *)(v+1))) - : ""); -#endif -} - - -char const * cwal_string_cstr2(cwal_string const *v, cwal_midsize_t * len){ - if(v && len) *len = CWAL_STRLEN(v); - return cwal_string_cstr(v); -} - -void cwal_value_cleanup_string( cwal_engine * e, void * V ){ - cwal_value * v = (cwal_value*)V; - cwal_string * s = cwal_value_get_string(v); - assert(s); - assert(CWAL_STRLEN(s) && "Empty string cannot be cleaned up - it doesn't refcount."); - if(CWAL_MEM_IS_BUILTIN(v)) return; - else if(CWAL_STR_ISZ(s)){ - unsigned char ** pos = (unsigned char **)(s+1); - char * cs = cwal_string_str_rw(s); - cwal_size_t const slen = CWAL_STRLEN(s); - assert(cs == (char *)*pos); - *pos = NULL; - if(e->flags & CWAL_FEATURE_ZERO_STRINGS_AT_CLEANUP){ - memset(cs, 0, slen+1/*NUL*/); - } - cwal_memchunk_add(e, cs, slen+1/*NUL*/); - /* cwal_free(e, cs); */ - }else if(CWAL_STR_ISX(s)){ - unsigned char const ** pos = (unsigned char const **)(s+1); -#ifdef DEBUG - char const * cs = cwal_string_cstr(s); - assert(cs == (char *)*pos); -#endif - *pos = NULL; - /* Nothing to free - the bytes are external */ - }else{/* Is a normal string, not an X/Y-string */ - cwal_interned_remove( e, v, 0 ); - if(e->flags & CWAL_FEATURE_ZERO_STRINGS_AT_CLEANUP){ - char * cs = cwal_string_str_rw(s); - memset(cs, 0, CWAL_STRLEN(s)); - } - } -} - -int cwal_string_unref(cwal_string * s){ - cwal_value * v = cwal_string_value(s); - return v - ? cwal_value_unref2( cwal_value_engine(v), v ) - : CWAL_RC_MISUSE; -} - -cwal_midsize_t cwal_string_length_bytes( cwal_string const * str ){ - return str - ? CWAL_STRLEN(str) - : 0U; -} - - -cwal_midsize_t cwal_string_length_utf8( cwal_string const * str ){ - return str - ? (CWAL_STR_ISASCII(str) - ? CWAL_STRLEN(str) - : cwal_strlen_utf8( cwal_string_cstr(str), - CWAL_STRLEN(str) ) - ) - : 0U; -} - -bool cwal_string_is_ascii( cwal_string const * str ){ - return str ? CWAL_STR_ISASCII(str) : 0; -} - -cwal_value * cwal_new_string_value(cwal_engine * e, char const * str, cwal_midsize_t len){ - return cwal_string_value( cwal_new_string(e, str, len) ); -} - -bool cwal_cstr_internable_predicate_f_default( void * state, char const * str, cwal_size_t len ){ - if(state || str){/*avoid unused param warning*/} - return !CwalConsts.MaxInternedStringSize - || (len <= CwalConsts.MaxInternedStringSize); -} - -#if CWAL_ENABLE_BUILTIN_LEN1_ASCII_STRINGS -/** - Expects (asserts) char to be in the range [0,127]. Gets the shared - length-1 string for that character and returns it. If it fails, ndx - is of an unexpected value. - - Intended ONLY to be called from cwal_new_string/xstring/zstring() - and ONLY after they have verified that ndx is in range. -*/ -static cwal_string * cwal_len1_ascii_string(int ndx){ - cwal_value * v; - assert(ndx>=0 && ndx<=127); - v = (cwal_value *)CWAL_BUILTIN_VALS.memAsciiPrintable[ndx]; - assert(CWAL_STR(v)); - return CWAL_STR(v); -} -#endif - -cwal_string * cwal_new_string(cwal_engine * e, char const * str, cwal_midsize_t len){ - if(!e || CWAL_STRLEN_TOO_LONG(len)){ - return NULL ; - } - else if( !str || !len ){ - METRICS_REQ_INCR(e,CWAL_TYPE_STRING); - return CWAL_BUILTIN_VALS.sEmptyString; - } -#if CWAL_ENABLE_BUILTIN_LEN1_ASCII_STRINGS - else if( 1==len - && ((unsigned char)*str)<=127 ){ - METRICS_REQ_INCR(e,CWAL_TYPE_STRING); - ++e->metrics.len1StringsSaved[0]; - return cwal_len1_ascii_string((signed char)*str); - } -#endif - else{ - cwal_value * c = 0; - cwal_string * s = 0; - assert(len); - if(CWAL_FEATURE_INTERN_STRINGS & e->flags){ - cwal_interned_search( e, str, len, &c, 0, 0 ); - } - if(c/* Got an interned string... */){ - s = cwal_value_get_string(c); - assert(0 != s); - METRICS_REQ_INCR(e,CWAL_TYPE_STRING); - CWAL_TR_V(e,c); - CWAL_TR3(e,CWAL_TRACE_VALUE_INTERNED, - "re-using interned string"); - assert(c->scope->level <= e->current->level); - } - else{ /* Create new string... */ - c = cwal_value_new(e, e->current, - CWAL_TYPE_STRING, - len); - if( c ){ - char * dest = NULL; - s = CWAL_STR(c); - assert( s ); - *s = cwal_string_empty; - s->length = ((cwal_size_t)CWAL_STRLEN_MASK) & len; - assert(CWAL_STRLEN(s) == len); - dest = cwal_string_str_rw(s) - /* maintenance note: this is the only place in the - library where _writing_ to a normal - (non-X/Z-string) cwal_string is allowed. - */; - assert( (NULL != dest) - && "Empty string should have been caught earlier!"); - { - unsigned char isAscii = 0; - unsigned char const * usrc = (unsigned char const *)str; - unsigned char * udest = (unsigned char *)dest; - unsigned char const * end = udest + len; - for( ; udest < end; ++udest, ++usrc ){ - isAscii |= (*udest = *usrc); - } - *udest = 0; - if(!(isAscii & 0x80)){ - s->length |= CWAL_STR_ASCII_MASK; - } - } - if((CWAL_FEATURE_INTERN_STRINGS & e->flags) - && (e->vtab->interning.is_internable - && e->vtab->interning.is_internable( e->vtab->interning.state, str, len ) - ) - ){ - cwal_interned_insert( e, c ) - /* This insertion effectively controls whether - or not interning of strings is on. If it - fails, the string is effectively not - interned, but otherwise no harm is - done. Allocation of a new interning table - could fail, but that's about the only - conceivable error condition here (and we - can ignore it by not interning). - */; - /* MARKER(("INTERNING rc=%d: %.*s\n", rc, (int)len, str)); */ - } - } - } - return s; - } -} - -cwal_string * cwal_new_xstring(cwal_engine * e, char const * str, - cwal_midsize_t len){ - if(!e || (len & ~((cwal_size_t)CWAL_STRLEN_MASK) /* too big */)){ - return NULL; - }else if( !len ){ - METRICS_REQ_INCR(e,CWAL_TYPE_XSTRING); - return CWAL_BUILTIN_VALS.sEmptyString; - } -#if CWAL_ENABLE_BUILTIN_LEN1_ASCII_STRINGS - else if( 1==len - && ((unsigned char)*str)<=127 ){ - METRICS_REQ_INCR(e,CWAL_TYPE_XSTRING); - ++e->metrics.len1StringsSaved[1]; - return cwal_len1_ascii_string((signed char)*str); - } -#endif - else{ - cwal_value * c = NULL; - cwal_string * s = NULL; - c = cwal_value_new(e, e->current, CWAL_TYPE_XSTRING, 0); - if( c ){ - unsigned char const ** dest; - s = CWAL_STR(c); - assert( NULL != s ); - *s = cwal_string_empty; - s->length = CWAL_STR_XMASK | len; - assert(s->length > len); - assert(CWAL_STRLEN(s) == len); - assert(CWAL_STR_ISX(s)); - assert(CWAL_STR_ISXZ(s)); - dest = (unsigned char const **)(s+1); - *dest = (unsigned char const *)str; - cwal_string_check_for_ascii( s ); - } - return s; - } -} - -cwal_value * cwal_new_xstring_value(cwal_engine * e, char const * str, - cwal_midsize_t len){ - cwal_string * s = cwal_new_xstring(e, str, len); - return s ? cwal_string_value(s) : NULL; -} - -cwal_string * cwal_new_zstring(cwal_engine * e, char * str, cwal_midsize_t len){ - if(!e || (len & ~((cwal_size_t)CWAL_STRLEN_MASK) /* too big */)){ - return NULL; - }else if(!str){ - METRICS_REQ_INCR(e,CWAL_TYPE_ZSTRING); - return CWAL_BUILTIN_VALS.sEmptyString; - } - else if(!len){ - /* Special case: free source memory immediately. */ - METRICS_REQ_INCR(e,CWAL_TYPE_ZSTRING); - cwal_free(e, str); - return CWAL_BUILTIN_VALS.sEmptyString; - } -#if CWAL_ENABLE_BUILTIN_LEN1_ASCII_STRINGS - else if( 1==len - && ((unsigned char)*str)<=127 ){ - /* Special case: free source memory immediately. */ - cwal_string * rc = cwal_len1_ascii_string((signed char)*str); - assert(rc && 1==CWAL_STRLEN(rc)); - METRICS_REQ_INCR(e,CWAL_TYPE_ZSTRING); - cwal_free(e, str); - ++e->metrics.len1StringsSaved[2]; - return rc; - } -#endif - else{ - cwal_value * c = NULL; - cwal_string * s = NULL; - assert(len>0); - c = cwal_value_new(e, e->current, CWAL_TYPE_ZSTRING, 0); - if( c ){ - unsigned char ** dest; - s = CWAL_STR(c); - assert( NULL != s ); - *s = cwal_string_empty; - s->length = CWAL_STR_ZMASK | len; - e->metrics.bytes[CWAL_TYPE_ZSTRING] += len +1 - /* we're going to assume a NUL byte for - metrics purposes, because there essentially - always is one for z-strings. */; - assert(s->length > len); - assert(CWAL_STRLEN(s) == len); - assert(CWAL_STR_ISZ(s)); - assert(CWAL_STR_ISXZ(s)); - dest = (unsigned char **)(s+1); - *dest = (unsigned char *)str; - cwal_string_check_for_ascii( s ); - }else{ - /* See the API docs for why we do this. */ - cwal_free2( e, str, len/*+1 would be safe, until it wasn't.*/ ); - } - return s; - } -} - -cwal_value * cwal_new_zstring_value(cwal_engine * e, char * str, cwal_midsize_t len){ - cwal_string * s = cwal_new_zstring(e, str, len); - return s ? cwal_string_value(s) : NULL; -} - - -int cwal_buffer_reset( cwal_buffer * b ){ - if(!b) return CWAL_RC_MISUSE; - else{ - if(b->capacity){ - assert(b->mem); - b->mem[0] = 0; - } - b->used = 0; - return 0; - } -} - -int cwal_buffer_resize( cwal_engine * e, cwal_buffer * buf, cwal_size_t n ){ - if( !buf ) return CWAL_RC_MISUSE; - else if(n && (buf->capacity == n+1)){ - buf->used = n; - buf->mem[n] = 0; - return 0; - }else{ - unsigned char * x = (unsigned char *)cwal_realloc( e, buf->mem, - n+1/*NUL*/ ); - if( ! x ) return CWAL_RC_OOM; - if(n > buf->capacity){ - /* zero-fill new parts */ - memset( x + buf->capacity, 0, n - buf->capacity +1/*NUL*/ ); - } - /* reminder to self: e->metrics.bytes[CWAL_TYPE_BUFFER] might be - 0 here because buf->mem might have come from a recycler. That - means we're not byte-counting buffer resize(), which is a bit - disturbing. We could measure it if over-allocation is on, but - we don't know which pool (if any) to modify the count in. e.g. - buf->mem might have come from the recycler after having been - allocated as a cwal_list::list. So... hmmm. - */ - /* assert(e->metrics.bytes[CWAL_TYPE_BUFFER]) >= buf->capacity; */ - /* e->metrics.bytes[CWAL_TYPE_BUFFER] -= buf->capacity; */ - buf->capacity = n + 1 /*NUL*/; - /* e->metrics.bytes[CWAL_TYPE_BUFFER] += buf->capacity; */ - buf->used = n; - buf->mem = x; - buf->mem[buf->used] = 0; - return 0; - } -} - - -cwal_string * cwal_new_stringfv(cwal_engine * e, char const * fmt, va_list args ){ - if(!e || !fmt) return 0; - else if(!*fmt) return cwal_new_string(e,"",0); - else{ - int rc; - cwal_size_t const oldUsed = e->buffer.used; - cwal_size_t slen; - rc = cwal_buffer_printfv(e, &e->buffer, fmt, args); - slen = e->buffer.used - oldUsed; - e->buffer.used = oldUsed; - return rc - ? NULL - : cwal_new_string(e, (char const*)(e->buffer.mem+oldUsed), slen); - ; - } -} - -cwal_string * cwal_new_stringf(cwal_engine * e, char const * fmt, ...){ - if(!e || !fmt) return 0; - else if(!*fmt) return cwal_new_string(e,NULL,0); - else{ - cwal_string * str; - va_list args; - va_start(args,fmt); - str = cwal_new_stringfv(e, fmt, args); - va_end(args); - return str; - } -} - - -cwal_value * cwal_string_value(cwal_string const * s){ - return s - ? (CWAL_STRLEN(s) - ? CWAL_VALPART(s) - : CWAL_BUILTIN_VALS.vEmptyString) - : NULL; -} - -cwal_engine * cwal_value_engine( cwal_value const * v ){ - return (v && v->scope) - ? v->scope->e - : 0; -} - -cwal_scope * cwal_value_scope( cwal_value const * v ){ - return v ? v->scope : NULL; -} - -cwal_value * cwal_string_concat( cwal_string const * s1, cwal_string const * s2 ){ - if(!s1 || !s2) return NULL; - else { - cwal_size_t newLen; - int rc; - cwal_engine * e = cwal_value_engine(cwal_string_value(s1)); - assert(e); - newLen = CWAL_STRLEN(s1) + CWAL_STRLEN(s2) + 1/*NUL byte*/; - if( CWAL_STRLEN_TOO_LONG(newLen) ) return NULL; - rc = cwal_buffer_reserve( e, &e->buffer, newLen ); - if(rc) return NULL; - e->buffer.used = 0; - rc = cwal_buffer_append( e, &e->buffer, cwal_string_cstr(s1), CWAL_STRLEN(s1) ); - if(rc) return NULL; - rc = cwal_buffer_append( e, &e->buffer, cwal_string_cstr(s2), CWAL_STRLEN(s2) ); - if(rc) return NULL; - e->buffer.mem[e->buffer.used] = 0; - return cwal_new_string_value( e, (char const *)e->buffer.mem, e->buffer.used ); - } -} - - -int cwal_value_fetch_bool( cwal_value const * val, char * v ) -{ - /** - FIXME: move the to-bool operation into cwal_value_vtab, like we - do in the C++ API. - */ - if( ! val || !val->vtab ) return CWAL_RC_MISUSE; - else - { - int rc = 0; - char b = NULL != CWAL_VOBASE(val); - if(!b) switch( val->vtab->typeID ){ - case CWAL_TYPE_BUFFER: - b = 1; - break; - case CWAL_TYPE_STRING: { - char const * str = cwal_string_cstr(cwal_value_get_string(val)); - b = (str && *str) ? 1 : 0; - break; - } - case CWAL_TYPE_UNDEF: - case CWAL_TYPE_NULL: - break; - case CWAL_TYPE_BOOL: - b = CWAL_BOOL(val); - break; - case CWAL_TYPE_INTEGER: { - cwal_int_t i = 0; - cwal_value_fetch_integer( val, &i ); - b = i ? 1 : 0; - break; - } - case CWAL_TYPE_DOUBLE: { - cwal_double_t d = 0.0; - cwal_value_fetch_double( val, &d ); - b = (0.0==d) ? 0 : 1; - break; - } - case CWAL_TYPE_UNIQUE: - b = 1; - break; - case CWAL_TYPE_TUPLE: - b = CWAL_TUPLE(val)->n ? 1 : 0; - break; - default: - rc = CWAL_RC_TYPE; - break; - } - if( !rc && v ) *v = b; - return rc; - } -} - -bool cwal_value_get_bool( cwal_value const * val ) -{ - char i = 0; - cwal_value_fetch_bool( val, &i ); - return i; -} - -int cwal_value_fetch_integer( cwal_value const * val, cwal_int_t * v ) -{ - if( ! val || !val->vtab ) return CWAL_RC_MISUSE; - else { - cwal_int_t i = 0; - int rc = 0; - switch(val->vtab->typeID){ - case CWAL_TYPE_UNIQUE: - case CWAL_TYPE_TUPLE: - case CWAL_TYPE_UNDEF: - case CWAL_TYPE_NULL: - i = 0; - break; - case CWAL_TYPE_BOOL:{ - char b = 0; - cwal_value_fetch_bool( val, &b ); - i = b; - break; - } - case CWAL_TYPE_INTEGER: { - i = *CWAL_INT(val); - break; - } - case CWAL_TYPE_DOUBLE:{ - cwal_double_t d = 0.0; - cwal_value_fetch_double( val, &d ); - i = (cwal_int_t)d; - break; - } - case CWAL_TYPE_STRING: - rc = cwal_string_to_int( cwal_value_get_string(val), - &i ); - break; - default: - rc = CWAL_RC_TYPE; - break; - } - if(!rc && v) *v = i; - return rc; - } -} - -cwal_int_t cwal_value_get_integer( cwal_value const * val ) -{ - cwal_int_t i = 0; - cwal_value_fetch_integer( val, &i ); - return i; -} - -int cwal_value_fetch_double( cwal_value const * val, cwal_double_t * v ) -{ - if( ! val || !val->vtab ) return CWAL_RC_MISUSE; - else - { - cwal_double_t d = 0.0; - int rc = 0; - switch(val->vtab->typeID) - { - case CWAL_TYPE_UNIQUE: - case CWAL_TYPE_TUPLE: - case CWAL_TYPE_UNDEF: - case CWAL_TYPE_NULL: - d = 0; - break; - case CWAL_TYPE_BOOL: { - char b = 0; - cwal_value_fetch_bool( val, &b ); - d = b ? 1.0 : 0.0; - break; - } - case CWAL_TYPE_INTEGER: { - cwal_int_t i = 0; - cwal_value_fetch_integer( val, &i ); - d = i; - break; - } - case CWAL_TYPE_DOUBLE: - memcpy(&d, CWAL_DBL_NONULL(val), sizeof(cwal_double_t)); - break; - case CWAL_TYPE_STRING: - rc = cwal_string_to_double( cwal_value_get_string(val), - &d ); - break; - default: - rc = CWAL_RC_TYPE; - break; - } - if(!rc && v) *v = d; - return rc; - } -} - -cwal_double_t cwal_value_get_double( cwal_value const * val ) -{ - cwal_double_t i = 0.0; - cwal_value_fetch_double( val, &i ); - return i; -} - -int cwal_value_fetch_string( cwal_value const * val, cwal_string ** dest ) -{ - if( ! val || ! dest ) return CWAL_RC_MISUSE; - else if( ! cwal_value_is_string(val) ) return CWAL_RC_TYPE; - else - { - if( dest ) *dest = CWAL_STR(val); - return CWAL_RC_OK; - } -} - -cwal_string * cwal_value_get_string( cwal_value const * val ) -{ - cwal_string * rc = NULL; - cwal_value_fetch_string( val, &rc ); - return rc; -} - -char const * cwal_value_get_cstr( cwal_value const * val, cwal_size_t * len ) -{ - switch(val ? val->vtab->typeID : 0){ - case CWAL_TYPE_STRING:{ - cwal_string const * s = cwal_value_get_string(val); - if(len) *len = CWAL_STRLEN(s); - return cwal_string_cstr(s); - } - case CWAL_TYPE_BUFFER:{ - cwal_buffer const * b = cwal_value_get_buffer(val); - if(len) *len = b->used; - return (char const *)b->mem; - } - default: - return NULL; - } -} - -int cwal_value_fetch_array( cwal_value const * val, cwal_array ** ar) -{ - if( ! val ) return CWAL_RC_MISUSE; - else if( !cwal_value_is_array(val) ) return CWAL_RC_TYPE; - else - { - if(ar) *ar = CWAL_ARRAY(val); - return 0; - } -} - -cwal_array * cwal_value_get_array( cwal_value const * v ) -{ - cwal_array * ar = NULL; - cwal_value_fetch_array( v, &ar ); - return ar; -} - -cwal_value * cwal_array_value(cwal_array const * s) -{ - return s - ? CWAL_VALPART(s) - : NULL; -} - -int cwal_array_unref(cwal_array *x) -{ - cwal_value * v = CWAL_VALPART(x); - return (v && v->scope) - ? cwal_value_unref2(v->scope->e, v) - : CWAL_RC_MISUSE; -} - -int cwal_array_value_fetch( cwal_array const * ar, cwal_size_t pos, cwal_value ** v ) -{ - if( !ar) return CWAL_RC_MISUSE; - if( pos >= ar->list.count ) return CWAL_RC_RANGE; - else - { - if(v) *v = (cwal_value*)ar->list.list[pos]; - return 0; - } -} - -cwal_value * cwal_array_get( cwal_array const * ar, cwal_midsize_t pos ) -{ - cwal_value *v = NULL; - cwal_array_value_fetch(ar, pos, &v); - return v; -} - -cwal_value * cwal_array_take( cwal_array * ar, cwal_size_t pos ) -{ - cwal_value *v = NULL; - cwal_array_value_fetch(ar, pos, &v); - if(v){ - if(CWAL_MEM_IS_BUILTIN(v)){ - cwal_array_set(ar, pos, NULL); - }else{ - cwal_value_ref(v); - cwal_array_set(ar, pos, NULL); - cwal_value_unhand(v); - assert(v->scope && "Already dead?"); - } - } - return v; -} - - -int cwal_array_length_fetch( cwal_array const * ar, cwal_midsize_t * v ) -{ - if( ! ar || !v ) return CWAL_RC_MISUSE; - else{ - if(v) *v = ar->list.count; - return 0; - } -} - -cwal_midsize_t cwal_array_length_get( cwal_array const * ar ) -{ - cwal_midsize_t i = 0; - cwal_array_length_fetch(ar, &i); - return i; -} - -int cwal_array_length_set( cwal_array * ar, cwal_midsize_t newSize ){ - cwal_midsize_t i; - if(!ar) return CWAL_RC_MISUSE; - else if(CWAL_V_IS_VISITING_LIST(CWAL_VALPART(ar))) return CWAL_RC_IS_VISITING_LIST; - else if(CWAL_OB_IS_LOCKED(ar)) return CWAL_RC_LOCKED; - else if(ar->list.count == newSize) return 0; - if( newSize < ar->list.count ){ - int rc = 0; - for( i = newSize; !rc && (i < ar->list.count); ++i ){ - rc = cwal_array_set( ar, i, NULL ); - } - ar->list.count = newSize; - return rc; - } - else { /* grow */ - int const rc = cwal_array_reserve( ar, newSize ); - if(!rc){ - ar->list.count = newSize; - } - return rc; - } -} - - -/** - Internal helper for recycling array list memory. li must be a new, - clean list with no memory (that might get assert()ed). If the - recyling list has an entry then that entry's memory is transfered - into li. If no entry is capable of holding it, li is left - unmolested. There are no error conditions except for precondition - violations (assertions). If minCount is not 0 then only a recycled - chunk with enough space for at least that many entries will serve - the request. -*/ -static void cwal_list_from_recycler( cwal_engine * e, cwal_list * li, - cwal_size_t minCount ); - -/** - Internal helper macro for array-centric functions. -*/ -#define SETUP_ARRAY_ARGS \ - cwal_scope * s = ar ? CWAL_VALPART(ar)->scope : 0; \ - cwal_engine * e = s ? s->e : 0; \ - if(!s || !e) return CWAL_RC_MISUSE - -int cwal_array_reserve( cwal_array * ar, cwal_midsize_t size ) -{ - SETUP_ARRAY_ARGS; - if( ! ar ) return CWAL_RC_MISUSE; - else if( size <= ar->list.alloced ) - { - /* We don't want to introduce a can of worms by trying to - handle the cleanup from here. - */ - return 0; - } -#if 0 - else if(!ar->list.list){ - cwal_list_from_recycler(e, &ar->list, size); - if(ar->list.list){ - assert(ar->list.alloced>=size); - assert(NULL == ar->list.list[0]); - assert(size ? (NULL == ar->list.list[size-1]) : 1); - return 0; - } - } -#endif - else{ - CWAL_UNUSED_VAR cwal_size_t const oldLen = ar->list.alloced; - cwal_size_t rrc; - rrc = cwal_list_reserve( e, &ar->list, size ); - if(rrc < size) return CWAL_RC_OOM; - else{ - assert(rrc > oldLen); - return 0; - } - } -} - - -/** @internal - - cwal_list_visitor_f which expects V to be a (cwal_value*) and - and VParent to be its (cwal_value*) scoping parent. - This makes sure that (sub)child are properly up-scoped - if needed. Returns 0 on success. -*/ -static int cwal_xscope_visitor_children_array( void * V, void * VParent ){ - cwal_value * par = (cwal_value*)VParent; - cwal_value * child = (cwal_value*)V; - assert(par && par->scope); - return cwal_value_xscope( par->scope->e, par->scope, child, 0 ); -} - -static void cwal_htable_rescope(cwal_scope * const sc, - cwal_htable * const h){ - /* cwal_dump_v(nv,"Re-scoping cwal_htable children..."); */ - int rc = 0; - cwal_midsize_t const max = h->list.alloced>=h->hashSize - ? h->hashSize : h->list.alloced; - for( cwal_midsize_t i = 0; !rc && (i < max); ++i ){ - cwal_kvp * kvp = (cwal_kvp*)h->list.list[i]; - if(!kvp) continue; - cwal_kvp * next = NULL; - for( ; !rc && kvp; kvp = next){ - next = kvp->right; - assert(kvp->key); - assert(kvp->value); - rc = cwal_value_xscope(sc->e, sc, kvp->key, 0); - if(!rc && kvp->key != kvp->value){ - rc = cwal_value_xscope(sc->e, sc, kvp->value, 0); - } - /* cwal_dump_v(kvp->key,"Re-scoped key"); */ - /* cwal_dump_v(kvp->value,"Re-scoped value"); */ - } - assert(!rc && "Rescoping failure is no longer be possible " - "except in the case of memory corruption."); - } -} - -int cwal_rescope_children_obase( cwal_value * v ){ - cwal_obase * const b = CWAL_VOBASE(v); - int rc = CWAL_RC_OK; - assert(b); - assert(CWAL_V_IS_RESCOPING(v)); - assert(v->scope); -#if CWAL_OBASE_ISA_HASH - cwal_htable_rescope(v->scope, &b->hprops); -#else - cwal_obase_kvp_iter iter; - cwal_kvp const * kvp = cwal_obase_kvp_iter_init(v, &iter); - for( ; kvp && (0==rc); kvp = cwal_obase_kvp_iter_next(&iter) ){ - if(kvp->key){ - rc = cwal_value_xscope( v->scope->e, v->scope, kvp->key, 0 ); - } - if((0==rc) && kvp->value){ - rc = cwal_value_xscope( v->scope->e, v->scope, kvp->value, 0 ); - } - } - if(rc){ - assert(!"Rescoping failure should no longer be possible."); - } -#endif - return rc; -} - -int cwal_rescope_children_native( cwal_value * v ){ - int rc; - cwal_native * n = cwal_value_get_native(v); - assert(v->scope); - assert(n); - rc = cwal_rescope_children_obase(v); - if(!rc && n->rescoper){ - rc = n->rescoper( v->scope, v ); - } - return rc; -} - -int cwal_rescope_children_function( cwal_value * v ){ - int rc; - cwal_function * f = cwal_value_get_function(v); - assert(v->scope); - assert(f); - assert(CWAL_V_IS_RESCOPING(v)); - rc = cwal_rescope_children_obase(v); - if(!rc && f->rescoper){ - rc = f->rescoper( v->scope, v ); - } - return rc; -} - -int cwal_rescope_children_unique( cwal_value * v ){ - cwal_value * ch = *CWAL_UNIQUE_VALPP(v); - int rc = 0; - assert(v->scope); - if(ch){ - *CWAL_UNIQUE_VALPP(v) = 0 - /* a poor man's recursion-prevention scheme. */; - rc = cwal_value_rescope(v->scope, ch); - - *CWAL_UNIQUE_VALPP(v) = ch; - } - return rc; -} - -int cwal_rescope_children_tuple( cwal_value * v ){ - cwal_tuple * p = CWAL_TUPLE(v); - cwal_size_t i; - cwal_value * ch; - int rc = 0; - assert(!CWAL_MEM_IS_BUILTIN(v)); - assert(p->n || !p->list /* this gets called once from cwal_value_new() */); - assert(v->scope); - for( i = 0; !rc && i < p->n; ++i ){ - if( (ch = p->list[i]) ){ - rc = cwal_value_xscope(v->scope->e, v->scope, ch, 0); - } - } - return rc; -} - -int cwal_rescope_children_array( cwal_value * v ){ - int rc; - cwal_array * ar = cwal_value_get_array(v); - assert(ar); - assert(CWAL_V_IS_RESCOPING(v)); - rc = cwal_rescope_children_obase( v ); - if(rc) return rc; - rc = cwal_list_visit( &ar->list, - -1, cwal_xscope_visitor_children_array, v ); - return rc; -} - -int cwal_value_rescope( cwal_scope * s, cwal_value * v ){ - return (!s || !s->e) - ? CWAL_RC_MISUSE - : ((v && CWAL_MEM_IS_BUILTIN(v)) - ? 0 - : cwal_value_xscope( s->e, s, v, NULL ) ); -} - -/** - Transfers child to the given scope if child is in a lower-level (newer) - scope. - - Returns 0 on success and theoretically has no error cases except - bad arguments or as side-effects of serious internal errors - elsewhere. If res is not NULL, it will be set to one of these values: - - -1=child was moved to a higher-level scope (with a lower - scope->level value). - - 0=child was kept where it is. - - 1=child was... hmm... damn, i should have written the docs as i wrote - the code :/. - - It may set e->fatalCode, in which case it returns that. -*/ -static int cwal_value_xscope( cwal_engine * e, cwal_scope * par, - cwal_value * child, int * res ){ - cwal_obase * chb; - int RC = res ? *res : 0; - if(!res) res = &RC/*simplifies some code below*/; - if(!par) { - *res = 1; - return 0;/*par = e->current;*/ - } - assert( e && par && child ); - start: - if( CWAL_MEM_IS_BUILTIN(child) ) { - *res = 1; - return CWAL_RC_OK; - } - else if(child->scope == par) { - *res = 0; - return CWAL_RC_OK; - } - chb = CWAL_VOBASE(child); - assert(chb ? !CWAL_RCFLAG_HAS(child,CWAL_RCF_IS_DESTRUCTING) : 1); - if(CWAL_V_IS_RESCOPING(child)){ - *res = 0; - assert(child->scope->level <= par->level); - /* MARKER(("Skipping re-rescoping.\n")); */ - /* haven't yet seen this happen! */ - return 0; - } - else -#if 0 - /* - 20160206: what was this for, way back when? This block IS being - triggered via s2 unit tests, but i'm curious what this is - supposed to accomplish. Seems to work fine without it, but - probably only because child->scope->level is always < par->level - in this case. And yet i'm not certain why! - - Was it for breaking cycles? The children-rescopers don't - set the CWAL_F_IS_VISITING flag. Maybe they used to? - - i think i see now... we've got a complex call chain which is - trying to upscope a child, but that child is currently being - visited. Failing to upscope would be an error, but continuing - from here would lead to an assertion later (and we'd be unable - to catch cycles). We need a flag for "is rescoping." - */ - if( chb && ( CWAL_F_IS_VISITING & chb->flags ) ){ - /* dump_val(child,"is visiting?"); */ - assert(child->scope->level <= par->level) - /* This assertion is triggered in at least 1 s2 unit test - script. Troubling. - */; - *res = 0; - return 0 - /* Normally we would return CWAL_RC_CYCLES_DETECTED, - but for this special case we need to return 0 - to keep list iteration from aborting. */; - } - else -#endif - { - int rc = CWAL_RC_OK; - if( child->scope ){ - CWAL_TR_V(e,child); - if( child->scope->level <= par->level ){ - CWAL_TR3(e,CWAL_TRACE_MESSAGE, - "Keeping value in its current scope."); - *res = 1; - return 0; - } - else{ - CWAL_TR3(e,CWAL_TRACE_MESSAGE, - "Migrating value to older scope."); - rc = cwal_value_take( e, child ); - if(rc){ - CWAL_TR_SV(e,child->scope,child); - CWAL_TR3(e,CWAL_TRACE_ERROR, - "POPPING FROM ITS PARENT SCOPE IS NO " - "LONGER SUPPOSED TO BE ABLE TO FAIL " - "IN THESE CONDITIONS."); - assert(!"Pop child from its scope failed."); - return e->fatalCode = rc; - } - } - } - assert(!child->scope); - *res = -1; - if( cwal_scope_insert( par, child ) ){ - assert(e->fatalCode); - return e->fatalCode; - } - if(child->vtab->rescope_children){ - /* For containers we now, for the sake of cross-scope - cycles, we need to ensure that any sub-(sub...)children - are up-scoped. - */ - if(!chb){ - assert(CWAL_TYPE_UNIQUE==child->vtab->typeID - || CWAL_TYPE_TUPLE==child->vtab->typeID); - /* - Doh... we have a potentially problem: we can - potentially endlessly cycle on cwal_uniques. They - have no flags which will let us stop recursion! - Does that matter, since the value being wrapped has - them (if a container, else it's moot)? In the - non-container case, the 2nd rescope would not - recurse because the scope level will have already - been adjusted. Whew. - */ - /* dump_val(child,"Has rescope_children but no obase!?!?!?"); */ - } - assert(!CWAL_V_IS_RESCOPING(child)); - CWAL_RCFLAG_ON(child,CWAL_RCF_IS_RESCOPING); - assert(CWAL_V_IS_RESCOPING(child)); - rc = child->vtab->rescope_children(child); - assert(CWAL_V_IS_RESCOPING(child)); - CWAL_RCFLAG_OFF(child,CWAL_RCF_IS_RESCOPING); - assert(!CWAL_V_IS_RESCOPING(child)); - if(0!=rc){ - /* Reminder: now that values are tracked in linked - lists, xscope can only fail if some assertion - fails. There is no longer the potential for an OOM - case. - */ - MARKER(("xscope returned %d/%s\n", rc, cwal_rc_cstr(rc))); - assert(!"NO RECOVERY STRATEGY HERE!"); - return e->fatalCode = rc; - } - } - assert(par == child->scope); - if(chb && chb->prototype && chb->prototype->scope - && chb->prototype->scope->level > par->level){ - /* - Added 20141205 when it suddenly occurred to me that we - do not otherwise make prototypes vacuum-safe (not that i - could find, anyway). Seems to have never been necessary - before. - */ - /* MARKER(("Rescoping my prototype! Why does this never need to happen?\n")); */ - child = chb->prototype; - res = &RC /* keep original res result in place */; - goto start; - } - return rc; - } -} - -int cwal_value_upscope( cwal_value * v ){ - cwal_engine * e = CWAL_VENGINE(v); - if(!e || !e->current || !v->scope) return CWAL_MEM_IS_BUILTIN(v) ? 0 : CWAL_RC_MISUSE; - else if(!e->current->parent){ - assert(1==e->current->level); - assert(e->current == v->scope); - return 0; - } - else if(e->current->parent == v->scope) return 0; - else { - int rc, dir = 0; - rc = cwal_value_xscope( e, e->current->parent, v, &dir); - assert(0==rc); - return rc; - } -} - - -cwal_value * cwal_propagating_get( cwal_engine * e ){ - return e->values.propagating; -} - -cwal_value * cwal_propagating_set( cwal_engine * e, cwal_value * v ){ - if(v != e->values.propagating){ - if(v) cwal_value_ref(v); - if(e->values.propagating){ - cwal_value_unref(e->values.propagating); - } - e->values.propagating = v; - } - return v; -} - -cwal_value * cwal_propagating_take( cwal_engine * e ){ - cwal_value * rv = e->values.propagating; - if(rv){ - cwal_value_ref(rv); - cwal_propagating_set(e, 0); - cwal_value_unhand(rv); - } - return rv; -} - - -int cwal_exception_set( cwal_engine * e, cwal_value * v ){ - if(!e || !e->current) return CWAL_RC_MISUSE; - else if(v && (v == e->values.exception)) /* This is ok. */ return CWAL_RC_EXCEPTION; - else if(!v) { -#if 0 - if(e->values.exception - && e->values.exception->scope==e->current - && 1==CWAL_REFCOUNT(e->values.exception)){ - /* Should we really be doing this? Assuming the scope - reference is the only ref? Previous attempts to do this - have bitten me in the buttox, but i "think" i can get away - with it for exceptions. - - Note that this routine does NOT add a ref to v, but instead - of taking back our own ref we're stealing that of the owning - scope. - - Nonono... this could open up cases where an exception is - moved around and set/unset as the exception state multiple - times, and we'd unref it too many times. So we'll only do - this "optimization" to when the scopes match and - 1==refcount, which we can fairly safely assume is the - scope-held ref unless the client has done something silly, - like... set exception state, move it into an object owned - by the same scope, unref the exception (refcount==1), set - the object as the exception state... blammo. Okay, turn - this off but leave the commentary as yet another reminder - of why we don't just generically unref values. - */ - cwal_value_unref2(e, e->values.exception); - } -#endif - if(e->values.exception) cwal_value_unref(e->values.exception); - e->values.exception = 0 /* its scope owns it */; - return 0; - } - else{ - cwal_value_ref(v); - if(e->values.exception) cwal_value_unref(e->values.exception); - e->values.exception = v; - /* cwal_value_ref(v); */ - return CWAL_RC_EXCEPTION; - } -} - -int cwal_exception_setfv(cwal_engine * e, int code, char const * fmt, va_list args){ - if(!e) return CWAL_RC_MISUSE; - else{ - int rc; - switch(code){ - case CWAL_RC_OOM: rc = code; - break; - default: { - cwal_exception * x; - x = (fmt && *fmt) - ? cwal_new_exceptionfv(e, code, fmt, args) - : cwal_new_exception(e, code, NULL); - if(!x) rc = CWAL_RC_OOM; - else{ - cwal_value * xv = cwal_exception_value(x); - cwal_value_ref(xv); - rc = cwal_exception_set( e, xv ); - cwal_value_unref(xv); - assert(0!=rc); - } - break; - } - } - return rc; - } -} -int cwal_exception_setf(cwal_engine * e, int code, char const * fmt, ...){ - if(!e || !fmt) return 0; - else{ - int rc; - va_list args; - va_start(args,fmt); - rc = cwal_exception_setfv(e, code, fmt, args); - va_end(args); - return rc; - } -} - -cwal_value * cwal_exception_get( cwal_engine * e ){ - return e ? e->values.exception : 0; -} - -#if 0 -/* keeping around for a look at its heurists later on. */ -/** - Internal helper for recycling buffer memory. dest must be a new, - clean buffer with no memory (that might get assert()ed). If the - recyling list has an entry which can serve at least forAllocSize - bytes, that entry's memory is transfered into dest. If no entry is - capable of holding it, dest->mem will still be 0 after - returning. There are no error conditions except for precondition - violations (assertions). - -*/ -/* static */ void cwal_buffer_steal_mem( cwal_engine * e, cwal_buffer * dest, - cwal_size_t forAllocSize){ -#if 0 - /*Enable this section to effectively disable buffer->mem recycling - for memory cost/savings comparisons. */ - return; -#else - assert(!dest->mem); - assert(!dest->used); - if(dest->mem || e->reBuf.cursor<0) return; - else{ - int i = e->reBuf.cursor; - /* Potential TODO: find the closest-(but >=)-fit entry */ - for( ; i < (int)(sizeof(e->reBuf.buffers)/sizeof(e->reBuf.buffers[0])); - ++i ){ - cwal_buffer * br = &e->reBuf.buffers[i]; - if(br->mem - /* Try an approximate fit... */ - && br->capacity>=forAllocSize -#if 1 - /* This heuristic is very basic, of course. */ - && (br->capacity <= 64 * CWAL_SIZE_T_BITS /* 1k, 2k, 4k */ - || br->capacity<= 2 * forAllocSize - ) -#endif - ){ - *dest = *br; - /* MARKER(("Re-using buffer memory (%"CWAL_SIZE_T_PFMT") from slot #%d\n", br->capacity, e->reBuf.cursor)); */ - if(e->reBuf.cursor != i){ - /* Move the final buffer in the list to this slot, - so that our list is always contiguous. */ - *br = e->reBuf.buffers[e->reBuf.cursor]; - e->reBuf.buffers[e->reBuf.cursor] = cwal_buffer_empty; - }else{ - *br = cwal_buffer_empty; - } - --e->reBuf.cursor; - break; - } - } - } -#endif -} -#endif - -void cwal_list_from_recycler( cwal_engine * e, cwal_list * list, - cwal_size_t minCount ){ -#if 0 - /*Enable this section to effectively disable array->list recycling - for memory cost/savings comparisons. */ - return; -#else - if(list->list) return; - else{ - void * mem; - cwal_size_t reqSize = minCount * sizeof(void*); - assert(!list->alloced); - if( (mem = cwal_memchunk_request(e, &reqSize, 1000, - minCount - ? "cwal_list_from_recycler(min)" - : "cwal_list_from_recycler(0)" - ))){ - assert(reqSize>= minCount * sizeof(void*)); - list->list = (void **)mem; - list->alloced = reqSize/sizeof(void*) - /* Yes, we might be losing a few bytes here. The alternatives - include: - - (A) Put it back and try for another (aligned) one - (or give up). - - (B) Add a flag to cwal_memchunk_request() which specifies - we need it aligned. - - (C) Make cwal_re/alloc() always align up and rely on that - in the recycler? The culprit is really cwal_buffer_reserve(), - so that would be the one to patch. - - (D) Something different? - */ - ; - assert(list->alloced >= minCount); - /*MARKER(("Reused array list memory: %u entries from %u bytes\n", - (unsigned)list->alloced, (unsigned)reqSize));*/ - } - } -#endif -} - -int cwal_array_set( cwal_array * const ar, cwal_midsize_t ndx, cwal_value * const v ) -{ - SETUP_ARRAY_ARGS; - if( !ar ) return CWAL_RC_MISUSE; - else if(CWAL_OB_IS_LOCKED(ar)) return CWAL_RC_LOCKED; - else if( (ndx+1) > CwalConsts.MaxSizeTCounter) /* overflow */return CWAL_RC_RANGE; - else{ - cwal_size_t len; - len = ar->list.alloced; - if(len <= ndx){ - len = cwal_list_reserve( e, &ar->list, - (ndxlist.list[ndx]; - assert( arV && (CWAL_TYPE_ARRAY==arV->vtab->typeID) ); - if( old ){ - if(old == v) return 0; - } - if(v){ - rc = cwal_value_xscope( e, arV->scope, v, 0 ); - if(rc){ - assert(!"WARNING: xscope failed! " - "THIS IS SUPPOSED TO BE IMPOSSIBLE :(\n"); - return rc; - } - cwal_value_ref2( e, v ); - } - if(old) cwal_value_unref2(e, old); - ar->list.list[ndx] = v; - if( ndx >= ar->list.count ){ - ar->list.count = ndx+1; - } - return 0; - } - } -} - -int cwal_array_append( cwal_array * const ar, cwal_value * const v ){ - SETUP_ARRAY_ARGS; - if( !ar ) return CWAL_RC_MISUSE; - else if(CWAL_OB_IS_LOCKED(ar)) return CWAL_RC_LOCKED; - else if( (ar->list.count+1) < ar->list.count ) return CWAL_RC_RANGE; - else{ - if(!ar->list.list) cwal_list_from_recycler(e, &ar->list, 0); - if( !ar->list.alloced - || (ar->list.count == ar->list.alloced-1)){ - unsigned const int n = ar->list.count - ? ar->list.alloced * 2 - : CwalConsts.InitialArrayLength; - if( n > cwal_list_reserve( e, &ar->list, n ) ){ - return CWAL_RC_OOM; - } - } - return cwal_array_set( ar, ar->list.count, v ); - } -} - -int cwal_array_prepend( cwal_array * const ar, cwal_value * const v ){ - SETUP_ARRAY_ARGS; - if( !ar || !v ) return CWAL_RC_MISUSE; - else if(CWAL_OB_IS_LOCKED(ar)) return CWAL_RC_LOCKED; - else{ - int rc; - cwal_value ** vlist; - if(!ar->list.list) cwal_list_from_recycler(e, &ar->list, 1); - if( !ar->list.alloced - || (ar->list.count == ar->list.alloced-1)){ - unsigned const int n = ar->list.count - ? ar->list.alloced * 2 - : CwalConsts.InitialArrayLength; - if( n > cwal_list_reserve( e, &ar->list, n ) ){ - return CWAL_RC_OOM; - } - } - if(ar->list.count){ - unsigned char * mem = - (unsigned char *)ar->list.list; - memmove( mem+sizeof(cwal_value*), mem, - sizeof(cwal_value*)*ar->list.count); - } - vlist = (cwal_value **)ar->list.list; - vlist[0] = NULL; - ++ar->list.count; - rc = cwal_array_set( ar, 0, v ); - /* A recovery here on error would be messy, but the - set() can only fail on allocation error and we've - already done the allocation. - */ - assert(!rc); - assert(v == *((cwal_value**)ar->list.list)); - return rc; - } -} - -int cwal_array_shift( cwal_array * ar, cwal_value **rv ){ - SETUP_ARRAY_ARGS; - if( !ar ) return CWAL_RC_MISUSE; - else{ - cwal_value ** vlist; - unsigned char * mem; - cwal_value * v; - if(!ar->list.count) return CWAL_RC_RANGE; - vlist = (cwal_value **)ar->list.list; - v = vlist[0]; - if(rv) *rv = v; - mem = (unsigned char *)ar->list.list; - memmove( mem, mem+sizeof(cwal_value*), - sizeof(cwal_value*)*(ar->list.count-1)); - vlist[--ar->list.count] = NULL; - if(v){ - if(rv) cwal_value_unhand(v); - else cwal_value_unref(v); - } - return 0; - } -} - -int cwal_array_index_of( cwal_array const * ar, cwal_value const * v, - cwal_size_t * index, char strictComparison ){ - if(!ar) return CWAL_RC_MISUSE; - else if(!ar->list.count) return CWAL_RC_NOT_FOUND; - else{ - cwal_size_t i; - cwal_value * const arv = CWAL_VALPART(ar); - int opaque; - cwal_visit_list_begin(arv, &opaque); - for( i = 0; i < ar->list.count; ++i ){ - cwal_value const * rhs = (cwal_value const *)ar->list.list[i]; - if(v==rhs) break /* also match on NULL */; - else if((v && !rhs) || (!v && rhs)) continue; - else if(strictComparison){ - if(v->vtab->typeID == rhs->vtab->typeID - && 0 == cwal_value_compare(v, rhs)) break; - }else if(0 == cwal_value_compare(v, rhs)) break; - } - cwal_visit_list_end(arv, opaque); - if(i < ar->list.count){ - if(index) *index = i; - return 0; - }else{ - return CWAL_RC_NOT_FOUND; - } - } -} - - -int cwal_array_copy_range( cwal_array * ar, cwal_size_t offset, - cwal_size_t count, - cwal_array **dest ){ - SETUP_ARRAY_ARGS; - if( !ar || !dest || (ar==*dest) ) return CWAL_RC_MISUSE; - else if(CWAL_OB_IS_LOCKED(ar) || (*dest && CWAL_OB_IS_LOCKED(*dest))) return CWAL_RC_LOCKED; - else{ - int rc = 0; - cwal_size_t i; - cwal_array * tgt = *dest ? *dest : cwal_new_array(e); - cwal_value ** vlist; - cwal_value * const arv = CWAL_VALPART(ar); - int opaque; - cwal_visit_list_begin(arv, &opaque); - vlist = (cwal_value **)ar->list.list; - if(offsetlist.count){ - cwal_size_t to; - if(!count) count = ar->list.count - offset; - to = offset + count; - if(to > ar->list.count) to = ar->list.count; - rc = cwal_array_reserve( tgt, count ); - for( i = offset; - !rc && (iscope) - ? cwal_value_unref2(v->scope->e, v) - : CWAL_RC_MISUSE; -} - -/** - The C-string equivalent of cwal_obase_search_v(). -*/ -static cwal_value * cwal_obase_search( cwal_obase const * base, - bool searchProto, - char const * const key, - cwal_midsize_t keyLen, - cwal_kvp ** prev){ - if(!base || !key) return NULL; - else { - cwal_kvp * kvp; - cwal_value * rc = NULL; - while(base){ - if(CWAL_F_LOCKED & base->flags) break; -#if CWAL_OBASE_ISA_HASH - kvp = cwal_htable_search_impl_cstr(&base->hprops, key, keyLen, - NULL, prev); -#else - kvp = cwal_kvp_search( base->kvp, key, keyLen, prev ); -#endif - if(kvp) { - rc = kvp->value; - break; - } - else base = searchProto ? CWAL_VOBASE(base->prototype) : 0; - } - return rc; - } -} - -#if 0 -static int cwal_prop_getter_check( cwal_obase const * originalThis, - /* cwal_obase const * foundIn, */ - cwal_value const * key, - cwal_value * value, - cwal_value ** rv ){ - cwal_function * f = cwal_value_get_function(value); - if(!