1
0
Fork 0
mirror of https://github.com/ctruLua/ctruLua.git synced 2025-10-27 16:39:29 +00:00

Moved lzlib to the libs directory (cleaner)

This commit is contained in:
Reuh 2015-10-04 12:08:25 +02:00
parent 406e17d321
commit 4aad32d5ab
23 changed files with 2593 additions and 991 deletions

51
libs/lzlib/.travis.yml Normal file
View file

@ -0,0 +1,51 @@
#
# LuaDist Travis-CI Hook
#
# We assume C build environments
language: C
# Try using multiple Lua Implementations
env:
- TOOL="gcc" # Use native compiler (GCC usually)
- TOOL="clang" # Use clang
- TOOL="i686-w64-mingw32" # 32bit MinGW
- TOOL="x86_64-w64-mingw32" # 64bit MinGW
- TOOL="arm-linux-gnueabihf" # ARM hard-float (hf), linux
# Crosscompile builds may fail
matrix:
allow_failures:
- env: TOOL="i686-w64-mingw32"
- env: TOOL="x86_64-w64-mingw32"
- env: TOOL="arm-linux-gnueabihf"
# Install dependencies
install:
- git clone git://github.com/LuaDist/Tools.git ~/_tools
- ~/_tools/travis/travis install
# Bootstap
before_script:
- ~/_tools/travis/travis bootstrap
# Build the module
script:
- ~/_tools/travis/travis build
# Execute additional tests or commands
after_script:
- ~/_tools/travis/travis test
# Only watch the master branch
branches:
only:
- master
# Notify the LuaDist Dev group if needed
notifications:
recipients:
- luadist-dev@googlegroups.com
email:
on_success: change
on_failure: always

42
libs/lzlib/CHANGES Normal file
View file

@ -0,0 +1,42 @@
0.4-work3 2010-11-19
====================
Compatibility with lua 5.2.
0.4-work2 2008-11-07
====================
Fix: In the stream interface, the write callback was always being called with
two parameters even if the callback only needed one.
Thanks to Ignacio Burgueño for reporting the problem and providing a patch.
0.4-work1 2008-04-08
====================
Unstable version of streaming interface. Many things need to me tested
properly, and code needs to be polished.
This adds an interface to zlib deflate/inflate streams similar to the io
file objects.
Check README file for more information.
gzip module is now a pure lua module.
Warning: minimal tests provided... need to change that.
0.3 2008-01-28
==============
This release makes the zlib/gzip bindings compatible with the latest
version of Lua (5.1) and now uses the package system to load the library.
It also fixes some incompatibilities that showed up with the changes
made to the Lua auxiliary library.
0.2 2004-07-22
==============
0.1 2003-12-09
==============
First released version.

19
libs/lzlib/CMakeLists.txt Normal file
View file

@ -0,0 +1,19 @@
# Copyright (C) 2007-2013 LuaDist.
# Created by Peter Drahoš
# Redistribution and use of this file is allowed according to the terms of the MIT license.
# For details see the COPYRIGHT file distributed with LuaDist.
# Please note that the package source code is licensed under its own license.
project ( lzlib C )
cmake_minimum_required ( VERSION 2.8 )
include ( cmake/dist.cmake )
include ( lua )
find_library ( Z_LIBRARY NAMES zlib zlibd z )
# Find zlib
install_lua_module ( zlib lzlib.c zlib.def LINK ${Z_LIBRARY} )
install_lua_module ( gzip gzip.lua )
install_data ( README README.lgzip )
install_test ( test_gzip.lua test_zlib_dict.lua test_zlib2.lua test_zlib3.lua )

62
libs/lzlib/Makefile Normal file
View file

@ -0,0 +1,62 @@
# $Id: Makefile,v 1.8 2004/07/22 19:10:47 tngd Exp $
# makefile for zlib library for Lua
# dist location
DISTDIR=dist
TMP=/tmp
# change these to reflect your Lua installation
LUA= $(HOME)/local/lua-5.2
LUAINC= $(LUA)/include
LUALIB= $(LUA)/lib
LUABIN= $(LUA)/bin
ZLIB=../zlib-1.2.3
# no need to change anything below here
CFLAGS= $(INCS) $(DEFS) $(WARN) -O0 -fPIC
WARN= -g -Werror -Wall -pedantic #-ansi
INCS= -I$(LUAINC) -I$(ZLIB)
LIBS= -L$(ZLIB) -lz -L$(LUALIB) -L$(LUABIN) #-llua51
MYLIB=lzlib
ZLIB_NAME = zlib
GZIP_NAME = gzip
T_ZLIB= $(ZLIB_NAME).so
T_GZIP= $(GZIP_NAME).so
VER=0.4-work3
TARFILE = $(DISTDIR)/$(MYLIB)-$(VER).tar.gz
TARFILES = Makefile README README.lgzip CHANGES \
lzlib.c gzip.lua \
test_zlib2.lua \
test_zlib3.lua \
test_gzip.lua \
test_prologue.lua
all: $(T_ZLIB) # $(T_GZIP)
test: $(T_ZLIB) # $(T_GZIP)
$(LUABIN)/lua -lluarc test_prologue.lua
$(LUABIN)/lua -lluarc test_gzip.lua
$(LUABIN)/lua -lluarc test_zlib2.lua
$(LUABIN)/lua -lluarc test_zlib3.lua
$(T_ZLIB): lzlib.o
$(CC) -o $@ -shared $< $(LIBS)
$(T_GZIP): lgzip.o
$(CC) -o $@ -shared $< $(LIBS)
clean:
rm -f *.o *.so core core.* a.out
dist: $(TARFILE)
$(TARFILE): $(TARFILES)
@ln -sf `pwd` $(TMP)/$(MYLIB)-$(VER)
tar -zcvf $(TARFILE) -C $(TMP) $(addprefix $(MYLIB)-$(VER)/,$(TARFILES))
@rm -f $(TMP)/$(MYLIB)-$(VER)
@# @lsum $(TARFILE) $(DISTDIR)/md5sums.txt

112
libs/lzlib/README Normal file
View file

@ -0,0 +1,112 @@
*************************************************************************
* Author : Tiago Dionizio <tiago.dionizio@gmail.com> *
* Library : lzlib - Lua 5.1 interface to access zlib library functions*
* *
* 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. *
*************************************************************************
To use this library you need zlib library.
You can get it from http://www.gzip.org/zlib/
Loading the library:
If you built the library as a loadable package
[local] zlib = require 'zlib'
If you compiled the package statically into your application, call
the function "luaopen_zlib(L)". It will create a table with the zlib
functions and leave it on the stack.
-- zlib functions --
zlib.version()
returns zlib version
zlib.adler32([int adler32, string buffer])
Without any parameters, returns the inicial adler32 value.
Call to update the adler32 value, adler is the current value, buffer is passed
to adler32 zlib function and the updated value is returned.
zlib.crc32([int crc32, string buffer])
Same as zlib.adler32.
zlib.compress(string buffer [, int level] [, int method] [, int windowBits] [, int memLevel] [, int strategy])
Return a string containing the compressed buffer according to the given parameters.
zlib.decompress(string buffer [, int windowBits])
Return the decompressed stream after processing the given buffer.
zlib.deflate(
sink: function | { write: function [, close: function, flush: function ] },
compression level, [Z_DEFAILT_COMPRESSION]
method, [Z_DEFLATED]
windowBits, [15]
memLevel, [8]
strategy, [Z_DEFAULT_STRATEGY]
dictionary, [""]
)
Return a deflate stream.
stream:read((number | '*l' | '*a')*)
Return a value for each given parameter. Returns a line when
no format is specified.
stream:lines()
Return iterator that returns a line each time it is called, or nil
on end of file.
stream:close()
Close the stream.
zlib.inflate(
source: string | function | { read: function, close: function },
windowBits: number, [15]
dictionary, [""]
)
Return an inflate stream.
deflate and inflate streams can be used almost like a normal file:
stream:write(...)
Write each parameter into the sream.
stream:read([option [, ...]])
Read from the stream, each parameter corresponds to
a return value.
With no arguments, it reads a line.
Parameters are interpreted as follows:
number - reads the specified number of bytes
'a' - reads the remaining bytes
'l' - reads a line
stream:lines(...)
Returns an iterator that returns a new line each time
it is called.
stream:flush(['sync' | 'full' | 'finish'])
Flush output for deflate streams.
stream:close()
Close the stream.

108
libs/lzlib/README.lgzip Normal file
View file

@ -0,0 +1,108 @@
*************************************************************************
* Author : Tiago Dionizio <tiago.dionizio@gmail.com> *
* Library : lgzip - a gzip file access binding for Lua 5 *
* based on liolib.c from Lua 5.0 library *
* *
* 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. *
*************************************************************************
To use this library you need zlib library.
You can get it from http://www.gzip.org/zlib/
GZIP file handling on top of the zlib interface.
TODO:
- detect plain text files
- proper testing
- improve implementation?
- check gzopen flags for consistency (ex: strategy flag)
Loading the library:
[local] gzip = require 'gzip'
gzip.open(filename [, mode])
Opens a file name using "gzopen". Behaviour is identical to the description
given in the zlib library. If mode is not given a default mode "r" will be
used. Mode is the same as interpreted by gzopen function, ie, it can
include special modes such as characters 1 to 9 that will be treated as the
compression level when opening a file for writing.
It returns a new file handle, or, in case of errors, nil plus an error
message
gzip.lines(filename)
Same behaviour as io.lines in the io standard library provided by lua
with the aditional feature of working with gzip files. If a normal text
file is read it will read it normaly.
gzip.close(file)
Same as file:close, use file:close instead.
file:flush()
This function takes no parameters and flushes all output to working file.
The same as calling 'gzflush(file, Z_FINISH)' so writing to the file will
most likely not work as expected. This is subject to change in the future
if there is a strong reason for it to happen.
file:read(format1, ...)
Reads the file file, according to the given formats, which specify what
to read. For each format, the function returns a string with the characters
read, or nil if it cannot read data with the specified format. When called
without formats, it uses a default format that reads the entire next line
(see below).
The available formats are
"*a" reads the whole file, starting at the current position. On end of
file, it returns the empty string.
"*l" reads the next line (skipping the end of line), returning nil on
end of file. This is the default format.
number reads a string with up to that number of characters, returning
nil on end of file. If number is zero, it reads nothing and
returns an empty string, or nil on end of file.
Unlike io.read, the "*n" format will not be available.
file:lines()
Returns an iterator function that, each time it is called, returns a new
line from the file. Therefore, the construction
for line in file:lines() do ... end
will iterate over all lines of the file.
file:write(value1, ...)
Writes the value of each of its arguments to the filehandle file. The
arguments must be strings or numbers. To write other values, use tostring
or string.format before write
file:close()
Closes the file.

View file

@ -0,0 +1,118 @@
# Locate Lua library
# This module defines
# LUA_EXECUTABLE, if found
# LUA_FOUND, if false, do not try to link to Lua
# LUA_LIBRARIES
# LUA_INCLUDE_DIR, where to find lua.h
# LUA_VERSION_STRING, the version of Lua found (since CMake 2.8.8)
#
# Note that the expected include convention is
# #include "lua.h"
# and not
# #include <lua/lua.h>
# This is because, the lua location is not standardized and may exist
# in locations other than lua/
#=============================================================================
# Copyright 2007-2009 Kitware, Inc.
# Modified to support Lua 5.2 by LuaDist 2012
#
# Distributed under the OSI-approved BSD License (the "License");
# see accompanying file Copyright.txt for details.
#
# This software is distributed WITHOUT ANY WARRANTY; without even the
# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the License for more information.
#=============================================================================
# (To distribute this file outside of CMake, substitute the full
# License text for the above reference.)
#
# The required version of Lua can be specified using the
# standard syntax, e.g. FIND_PACKAGE(Lua 5.1)
# Otherwise the module will search for any available Lua implementation
# Always search for non-versioned lua first (recommended)
SET(_POSSIBLE_LUA_INCLUDE include include/lua)
SET(_POSSIBLE_LUA_EXECUTABLE lua)
SET(_POSSIBLE_LUA_LIBRARY lua)
# Determine possible naming suffixes (there is no standard for this)
IF(Lua_FIND_VERSION_MAJOR AND Lua_FIND_VERSION_MINOR)
SET(_POSSIBLE_SUFFIXES "${Lua_FIND_VERSION_MAJOR}${Lua_FIND_VERSION_MINOR}" "${Lua_FIND_VERSION_MAJOR}.${Lua_FIND_VERSION_MINOR}" "-${Lua_FIND_VERSION_MAJOR}.${Lua_FIND_VERSION_MINOR}")
ELSE(Lua_FIND_VERSION_MAJOR AND Lua_FIND_VERSION_MINOR)
SET(_POSSIBLE_SUFFIXES "52" "5.2" "-5.2" "51" "5.1" "-5.1")
ENDIF(Lua_FIND_VERSION_MAJOR AND Lua_FIND_VERSION_MINOR)
# Set up possible search names and locations
FOREACH(_SUFFIX ${_POSSIBLE_SUFFIXES})
LIST(APPEND _POSSIBLE_LUA_INCLUDE "include/lua${_SUFFIX}")
LIST(APPEND _POSSIBLE_LUA_EXECUTABLE "lua${_SUFFIX}")
LIST(APPEND _POSSIBLE_LUA_LIBRARY "lua${_SUFFIX}")
ENDFOREACH(_SUFFIX)
# Find the lua executable
FIND_PROGRAM(LUA_EXECUTABLE
NAMES ${_POSSIBLE_LUA_EXECUTABLE}
)
# Find the lua header
FIND_PATH(LUA_INCLUDE_DIR lua.h
HINTS
$ENV{LUA_DIR}
PATH_SUFFIXES ${_POSSIBLE_LUA_INCLUDE}
PATHS
~/Library/Frameworks
/Library/Frameworks
/usr/local
/usr
/sw # Fink
/opt/local # DarwinPorts
/opt/csw # Blastwave
/opt
)
# Find the lua library
FIND_LIBRARY(LUA_LIBRARY
NAMES ${_POSSIBLE_LUA_LIBRARY}
HINTS
$ENV{LUA_DIR}
PATH_SUFFIXES lib64 lib
PATHS
~/Library/Frameworks
/Library/Frameworks
/usr/local
/usr
/sw
/opt/local
/opt/csw
/opt
)
IF(LUA_LIBRARY)
# include the math library for Unix
IF(UNIX AND NOT APPLE)
FIND_LIBRARY(LUA_MATH_LIBRARY m)
SET( LUA_LIBRARIES "${LUA_LIBRARY};${LUA_MATH_LIBRARY}" CACHE STRING "Lua Libraries")
# For Windows and Mac, don't need to explicitly include the math library
ELSE(UNIX AND NOT APPLE)
SET( LUA_LIBRARIES "${LUA_LIBRARY}" CACHE STRING "Lua Libraries")
ENDIF(UNIX AND NOT APPLE)
ENDIF(LUA_LIBRARY)
# Determine Lua version
IF(LUA_INCLUDE_DIR AND EXISTS "${LUA_INCLUDE_DIR}/lua.h")
FILE(STRINGS "${LUA_INCLUDE_DIR}/lua.h" lua_version_str REGEX "^#define[ \t]+LUA_RELEASE[ \t]+\"Lua .+\"")
STRING(REGEX REPLACE "^#define[ \t]+LUA_RELEASE[ \t]+\"Lua ([^\"]+)\".*" "\\1" LUA_VERSION_STRING "${lua_version_str}")
UNSET(lua_version_str)
ENDIF()
INCLUDE(FindPackageHandleStandardArgs)
# handle the QUIETLY and REQUIRED arguments and set LUA_FOUND to TRUE if
# all listed variables are TRUE
FIND_PACKAGE_HANDLE_STANDARD_ARGS(Lua
REQUIRED_VARS LUA_LIBRARIES LUA_INCLUDE_DIR
VERSION_VAR LUA_VERSION_STRING)
MARK_AS_ADVANCED(LUA_INCLUDE_DIR LUA_LIBRARIES LUA_LIBRARY LUA_MATH_LIBRARY LUA_EXECUTABLE)

321
libs/lzlib/cmake/dist.cmake Normal file
View file

@ -0,0 +1,321 @@
# LuaDist CMake utility library.
# Provides sane project defaults and macros common to LuaDist CMake builds.
#
# Copyright (C) 2007-2012 LuaDist.
# by David Manura, Peter Drahoš
# Redistribution and use of this file is allowed according to the terms of the MIT license.
# For details see the COPYRIGHT file distributed with LuaDist.
# Please note that the package source code is licensed under its own license.
## Extract information from dist.info
if ( NOT EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/dist.info )
message ( FATAL_ERROR
"Missing dist.info file (${CMAKE_CURRENT_SOURCE_DIR}/dist.info)." )
endif ()
file ( READ ${CMAKE_CURRENT_SOURCE_DIR}/dist.info DIST_INFO )
if ( "${DIST_INFO}" STREQUAL "" )
message ( FATAL_ERROR "Failed to load dist.info." )
endif ()
# Reads field `name` from dist.info string `DIST_INFO` into variable `var`.
macro ( _parse_dist_field name var )
string ( REGEX REPLACE ".*${name}[ \t]?=[ \t]?[\"']([^\"']+)[\"'].*" "\\1"
${var} "${DIST_INFO}" )
if ( ${var} STREQUAL DIST_INFO )
message ( FATAL_ERROR "Failed to extract \"${var}\" from dist.info" )
endif ()
endmacro ()
#
_parse_dist_field ( name DIST_NAME )
_parse_dist_field ( version DIST_VERSION )
_parse_dist_field ( license DIST_LICENSE )
_parse_dist_field ( author DIST_AUTHOR )
_parse_dist_field ( maintainer DIST_MAINTAINER )
_parse_dist_field ( url DIST_URL )
_parse_dist_field ( desc DIST_DESC )
message ( "DIST_NAME: ${DIST_NAME}")
message ( "DIST_VERSION: ${DIST_VERSION}")
message ( "DIST_LICENSE: ${DIST_LICENSE}")
message ( "DIST_AUTHOR: ${DIST_AUTHOR}")
message ( "DIST_MAINTAINER: ${DIST_MAINTAINER}")
message ( "DIST_URL: ${DIST_URL}")
message ( "DIST_DESC: ${DIST_DESC}")
string ( REGEX REPLACE ".*depends[ \t]?=[ \t]?[\"']([^\"']+)[\"'].*" "\\1"
DIST_DEPENDS ${DIST_INFO} )
if ( DIST_DEPENDS STREQUAL DIST_INFO )
set ( DIST_DEPENDS "" )
endif ()
message ( "DIST_DEPENDS: ${DIST_DEPENDS}")
## 2DO: Parse DIST_DEPENDS and try to install Dependencies with automatically using externalproject_add
## INSTALL DEFAULTS (Relative to CMAKE_INSTALL_PREFIX)
# Primary paths
set ( INSTALL_BIN bin CACHE PATH "Where to install binaries to." )
set ( INSTALL_LIB lib CACHE PATH "Where to install libraries to." )
set ( INSTALL_INC include CACHE PATH "Where to install headers to." )
set ( INSTALL_ETC etc CACHE PATH "Where to store configuration files" )
set ( INSTALL_SHARE share CACHE PATH "Directory for shared data." )
# Secondary paths
option ( INSTALL_VERSION
"Install runtime libraries and executables with version information." OFF)
set ( INSTALL_DATA ${INSTALL_SHARE}/${DIST_NAME} CACHE PATH
"Directory the package can store documentation, tests or other data in.")
set ( INSTALL_DOC ${INSTALL_DATA}/doc CACHE PATH
"Recommended directory to install documentation into.")
set ( INSTALL_EXAMPLE ${INSTALL_DATA}/example CACHE PATH
"Recommended directory to install examples into.")
set ( INSTALL_TEST ${INSTALL_DATA}/test CACHE PATH
"Recommended directory to install tests into.")
set ( INSTALL_FOO ${INSTALL_DATA}/etc CACHE PATH
"Where to install additional files")
# Tweaks and other defaults
# Setting CMAKE to use loose block and search for find modules in source directory
set ( CMAKE_ALLOW_LOOSE_LOOP_CONSTRUCTS true )
set ( CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake" ${CMAKE_MODULE_PATH} )
option ( BUILD_SHARED_LIBS "Build shared libraries" ON )
# In MSVC, prevent warnings that can occur when using standard libraries.
if ( MSVC )
add_definitions ( -D_CRT_SECURE_NO_WARNINGS )
endif ()
# RPath and relative linking
option ( USE_RPATH "Use relative linking." ON)
if ( USE_RPATH )
string ( REGEX REPLACE "[^!/]+" ".." UP_DIR ${INSTALL_BIN} )
set ( CMAKE_SKIP_BUILD_RPATH FALSE CACHE STRING "" FORCE )
set ( CMAKE_BUILD_WITH_INSTALL_RPATH FALSE CACHE STRING "" FORCE )
set ( CMAKE_INSTALL_RPATH $ORIGIN/${UP_DIR}/${INSTALL_LIB}
CACHE STRING "" FORCE )
set ( CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE CACHE STRING "" FORCE )
set ( CMAKE_INSTALL_NAME_DIR @executable_path/${UP_DIR}/${INSTALL_LIB}
CACHE STRING "" FORCE )
endif ()
## MACROS
# Parser macro
macro ( parse_arguments prefix arg_names option_names)
set ( DEFAULT_ARGS )
foreach ( arg_name ${arg_names} )
set ( ${prefix}_${arg_name} )
endforeach ()
foreach ( option ${option_names} )
set ( ${prefix}_${option} FALSE )
endforeach ()
set ( current_arg_name DEFAULT_ARGS )
set ( current_arg_list )
foreach ( arg ${ARGN} )
set ( larg_names ${arg_names} )
list ( FIND larg_names "${arg}" is_arg_name )
if ( is_arg_name GREATER -1 )
set ( ${prefix}_${current_arg_name} ${current_arg_list} )
set ( current_arg_name ${arg} )
set ( current_arg_list )
else ()
set ( loption_names ${option_names} )
list ( FIND loption_names "${arg}" is_option )
if ( is_option GREATER -1 )
set ( ${prefix}_${arg} TRUE )
else ()
set ( current_arg_list ${current_arg_list} ${arg} )
endif ()
endif ()
endforeach ()
set ( ${prefix}_${current_arg_name} ${current_arg_list} )
endmacro ()
# install_executable ( executable_targets )
# Installs any executables generated using "add_executable".
# USE: install_executable ( lua )
# NOTE: subdirectories are NOT supported
set ( CPACK_COMPONENT_RUNTIME_DISPLAY_NAME "${DIST_NAME} Runtime" )
set ( CPACK_COMPONENT_RUNTIME_DESCRIPTION
"Executables and runtime libraries. Installed into ${INSTALL_BIN}." )
macro ( install_executable )
foreach ( _file ${ARGN} )
if ( INSTALL_VERSION )
set_target_properties ( ${_file} PROPERTIES VERSION ${DIST_VERSION}
SOVERSION ${DIST_VERSION} )
endif ()
install ( TARGETS ${_file} RUNTIME DESTINATION ${INSTALL_BIN}
COMPONENT Runtime )
endforeach()
endmacro ()
# install_library ( library_targets )
# Installs any libraries generated using "add_library" into apropriate places.
# USE: install_library ( libexpat )
# NOTE: subdirectories are NOT supported
set ( CPACK_COMPONENT_LIBRARY_DISPLAY_NAME "${DIST_NAME} Development Libraries" )
set ( CPACK_COMPONENT_LIBRARY_DESCRIPTION
"Static and import libraries needed for development. Installed into ${INSTALL_LIB} or ${INSTALL_BIN}." )
macro ( install_library )
foreach ( _file ${ARGN} )
if ( INSTALL_VERSION )
set_target_properties ( ${_file} PROPERTIES VERSION ${DIST_VERSION}
SOVERSION ${DIST_VERSION} )
endif ()
install ( TARGETS ${_file}
RUNTIME DESTINATION ${INSTALL_BIN} COMPONENT Runtime
LIBRARY DESTINATION ${INSTALL_LIB} COMPONENT Runtime
ARCHIVE DESTINATION ${INSTALL_LIB} COMPONENT Library )
endforeach()
endmacro ()
# helper function for various install_* functions, for PATTERN/REGEX args.
macro ( _complete_install_args )
if ( NOT("${_ARG_PATTERN}" STREQUAL "") )
set ( _ARG_PATTERN PATTERN ${_ARG_PATTERN} )
endif ()
if ( NOT("${_ARG_REGEX}" STREQUAL "") )
set ( _ARG_REGEX REGEX ${_ARG_REGEX} )
endif ()
endmacro ()
# install_header ( files/directories [INTO destination] )
# Install a directories or files into header destination.
# USE: install_header ( lua.h luaconf.h ) or install_header ( GL )
# USE: install_header ( mylib.h INTO mylib )
# For directories, supports optional PATTERN/REGEX arguments like install().
set ( CPACK_COMPONENT_HEADER_DISPLAY_NAME "${DIST_NAME} Development Headers" )
set ( CPACK_COMPONENT_HEADER_DESCRIPTION
"Headers needed for development. Installed into ${INSTALL_INC}." )
macro ( install_header )
parse_arguments ( _ARG "INTO;PATTERN;REGEX" "" ${ARGN} )
_complete_install_args()
foreach ( _file ${_ARG_DEFAULT_ARGS} )
if ( IS_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/${_file}" )
install ( DIRECTORY ${_file} DESTINATION ${INSTALL_INC}/${_ARG_INTO}
COMPONENT Header ${_ARG_PATTERN} ${_ARG_REGEX} )
else ()
install ( FILES ${_file} DESTINATION ${INSTALL_INC}/${_ARG_INTO}
COMPONENT Header )
endif ()
endforeach()
endmacro ()
# install_data ( files/directories [INTO destination] )
# This installs additional data files or directories.
# USE: install_data ( extra data.dat )
# USE: install_data ( image1.png image2.png INTO images )
# For directories, supports optional PATTERN/REGEX arguments like install().
set ( CPACK_COMPONENT_DATA_DISPLAY_NAME "${DIST_NAME} Data" )
set ( CPACK_COMPONENT_DATA_DESCRIPTION
"Application data. Installed into ${INSTALL_DATA}." )
macro ( install_data )
parse_arguments ( _ARG "INTO;PATTERN;REGEX" "" ${ARGN} )
_complete_install_args()
foreach ( _file ${_ARG_DEFAULT_ARGS} )
if ( IS_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/${_file}" )
install ( DIRECTORY ${_file}
DESTINATION ${INSTALL_DATA}/${_ARG_INTO}
COMPONENT Data ${_ARG_PATTERN} ${_ARG_REGEX} )
else ()
install ( FILES ${_file} DESTINATION ${INSTALL_DATA}/${_ARG_INTO}
COMPONENT Data )
endif ()
endforeach()
endmacro ()
# INSTALL_DOC ( files/directories [INTO destination] )
# This installs documentation content
# USE: install_doc ( doc/ doc.pdf )
# USE: install_doc ( index.html INTO html )
# For directories, supports optional PATTERN/REGEX arguments like install().
set ( CPACK_COMPONENT_DOCUMENTATION_DISPLAY_NAME "${DIST_NAME} Documentation" )
set ( CPACK_COMPONENT_DOCUMENTATION_DESCRIPTION
"Application documentation. Installed into ${INSTALL_DOC}." )
macro ( install_doc )
parse_arguments ( _ARG "INTO;PATTERN;REGEX" "" ${ARGN} )
_complete_install_args()
foreach ( _file ${_ARG_DEFAULT_ARGS} )
if ( IS_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/${_file}" )
install ( DIRECTORY ${_file} DESTINATION ${INSTALL_DOC}/${_ARG_INTO}
COMPONENT Documentation ${_ARG_PATTERN} ${_ARG_REGEX} )
else ()
install ( FILES ${_file} DESTINATION ${INSTALL_DOC}/${_ARG_INTO}
COMPONENT Documentation )
endif ()
endforeach()
endmacro ()
# install_example ( files/directories [INTO destination] )
# This installs additional examples
# USE: install_example ( examples/ exampleA )
# USE: install_example ( super_example super_data INTO super)
# For directories, supports optional PATTERN/REGEX argument like install().
set ( CPACK_COMPONENT_EXAMPLE_DISPLAY_NAME "${DIST_NAME} Examples" )
set ( CPACK_COMPONENT_EXAMPLE_DESCRIPTION
"Examples and their associated data. Installed into ${INSTALL_EXAMPLE}." )
macro ( install_example )
parse_arguments ( _ARG "INTO;PATTERN;REGEX" "" ${ARGN} )
_complete_install_args()
foreach ( _file ${_ARG_DEFAULT_ARGS} )
if ( IS_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/${_file}" )
install ( DIRECTORY ${_file} DESTINATION ${INSTALL_EXAMPLE}/${_ARG_INTO}
COMPONENT Example ${_ARG_PATTERN} ${_ARG_REGEX} )
else ()
install ( FILES ${_file} DESTINATION ${INSTALL_EXAMPLE}/${_ARG_INTO}
COMPONENT Example )
endif ()
endforeach()
endmacro ()
# install_test ( files/directories [INTO destination] )
# This installs tests and test files, DOES NOT EXECUTE TESTS
# USE: install_test ( my_test data.sql )
# USE: install_test ( feature_x_test INTO x )
# For directories, supports optional PATTERN/REGEX argument like install().
set ( CPACK_COMPONENT_TEST_DISPLAY_NAME "${DIST_NAME} Tests" )
set ( CPACK_COMPONENT_TEST_DESCRIPTION
"Tests and associated data. Installed into ${INSTALL_TEST}." )
macro ( install_test )
parse_arguments ( _ARG "INTO;PATTERN;REGEX" "" ${ARGN} )
_complete_install_args()
foreach ( _file ${_ARG_DEFAULT_ARGS} )
if ( IS_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/${_file}" )
install ( DIRECTORY ${_file} DESTINATION ${INSTALL_TEST}/${_ARG_INTO}
COMPONENT Test ${_ARG_PATTERN} ${_ARG_REGEX} )
else ()
install ( FILES ${_file} DESTINATION ${INSTALL_TEST}/${_ARG_INTO}
COMPONENT Test )
endif ()
endforeach()
endmacro ()
# install_foo ( files/directories [INTO destination] )
# This installs optional or otherwise unneeded content
# USE: install_foo ( etc/ example.doc )
# USE: install_foo ( icon.png logo.png INTO icons)
# For directories, supports optional PATTERN/REGEX argument like install().
set ( CPACK_COMPONENT_OTHER_DISPLAY_NAME "${DIST_NAME} Unspecified Content" )
set ( CPACK_COMPONENT_OTHER_DESCRIPTION
"Other unspecified content. Installed into ${INSTALL_FOO}." )
macro ( install_foo )
parse_arguments ( _ARG "INTO;PATTERN;REGEX" "" ${ARGN} )
_complete_install_args()
foreach ( _file ${_ARG_DEFAULT_ARGS} )
if ( IS_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/${_file}" )
install ( DIRECTORY ${_file} DESTINATION ${INSTALL_FOO}/${_ARG_INTO}
COMPONENT Other ${_ARG_PATTERN} ${_ARG_REGEX} )
else ()
install ( FILES ${_file} DESTINATION ${INSTALL_FOO}/${_ARG_INTO}
COMPONENT Other )
endif ()
endforeach()
endmacro ()
## CTest defaults
## CPack defaults
set ( CPACK_GENERATOR "ZIP" )
set ( CPACK_STRIP_FILES TRUE )
set ( CPACK_PACKAGE_NAME "${DIST_NAME}" )
set ( CPACK_PACKAGE_VERSION "${DIST_VERSION}")
set ( CPACK_PACKAGE_VENDOR "LuaDist" )
set ( CPACK_COMPONENTS_ALL Runtime Library Header Data Documentation Example Other )
include ( CPack )

293
libs/lzlib/cmake/lua.cmake Normal file
View file

@ -0,0 +1,293 @@
# LuaDist CMake utility library for Lua.
#
# Copyright (C) 2007-2012 LuaDist.
# by David Manura, Peter Drahos
# Redistribution and use of this file is allowed according to the terms of the MIT license.
# For details see the COPYRIGHT file distributed with LuaDist.
# Please note that the package source code is licensed under its own license.
set ( INSTALL_LMOD ${INSTALL_LIB}/lua
CACHE PATH "Directory to install Lua modules." )
set ( INSTALL_CMOD ${INSTALL_LIB}/lua
CACHE PATH "Directory to install Lua binary modules." )
option ( SKIP_LUA_WRAPPER
"Do not build and install Lua executable wrappers." OFF)
# List of (Lua module name, file path) pairs.
# Used internally by add_lua_test. Built by add_lua_module.
set ( _lua_modules )
# utility function: appends path `path` to path `basepath`, properly
# handling cases when `path` may be relative or absolute.
macro ( _append_path basepath path result )
if ( IS_ABSOLUTE "${path}" )
set ( ${result} "${path}" )
else ()
set ( ${result} "${basepath}/${path}" )
endif ()
endmacro ()
# install_lua_executable ( target source )
# Automatically generate a binary if srlua package is available
# The application or its source will be placed into /bin
# If the application source did not have .lua suffix then it will be added
# USE: lua_executable ( sputnik src/sputnik.lua )
macro ( install_lua_executable _name _source )
get_filename_component ( _source_name ${_source} NAME_WE )
# Find srlua and glue
find_program( SRLUA_EXECUTABLE NAMES srlua )
find_program( GLUE_EXECUTABLE NAMES glue )
# Executable output
set ( _exe ${CMAKE_CURRENT_BINARY_DIR}/${_name}${CMAKE_EXECUTABLE_SUFFIX} )
if ( NOT SKIP_LUA_WRAPPER AND SRLUA_EXECUTABLE AND GLUE_EXECUTABLE )
# Generate binary gluing the lua code to srlua, this is a robuust approach for most systems
add_custom_command(
OUTPUT ${_exe}
COMMAND ${GLUE_EXECUTABLE}
ARGS ${SRLUA_EXECUTABLE} ${_source} ${_exe}
DEPENDS ${_source}
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
VERBATIM
)
# Make sure we have a target associated with the binary
add_custom_target(${_name} ALL
DEPENDS ${_exe}
)
# Install with run permissions
install ( PROGRAMS ${_exe} DESTINATION ${INSTALL_BIN} COMPONENT Runtime)
# Also install source as optional resurce
install ( FILES ${_source} DESTINATION ${INSTALL_FOO} COMPONENT Other )
else()
# Install into bin as is but without the lua suffix, we assume the executable uses UNIX shebang/hash-bang magic
install ( PROGRAMS ${_source} DESTINATION ${INSTALL_BIN}
RENAME ${_source_name}
COMPONENT Runtime
)
endif()
endmacro ()
macro ( _lua_module_helper is_install _name )
parse_arguments ( _MODULE "LINK;ALL_IN_ONE" "" ${ARGN} )
# _target is CMake-compatible target name for module (e.g. socket_core).
# _module is relative path of target (e.g. socket/core),
# without extension (e.g. .lua/.so/.dll).
# _MODULE_SRC is list of module source files (e.g. .lua and .c files).
# _MODULE_NAMES is list of module names (e.g. socket.core).
if ( _MODULE_ALL_IN_ONE )
string ( REGEX REPLACE "\\..*" "" _target "${_name}" )
string ( REGEX REPLACE "\\..*" "" _module "${_name}" )
set ( _target "${_target}_all_in_one")
set ( _MODULE_SRC ${_MODULE_ALL_IN_ONE} )
set ( _MODULE_NAMES ${_name} ${_MODULE_DEFAULT_ARGS} )
else ()
string ( REPLACE "." "_" _target "${_name}" )
string ( REPLACE "." "/" _module "${_name}" )
set ( _MODULE_SRC ${_MODULE_DEFAULT_ARGS} )
set ( _MODULE_NAMES ${_name} )
endif ()
if ( NOT _MODULE_SRC )
message ( FATAL_ERROR "no module sources specified" )
endif ()
list ( GET _MODULE_SRC 0 _first_source )
get_filename_component ( _ext ${_first_source} EXT )
if ( _ext STREQUAL ".lua" ) # Lua source module
list ( LENGTH _MODULE_SRC _len )
if ( _len GREATER 1 )
message ( FATAL_ERROR "more than one source file specified" )
endif ()
set ( _module "${_module}.lua" )
get_filename_component ( _module_dir ${_module} PATH )
get_filename_component ( _module_filename ${_module} NAME )
_append_path ( "${CMAKE_CURRENT_SOURCE_DIR}" "${_first_source}" _module_path )
list ( APPEND _lua_modules "${_name}" "${_module_path}" )
if ( ${is_install} )
install ( FILES ${_first_source} DESTINATION ${INSTALL_LMOD}/${_module_dir}
RENAME ${_module_filename}
COMPONENT Runtime
)
endif ()
else () # Lua C binary module
enable_language ( C )
find_package ( Lua REQUIRED )
include_directories ( ${LUA_INCLUDE_DIR} )
set ( _module "${_module}${CMAKE_SHARED_MODULE_SUFFIX}" )
get_filename_component ( _module_dir ${_module} PATH )
get_filename_component ( _module_filenamebase ${_module} NAME_WE )
foreach ( _thisname ${_MODULE_NAMES} )
list ( APPEND _lua_modules "${_thisname}"
"${CMAKE_CURRENT_BINARY_DIR}/\${CMAKE_CFG_INTDIR}/${_module}" )
endforeach ()
add_library( ${_target} MODULE ${_MODULE_SRC})
target_link_libraries ( ${_target} ${LUA_LIBRARY} ${_MODULE_LINK} )
set_target_properties ( ${_target} PROPERTIES LIBRARY_OUTPUT_DIRECTORY
"${_module_dir}" PREFIX "" OUTPUT_NAME "${_module_filenamebase}" )
if ( ${is_install} )
install ( TARGETS ${_target} DESTINATION ${INSTALL_CMOD}/${_module_dir} COMPONENT Runtime)
endif ()
endif ()
endmacro ()
# add_lua_module
# Builds a Lua source module into a destination locatable by Lua
# require syntax.
# Binary modules are also supported where this function takes sources and
# libraries to compile separated by LINK keyword.
# USE: add_lua_module ( socket.http src/http.lua )
# USE2: add_lua_module ( mime.core src/mime.c )
# USE3: add_lua_module ( socket.core ${SRC_SOCKET} LINK ${LIB_SOCKET} )
# USE4: add_lua_module ( ssl.context ssl.core ALL_IN_ONE src/context.c src/ssl.c )
# This form builds an "all-in-one" module (e.g. ssl.so or ssl.dll containing
# both modules ssl.context and ssl.core). The CMake target name will be
# ssl_all_in_one.
# Also sets variable _module_path (relative path where module typically
# would be installed).
macro ( add_lua_module )
_lua_module_helper ( 0 ${ARGN} )
endmacro ()
# install_lua_module
# This is the same as `add_lua_module` but also installs the module.
# USE: install_lua_module ( socket.http src/http.lua )
# USE2: install_lua_module ( mime.core src/mime.c )
# USE3: install_lua_module ( socket.core ${SRC_SOCKET} LINK ${LIB_SOCKET} )
macro ( install_lua_module )
_lua_module_helper ( 1 ${ARGN} )
endmacro ()
# Builds string representing Lua table mapping Lua modules names to file
# paths. Used internally.
macro ( _make_module_table _outvar )
set ( ${_outvar} )
list ( LENGTH _lua_modules _n )
if ( ${_n} GREATER 0 ) # avoids cmake complaint
foreach ( _i RANGE 1 ${_n} 2 )
list ( GET _lua_modules ${_i} _path )
math ( EXPR _ii ${_i}-1 )
list ( GET _lua_modules ${_ii} _name )
set ( ${_outvar} "${_table} ['${_name}'] = '${_path}'\;\n")
endforeach ()
endif ()
set ( ${_outvar}
"local modules = {
${_table}}" )
endmacro ()
# add_lua_test ( _testfile [ WORKING_DIRECTORY _working_dir ] )
# Runs Lua script `_testfile` under CTest tester.
# Optional named argument `WORKING_DIRECTORY` is current working directory to
# run test under (defaults to ${CMAKE_CURRENT_BINARY_DIR}).
# Both paths, if relative, are relative to ${CMAKE_CURRENT_SOURCE_DIR}.
# Any modules previously defined with install_lua_module are automatically
# preloaded (via package.preload) prior to running the test script.
# Under LuaDist, set test=true in config.lua to enable testing.
# USE: add_lua_test ( test/test1.lua [args...] [WORKING_DIRECTORY dir])
macro ( add_lua_test _testfile )
if ( NOT SKIP_TESTING )
parse_arguments ( _ARG "WORKING_DIRECTORY" "" ${ARGN} )
include ( CTest )
find_program ( LUA NAMES lua lua.bat )
get_filename_component ( TESTFILEABS ${_testfile} ABSOLUTE )
get_filename_component ( TESTFILENAME ${_testfile} NAME )
get_filename_component ( TESTFILEBASE ${_testfile} NAME_WE )
# Write wrapper script.
# Note: One simple way to allow the script to find modules is
# to just put them in package.preload.
set ( TESTWRAPPER ${CMAKE_CURRENT_BINARY_DIR}/${TESTFILENAME} )
_make_module_table ( _table )
set ( TESTWRAPPERSOURCE
"local CMAKE_CFG_INTDIR = ... or '.'
${_table}
local function preload_modules(modules)
for name, path in pairs(modules) do
if path:match'%.lua' then
package.preload[name] = assert(loadfile(path))
else
local name = name:gsub('.*%-', '') -- remove any hyphen prefix
local symbol = 'luaopen_' .. name:gsub('%.', '_')
--improve: generalize to support all-in-one loader?
local path = path:gsub('%$%{CMAKE_CFG_INTDIR%}', CMAKE_CFG_INTDIR)
package.preload[name] = assert(package.loadlib(path, symbol))
end
end
end
preload_modules(modules)
arg[0] = '${TESTFILEABS}'
table.remove(arg, 1)
return assert(loadfile '${TESTFILEABS}')(unpack(arg))
" )
if ( _ARG_WORKING_DIRECTORY )
get_filename_component (
TESTCURRENTDIRABS ${_ARG_WORKING_DIRECTORY} ABSOLUTE )
# note: CMake 2.6 (unlike 2.8) lacks WORKING_DIRECTORY parameter.
set ( _pre ${CMAKE_COMMAND} -E chdir "${TESTCURRENTDIRABS}" )
endif ()
file ( WRITE ${TESTWRAPPER} ${TESTWRAPPERSOURCE})
add_test ( NAME ${TESTFILEBASE} COMMAND ${_pre} ${LUA}
${TESTWRAPPER} "${CMAKE_CFG_INTDIR}"
${_ARG_DEFAULT_ARGS} )
endif ()
# see also http://gdcm.svn.sourceforge.net/viewvc/gdcm/Sandbox/CMakeModules/UsePythonTest.cmake
# Note: ${CMAKE_CFG_INTDIR} is a command-line argument to allow proper
# expansion by the native build tool.
endmacro ()
# Converts Lua source file `_source` to binary string embedded in C source
# file `_target`. Optionally compiles Lua source to byte code (not available
# under LuaJIT2, which doesn't have a bytecode loader). Additionally, Lua
# versions of bin2c [1] and luac [2] may be passed respectively as additional
# arguments.
#
# [1] http://lua-users.org/wiki/BinToCee
# [2] http://lua-users.org/wiki/LuaCompilerInLua
function ( add_lua_bin2c _target _source )
find_program ( LUA NAMES lua lua.bat )
execute_process ( COMMAND ${LUA} -e "string.dump(function()end)"
RESULT_VARIABLE _LUA_DUMP_RESULT ERROR_QUIET )
if ( NOT ${_LUA_DUMP_RESULT} )
SET ( HAVE_LUA_DUMP true )
endif ()
message ( "-- string.dump=${HAVE_LUA_DUMP}" )
if ( ARGV2 )
get_filename_component ( BIN2C ${ARGV2} ABSOLUTE )
set ( BIN2C ${LUA} ${BIN2C} )
else ()
find_program ( BIN2C NAMES bin2c bin2c.bat )
endif ()
if ( HAVE_LUA_DUMP )
if ( ARGV3 )
get_filename_component ( LUAC ${ARGV3} ABSOLUTE )
set ( LUAC ${LUA} ${LUAC} )
else ()
find_program ( LUAC NAMES luac luac.bat )
endif ()
endif ( HAVE_LUA_DUMP )
message ( "-- bin2c=${BIN2C}" )
message ( "-- luac=${LUAC}" )
get_filename_component ( SOURCEABS ${_source} ABSOLUTE )
if ( HAVE_LUA_DUMP )
get_filename_component ( SOURCEBASE ${_source} NAME_WE )
add_custom_command (
OUTPUT ${_target} DEPENDS ${_source}
COMMAND ${LUAC} -o ${CMAKE_CURRENT_BINARY_DIR}/${SOURCEBASE}.lo
${SOURCEABS}
COMMAND ${BIN2C} ${CMAKE_CURRENT_BINARY_DIR}/${SOURCEBASE}.lo
">${_target}" )
else ()
add_custom_command (
OUTPUT ${_target} DEPENDS ${SOURCEABS}
COMMAND ${BIN2C} ${_source} ">${_target}" )
endif ()
endfunction()

15
libs/lzlib/dist.info Normal file
View file

@ -0,0 +1,15 @@
--- This file is part of LuaDist project
name = "lzlib"
version = "0.4.2"
desc = "Lua bindings to the ZLib compression library"
author = "Tiago Dionizio"
url = "http://luaforge.net/projects/lzlib/"
license = "MIT/X11"
maintainer = "Peter Drahoš"
depends = {
"lua >= 5.1, < 5.4",
"zlib >=1.2.3"
}

83
libs/lzlib/gzip.lua Normal file
View file

@ -0,0 +1,83 @@
--[===================================================================[
TODO:
- add a nice header with license and stuff..
- detect plain text files
- proper testing
- improve implementation?
- check gzopen flags for consistency (ex: strategy flag)
--]===================================================================]
local io = require 'io'
local zlib = require 'zlib'
local error, assert, setmetatable, tostring = error, assert, setmetatable, tostring
local _M = {}
function _M.open(filename, mode)
mode = mode or 'r'
local r = mode:find('r', 1, true) and true
local w = mode:find('w', 1, true) and true
local level = -1
local lstart, lend = mode:find('%d')
if (lstart and lend) then
level = mode:sub(lstart, lend)
end
if (not (r or w)) then
error('file open mode must specify read or write operation')
end
local f, z
local mt = {
__index = {
read = function(self, ...)
return z:read(...)
end,
write = function(self, ...)
return z:write(...)
end,
seek = function(self, ...)
error 'seek not supported on gzip files'
end,
lines = function(self, ...)
return z:lines(...)
end,
flush = function(self, ...)
return z:flush(...) and f:flush()
end,
close = function(self, ...)
return z:close() and f:close()
end,
},
__tostring = function(self)
return 'gzip object (' .. mode .. ') [' .. tostring(z) .. '] [' .. tostring(f) .. ']'
end,
}
if r then
f = assert(io.open(filename, 'rb'))
z = assert(zlib.inflate(f))
else
f = assert(io.open(filename, 'wb'))
z = assert(zlib.deflate(f, level, nil, 15 + 16))
end
return setmetatable({}, mt)
end
function _M.lines(filename)
local gz = _M.open(filename, 'r')
return function()
local line = gz and gz:read()
if line == nil then
gz:close()
end
return line
end
end
return _M

58
libs/lzlib/lakefile Normal file
View file

@ -0,0 +1,58 @@
PROJECT = 'zlib'
IF=choose
J=path.join
if LUA_VER == '5.2' then
LUA_NEED = 'lua52'
LUA_DIR = ENV.LUA_DIR_5_2 or ENV.LUA_DIR
LUA_RUNNER = 'lua52'
else
LUA_NEED = 'lua'
LUA_DIR = ENV.LUA_DIR
LUA_RUNNER = 'lua'
end
DYNAMIC = DYNAMIC or false
ZLIB_NEED = IF(DYNAMIC, 'zlib-static-md', 'zlib-static-mt')
INSTALL_DIR = INSTALL_DIR or J(LUA_DIR,'libs',PROJECT)
build = c.shared{PROJECT,
-- base = 'src',
src = '*.c',
needs = { LUA_NEED, ZLIB_NEED },
dynamic = DYNAMIC,
strip = true,
defines = IF(MSVC, "STRUCT_INT=__int64"),
libflags = IF(MSVC, "/EXPORT:luaopen_" .. PROJECT),
}
target('build', build)
install = target('install', {
file.group{odir=J(INSTALL_DIR, 'share');src = build };
file.group{odir=J(INSTALL_DIR, 'share');src = 'gzip.lua' };
file.group{odir=J(INSTALL_DIR, 'test'); src = 'test_*.lua'};
})
local function run(file, cwd)
print()
print("run " .. file)
if not TESTING then
if cwd then lake.chdir(cwd) end
os.execute( LUA_RUNNER .. ' ' .. file )
if cwd then lake.chdir("<") end
print()
end
end
target('test', install, function()
local test_dir = J(INSTALL_DIR,'test')
run(J(test_dir,'test_zlib3.lua'), test_dir)
run(J(test_dir,'test_zlib2.lua'), test_dir)
run(J(test_dir,'test_prologue.lua'), test_dir)
run(J(test_dir,'test_gzip.lua'), test_dir)
end)

986
libs/lzlib/lzlib.c Normal file
View file

@ -0,0 +1,986 @@
/************************************************************************
* Author : Tiago Dionizio <tiago.dionizio@gmail.com> *
* Library : lzlib - Lua 5 interface to access zlib library functions *
* *
* 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. *
************************************************************************/
#include <stdlib.h>
#include <string.h>
#include "lua.h"
#include "lauxlib.h"
#include "zlib.h"
/*
** =========================================================================
** compile time options wich determine available functionality
** =========================================================================
*/
/* TODO
- also call flush on table/userdata when flush function is detected
- remove io_cb check inflate_block if condition
- only set eos when ZSTREAM_END is reached
- check for stream errors to close stream when really needed
*/
/*
** =========================================================================
** zlib stream metamethods
** =========================================================================
*/
#define ZSTREAMMETA "zlib:zstream"
#define LZ_ANY -1
#define LZ_NONE 0
#define LZ_DEFLATE 1
#define LZ_INFLATE 2
#if 0
#define LZ_BUFFER_SIZE LUAL_BUFFERSIZE
#else
#define LZ_BUFFER_SIZE 8192
#endif
typedef struct {
/* zlib structures */
z_stream zstream;
/* stream state. LZ_DEFLATE | LZ_INFLATE */
int state;
int error;
int peek;
int eos;
/* user callback source for reading/writing */
int io_cb;
/* input buffer */
int i_buffer_ref;
size_t i_buffer_pos;
size_t i_buffer_len;
const char *i_buffer;
/* output buffer */
size_t o_buffer_len;
size_t o_buffer_max;
char o_buffer[LZ_BUFFER_SIZE];
/* dictionary */
const Bytef *dictionary;
size_t dictionary_len;
} lz_stream;
/* forward declarations */
static int lzstream_docompress(lua_State *L, lz_stream *s, int from, int to, int flush);
static lz_stream *lzstream_new(lua_State *L, int src) {
lz_stream *s = (lz_stream*)lua_newuserdata(L, sizeof(lz_stream));
luaL_getmetatable(L, ZSTREAMMETA);
lua_setmetatable(L, -2); /* set metatable */
s->state = LZ_NONE;
s->error = Z_OK;
s->eos = 0;
s->io_cb = LUA_REFNIL;
s->i_buffer = NULL;
s->i_buffer_ref = LUA_REFNIL;
s->i_buffer_pos = 0;
s->i_buffer_len = 0;
s->peek = 0;
s->o_buffer_len = 0;
s->o_buffer_max = sizeof(s->o_buffer) / sizeof(s->o_buffer[0]);
s->zstream.zalloc = Z_NULL;
s->zstream.zfree = Z_NULL;
/* prepare source */
if (lua_isstring(L, src)) {
lua_pushvalue(L, src);
s->i_buffer_ref = luaL_ref(L, LUA_REGISTRYINDEX);
s->i_buffer = lua_tolstring(L, src, &s->i_buffer_len);
} else {
/* table | function | userdata */
lua_pushvalue(L, src);
s->io_cb = luaL_ref(L, LUA_REGISTRYINDEX);
}
return s;
}
static void lzstream_cleanup(lua_State *L, lz_stream *s) {
if (s && s->state != LZ_NONE) {
if (s->state == LZ_INFLATE) {
inflateEnd(&s->zstream);
}
if (s->state == LZ_DEFLATE) {
deflateEnd(&s->zstream);
}
luaL_unref(L, LUA_REGISTRYINDEX, s->io_cb);
luaL_unref(L, LUA_REGISTRYINDEX, s->i_buffer_ref);
s->state = LZ_NONE;
}
}
/* ====================================================================== */
static lz_stream *lzstream_get(lua_State *L, int index) {
lz_stream *s = (lz_stream*)luaL_checkudata(L, index, ZSTREAMMETA);
if (s == NULL) luaL_argerror(L, index, "bad zlib stream");
return s;
}
static lz_stream *lzstream_check(lua_State *L, int index, int state) {
lz_stream *s = lzstream_get(L, index);
if ((state != LZ_ANY && s->state != state) || s->state == LZ_NONE) {
luaL_argerror(L, index, "attempt to use invalid zlib stream");
}
return s;
}
/* ====================================================================== */
static int lzstream_tostring(lua_State *L) {
lz_stream *s = (lz_stream*)luaL_checkudata(L, 1, ZSTREAMMETA);
if (s == NULL) luaL_argerror(L, 1, "bad zlib stream");
if (s->state == LZ_NONE) {
lua_pushstring(L, "zlib stream (closed)");
} else if (s->state == LZ_DEFLATE) {
lua_pushfstring(L, "zlib deflate stream (%p)", (void*)s);
} else if (s->state == LZ_INFLATE) {
lua_pushfstring(L, "zlib inflate stream (%p)", (void*)s);
} else {
lua_pushfstring(L, "%p", (void*)s);
}
return 1;
}
/* ====================================================================== */
static int lzstream_gc(lua_State *L) {
lz_stream *s = lzstream_get(L, 1);
lzstream_cleanup(L, s);
return 0;
}
/* ====================================================================== */
static int lzstream_close(lua_State *L) {
lz_stream *s = lzstream_get(L, 1);
if (s->state == LZ_DEFLATE) {
lua_settop(L, 0);
lua_pushliteral(L, "");
return lzstream_docompress(L, s, 1, 1, Z_FINISH);
}
lzstream_cleanup(L, s);
lua_pushboolean(L, 1);
return 1;
}
/* ====================================================================== */
static int lzstream_adler(lua_State *L) {
lz_stream *s = lzstream_check(L, 1, LZ_ANY);
lua_pushnumber(L, s->zstream.adler);
return 1;
}
/* ====================================================================== */
/*
zlib.deflate(
sink: function | { write: function [, close: function, flush: function] },
compression level, [Z_DEFAILT_COMPRESSION]
method, [Z_DEFLATED]
windowBits, [15]
memLevel, [8]
strategy, [Z_DEFAULT_STRATEGY]
dictionary: [""]
)
*/
static int lzlib_deflate(lua_State *L) {
int level, method, windowBits, memLevel, strategy;
lz_stream *s;
const char *dictionary;
size_t dictionary_len;
if (lua_istable(L, 1) || lua_isuserdata(L, 1)) {
/* is there a :write function? */
lua_getfield(L, 1, "write");
if (!lua_isfunction(L, -1)) {
luaL_argerror(L, 1, "output parameter does not provide :write function");
}
lua_pop(L, 1);
}
else if (!lua_isfunction(L, 1)) {
luaL_argerror(L, 1, "output parameter must be a function, table or userdata value");
}
level = (int) luaL_optinteger(L, 2, Z_DEFAULT_COMPRESSION);
method = (int) luaL_optinteger(L, 3, Z_DEFLATED);
windowBits = (int) luaL_optinteger(L, 4, 15);
memLevel = (int) luaL_optinteger(L, 5, 8);
strategy = (int) luaL_optinteger(L, 6, Z_DEFAULT_STRATEGY);
dictionary = luaL_optlstring(L, 7, NULL, &dictionary_len);
s = lzstream_new(L, 1);
if (deflateInit2(&s->zstream, level, method, windowBits, memLevel, strategy) != Z_OK) {
lua_pushliteral(L, "call to deflateInit2 failed");
lua_error(L);
}
if (dictionary) {
if (deflateSetDictionary(&s->zstream, (const Bytef *) dictionary, dictionary_len) != Z_OK) {
lua_pushliteral(L, "call to deflateSetDictionnary failed");
lua_error(L);
}
}
s->state = LZ_DEFLATE;
return 1;
}
/*
zlib.inflate(
source: string | function | { read: function, close: function },
windowBits: number, [15]
dictionary: [""]
)
*/
static int lzlib_inflate(lua_State *L)
{
int windowBits;
lz_stream *s;
int have_peek = 0;
const char *dictionary;
size_t dictionary_len;
if (lua_istable(L, 1) || lua_isuserdata(L, 1)) {
/* is there a :read function? */
lua_getfield(L, 1, "read");
if (!lua_isfunction(L, -1)) {
luaL_argerror(L, 1, "input parameter does not provide :read function");
}
lua_pop(L, 1);
/* check for peek function */
lua_getfield(L, 1, "peek");
have_peek = lua_isfunction(L, -1);
lua_pop(L, 1);
}
else if (!lua_isstring(L, 1) && !lua_isfunction(L, 1)) {
luaL_argerror(L, 1, "input parameter must be a string, function, table or userdata value");
}
windowBits = (int) luaL_optinteger(L, 2, 15);
dictionary = luaL_optlstring(L, 3, NULL, &dictionary_len);
s = lzstream_new(L, 1);
if (windowBits > 0 && windowBits < 16) {
windowBits |= 32;
}
if (inflateInit2(&s->zstream, windowBits) != Z_OK) {
lua_pushliteral(L, "call to inflateInit2 failed");
lua_error(L);
}
if (dictionary) {
s->dictionary = (const Bytef *) dictionary;
s->dictionary_len = dictionary_len;
}
s->peek = have_peek;
s->state = LZ_INFLATE;
return 1;
}
/* ====================================================================== */
static int lz_pushresult (lua_State *L, lz_stream *s) {
if (s->error == Z_OK) {
lua_pushboolean(L, 1);
return 1;
} else {
lua_pushnil(L);
lua_pushstring(L, zError(s->error));
lua_pushinteger(L, s->error);
return 3;
}
}
/*
Get block to process:
- top of stack gets
*/
static const char* lzstream_fetch_block(lua_State *L, lz_stream *s, int hint) {
if (s->i_buffer_pos >= s->i_buffer_len) {
luaL_unref(L, LUA_REGISTRYINDEX, s->i_buffer_ref);
s->i_buffer_ref = LUA_NOREF;
s->i_buffer = NULL;
lua_rawgeti(L, LUA_REGISTRYINDEX, s->io_cb);
if (!lua_isnil(L, -1)) {
if (lua_isfunction(L, -1)) {
lua_pushinteger(L, hint);
lua_call(L, 1, 1);
} else {
lua_getfield(L, -1, (s->peek ? "peek" : "read"));
lua_insert(L, -2);
lua_pushinteger(L, hint);
lua_call(L, 2, 1);
}
if (lua_isstring(L, -1)) {
s->i_buffer_pos = 0;
s->i_buffer = lua_tolstring(L, -1, &s->i_buffer_len);
if (s->i_buffer_len > 0) {
s->i_buffer_ref = luaL_ref(L, LUA_REGISTRYINDEX);
} else {
lua_pop(L, 1);
}
} else if (lua_isnil(L, -1)) {
lua_pop(L, 1);
} else {
lua_pushliteral(L, "deflate callback must return string or nil");
lua_error(L);
}
} else {
lua_pop(L, 1);
}
}
return s->i_buffer;
}
static int lzstream_inflate_block(lua_State *L, lz_stream *s) {
if (lzstream_fetch_block(L, s, LZ_BUFFER_SIZE) || !s->eos) {
int r;
if (s->i_buffer_len == s->i_buffer_pos) {
s->zstream.next_in = NULL;
s->zstream.avail_in = 0;
} else {
s->zstream.next_in = (unsigned char*)(s->i_buffer + s->i_buffer_pos);
s->zstream.avail_in = s->i_buffer_len - s->i_buffer_pos;
}
s->zstream.next_out = (unsigned char*)s->o_buffer + s->o_buffer_len;
s->zstream.avail_out = s->o_buffer_max - s->o_buffer_len;
/* munch some more */
r = inflate(&s->zstream, Z_SYNC_FLUSH);
if (r == Z_NEED_DICT) {
if (s->dictionary == NULL) {
lua_pushliteral(L, "no inflate dictionary provided");
lua_error(L);
}
if (inflateSetDictionary(&s->zstream, s->dictionary, s->dictionary_len) != Z_OK) {
lua_pushliteral(L, "call to inflateSetDictionnary failed");
lua_error(L);
}
r = inflate(&s->zstream, Z_SYNC_FLUSH);
}
if (r != Z_OK && r != Z_STREAM_END && r != Z_BUF_ERROR) {
lzstream_cleanup(L, s);
s->error = r;
#if 1
lua_pushfstring(L, "failed to decompress [%d]", r);
lua_error(L);
#endif
}
if (r == Z_STREAM_END) {
luaL_unref(L, LUA_REGISTRYINDEX, s->i_buffer_ref);
s->i_buffer_ref = LUA_NOREF;
s->i_buffer = NULL;
s->eos = 1;
}
/* number of processed bytes */
if (s->peek) {
size_t processed = s->i_buffer_len - s->i_buffer_pos - s->zstream.avail_in;
lua_rawgeti(L, LUA_REGISTRYINDEX, s->io_cb);
lua_getfield(L, -1, "read");
lua_insert(L, -2);
lua_pushinteger(L, processed);
lua_call(L, 2, 0);
}
s->i_buffer_pos = s->i_buffer_len - s->zstream.avail_in;
s->o_buffer_len = s->o_buffer_max - s->zstream.avail_out;
}
return s->o_buffer_len;
}
/*
** Remove n bytes from the output buffer.
*/
static void lzstream_remove(lz_stream *s, size_t n) {
memmove(s->o_buffer, s->o_buffer + n, s->o_buffer_len - n);
s->o_buffer_len -= n;
}
/*
** Copy at most n bytes to buffer b and remove them from the
** output stream buffer.
*/
static int lzstream_flush_buffer(lua_State *L, lz_stream *s, size_t n, luaL_Buffer *b) {
/* check output */
if (n > s->o_buffer_len) {
n = s->o_buffer_len;
}
if (n > 0) {
lua_pushlstring(L, s->o_buffer, n);
luaL_addvalue(b);
lzstream_remove(s, n);
}
return n;
}
/*
z:read(
{number | '*l' | '*a'}*
)
*/
static int lz_test_eof(lua_State *L, lz_stream *s) {
lua_pushlstring(L, NULL, 0);
if (s->o_buffer_len > 0) {
return 1;
} else if (s->eos) {
return 0;
} else {
return lzstream_inflate_block(L, s);
}
}
static int lz_read_line(lua_State *L, lz_stream *s) {
luaL_Buffer b;
size_t l = 0, n;
luaL_buffinit(L, &b);
if (s->o_buffer_len > 0 || !s->eos) do {
char *p = s->o_buffer;
size_t len = s->o_buffer_len;
/* find newline in output buffer */
for (n = 0; n < len; ++n, ++p) {
if (*p == '\n' || *p == '\r') {
int eat_nl = *p == '\r';
luaL_addlstring(&b, s->o_buffer, n);
lzstream_remove(s, n+1);
l += n;
if (eat_nl && lzstream_inflate_block(L, s)) {
if (s->o_buffer_len > 0 && *s->o_buffer == '\n') {
lzstream_remove(s, 1);
}
}
luaL_pushresult(&b);
return 1;
}
}
if (len > 0) {
luaL_addlstring(&b, s->o_buffer, len);
lzstream_remove(s, len);
l += len;
}
} while (lzstream_inflate_block(L, s));
luaL_pushresult(&b);
return l > 0 || !s->eos || s->o_buffer_len > 0;
}
static int lz_read_chars(lua_State *L, lz_stream *s, size_t n) {
size_t len;
luaL_Buffer b;
luaL_buffinit(L, &b);
if (s->o_buffer_len > 0 || !s->eos) do {
size_t rlen = lzstream_flush_buffer(L, s, n, &b);
n -= rlen;
} while (n > 0 && lzstream_inflate_block(L, s));
luaL_pushresult(&b);
lua_tolstring(L, -1, &len);
return n == 0 || len > 0;
}
static int lzstream_decompress(lua_State *L) {
lz_stream *s = lzstream_check(L, 1, LZ_INFLATE);
int nargs = lua_gettop(L) - 1;
int success;
int n;
if (nargs == 0) { /* no arguments? */
success = lz_read_line(L, s);
n = 3; /* to return 1 result */
}
else { /* ensure stack space for all results and for auxlib's buffer */
luaL_checkstack(L, nargs+LUA_MINSTACK, "too many arguments");
success = 1;
for (n = 2; nargs-- && success; n++) {
if (lua_type(L, n) == LUA_TNUMBER) {
size_t l = (size_t)lua_tointeger(L, n);
success = (l == 0) ? lz_test_eof(L, s) : lz_read_chars(L, s, l);
}
else {
const char *p = lua_tostring(L, n);
luaL_argcheck(L, p && p[0] == '*', n, "invalid option");
switch (p[1]) {
case 'l': /* line */
success = lz_read_line(L, s);
break;
case 'a': /* file */
lz_read_chars(L, s, ~((size_t)0)); /* read MAX_SIZE_T chars */
success = 1; /* always success */
break;
default:
return luaL_argerror(L, n, "invalid format");
}
}
}
}
if (s->error != Z_OK) {
return lz_pushresult(L, s);
}
if (!success) {
lua_pop(L, 1); /* remove last result */
lua_pushnil(L); /* push nil instead */
}
return n - 2;
}
static int lzstream_readline(lua_State *L) {
lz_stream *s;
int sucess;
s = lzstream_check(L, lua_upvalueindex(1), LZ_INFLATE);
sucess = lz_read_line(L, s);
if (s->error != Z_OK) {
return lz_pushresult(L, s);
}
if (sucess) {
return 1;
} else {
/* EOF */
return 0;
}
}
static int lzstream_lines(lua_State *L) {
lzstream_check(L, 1, LZ_INFLATE);
lua_settop(L, 1);
lua_pushcclosure(L, lzstream_readline, 1);
return 1;
}
/* ====================================================================== */
static int lzstream_docompress(lua_State *L, lz_stream *s, int from, int to, int flush) {
int r, arg;
int self = 0;
size_t b_size = s->o_buffer_max;
unsigned char *b = (unsigned char *)s->o_buffer;
/* number of processed bytes */
lua_rawgeti(L, LUA_REGISTRYINDEX, s->io_cb);
if (!lua_isfunction(L, -1)) {
self = 1;
lua_getfield(L, -1, "write");
}
for (arg = from; arg <= to; arg++) {
s->zstream.next_in = (unsigned char*)luaL_checklstring(L, arg, (size_t*)&s->zstream.avail_in);
do {
s->zstream.next_out = b;
s->zstream.avail_out = b_size;
/* bake some more */
r = deflate(&s->zstream, flush);
if (r != Z_OK && r != Z_STREAM_END && r != Z_BUF_ERROR) {
lzstream_cleanup(L, s);
lua_pushboolean(L, 0);
lua_pushfstring(L, "failed to compress [%d]", r);
return 2;
}
if (s->zstream.avail_out != b_size) {
/* write output */
lua_pushvalue(L, -1); /* function */
if (self) lua_pushvalue(L, -3); /* self */
lua_pushlstring(L, (char*)b, b_size - s->zstream.avail_out); /* data */
lua_call(L, (self ? 2 : 1), 0);
}
if (r == Z_STREAM_END) {
lzstream_cleanup(L, s);
break;
}
/* process all input */
} while (s->zstream.avail_in > 0 || s->zstream.avail_out == 0);
}
lua_pushboolean(L, 1);
return 1;
}
static int lzstream_compress(lua_State *L) {
lz_stream *s = lzstream_check(L, 1, LZ_DEFLATE);
return lzstream_docompress(L, s, 2, lua_gettop(L), Z_NO_FLUSH);
}
/* ====================================================================== */
static int lzstream_flush(lua_State *L) {
static int flush_values[] = { Z_SYNC_FLUSH, Z_FULL_FLUSH, Z_FINISH };
static const char *const flush_opts[] = { "sync", "full", "finish" };
lz_stream *s = lzstream_check(L, 1, LZ_DEFLATE);
int flush = luaL_checkoption(L, 2, flush_opts[0], flush_opts);
lua_settop(L, 0);
lua_pushliteral(L, "");
return lzstream_docompress(L, s, 1, 1, flush_values[flush]);
}
/*
** =========================================================================
** zlib functions
** =========================================================================
*/
static int lzlib_version(lua_State *L)
{
lua_pushstring(L, zlibVersion());
return 1;
}
/* ====================================================================== */
static int lzlib_adler32(lua_State *L)
{
if (lua_gettop(L) == 0)
{
/* adler32 initial value */
lua_pushnumber(L, adler32(0L, Z_NULL, 0));
}
else
{
/* update adler32 checksum */
size_t len;
int adler = (int) luaL_checkinteger(L, 1);
const unsigned char* buf = (unsigned char*)luaL_checklstring(L, 2, &len);
lua_pushnumber(L, adler32(adler, buf, len));
}
return 1;
}
/* ====================================================================== */
static int lzlib_crc32(lua_State *L)
{
if (lua_gettop(L) == 0)
{
/* crc32 initial value */
lua_pushnumber(L, crc32(0L, Z_NULL, 0));
}
else
{
/* update crc32 checksum */
size_t len;
int crc = (int) luaL_checkinteger(L, 1);
const unsigned char* buf = (unsigned char*)luaL_checklstring(L, 2, &len);
lua_pushnumber(L, crc32(crc, buf, len));
}
return 1;
}
/* ====================================================================== */
static int lzlib_compress(lua_State *L) {
size_t avail_in;
const char *next_in = luaL_checklstring(L, 1, &avail_in);
int level = (int) luaL_optinteger(L, 2, Z_DEFAULT_COMPRESSION);
int method = (int) luaL_optinteger(L, 3, Z_DEFLATED);
int windowBits = (int) luaL_optinteger(L, 4, 15);
int memLevel = (int) luaL_optinteger(L, 5, 8);
int strategy = (int) luaL_optinteger(L, 6, Z_DEFAULT_STRATEGY);
int ret;
luaL_Buffer b;
z_stream zs;
luaL_buffinit(L, &b);
zs.zalloc = Z_NULL;
zs.zfree = Z_NULL;
zs.next_out = Z_NULL;
zs.avail_out = 0;
zs.next_in = Z_NULL;
zs.avail_in = 0;
ret = deflateInit2(&zs, level, method, windowBits, memLevel, strategy);
if (ret != Z_OK)
{
lua_pushnil(L);
lua_pushnumber(L, ret);
return 2;
}
zs.next_in = (unsigned char*)next_in;
zs.avail_in = avail_in;
for(;;)
{
zs.next_out = (unsigned char*)luaL_prepbuffer(&b);
zs.avail_out = LUAL_BUFFERSIZE;
/* munch some more */
ret = deflate(&zs, Z_FINISH);
/* push gathered data */
luaL_addsize(&b, LUAL_BUFFERSIZE - zs.avail_out);
/* done processing? */
if (ret == Z_STREAM_END)
break;
/* error condition? */
if (ret != Z_OK)
break;
}
/* cleanup */
deflateEnd(&zs);
luaL_pushresult(&b);
lua_pushnumber(L, ret);
return 2;
}
/* ====================================================================== */
static int lzlib_decompress(lua_State *L)
{
size_t avail_in;
const char *next_in = luaL_checklstring(L, 1, &avail_in);
int windowBits = (int) luaL_optinteger(L, 2, 15);
int ret;
luaL_Buffer b;
z_stream zs;
luaL_buffinit(L, &b);
zs.zalloc = Z_NULL;
zs.zfree = Z_NULL;
zs.next_out = Z_NULL;
zs.avail_out = 0;
zs.next_in = Z_NULL;
zs.avail_in = 0;
ret = inflateInit2(&zs, windowBits);
if (ret != Z_OK) {
lua_pushliteral(L, "failed to initialize zstream structures");
lua_error(L);
}
zs.next_in = (unsigned char*)next_in;
zs.avail_in = avail_in;
for (;;) {
zs.next_out = (unsigned char*)luaL_prepbuffer(&b);
zs.avail_out = LUAL_BUFFERSIZE;
/* bake some more */
ret = inflate(&zs, Z_FINISH);
/* push gathered data */
luaL_addsize(&b, LUAL_BUFFERSIZE - zs.avail_out);
/* done processing? */
if (ret == Z_STREAM_END)
break;
if (ret != Z_OK && ret != Z_BUF_ERROR) {
/* cleanup */
inflateEnd(&zs);
lua_pushliteral(L, "failed to process zlib stream");
lua_error(L);
}
}
/* cleanup */
inflateEnd(&zs);
luaL_pushresult(&b);
return 1;
}
/*
** =========================================================================
** Register functions
** =========================================================================
*/
#if (LUA_VERSION_NUM >= 502)
#define luaL_register(L,n,f) luaL_setfuncs(L,f,0)
#endif
LUALIB_API int luaopen_zlib(lua_State *L)
{
const luaL_Reg lzstream_meta[] =
{
{"write", lzstream_compress },
{"read", lzstream_decompress },
{"lines", lzstream_lines },
{"flush", lzstream_flush },
{"close", lzstream_close },
{"adler", lzstream_adler },
{"__tostring", lzstream_tostring },
{"__gc", lzstream_gc },
{NULL, NULL}
};
const luaL_Reg zlib[] =
{
{"version", lzlib_version },
{"adler32", lzlib_adler32 },
{"crc32", lzlib_crc32 },
{"deflate", lzlib_deflate },
{"inflate", lzlib_inflate },
{"compress", lzlib_compress },
{"decompress", lzlib_decompress },
{NULL, NULL}
};
/* ====================================================================== */
/* create new metatable for zlib compression structures */
luaL_newmetatable(L, ZSTREAMMETA);
lua_pushliteral(L, "__index");
lua_pushvalue(L, -2); /* push metatable */
lua_rawset(L, -3); /* metatable.__index = metatable */
/*
** Stack: metatable
*/
luaL_register(L, NULL, lzstream_meta);
lua_pop(L, 1); /* remove metatable from stack */
/*
** Stack:
*/
lua_newtable(L);
lua_pushliteral (L, "_COPYRIGHT");
lua_pushliteral (L, "Copyright (C) 2003-2010 Tiago Dionizio");
lua_settable (L, -3);
lua_pushliteral (L, "_DESCRIPTION");
lua_pushliteral (L, "Lua 5 interface to access zlib library functions");
lua_settable (L, -3);
lua_pushliteral (L, "_VERSION");
lua_pushliteral (L, "lzlib 0.4-work3");
lua_settable (L, -3);
#define PUSH_LITERAL(name) \
lua_pushliteral (L, #name); \
lua_pushinteger (L, Z_##name); \
lua_settable (L, -3);
#define PUSH_NUMBER(name, value) \
lua_pushliteral (L, #name); \
lua_pushinteger (L, value); \
lua_settable (L, -3);
PUSH_LITERAL(NO_COMPRESSION)
PUSH_LITERAL(BEST_SPEED)
PUSH_LITERAL(BEST_COMPRESSION)
PUSH_LITERAL(DEFAULT_COMPRESSION)
PUSH_LITERAL(FILTERED)
PUSH_LITERAL(HUFFMAN_ONLY)
PUSH_LITERAL(RLE)
PUSH_LITERAL(FIXED)
PUSH_LITERAL(DEFAULT_STRATEGY)
PUSH_NUMBER(MINIMUM_MEMLEVEL, 1)
PUSH_NUMBER(MAXIMUM_MEMLEVEL, 9)
PUSH_NUMBER(DEFAULT_MEMLEVEL, 8)
PUSH_NUMBER(DEFAULT_WINDOWBITS, 15)
PUSH_NUMBER(MINIMUM_WINDOWBITS, 8)
PUSH_NUMBER(MAXIMUM_WINDOWBITS, 15)
PUSH_NUMBER(GZIP_WINDOWBITS, 16)
PUSH_NUMBER(RAW_WINDOWBITS, -1)
luaL_register(L, NULL, zlib);
/*
** Stack: zlib table
*/
return 1;
}

View file

@ -0,0 +1,23 @@
Installation
------------
luarocks build lzlib-git-1.rockspec
Troubleshooting
---------------
* Error: Could not find expected file libz.a, or libz.so, or libz.so.*
for ZLIB -- you may have to install ZLIB in your system and/or pass
ZLIB_DIR or ZLIB_LIBDIR to the luarocks command. Example: luarocks
install lzlib ZLIB_DIR=/usr/local
lzlib has a dependency on zlib, and currently (on Linux) LuaRocks
checks .so file existence by searching for the file in two hardcoded
paths, /usr/lib and /usr/local/lib. (instead of reading
/etc/ld.so.conf)
Try to locate libz.so, libz.a or libz.dll and re-run the command
with ZLIB_LIBDIR=/path/to/libz.so. In my case on Ubuntu 12.04 :
luarocks build --local lzlib-git-1.rockspec ZLIB_LIBDIR=/lib/x86_64-linux-gnu/

View file

@ -0,0 +1,37 @@
package="lzlib"
version="git-1"
source = {
url = "git://github.com/LuaDist/lzlib.git",
branch = "master",
}
description = {
summary = "Lua bindings to the ZLib compression library",
detailed = [[
This package provides a library to access zlib library functions
and also to read/write gzip files using an interface similar
to the base io package.
]],
homepage = "http://luaforge.net/projects/lzlib/",
license = "MIT/X11"
}
dependencies = {
"lua >= 5.1"
}
external_dependencies = {
ZLIB = {
header = "zlib.h",
library = "z",
}
}
build = {
type = "builtin",
modules = {
zlib = {
sources = "lzlib.c",
libdirs = "$(ZLIB_LIBDIR)",
incdirs = "$(ZLIB_INCDIR)",
libraries = "z",
},
gzip = "gzip.lua",
}
}

101
libs/lzlib/test_gzip.lua Normal file
View file

@ -0,0 +1,101 @@
local gzip = require 'gzip'
local function line(header, c)
header = header or ''
c = c or '-'
print(string.rep(string.sub(c, 1, 1), 78 - string.len(header))..header)
end
line(' gzip', '=')
line(' gzip writing')
local loops = 1000
local testfile = "test.gz"
local of = gzip.open(testfile, "wb9")
if (not of) then
error("Failed to open file test.gz for writing")
end
for i = 1, loops do
of:write(i, "\n")
end
of:close()
local i = 0
for l in gzip.lines(testfile) do
i = i + 1
if (tostring(i) ~= l) then
error(tostring(i))
end
end
assert(i == loops)
print('Ok.')
line(' gzip reading')
local inf = gzip.open(testfile)
if (not inf) then
error("Failed to open file test.gz for reading")
end
for i = 1, loops do
if (tostring(i) ~= inf:read("*l")) then
error(tostring(i))
end
end
inf:close()
print('Ok.')
if false then
line(' compress seek')
of = gzip.open(testfile, "wb1")
if (not of) then
error("Failed to open file test.gz for writing")
end
assert(of:seek("cur", 5) == 5)
assert(of:seek("set", 10) == 10)
of:write("1")
of:close()
print('Ok.')
line(' uncompress seek')
inf = gzip.open(testfile)
if (not inf) then
error("Failed to open file test.gz for reading")
end
assert(inf:seek("set", 6) == 6)
assert(inf:seek("set", 4) == 4)
assert(inf:seek("cur", 1) == 5)
assert(inf:seek("cur", -1) == 4)
assert(inf:seek("cur", 1) == 5)
assert(inf:seek("set", 6) == 6)
inf:read(4)
assert(inf:read(1) == "1")
inf:close()
print('Ok.')
end
os.remove(testfile)
line(' gzip', '=')

View file

@ -0,0 +1,2 @@
print('lua version : ' .. _VERSION)
print('zlib version: ' .. (require('zlib')._VERSION))

93
libs/lzlib/test_zlib2.lua Normal file
View file

@ -0,0 +1,93 @@
local zlib = require 'zlib'
local gzip = require 'gzip'
local data = 'abcde'
local cdata = zlib.compress(data)
local udata = zlib.decompress(cdata)
print('udata=['..udata..']')
local z = zlib.inflate(cdata)
print('z', z)
for i = 1, 5 do
print(i, z:read(1))
end
z:close()
of = gzip.open('txt.gz', "wb9")
i = assert(io.open('txt', 'w'))
for _,str in ipairs{'a', 'b', 'c'} do
local s = (str:rep(10)) ,'\n'
i:write(s)
of:write(s)
end
i:close()
of:close()
i = assert(io.open('txt', 'rb')) org = i:read('*a') i:close()
i = io.open('txt.gz', 'rb')
dup = ''
o = io.open('txt.out', 'wb')
z = zlib.inflate(i)
print('z = ', z)
repeat
local l = z:read(1024)
if not l then
break
end
dup = dup .. l
o:write(l)
until false
i:close()
o:close()
z:close()
print('result:', (org == dup), org:len(), dup:len())
i = io.open('txt.gz', 'rb')
o = io.open('txt.lines.out', 'w')
cpeek = 0
ccon = 0
z = zlib.inflate({
peek = function(self, hint)
local d = i:read(hint)
if (d ~= nil) then
i:seek('cur', -d:len())
cpeek = cpeek + d:len()
end
--print('called peek with', hint, 'got', d and d:len())
return d
end,
read = function(self, consume)
--print('called read with', consume)
ccon = ccon + consume
i:read(consume)
end
})
print('z = ', z)
for line in z:lines() do
o:write(line, '\n')
end
i:close()
o:close()
z:close()
print('stats:', cpeek, ccon)
print('z = ', z)
i = io.open('txt', 'r')
o = io.open('txt-zlib.gz', 'wb')
z = zlib.deflate(o, nil, nil, 15 + 16)
for line in i:lines() do
z:write(line, '\n')
end
z:flush('finish')
z:close()
o:close()
i:close()
os.remove("txt")
os.remove("txt.gz")

29
libs/lzlib/test_zlib3.lua Normal file
View file

@ -0,0 +1,29 @@
local zlib = require"zlib"
local dataToDeflate = {}
print("Generating test data...")
for i = 0, 10000 do
table.insert(dataToDeflate, string.sub(tostring(math.random()), 3))
end
dataToDeflate = table.concat(dataToDeflate)
print("Length of data to deflate", #dataToDeflate)
local buffer = {}
local func = function(data)
table.insert(buffer, data)
end
stream = zlib.deflate(func) --best compression, deflated
stream:write(dataToDeflate)
--stream:flush("sync")
--stream:flush()
stream:close()
--local deflatedData = string.sub(table.concat(buffer), 3) -- needed for IE
local deflatedData = table.concat(buffer)
print(#deflatedData)
streamIn = zlib.inflate(deflatedData)
local inflatedData = streamIn:read()
assert(dataToDeflate == inflatedData)

View file

@ -0,0 +1,34 @@
local zlib = require"zlib"
-- dict used by the SPDY protocol
local spdy_dict = "optionsheadpostputdeletetraceaccept:accept-charset:accept-encoding:accept-language:accept-ranges:age:allow:authorization:cache-control:connection:content-base:content-encoding:content-language:content-length:content-location:content-md5:content-range:content-type:date:etag:expect:expires:from:host:if-match:if-modified-since:if-none-match:if-range:if-unmodified-since:last-modified:location:max-forwards:pragma:proxy-authenticate:proxy-authorization:range:referer:retry-after:server:trailer:transfer-encoding:upgrade:user-agent:vary:via:warning:www-authenticate:methodgetstatus200 OKversionHTTP/1.1urlpublicset-cookie:keep-aliveorigin:100101201202205206300302303304305306307402405406407408409410411412413414415416417502504505203 Non-Authoritative Information204 No Content301 Moved Permanently400 Bad Request401 Unauthorized403 Forbidden404 Not Found500 Internal Server Error501 Not Implemented503 Service UnavailableJan Feb Mar Apr May Jun Jul Aug Sept Oct Nov Dec 00:00:00 Mon, Tue, Wed, Thu, Fri, Sat, Sun, GMTchunked,text/html,image/png,image/jpg,image/gif,application/xml,application/xhtml+xml,text/plain,text/javascript,publicprivatemax-age=gzip,deflate,sdchcharset=utf-8charset=iso-8859-1,utf-,*,enq=0."
local dataToDeflate = {}
print("Generating test data...")
for i = 0, 10000 do
table.insert(dataToDeflate, string.sub(tostring(math.random()), 3))
end
dataToDeflate = table.concat(dataToDeflate)
print("Length of data to deflate", #dataToDeflate)
local buffer = {}
local func = function(data)
table.insert(buffer, data)
end
stream = zlib.deflate(func, nil, nil, nil, nil, nil, spdy_dict) --best compression, deflated
stream:write(dataToDeflate)
--stream:flush("sync")
--stream:flush()
stream:close()
--local deflatedData = string.sub(table.concat(buffer), 3) -- needed for IE
local deflatedData = table.concat(buffer)
print(#deflatedData)
streamIn = zlib.inflate(deflatedData, nil, spdy_dict)
local inflatedData = streamIn:read()
assert(dataToDeflate == inflatedData,
table.concat{"inflated data: ", inflatedData, "\n",
"deflated_data: ", dataToDeflate, "\n"})

2
libs/lzlib/zlib.def Normal file
View file

@ -0,0 +1,2 @@
EXPORTS
luaopen_zlib