Compare commits

...

23 Commits

Author SHA1 Message Date
KimLS 307923598b Merge fixes 2019-08-24 23:39:31 -07:00
KimLS 644d9c15c6 Update gitignore to ignore editor config 2019-08-24 14:30:41 -07:00
KimLS cf4f628340 Remove editor config 2019-08-24 14:29:57 -07:00
KimLS 8af508d8c5 Merge remote-tracking branch 'origin/master' into unstable 2019-07-12 00:11:46 -07:00
KimLS f85644a09c Merge fix for master 2019-07-05 21:07:56 -07:00
KimLS 1a6c6cf768 Delete old ngzlib lib 2019-06-30 18:20:31 -07:00
KimLS c5ffb44edb Merge fix 2019-06-30 18:19:56 -07:00
KimLS e0637e29f1 double semicolon 2019-06-30 18:03:15 -07:00
KimLS 40980a9d39 Don't link zlib when we're not using it 2019-06-24 19:52:24 -07:00
KimLS d906f79e6f Merge remote-tracking branch 'origin/master' into unstable 2019-06-24 17:45:44 -07:00
KimLS 8293225ecc Merge remote-tracking branch 'origin/feature/eqemu-api-data-service-netstats-ws' into unstable 2019-06-24 17:45:37 -07:00
KimLS e06a845921 Idle wip 2019-06-24 17:45:31 -07:00
KimLS aa4aced94d Zlib ng optional dependency 2019-06-24 17:35:33 -07:00
KimLS 0e0027ca20 Decoupling eventloop singleton from the event loop (for now not complete but later we will) 2019-06-24 00:15:02 -07:00
KimLS 5c7ab59fd3 More cmake streamlining 2019-06-23 19:39:17 -07:00
KimLS 120cf6a4b8 Add mbedtls as an alternative to OpenSSL, plan to implement TLS connections later 2019-06-23 17:04:33 -07:00
KimLS 3ddfed8bb6 Change to make cmake files a little more straight forward 2019-06-22 19:42:20 -07:00
KimLS 586eb9e5c1 Fix for bad cmakefile 2019-06-22 19:05:54 -07:00
KimLS 32227d19ce Merge fix 2019-06-22 18:59:34 -07:00
KimLS c233379894 Changes to packet, fixes for lua compile issue 2019-06-22 17:00:15 -07:00
KimLS a51a1d7106 Change out luabind as in the PR 2019-06-22 16:23:14 -07:00
KimLS 6d05903170 Use builtin find lua 2019-06-22 16:15:59 -07:00
KimLS 4ae0f2a1d7 Remove old non-compliant win32 defines. 2019-06-22 16:00:06 -07:00
361 changed files with 10977 additions and 40954 deletions
-23
View File
@@ -1,23 +0,0 @@
# EditorConfig is awesome: http://EditorConfig.org
# top-most EditorConfig file
root = true
# Unix-style newlines with a newline ending every file
[*]
end_of_line = lf
insert_final_newline = true
# Matches multiple files with brace expansion notation
# Set default charset
[*.{js,py}]
charset = utf-8
[*.cpp]
indent_style = tab
[*.h]
indent_style = tab
# Tab indentation (no size specified)
[Makefile]
indent_style = tab
+1
View File
@@ -30,3 +30,4 @@ vcpkg/
.idea/* .idea/*
*cbp *cbp
.editorconfig
+3
View File
@@ -16,3 +16,6 @@
[submodule "submodules/recastnavigation"] [submodule "submodules/recastnavigation"]
path = submodules/recastnavigation path = submodules/recastnavigation
url = https://github.com/EQEmu/recastnavigation.git url = https://github.com/EQEmu/recastnavigation.git
[submodule "submodules/zlibng"]
path = submodules/zlibng
url = https://github.com/zlib-ng/zlib-ng.git
+238 -321
View File
@@ -1,128 +1,24 @@
#EQEmu CMake CMAKE_MINIMUM_REQUIRED(VERSION 3.10)
#Variables used:
#EQEMU_DISABLE_CRT_SECURE_WARNINGS
#EQEMU_FAST_FLOATINGPOINT
#EQEMU_ENABLE_CRASH_LOGGING
#EQEMU_DISABLE_SAFESEH
#EQEMU_BUILD_MSVC_MP
#EQEMU_DEBUG_LEVEL
#EQEMU_LOG_LEVEL_STATUS
#EQEMU_LOG_LEVEL_NORMAL
#EQEMU_LOG_LEVEL_ERROR
#EQEMU_LOG_LEVEL_DEBUG
#EQEMU_LOG_LEVEL_QUEST
#EQEMU_LOG_LEVEL_COMMANDS
#EQEMU_LOG_LEVEL_CRASH
#EQEMU_DEPOP_INVALIDATES_CACHE
#EQEMU_ENABLE_BOTS
#EQEMU_DISABLE_LOGSYS
#EQEMU_COMMANDS_LOGGING
#EQEMU_BUILD_SERVER
#EQEMU_BUILD_LOGIN
#EQEMU_BUILD_TESTS
#EQEMU_BUILD_PERL
#EQEMU_BUILD_LUA
#EQEMU_SANITIZE_LUA_LIBS
#EQEMU_BUILD_CLIENT_FILES
#EQEMU_USE_MAP_MMFS
#EQEMU_MAP_DIR
#EQEMU_ARCH
#EQEMU_ARCH_ALT
CMAKE_MINIMUM_REQUIRED(VERSION 2.8)
IF(POLICY CMP0074)
cmake_policy(SET CMP0074 NEW)
ENDIF()
#FindMySQL is located here so lets make it so CMake can find it
SET(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake/" ${CMAKE_MODULE_PATH}) SET(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake/" ${CMAKE_MODULE_PATH})
#Our project name is EQEmu
PROJECT(EQEmu) PROJECT(EQEmu)
#Default build type is set to RelWithDebInfo for generators that honor that like makefiles
IF(NOT CMAKE_BUILD_TYPE) IF(NOT CMAKE_BUILD_TYPE)
SET(CMAKE_BUILD_TYPE RelWithDebInfo CACHE STRING "Choose the type of build." FORCE) SET(CMAKE_BUILD_TYPE RelWithDebInfo CACHE STRING "Choose the type of build." FORCE)
ENDIF(NOT CMAKE_BUILD_TYPE) ENDIF(NOT CMAKE_BUILD_TYPE)
SET(CMAKE_PREFIX_PATH "${CMAKE_CURRENT_SOURCE_DIR}/dependencies" "${CMAKE_PREFIX_PATH}") SET(CMAKE_CXX_STANDARD 14)
SET(CMAKE_CXX_STANDARD_REQUIRED ON)
#Add our various windows definitions SET(CMAKE_CXX_EXTENSIONS OFF)
IF(MSVC OR MINGW)
ADD_DEFINITIONS(-D_WINDOWS)
IF(CMAKE_CL_64)
ADD_DEFINITIONS(-DWIN64)
ELSE(CMAKE_CL_64)
ADD_DEFINITIONS(-DWIN32)
ENDIF(CMAKE_CL_64)
ENDIF(MSVC OR MINGW)
IF(MSVC) IF(MSVC)
IF(CMAKE_CL_64)
SET(EQEMU_ARCH "x64")
SET(EQEMU_ARCH_ALT "x64")
ELSE(CMAKE_CL_64)
SET(EQEMU_ARCH "x86")
SET(EQEMU_ARCH_ALT "Win32")
ENDIF(CMAKE_CL_64)
SET(MYSQL_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/dependencies/mysql_${EQEMU_ARCH}")
IF(VCPKG_TOOLCHAIN)
IF(NOT MSVC_VERSION GREATER 1800)
SET(SODIUM_INCLUDE_HINTS "${CMAKE_CURRENT_SOURCE_DIR}/dependencies/libsodium/include")
ENDIF()
ELSE(VCPKG_TOOLCHAIN)
SET(ZLIB_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/dependencies/zlib_${EQEMU_ARCH}")
SET(LUA_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/dependencies/luaj_${EQEMU_ARCH}")
SET(OPENSSL_ROOT_DIR "${CMAKE_CURRENT_SOURCE_DIR}/dependencies/openssl_${EQEMU_ARCH}")
SET(SODIUM_INCLUDE_HINTS "${CMAKE_CURRENT_SOURCE_DIR}/dependencies/libsodium/include")
ENDIF(VCPKG_TOOLCHAIN)
IF(SODIUM_INCLUDE_HINTS)
IF(MSVC_VERSION GREATER 1800)
SET(SODIUM_LIBRARY_HINTS "${CMAKE_CURRENT_SOURCE_DIR}/dependencies/libsodium/${EQEMU_ARCH_ALT}/Release/v140/dynamic")
ELSEIF(MSVC_VERSION EQUAL 1800)
SET(SODIUM_LIBRARY_HINTS "${CMAKE_CURRENT_SOURCE_DIR}/dependencies/libsodium/${EQEMU_ARCH_ALT}/Release/v120/dynamic")
ELSE()
SET(SODIUM_LIBRARY_HINTS "${CMAKE_CURRENT_SOURCE_DIR}/dependencies/libsodium/${EQEMU_ARCH_ALT}/Release/v110/dynamic")
ENDIF()
ENDIF(SODIUM_INCLUDE_HINTS)
#disable CRT warnings on windows cause they're annoying as shit and we use C functions everywhere
OPTION(EQEMU_DISABLE_CRT_SECURE_WARNINGS "Disable Secure CRT Warnings" ON)
IF(EQEMU_DISABLE_CRT_SECURE_WARNINGS)
ADD_DEFINITIONS(-D_CRT_SECURE_NO_WARNINGS) ADD_DEFINITIONS(-D_CRT_SECURE_NO_WARNINGS)
ENDIF(EQEMU_DISABLE_CRT_SECURE_WARNINGS)
#fast FP if you'd like it
OPTION(EQEMU_FAST_FLOATINGPOINT "Use MSVC /fp:fast option" ON)
IF(EQEMU_FAST_FLOATINGPOINT)
ADD_DEFINITIONS(/fp:fast)
ENDIF(EQEMU_FAST_FLOATINGPOINT)
#crash logging currently only works on windows x86/x64
OPTION(EQEMU_ENABLE_CRASH_LOGGING "Enable crash logging" ON)
IF(EQEMU_ENABLE_CRASH_LOGGING)
ADD_DEFINITIONS(-DCRASH_LOGGING)
ENDIF(EQEMU_ENABLE_CRASH_LOGGING)
OPTION(EQEMU_BUILD_MSVC_MP "Enable build with multiple processes." ON)
IF(EQEMU_BUILD_MSVC_MP)
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /MP")
ENDIF(EQEMU_BUILD_MSVC_MP)
#We want to compile /MT not /MD so we change that
FOREACH(flag_var CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELEASE CMAKE_CXX_FLAGS_RELWITHDEBINFO CMAKE_C_FLAGS_DEBUG CMAKE_C_FLAGS_MINSIZEREL CMAKE_C_FLAGS_RELEASE CMAKE_C_FLAGS_RELWITHDEBINFO)
IF(${flag_var} MATCHES "/MD")
STRING(REGEX REPLACE "/MD" "/MT" ${flag_var} "${${flag_var}}")
ENDIF(${flag_var} MATCHES "/MD")
ENDFOREACH(flag_var)
ADD_DEFINITIONS(-DNOMINMAX) ADD_DEFINITIONS(-DNOMINMAX)
ADD_DEFINITIONS(-DCRASH_LOGGING)
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /MP")
ELSE(MSVC) ELSE(MSVC)
#Normally set by perl but we don't use the perl flags anymore so we set it.
ADD_DEFINITIONS(-DHAS_UNION_SEMUN) ADD_DEFINITIONS(-DHAS_UNION_SEMUN)
ENDIF(MSVC) ENDIF(MSVC)
@@ -139,197 +35,239 @@ IF(UNIX)
ENDIF(CMAKE_SYSTEM_NAME MATCHES "Darwin") ENDIF(CMAKE_SYSTEM_NAME MATCHES "Darwin")
ENDIF(UNIX) ENDIF(UNIX)
#debug level, 5 is default. Most people wont ever change this but it's there if you want to
SET(EQEMU_DEBUG_LEVEL 5 CACHE STRING "EQEmu debug level:
0 - Quiet mode Errors to file Status and Normal ignored
1 - Status and Normal to console, Errors to logfile
2 - Status, Normal, and Error to console and logfile
3 - Light debug release errors and status
4 - Moderate debug release errors and status
5 - Maximum debug release errors and status
10 - More errors than you ever wanted to see"
)
SET(EQEMU_LOG_LEVEL_STATUS 2 CACHE STRING "EQEmu logging level for [Status]:
0 - Disabled
1 - Ouput to File Enabled
2 - Output to stdout Enabled
3 - Output to File and stdout Enabled
8 - Output to stderr Enabled
9 - Output to File and stderr Enabled
11 - Output to File, stdout and stderr Enabled"
)
SET(EQEMU_LOG_LEVEL_NORMAL 3 CACHE STRING "EQEmu logging level for [Normal]:
0 - Disabled
1 - Ouput to File Enabled
2 - Output to stdout Enabled
3 - Output to File and stdout Enabled
8 - Output to stderr Enabled
9 - Output to File and stderr Enabled
11 - Output to File, stdout and stderr Enabled"
)
SET(EQEMU_LOG_LEVEL_ERROR 2 CACHE STRING "EQEmu logging level for [Error]:
0 - Disabled
1 - Ouput to File Enabled
2 - Output to stdout Enabled
3 - Output to File and stdout Enabled
8 - Output to stderr Enabled
9 - Output to File and stderr Enabled
11 - Output to File, stdout and stderr Enabled"
)
SET(EQEMU_LOG_LEVEL_DEBUG 3 CACHE STRING "EQEmu logging level for [Debug]:
0 - Disabled
1 - Ouput to File Enabled
2 - Output to stdout Enabled
3 - Output to File and stdout Enabled
8 - Output to stderr Enabled
9 - Output to File and stderr Enabled
11 - Output to File, stdout and stderr Enabled"
)
SET(EQEMU_LOG_LEVEL_QUEST 2 CACHE STRING "EQEmu logging level for [Quest]:
0 - Disabled
1 - Ouput to File Enabled
2 - Output to stdout Enabled
3 - Output to File and stdout Enabled
8 - Output to stderr Enabled
9 - Output to File and stderr Enabled
11 - Output to File, stdout and stderr Enabled"
)
SET(EQEMU_LOG_LEVEL_COMMANDS 1 CACHE STRING "EQEmu logging level for [Commands]:
0 - Disabled
1 - Ouput to File Enabled
2 - Output to stdout Enabled
3 - Output to File and stdout Enabled
8 - Output to stderr Enabled
9 - Output to File and stderr Enabled
11 - Output to File, stdout and stderr Enabled"
)
SET(EQEMU_LOG_LEVEL_CRASH 3 CACHE STRING "EQEmu logging level for [Crash]:
0 - Disabled
1 - Ouput to File Enabled
2 - Output to stdout Enabled
3 - Output to File and stdout Enabled
8 - Output to stderr Enabled
9 - Output to File and stderr Enabled
11 - Output to File, stdout and stderr Enabled"
)
MARK_AS_ADVANCED(EQEMU_LOG_LEVEL_STATUS EQEMU_LOG_LEVEL_NORMAL EQEMU_LOG_LEVEL_ERROR EQEMU_LOG_LEVEL_DEBUG EQEMU_LOG_LEVEL_QUEST EQEMU_LOG_LEVEL_COMMANDS EQEMU_LOG_LEVEL_CRASH)
#NPC Types Cache Behavior
OPTION(EQEMU_DEPOP_INVALIDATES_CACHE "#repop invalidates the npc_types cache (will cause a larger database hit on #repop but is more convienent)." ON)
#Bots are a compile time option so on/off
OPTION(EQEMU_ENABLE_BOTS "Enable Bots" OFF)
#Disable entire _mlog system (excludes trade/command logs)
OPTION(EQEMU_DISABLE_LOGSYS "Disable Logging INI System" ON)
#Enable GM Command log system
OPTION(EQEMU_COMMANDS_LOGGING "Enable GM Command logs" ON)
IF(EQEMU_COMMANDS_LOGGING)
ADD_DEFINITIONS(-DCOMMANDS_LOGGING)
ENDIF(EQEMU_COMMANDS_LOGGING)
IF(EQEMU_DISABLE_LOGSYS)
ADD_DEFINITIONS(-DDISABLE_LOGSYS)
ENDIF(EQEMU_DISABLE_LOGSYS)
IF(EQEMU_ENABLE_BOTS)
ADD_DEFINITIONS(-DBOTS)
ENDIF(EQEMU_ENABLE_BOTS)
#What to build
OPTION(EQEMU_BUILD_SERVER "Build the game server." ON)
OPTION(EQEMU_BUILD_LOGIN "Build the login server." OFF)
OPTION(EQEMU_BUILD_HC "Build the headless client." OFF)
OPTION(EQEMU_BUILD_TESTS "Build utility tests." OFF)
OPTION(EQEMU_BUILD_PERL "Build Perl parser." ON)
OPTION(EQEMU_BUILD_LUA "Build Lua parser." ON)
OPTION(EQEMU_BUILD_CLIENT_FILES "Build Client Import/Export Data Programs." ON)
#C++11 stuff
IF(NOT MSVC)
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x")
IF("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang")
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-reserved-user-defined-literal")
ENDIF()
ENDIF(NOT MSVC)
#Various definitions
IF(EQEMU_BUILD_PERL)
ADD_DEFINITIONS(-DEMBPERL)
ADD_DEFINITIONS(-DEMBPERL_PLUGIN)
ENDIF(EQEMU_BUILD_PERL)
IF(EQEMU_BUILD_LUA)
ADD_DEFINITIONS(-DLUA_EQEMU)
ENDIF(EQEMU_BUILD_LUA)
#Disabled until reevaluation performed
#OPTION(EQEMU_USE_MAP_MMFS "Create and use Zone Map MMF files." OFF)
#IF(EQEMU_USE_MAP_MMFS)
# ADD_DEFINITIONS(-DUSE_MAP_MMFS)
#ENDIF(EQEMU_USE_MAP_MMFS)
SET(EQEMU_MAP_DIR "./Maps" CACHE STRING "The dir that maps, water maps, and paths are located in.")
ADD_DEFINITIONS(-DEQDEBUG=${EQEMU_DEBUG_LEVEL})
ADD_DEFINITIONS(-DINVERSEXY)
ADD_DEFINITIONS(-DFIELD_ITEMS)
ADD_DEFINITIONS(-DMAP_DIR="${EQEMU_MAP_DIR}")
ADD_DEFINITIONS(-DLOG_LEVEL_STATUS=${EQEMU_LOG_LEVEL_STATUS})
ADD_DEFINITIONS(-DLOG_LEVEL_NORMAL=${EQEMU_LOG_LEVEL_NORMAL})
ADD_DEFINITIONS(-DLOG_LEVEL_ERROR=${EQEMU_LOG_LEVEL_ERROR})
ADD_DEFINITIONS(-DLOG_LEVEL_DEBUG=${EQEMU_LOG_LEVEL_DEBUG})
ADD_DEFINITIONS(-DLOG_LEVEL_QUEST=${EQEMU_LOG_LEVEL_QUEST})
ADD_DEFINITIONS(-DLOG_LEVEL_COMMANDS=${EQEMU_LOG_LEVEL_COMMANDS})
ADD_DEFINITIONS(-DLOG_LEVEL_CRASH=${EQEMU_LOG_LEVEL_CRASH})
ADD_DEFINITIONS(-DGLM_FORCE_RADIANS) ADD_DEFINITIONS(-DGLM_FORCE_RADIANS)
ADD_DEFINITIONS(-DGLM_FORCE_CTOR_INIT) ADD_DEFINITIONS(-DGLM_FORCE_CTOR_INIT)
ADD_DEFINITIONS(-DGLM_ENABLE_EXPERIMENTAL) ADD_DEFINITIONS(-DGLM_ENABLE_EXPERIMENTAL)
#Find everything we need #Find everything we need
FIND_PACKAGE(MySQL)
FIND_PACKAGE(MariaDB)
FIND_PACKAGE(Boost REQUIRED)
FIND_PACKAGE(ZLIB) FIND_PACKAGE(ZLIB)
FIND_PACKAGE(MySQL REQUIRED) FIND_PACKAGE(OpenSSL)
IF(EQEMU_BUILD_PERL) FIND_PACKAGE(Lua51)
FIND_PACKAGE(PerlLibs REQUIRED) FIND_PACKAGE(PerlLibs)
INCLUDE_DIRECTORIES(SYSTEM "${PERL_INCLUDE_PATH}") FIND_PACKAGE(Sodium)
ENDIF(EQEMU_BUILD_PERL) FIND_PACKAGE(mbedTLS)
SET(SERVER_LIBS common debug ${MySQL_LIBRARY_DEBUG} optimized ${MySQL_LIBRARY_RELEASE} uv_a fmt RecastNavigation::Detour) MESSAGE(STATUS "**************************************************")
MESSAGE(STATUS "* Library Detection *")
MESSAGE(STATUS "**************************************************")
FIND_PACKAGE(Sodium REQUIRED) IF(MYSQL_FOUND)
IF(SODIUM_FOUND) MESSAGE(STATUS "* MySQL: FOUND *")
OPTION(EQEMU_ENABLE_SECURITY "Use Encryption For TCP Connections" ON) ELSE()
IF(EQEMU_ENABLE_SECURITY) MESSAGE(STATUS "* MySQL: MISSING *")
INCLUDE_DIRECTORIES(SYSTEM "${SODIUM_INCLUDE_DIRS}")
ADD_DEFINITIONS(-DENABLE_SECURITY)
SET(SERVER_LIBS ${SERVER_LIBS} ${SODIUM_LIBRARIES})
ENDIF() ENDIF()
IF(MARIADB_FOUND)
MESSAGE(STATUS "* MariaDB: FOUND *")
ELSE()
MESSAGE(STATUS "* MariaDB: MISSING *")
ENDIF() ENDIF()
IF(ZLIB_FOUND) IF(ZLIB_FOUND)
OPTION(EQEMU_BUILD_ZLIB "Build internal version of zlib." OFF) MESSAGE(STATUS "* ZLIB: FOUND *")
IF(EQEMU_BUILD_ZLIB)
INCLUDE_DIRECTORIES(BEFORE SYSTEM "${CMAKE_CURRENT_BINARY_DIR}/libs/zlibng" "${CMAKE_CURRENT_SOURCE_DIR}/libs/zlibng")
SET(SERVER_LIBS ${SERVER_LIBS} "zlibstatic")
ELSE() ELSE()
INCLUDE_DIRECTORIES(SYSTEM "${ZLIB_INCLUDE_DIRS}") MESSAGE(STATUS "* ZLIB: MISSING *")
SET(SERVER_LIBS ${SERVER_LIBS} ${ZLIB_LIBRARY}) ENDIF()
IF(Lua51_FOUND)
MESSAGE(STATUS "* Lua: FOUND *")
ELSE()
MESSAGE(STATUS "* Lua: MISSING *")
ENDIF()
IF(PerlLibs_FOUND)
MESSAGE(STATUS "* Perl: FOUND *")
ELSE()
MESSAGE(STATUS "* Perl: MISSING *")
ENDIF()
IF(SODIUM_FOUND)
MESSAGE(STATUS "* libsodium: FOUND *")
ELSE()
MESSAGE(STATUS "* libsodium: MISSING *")
ENDIF()
IF(OpenSSL_FOUND)
MESSAGE(STATUS "* OpenSSL: FOUND *")
ELSE()
MESSAGE(STATUS "* OpenSSL: MISSING *")
ENDIF()
IF(MBEDTLS_FOUND)
MESSAGE(STATUS "* mbedTLS: FOUND *")
ELSE()
MESSAGE(STATUS "* mbedTLS: MISSING *")
ENDIF()
MESSAGE(STATUS "**************************************************")
#options
OPTION(EQEMU_DEPOP_INVALIDATES_CACHE "#repop invalidates the npc_types cache (will cause a larger database hit on #repop but is more convienent)." ON)
OPTION(EQEMU_ENABLE_BOTS "Enable Bots" OFF)
OPTION(EQEMU_COMMANDS_LOGGING "Enable GM Command logs" ON)
OPTION(EQEMU_BUILD_SERVER "Build the game server." ON)
OPTION(EQEMU_BUILD_HC "Build the headless client." OFF)
OPTION(EQEMU_BUILD_TESTS "Build utility tests." OFF)
OPTION(EQEMU_BUILD_CLIENT_FILES "Build Client Import/Export Data Programs." ON)
IF(EQEMU_COMMANDS_LOGGING)
ADD_DEFINITIONS(-DCOMMANDS_LOGGING)
ENDIF(EQEMU_COMMANDS_LOGGING)
IF(EQEMU_ENABLE_BOTS)
ADD_DEFINITIONS(-DBOTS)
ENDIF(EQEMU_ENABLE_BOTS)
#database
#prefer mariadb to mysql (arbitrary)
IF(MySQL_FOUND AND MariaDB_FOUND)
SET(DATABASE_LIBRARY_TYPE "MariaDB")
SET(DATABASE_LIBRARY_LIBS ${MariaDB_LIBRARIES})
SET(DATABASE_LIBRARY_INCLUDE ${MariaDB_INCLUDE_DIR})
ELSEIF(MariaDB_FOUND)
SET(DATABASE_LIBRARY_TYPE "MariaDB")
SET(DATABASE_LIBRARY_LIBS ${MariaDB_LIBRARIES})
SET(DATABASE_LIBRARY_INCLUDE ${MariaDB_INCLUDE_DIR})
ELSEIF(MySQL_FOUND)
SET(DATABASE_LIBRARY_TYPE " MySQL")
SET(DATABASE_LIBRARY_LIBS ${MySQL_LIBRARIES})
SET(DATABASE_LIBRARY_INCLUDE ${MySQL_INCLUDE_DIR})
ELSE()
MESSAGE(FATAL_ERROR "One of MySQL or MariaDB is a required dependency.")
ENDIF()
#security
#prefer openssl to mbedtls (arbitrary)
IF(OpenSSL_FOUND AND MBEDTLS_FOUND)
SET(SSL_LIBRARY_TYPE " OpenSSL")
SET(SSL_LIBRARY_ENABLED ON)
SET(SSL_LIBRARY_LIBS ${OPENSSL_LIBRARIES})
SET(SSL_LIBRARY_INCLUDE ${OPENSSL_INCLUDE_DIR})
ELSEIF(OpenSSL_FOUND)
SET(SSL_LIBRARY_TYPE " OpenSSL")
SET(SSL_LIBRARY_ENABLED ON)
SET(SSL_LIBRARY_LIBS ${OPENSSL_LIBRARIES})
SET(SSL_LIBRARY_INCLUDE ${OPENSSL_INCLUDE_DIR})
ELSEIF(MBEDTLS_FOUND)
SET(SSL_LIBRARY_TYPE " mbedTLS")
SET(SSL_LIBRARY_ENABLED ON)
SET(SSL_LIBRARY_LIBS ${MBEDTLS_LIBRARY} ${MBEDX509_LIBRARY} ${MBEDCRYPTO_LIBRARY})
SET(SSL_LIBRARY_INCLUDE ${MBEDTLS_INCLUDE_DIR})
ELSE()
SET(SSL_LIBRARY_TYPE "Disabled")
SET(SSL_LIBRARY_ENABLED OFF)
ENDIF()
IF(SODIUM_FOUND)
SET(SODIUM_LIBRARY_TYPE "Libsodium")
SET(SODIUM_LIBRARY_ENABLED ON)
SET(SODIUM_LIBRARY_LIBS ${SODIUM_LIBRARIES})
SET(SODIUM_LIBRARY_INCLUDE ${SODIUM_INCLUDE_DIRS})
ADD_DEFINITIONS(-DENABLE_SECURITY)
ELSE()
SET(SODIUM_LIBRARY_TYPE " Disabled")
SET(SODIUM_LIBRARY_ENABLED OFF)
ENDIF()
IF(Lua51_FOUND)
SET(LUA_LIBRARY_TYPE " Lua 5.1")
SET(LUA_LIBRARY_LIBS ${LUA_LIBRARY} luabind)
SET(LUA_LIBRARY_INCLUDE ${LUA_INCLUDE_DIR} "${CMAKE_CURRENT_SOURCE_DIR}/libs/luabind")
OPTION(EQEMU_BUILD_LUA "Build Lua parser." ON)
IF(EQEMU_BUILD_LUA)
ADD_DEFINITIONS(-DLUA_EQEMU)
OPTION(EQEMU_SANITIZE_LUA_LIBS "Sanitize Lua Libraries (Remove OS and IO standard libraries from being able to run)." ON)
IF(EQEMU_SANITIZE_LUA_LIBS)
ADD_DEFINITIONS(-DSANITIZE_LUA_LIBS)
ENDIF()
ENDIF() ENDIF()
ELSE() ELSE()
MESSAGE(STATUS "Could NOT find ZLIB - using ZLIBSTATIC package.") SET(LUA_LIBRARY_TYPE "Disabled")
SET(EQEMU_BUILD_ZLIB ON) ENDIF()
INCLUDE_DIRECTORIES(BEFORE SYSTEM "${CMAKE_CURRENT_BINARY_DIR}/libs/zlibng" "${CMAKE_CURRENT_SOURCE_DIR}/libs/zlibng")
SET(SERVER_LIBS ${SERVER_LIBS} "zlibstatic") IF(PerlLibs_FOUND)
SET(PERL_LIBRARY_TYPE " Perl")
SET(PERL_LIBRARY_LIBS ${PERL_LIBRARY})
SET(PERL_LIBRARY_INCLUDE ${PERL_INCLUDE_PATH})
OPTION(EQEMU_BUILD_PERL "Build Perl parser." ON)
IF(EQEMU_BUILD_PERL)
ADD_DEFINITIONS(-DEMBPERL)
ADD_DEFINITIONS(-DEMBPERL_PLUGIN)
ENDIF()
ELSE()
SET(PERL_LIBRARY_TYPE "Disabled")
ENDIF()
#use zlib if exists
IF(ZLIB_FOUND)
OPTION(EQEMU_BUILD_ZLIB "Build internal version of zlib." OFF)
IF(EQEMU_BUILD_ZLIB)
SET(ZLIB_LIBRARY_TYPE "zlib-ng")
SET(ZLIB_LIBRARY_LIBS "zlibstatic")
SET(ZLIB_LIBRARY_INCLUDE "${CMAKE_CURRENT_SOURCE_DIR}/submodules/zlibng")
ELSE()
SET(ZLIB_LIBRARY_TYPE " zlib")
SET(ZLIB_LIBRARY_LIBS ${ZLIB_LIBRARY})
SET(ZLIB_LIBRARY_INCLUDE ${ZLIB_INCLUDE_DIRS})
ENDIF()
ELSE()
SET(ZLIB_LIBRARY_TYPE "zlib-ng")
SET(ZLIB_LIBRARY_LIBS "zlibstatic")
SET(ZLIB_LIBRARY_INCLUDE "${CMAKE_CURRENT_SOURCE_DIR}/submodules/zlibng")
ENDIF()
MESSAGE(STATUS "")
MESSAGE(STATUS "**************************************************")
MESSAGE(STATUS "* Library Usage *")
MESSAGE(STATUS "**************************************************")
MESSAGE(STATUS "* Database: ${DATABASE_LIBRARY_TYPE} *")
MESSAGE(STATUS "* TLS: ${SSL_LIBRARY_TYPE} *")
MESSAGE(STATUS "* Sodium: ${SODIUM_LIBRARY_TYPE} *")
MESSAGE(STATUS "* Lua: ${LUA_LIBRARY_TYPE} *")
MESSAGE(STATUS "* Perl: ${PERL_LIBRARY_TYPE} *")
MESSAGE(STATUS "* zlib: ${ZLIB_LIBRARY_TYPE} *")
MESSAGE(STATUS "**************************************************")
#setup server libs and headers
SET(SERVER_LIBS common ${DATABASE_LIBRARY_LIBS} ${ZLIB_LIBRARY_LIBS} ${Boost_LIBRARIES} uv_a fmt RecastNavigation::Detour)
INCLUDE_DIRECTORIES(SYSTEM "${DATABASE_LIBRARY_INCLUDE}")
INCLUDE_DIRECTORIES(SYSTEM "${ZLIB_LIBRARY_INCLUDE}")
INCLUDE_DIRECTORIES(SYSTEM "${Boost_INCLUDE_DIRS}")
INCLUDE_DIRECTORIES(SYSTEM "${CMAKE_CURRENT_SOURCE_DIR}/submodules/glm")
INCLUDE_DIRECTORIES(SYSTEM "${CMAKE_CURRENT_SOURCE_DIR}/submodules/cereal/include")
INCLUDE_DIRECTORIES(SYSTEM "${CMAKE_CURRENT_SOURCE_DIR}/submodules/fmt/include")
INCLUDE_DIRECTORIES(SYSTEM "${CMAKE_CURRENT_SOURCE_DIR}/submodules/libuv/include" )
INCLUDE_DIRECTORIES(SYSTEM "${CMAKE_CURRENT_SOURCE_DIR}/submodules/recastnavigation/DebugUtils/Include")
INCLUDE_DIRECTORIES(SYSTEM "${CMAKE_CURRENT_SOURCE_DIR}/submodules/recastnavigation/Detour/Include")
INCLUDE_DIRECTORIES(SYSTEM "${CMAKE_CURRENT_SOURCE_DIR}/submodules/recastnavigation/DetourCrowd/Include")
INCLUDE_DIRECTORIES(SYSTEM "${CMAKE_CURRENT_SOURCE_DIR}/submodules/recastnavigation/DetourTileCache/Include")
INCLUDE_DIRECTORIES(SYSTEM "${CMAKE_CURRENT_SOURCE_DIR}/submodules/recastnavigation/Recast/Include")
INCLUDE_DIRECTORIES(SYSTEM "${CMAKE_CURRENT_SOURCE_DIR}/submodules/websocketpp")
IF(SSL_LIBRARY_ENABLED)
SET(SERVER_LIBS ${SERVER_LIBS} ${SSL_LIBRARY_LIBS})
INCLUDE_DIRECTORIES(SYSTEM "${SSL_LIBRARY_INCLUDE}")
ENDIF()
IF(SODIUM_LIBRARY_ENABLED)
SET(SERVER_LIBS ${SERVER_LIBS} ${SODIUM_LIBRARY_LIBS})
INCLUDE_DIRECTORIES(SYSTEM "${SODIUM_LIBRARY_INCLUDE}")
ENDIF()
IF(EQEMU_BUILD_LUA)
SET(SERVER_LIBS ${SERVER_LIBS} ${LUA_LIBRARY_LIBS})
INCLUDE_DIRECTORIES(SYSTEM "${LUA_LIBRARY_INCLUDE}")
ENDIF()
IF(EQEMU_BUILD_PERL)
SET(SERVER_LIBS ${SERVER_LIBS} ${PERL_LIBRARY_LIBS})
INCLUDE_DIRECTORIES(SYSTEM "${PERL_LIBRARY_INCLUDE}")
ENDIF() ENDIF()
IF(WIN32) IF(WIN32)
@@ -344,34 +282,9 @@ IF(UNIX)
SET(SERVER_LIBS ${SERVER_LIBS} "uuid") SET(SERVER_LIBS ${SERVER_LIBS} "uuid")
ENDIF() ENDIF()
IF(EQEMU_BUILD_LUA) IF(EQEMU_BUILD_LOGIN AND NOT SSL_LIBRARY_ENABLED)
FIND_PACKAGE(EQLua51 REQUIRED) MESSAGE(FATAL_ERROR "Login server requires a SSL Library to build.")
SET(Boost_USE_STATIC_LIBS OFF) ENDIF()
SET(Boost_USE_MULTITHREADED ON)
SET(Boost_USE_STATIC_RUNTIME OFF)
SET(BOOST_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/dependencies/boost")
FIND_PACKAGE(Boost REQUIRED)
INCLUDE_DIRECTORIES(SYSTEM "${LUA_INCLUDE_DIR}" "${Boost_INCLUDE_DIRS}")
INCLUDE_DIRECTORIES(SYSTEM "${CMAKE_CURRENT_SOURCE_DIR}/libs/luabind")
OPTION(EQEMU_SANITIZE_LUA_LIBS "Sanitize Lua Libraries (Remove OS and IO standard libraries from being able to run)." ON)
IF(EQEMU_SANITIZE_LUA_LIBS)
ADD_DEFINITIONS(-DSANITIZE_LUA_LIBS)
ENDIF(EQEMU_SANITIZE_LUA_LIBS)
ENDIF(EQEMU_BUILD_LUA)
INCLUDE_DIRECTORIES(SYSTEM "${MySQL_INCLUDE_DIR}")
INCLUDE_DIRECTORIES(SYSTEM "${CMAKE_CURRENT_SOURCE_DIR}/submodules/glm")
INCLUDE_DIRECTORIES(SYSTEM "${CMAKE_CURRENT_SOURCE_DIR}/submodules/cereal/include")
INCLUDE_DIRECTORIES(SYSTEM "${CMAKE_CURRENT_SOURCE_DIR}/submodules/fmt/include")
INCLUDE_DIRECTORIES(SYSTEM "${CMAKE_CURRENT_SOURCE_DIR}/submodules/libuv/include" )
INCLUDE_DIRECTORIES(SYSTEM "${CMAKE_CURRENT_SOURCE_DIR}/submodules/recastnavigation/DebugUtils/Include")
INCLUDE_DIRECTORIES(SYSTEM "${CMAKE_CURRENT_SOURCE_DIR}/submodules/recastnavigation/Detour/Include")
INCLUDE_DIRECTORIES(SYSTEM "${CMAKE_CURRENT_SOURCE_DIR}/submodules/recastnavigation/DetourCrowd/Include")
INCLUDE_DIRECTORIES(SYSTEM "${CMAKE_CURRENT_SOURCE_DIR}/submodules/recastnavigation/DetourTileCache/Include")
INCLUDE_DIRECTORIES(SYSTEM "${CMAKE_CURRENT_SOURCE_DIR}/submodules/recastnavigation/Recast/Include")
INCLUDE_DIRECTORIES(SYSTEM "${CMAKE_CURRENT_SOURCE_DIR}/submodules/websocketpp")
IF(EQEMU_BUILD_SERVER OR EQEMU_BUILD_LOGIN OR EQEMU_BUILD_TESTS OR EQEMU_BUILD_HC) IF(EQEMU_BUILD_SERVER OR EQEMU_BUILD_LOGIN OR EQEMU_BUILD_TESTS OR EQEMU_BUILD_HC)
ADD_SUBDIRECTORY(common) ADD_SUBDIRECTORY(common)
@@ -379,17 +292,20 @@ IF(EQEMU_BUILD_SERVER OR EQEMU_BUILD_LOGIN OR EQEMU_BUILD_TESTS OR EQEMU_BUILD_H
ADD_SUBDIRECTORY(submodules/fmt) ADD_SUBDIRECTORY(submodules/fmt)
ADD_SUBDIRECTORY(submodules/libuv) ADD_SUBDIRECTORY(submodules/libuv)
IF(EQEMU_BUILD_ZLIB)
SET(ZLIB_COMPAT ON CACHE BOOL "Compile with zlib compatible API")
SET(ZLIB_ENABLE_TESTS OFF CACHE BOOL "Build test binaries")
ADD_SUBDIRECTORY(submodules/zlibng)
ENDIF()
SET(RECASTNAVIGATION_DEMO OFF CACHE BOOL "Build demo") SET(RECASTNAVIGATION_DEMO OFF CACHE BOOL "Build demo")
SET(RECASTNAVIGATION_TESTS OFF CACHE BOOL "Build tests") SET(RECASTNAVIGATION_TESTS OFF CACHE BOOL "Build tests")
SET(RECASTNAVIGATION_EXAMPLES OFF CACHE BOOL "Build examples") SET(RECASTNAVIGATION_EXAMPLES OFF CACHE BOOL "Build examples")
ADD_SUBDIRECTORY(submodules/recastnavigation) ADD_SUBDIRECTORY(submodules/recastnavigation)
IF(EQEMU_BUILD_ZLIB)
SET(ZLIB_COMPAT ON CACHE BOOL "Compile with zlib compatible API")
SET(ZLIB_ENABLE_TESTS OFF CACHE BOOL "Build test binaries")
ADD_SUBDIRECTORY(libs/zlibng)
ENDIF()
ENDIF(EQEMU_BUILD_SERVER OR EQEMU_BUILD_LOGIN OR EQEMU_BUILD_TESTS OR EQEMU_BUILD_HC) ENDIF(EQEMU_BUILD_SERVER OR EQEMU_BUILD_LOGIN OR EQEMU_BUILD_TESTS OR EQEMU_BUILD_HC)
MESSAGE(STATUS "Libs: ${SERVER_LIBS}")
IF(EQEMU_BUILD_SERVER) IF(EQEMU_BUILD_SERVER)
ADD_SUBDIRECTORY(shared_memory) ADD_SUBDIRECTORY(shared_memory)
ADD_SUBDIRECTORY(world) ADD_SUBDIRECTORY(world)
@@ -398,6 +314,7 @@ IF(EQEMU_BUILD_SERVER)
ADD_SUBDIRECTORY(queryserv) ADD_SUBDIRECTORY(queryserv)
ADD_SUBDIRECTORY(eqlaunch) ADD_SUBDIRECTORY(eqlaunch)
ENDIF(EQEMU_BUILD_SERVER) ENDIF(EQEMU_BUILD_SERVER)
IF(EQEMU_BUILD_LOGIN) IF(EQEMU_BUILD_LOGIN)
ADD_SUBDIRECTORY(loginserver) ADD_SUBDIRECTORY(loginserver)
ENDIF(EQEMU_BUILD_LOGIN) ENDIF(EQEMU_BUILD_LOGIN)
+1 -1
View File
@@ -1,4 +1,4 @@
CMAKE_MINIMUM_REQUIRED(VERSION 2.8) CMAKE_MINIMUM_REQUIRED(VERSION 3.10)
add_subdirectory(import) add_subdirectory(import)
add_subdirectory(export) add_subdirectory(export)
+1 -1
View File
@@ -1,4 +1,4 @@
CMAKE_MINIMUM_REQUIRED(VERSION 2.8) CMAKE_MINIMUM_REQUIRED(VERSION 3.10)
SET(export_sources SET(export_sources
main.cpp main.cpp
+1 -1
View File
@@ -1,4 +1,4 @@
CMAKE_MINIMUM_REQUIRED(VERSION 2.8) CMAKE_MINIMUM_REQUIRED(VERSION 3.10)
SET(import_sources SET(import_sources
main.cpp main.cpp
-124
View File
@@ -1,124 +0,0 @@
#CMake - Cross Platform Makefile Generator
#Copyright 2000-2011 Kitware, Inc., Insight Software Consortium
#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.
#
#* Neither the names of Kitware, Inc., the Insight Software Consortium,
# nor the names of their contributors may be used to endorse or promote
# products derived from this software without specific prior written
# permission.
#
#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.
# This module defines
# LUA51_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)
IF(LUA_ROOT)
FIND_PATH(LUA_INCLUDE_DIR
NAMES lua.h
HINTS
ENV LUA_DIR
PATHS
${LUA_ROOT}
~/Library/Frameworks
/Library/Frameworks
/sw
/opt/local
/opt/csw
/opt
PATH_SUFFIXES include/lua51 include/lua5.1 include/lua include src
)
FIND_LIBRARY(LUA_LIBRARY
NAMES lua51 lua5.1 lua-5.1 lua
HINTS
ENV LUA_DIR
PATHS
${LUA_ROOT}
~/Library/Frameworks
/Library/Frameworks
/sw
/opt/local
/opt/csw
/opt
PATH_SUFFIXES lib bin
)
ELSE(LUA_ROOT)
FIND_PATH(LUA_INCLUDE_DIR
NAMES lua.h
HINTS
ENV LUA_DIR
PATHS
~/Library/Frameworks
/Library/Frameworks
/sw
/opt/local
/opt/csw
/opt
PATH_SUFFIXES include/lua51 include/lua5.1 include/lua include
)
FIND_LIBRARY(LUA_LIBRARY
NAMES lua51 lua5.1 lua-5.1 lua
HINTS
ENV LUA_DIR
PATHS
~/Library/Frameworks
/Library/Frameworks
/sw
/opt/local
/opt/csw
/opt
PATH_SUFFIXES lib bin
)
ENDIF(LUA_ROOT)
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()
SET( LUA_LIBRARIES "${LUA_LIBRARY}" CACHE STRING "Lua Libraries")
ENDIF()
ENDIF()
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)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(Lua51
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)
+87
View File
@@ -0,0 +1,87 @@
# - Find mariadbclient
#
# -*- cmake -*-
#
# Find the native MariaDB includes and library
#
# MariaDB_INCLUDE_DIR - where to find mysql.h, etc.
# MariaDB_LIBRARIES - List of libraries when using MariaDB.
# MariaDB_FOUND - True if MariaDB found.
# The following can be used as a hint as to where to search:
# MARIADB_ROOT
IF (MariaDB_INCLUDE_DIR AND MariaDB_LIBRARIES)
# Already in cache, be silent
SET(MariaDB_FIND_QUIETLY TRUE)
ENDIF (MariaDB_INCLUDE_DIR AND MariaDB_LIBRARIES)
# Include dir
IF(MARIADB_ROOT)
FIND_PATH(MariaDB_INCLUDE_DIR
NAMES mariadb_version.h
PATHS ${MARIADB_ROOT}/include
PATH_SUFFIXES mysql mariadb
NO_DEFAULT_PATH
NO_SYSTEM_ENVIRONMENT_PATH
)
FIND_PATH(MariaDB_INCLUDE_DIR
NAMES mariadb_version.h
PATH_SUFFIXES mysql mariadb
)
ELSE(MARIADB_ROOT)
FIND_PATH(MariaDB_INCLUDE_DIR
NAMES mariadb_version.h
PATH_SUFFIXES mysql mariadb
)
ENDIF(MARIADB_ROOT)
# Library
SET(MariaDB_NAMES libmariadb)
IF(MARIADB_ROOT)
FIND_LIBRARY(MariaDB_LIBRARY
NAMES ${MariaDB_NAMES}
PATHS ${MARIADB_ROOT}/lib
PATH_SUFFIXES mysql mariadb
NO_DEFAULT_PATH
NO_SYSTEM_ENVIRONMENT_PATH
)
FIND_LIBRARY(MariaDB_LIBRARY
NAMES ${MariaDB_NAMES}
PATH_SUFFIXES mysql mariadb
)
ELSE(MARIADB_ROOT)
FIND_LIBRARY(MariaDB_LIBRARY
NAMES ${MariaDB_NAMES} mariadbclient_r mariadbclient
PATHS /usr/lib /usr/local/lib /usr/lib64 /usr/local/lib64
PATH_SUFFIXES mysql mariadb
)
ENDIF(MARIADB_ROOT)
IF (MariaDB_INCLUDE_DIR AND MariaDB_LIBRARY)
SET(MariaDB_FOUND TRUE)
SET(MariaDB_LIBRARIES ${MariaDB_LIBRARY})
ELSE (MariaDB_INCLUDE_DIR AND MariaDB_LIBRARY)
SET(MariaDB_FOUND FALSE)
SET(MariaDB_LIBRARIES)
ENDIF (MariaDB_INCLUDE_DIR AND MariaDB_LIBRARY)
# handle the QUIETLY and REQUIRED arguments and set MariaDB_FOUND to TRUE if
# all listed variables are TRUE
INCLUDE(FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(MariaDB DEFAULT_MSG MariaDB_LIBRARY MariaDB_INCLUDE_DIR)
IF(MariaDB_FOUND)
SET( MariaDB_LIBRARY_RELEASE ${MariaDB_LIBRARY} )
SET( MariaDB_LIBRARY_DEBUG ${MariaDB_LIBRARY} )
SET( MariaDB_LIBRARIES ${MariaDB_LIBRARY_RELEASE} ${MariaDB_LIBRARY_DEBUG} )
ELSE(MariaDB_FOUND)
SET( MariaDB_LIBRARIES )
ENDIF(MariaDB_FOUND)
MARK_AS_ADVANCED(
MariaDB_LIBRARY_DEBUG
MariaDB_LIBRARY_RELEASE
MariaDB_INCLUDE_DIR
)
+93
View File
@@ -0,0 +1,93 @@
# - Try to find mbedTLS
# Once done this will define
#
# Read-Only variables
# MBEDTLS_FOUND - system has mbedTLS
# MBEDTLS_INCLUDE_DIR - the mbedTLS include directory
# MBEDTLS_LIBRARY_DIR - the mbedTLS library directory
# MBEDTLS_LIBRARIES - Link these to use mbedTLS
# MBEDTLS_LIBRARY - path to mbedTLS library
# MBEDX509_LIBRARY - path to mbedTLS X.509 library
# MBEDCRYPTO_LIBRARY - path to mbedTLS Crypto library
#
# Hint
# MBEDTLS_ROOT_DIR can be pointed to a local mbedTLS installation.
SET(_MBEDTLS_ROOT_HINTS
${MBEDTLS_ROOT_DIR}
ENV MBEDTLS_ROOT_DIR
)
SET(_MBEDTLS_ROOT_HINTS_AND_PATHS
HINTS ${_MBEDTLS_ROOT_HINTS}
PATHS ${_MBEDTLS_ROOT_PATHS}
)
FIND_PATH(MBEDTLS_INCLUDE_DIR
NAMES mbedtls/version.h
${_MBEDTLS_ROOT_HINTS_AND_PATHS}
PATH_SUFFIXES include
)
IF(MBEDTLS_INCLUDE_DIR AND MBEDTLS_LIBRARIES)
# Already in cache, be silent
SET(MBEDTLS_FIND_QUIETLY TRUE)
ENDIF()
FIND_LIBRARY(MBEDTLS_LIBRARY
NAMES mbedtls libmbedtls
${_MBEDTLS_ROOT_HINTS_AND_PATHS}
PATH_SUFFIXES library
)
FIND_LIBRARY(MBEDX509_LIBRARY
NAMES mbedx509 libmbedx509
${_MBEDTLS_ROOT_HINTS_AND_PATHS}
PATH_SUFFIXES library
)
FIND_LIBRARY(MBEDCRYPTO_LIBRARY
NAMES mbedcrypto libmbedcrypto
${_MBEDTLS_ROOT_HINTS_AND_PATHS}
PATH_SUFFIXES library
)
IF(MBEDTLS_INCLUDE_DIR AND MBEDTLS_LIBRARY AND MBEDX509_LIBRARY AND MBEDCRYPTO_LIBRARY)
SET(MBEDTLS_FOUND TRUE)
ENDIF()
IF(MBEDTLS_FOUND)
# split mbedTLS into -L and -l linker options, so we can set them for pkg-config
GET_FILENAME_COMPONENT(MBEDTLS_LIBRARY_DIR ${MBEDTLS_LIBRARY} PATH)
GET_FILENAME_COMPONENT(MBEDTLS_LIBRARY_FILE ${MBEDTLS_LIBRARY} NAME_WE)
GET_FILENAME_COMPONENT(MBEDX509_LIBRARY_FILE ${MBEDX509_LIBRARY} NAME_WE)
GET_FILENAME_COMPONENT(MBEDCRYPTO_LIBRARY_FILE ${MBEDCRYPTO_LIBRARY} NAME_WE)
STRING(REGEX REPLACE "^lib" "" MBEDTLS_LIBRARY_FILE ${MBEDTLS_LIBRARY_FILE})
STRING(REGEX REPLACE "^lib" "" MBEDX509_LIBRARY_FILE ${MBEDX509_LIBRARY_FILE})
STRING(REGEX REPLACE "^lib" "" MBEDCRYPTO_LIBRARY_FILE ${MBEDCRYPTO_LIBRARY_FILE})
SET(MBEDTLS_LIBRARIES "-L${MBEDTLS_LIBRARY_DIR} -l${MBEDTLS_LIBRARY_FILE} -l${MBEDX509_LIBRARY_FILE} -l${MBEDCRYPTO_LIBRARY_FILE}")
IF(NOT MBEDTLS_FIND_QUIETLY)
MESSAGE(STATUS "Found mbedTLS:")
FILE(READ ${MBEDTLS_INCLUDE_DIR}/mbedtls/version.h MBEDTLSCONTENT)
STRING(REGEX MATCH "MBEDTLS_VERSION_STRING +\"[0-9|.]+\"" MBEDTLSMATCH ${MBEDTLSCONTENT})
IF (MBEDTLSMATCH)
STRING(REGEX REPLACE "MBEDTLS_VERSION_STRING +\"([0-9|.]+)\"" "\\1" MBEDTLS_VERSION ${MBEDTLSMATCH})
MESSAGE(STATUS " version ${MBEDTLS_VERSION}")
ENDIF(MBEDTLSMATCH)
MESSAGE(STATUS " TLS: ${MBEDTLS_LIBRARY}")
MESSAGE(STATUS " X509: ${MBEDX509_LIBRARY}")
MESSAGE(STATUS " Crypto: ${MBEDCRYPTO_LIBRARY}")
ENDIF(NOT MBEDTLS_FIND_QUIETLY)
ELSE(MBEDTLS_FOUND)
IF(MBEDTLS_FIND_REQUIRED)
MESSAGE(FATAL_ERROR "Could not find mbedTLS")
ENDIF(MBEDTLS_FIND_REQUIRED)
ENDIF(MBEDTLS_FOUND)
MARK_AS_ADVANCED(
MBEDTLS_INCLUDE_DIR
MBEDTLS_LIBRARY_DIR
MBEDTLS_LIBRARIES
MBEDTLS_LIBRARY
MBEDX509_LIBRARY
MBEDCRYPTO_LIBRARY
)
+3 -2
View File
@@ -1,5 +1,4 @@
CMAKE_MINIMUM_REQUIRED(VERSION 2.8) CMAKE_MINIMUM_REQUIRED(VERSION 3.10)
SET(common_sources SET(common_sources
base_packet.cpp base_packet.cpp
classes.cpp classes.cpp
@@ -212,6 +211,7 @@ SET(common_headers
xml_parser.h xml_parser.h
zone_numbers.h zone_numbers.h
event/event_loop.h event/event_loop.h
event/idle.h
event/task.h event/task.h
event/timer.h event/timer.h
json/json.h json/json.h
@@ -272,6 +272,7 @@ SET(common_headers
SOURCE_GROUP(Event FILES SOURCE_GROUP(Event FILES
event/event_loop.h event/event_loop.h
event/idle.h
event/timer.h event/timer.h
event/task.h event/task.h
) )
+1 -1
View File
@@ -23,7 +23,7 @@
* 2005-08-05 v5 - Removed most Lint (http://www.gimpel.com/) errors... thanks to Okko Willeboordse! * 2005-08-05 v5 - Removed most Lint (http://www.gimpel.com/) errors... thanks to Okko Willeboordse!
* *
**********************************************************************/ **********************************************************************/
#ifdef _WINDOWS #ifdef _WIN32
#include <windows.h> #include <windows.h>
#include <tchar.h> #include <tchar.h>
#include <stdio.h> #include <stdio.h>
+1 -1
View File
@@ -9,7 +9,7 @@
* 2013-01-26 - Modified by KimLS(KLS) for EQEmu's purposes * 2013-01-26 - Modified by KimLS(KLS) for EQEmu's purposes
* *
**********************************************************************/ **********************************************************************/
#ifdef _WINDOWS #ifdef _WIN32
// #pragma once is supported starting with _MCS_VER 1000, // #pragma once is supported starting with _MCS_VER 1000,
// so we need not to check the version (because we only support _MSC_VER >= 1100)! // so we need not to check the version (because we only support _MSC_VER >= 1100)!
#pragma once #pragma once
+1 -1
View File
@@ -23,7 +23,7 @@
#include <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>
#ifdef _WINDOWS #ifdef _WIN32
#include <time.h> #include <time.h>
#include <winsock2.h> #include <winsock2.h>
#include <windows.h> #include <windows.h>
+1 -1
View File
@@ -18,7 +18,7 @@
#include "condition.h" #include "condition.h"
#ifdef _WINDOWS #ifdef _WIN32
Condition::Condition() Condition::Condition()
{ {
+2 -2
View File
@@ -20,7 +20,7 @@
#include "global_define.h" #include "global_define.h"
#include "mutex.h" #include "mutex.h"
#ifndef WIN32 #ifndef _WIN32
#include <pthread.h> #include <pthread.h>
#endif #endif
@@ -30,7 +30,7 @@
class Condition { class Condition {
private: private:
#ifdef WIN32 #ifdef _WIN32
enum { enum {
SignalEvent = 0, SignalEvent = 0,
BroadcastEvent, BroadcastEvent,
+1 -1
View File
@@ -2,7 +2,7 @@
#include "eqemu_logsys.h" #include "eqemu_logsys.h"
#include "crash.h" #include "crash.h"
#if defined(_WINDOWS) && defined(CRASH_LOGGING) #if defined(_WIN32) && defined(CRASH_LOGGING)
#include "StackWalker.h" #include "StackWalker.h"
class EQEmuStackWalker : public StackWalker class EQEmuStackWalker : public StackWalker
+1 -1
View File
@@ -30,7 +30,7 @@
#include <string.h> #include <string.h>
// Disgrace: for windows compile // Disgrace: for windows compile
#ifdef _WINDOWS #ifdef _WIN32
#include <windows.h> #include <windows.h>
#define snprintf _snprintf #define snprintf _snprintf
#define strncasecmp _strnicmp #define strncasecmp _strnicmp
-10
View File
@@ -82,17 +82,7 @@ struct VarCache_Struct {
}; };
class PTimerList; class PTimerList;
#ifdef _WINDOWS
#if _MSC_VER > 1700 // greater than 2012 (2013+)
# define _ISNAN_(a) std::isnan(a) # define _ISNAN_(a) std::isnan(a)
#else
# include <float.h>
# define _ISNAN_(a) _isnan(a)
#endif
#else
# define _ISNAN_(a) std::isnan(a)
#endif
#define SQL(...) #__VA_ARGS__ #define SQL(...) #__VA_ARGS__
+1 -1
View File
@@ -28,7 +28,7 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#include <iostream> #include <iostream>
// Disgrace: for windows compile // Disgrace: for windows compile
#ifdef _WINDOWS #ifdef _WIN32
#include <windows.h> #include <windows.h>
#define snprintf _snprintf #define snprintf _snprintf
#define strncasecmp _strnicmp #define strncasecmp _strnicmp
+1 -1
View File
@@ -27,7 +27,7 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#include <iostream> #include <iostream>
// Disgrace: for windows compile // Disgrace: for windows compile
#ifdef _WINDOWS #ifdef _WIN32
#include <windows.h> #include <windows.h>
#define snprintf _snprintf #define snprintf _snprintf
#define strncasecmp _strnicmp #define strncasecmp _strnicmp
+2 -2
View File
@@ -1,4 +1,4 @@
#ifdef _WINDOWS #ifdef _WIN32
#include <winsock2.h> #include <winsock2.h>
#endif #endif
@@ -13,7 +13,7 @@
#include <mysqld_error.h> #include <mysqld_error.h>
#include <string.h> #include <string.h>
#ifdef _WINDOWS #ifdef _WIN32
#define snprintf _snprintf #define snprintf _snprintf
#define strncasecmp _strnicmp #define strncasecmp _strnicmp
#define strcasecmp _stricmp #define strcasecmp _stricmp
+1 -1
View File
@@ -1,7 +1,7 @@
#ifndef DBCORE_H #ifndef DBCORE_H
#define DBCORE_H #define DBCORE_H
#ifdef _WINDOWS #ifdef _WIN32
#include <winsock2.h> #include <winsock2.h>
#include <windows.h> #include <windows.h>
#endif #endif
+1 -1
View File
@@ -152,7 +152,7 @@ void EQEmuConfig::parse_config()
TerminateWait = atoi(_root["server"]["launcher"]["timers"].get("reterminate", "10000").asString().c_str()); TerminateWait = atoi(_root["server"]["launcher"]["timers"].get("reterminate", "10000").asString().c_str());
InitialBootWait = atoi(_root["server"]["launcher"]["timers"].get("initial", "20000").asString().c_str()); InitialBootWait = atoi(_root["server"]["launcher"]["timers"].get("initial", "20000").asString().c_str());
ZoneBootInterval = atoi(_root["server"]["launcher"]["timers"].get("interval", "2000").asString().c_str()); ZoneBootInterval = atoi(_root["server"]["launcher"]["timers"].get("interval", "2000").asString().c_str());
#ifdef WIN32 #ifdef _WIN32
ZoneExe = _root["server"]["launcher"].get("exe", "zone.exe").asString(); ZoneExe = _root["server"]["launcher"].get("exe", "zone.exe").asString();
#else #else
ZoneExe = _root["server"]["launcher"].get("exe", "./zone").asString(); ZoneExe = _root["server"]["launcher"].get("exe", "./zone").asString();
+3 -3
View File
@@ -33,7 +33,7 @@
std::ofstream process_log; std::ofstream process_log;
#ifdef _WINDOWS #ifdef _WIN32
#include <direct.h> #include <direct.h>
#include <conio.h> #include <conio.h>
#include <iostream> #include <iostream>
@@ -324,7 +324,7 @@ uint16 EQEmuLogSys::GetGMSayColorFromCategory(uint16 log_category)
*/ */
void EQEmuLogSys::ProcessConsoleMessage(uint16 debug_level, uint16 log_category, const std::string &message) void EQEmuLogSys::ProcessConsoleMessage(uint16 debug_level, uint16 log_category, const std::string &message)
{ {
#ifdef _WINDOWS #ifdef _WIN32
HANDLE console_handle; HANDLE console_handle;
console_handle = GetStdHandle(STD_OUTPUT_HANDLE); console_handle = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_FONT_INFOEX info = { 0 }; CONSOLE_FONT_INFOEX info = { 0 };
@@ -408,7 +408,7 @@ void EQEmuLogSys::SetCurrentTimeStamp(char *time_stamp)
*/ */
void EQEmuLogSys::MakeDirectory(const std::string &directory_name) void EQEmuLogSys::MakeDirectory(const std::string &directory_name)
{ {
#ifdef _WINDOWS #ifdef _WIN32
struct _stat st; struct _stat st;
if (_stat(directory_name.c_str(), &st) == 0) // exists if (_stat(directory_name.c_str(), &st) == 0) // exists
return; return;
+11 -11
View File
@@ -8,15 +8,23 @@ namespace EQ
class EventLoop class EventLoop
{ {
public: public:
static EventLoop &Get() { EventLoop() {
static thread_local EventLoop inst; memset(&m_loop, 0, sizeof(uv_loop_t));
return inst; uv_loop_init(&m_loop);
} }
~EventLoop() { ~EventLoop() {
uv_loop_close(&m_loop); uv_loop_close(&m_loop);
} }
EventLoop(const EventLoop&) = delete;
EventLoop& operator=(const EventLoop&) = delete;
static EventLoop &GetDefault() {
static thread_local EventLoop inst;
return inst;
}
void Process() { void Process() {
uv_run(&m_loop, UV_RUN_NOWAIT); uv_run(&m_loop, UV_RUN_NOWAIT);
} }
@@ -24,14 +32,6 @@ namespace EQ
uv_loop_t* Handle() { return &m_loop; } uv_loop_t* Handle() { return &m_loop; }
private: private:
EventLoop() {
memset(&m_loop, 0, sizeof(uv_loop_t));
uv_loop_init(&m_loop);
}
EventLoop(const EventLoop&);
EventLoop& operator=(const EventLoop&);
uv_loop_t m_loop; uv_loop_t m_loop;
}; };
} }
View File
+22 -17
View File
@@ -24,8 +24,12 @@ namespace EQ {
std::exception error; std::exception error;
}; };
Task(TaskFn fn) { Task(EventLoop &loop, TaskFn fn) : _loop(loop) {
m_fn = fn; _fn = fn;
}
Task(TaskFn fn) : _loop(EventLoop::GetDefault()) {
_fn = fn;
} }
~Task() { ~Task() {
@@ -33,34 +37,34 @@ namespace EQ {
} }
Task& Then(ResolveFn fn) { Task& Then(ResolveFn fn) {
m_then = fn; _then = fn;
return *this; return *this;
} }
Task& Catch(RejectFn fn) { Task& Catch(RejectFn fn) {
m_catch = fn; _catch = fn;
return *this; return *this;
} }
Task& Finally(FinallyFn fn) { Task& Finally(FinallyFn fn) {
m_finally = fn; _fin = fn;
return *this; return *this;
} }
void Run() { void Run() {
uv_work_t *m_work = new uv_work_t; uv_work_t *work = new uv_work_t;
memset(m_work, 0, sizeof(uv_work_t)); memset(work, 0, sizeof(uv_work_t));
TaskBaton *baton = new TaskBaton(); TaskBaton *baton = new TaskBaton();
baton->fn = m_fn; baton->fn = _fn;
baton->on_then = m_then; baton->on_then = _then;
baton->on_catch = m_catch; baton->on_catch = _catch;
baton->on_finally = m_finally; baton->on_finally = _fin;
baton->has_result = false; baton->has_result = false;
baton->has_error = false; baton->has_error = false;
m_work->data = baton; work->data = baton;
uv_queue_work(EventLoop::Get().Handle(), m_work, [](uv_work_t* req) { uv_queue_work(_loop.Handle(), work, [](uv_work_t* req) {
TaskBaton *baton = (TaskBaton*)req->data; TaskBaton *baton = (TaskBaton*)req->data;
baton->fn([baton](const EQEmu::Any& result) { baton->fn([baton](const EQEmu::Any& result) {
@@ -92,9 +96,10 @@ namespace EQ {
} }
private: private:
TaskFn m_fn; TaskFn _fn;
ResolveFn m_then; ResolveFn _then;
RejectFn m_catch; RejectFn _catch;
FinallyFn m_finally; FinallyFn _fin;
EventLoop &_loop;
}; };
} }
+34 -20
View File
@@ -6,16 +6,29 @@ namespace EQ {
class Timer class Timer
{ {
public: public:
Timer(std::function<void(Timer *)> cb) Timer(EventLoop &loop, std::function<void(Timer *)> cb) : _loop(loop)
{ {
m_timer = nullptr; _timer = nullptr;
m_cb = cb; _cb = cb;
} }
Timer(uint64_t duration_ms, bool repeats, std::function<void(Timer *)> cb) Timer(EventLoop &loop, uint64_t duration_ms, bool repeats, std::function<void(Timer *)> cb) : _loop(loop)
{ {
m_timer = nullptr; _timer = nullptr;
m_cb = cb; _cb = cb;
Start(duration_ms, repeats);
}
Timer(std::function<void(Timer *)> cb) : _loop(EventLoop::GetDefault())
{
_timer = nullptr;
_cb = cb;
}
Timer(uint64_t duration_ms, bool repeats, std::function<void(Timer *)> cb) : _loop(EventLoop::GetDefault())
{
_timer = nullptr;
_cb = cb;
Start(duration_ms, repeats); Start(duration_ms, repeats);
} }
@@ -25,21 +38,21 @@ namespace EQ {
} }
void Start(uint64_t duration_ms, bool repeats) { void Start(uint64_t duration_ms, bool repeats) {
auto loop = EventLoop::Get().Handle(); auto loop = EventLoop::GetDefault().Handle();
if (!m_timer) { if (!_timer) {
m_timer = new uv_timer_t; _timer = new uv_timer_t;
memset(m_timer, 0, sizeof(uv_timer_t)); memset(_timer, 0, sizeof(uv_timer_t));
uv_timer_init(loop, m_timer); uv_timer_init(loop, _timer);
m_timer->data = this; _timer->data = this;
if (repeats) { if (repeats) {
uv_timer_start(m_timer, [](uv_timer_t *handle) { uv_timer_start(_timer, [](uv_timer_t *handle) {
Timer *t = (Timer*)handle->data; Timer *t = (Timer*)handle->data;
t->Execute(); t->Execute();
}, duration_ms, duration_ms); }, duration_ms, duration_ms);
} }
else { else {
uv_timer_start(m_timer, [](uv_timer_t *handle) { uv_timer_start(_timer, [](uv_timer_t *handle) {
Timer *t = (Timer*)handle->data; Timer *t = (Timer*)handle->data;
t->Stop(); t->Stop();
t->Execute(); t->Execute();
@@ -49,19 +62,20 @@ namespace EQ {
} }
void Stop() { void Stop() {
if (m_timer) { if (_timer) {
uv_close((uv_handle_t*)m_timer, [](uv_handle_t* handle) { uv_close((uv_handle_t*)_timer, [](uv_handle_t* handle) {
delete handle; delete handle;
}); });
m_timer = nullptr; _timer = nullptr;
} }
} }
private: private:
void Execute() { void Execute() {
m_cb(this); _cb(this);
} }
uv_timer_t *m_timer; EventLoop &_loop;
std::function<void(Timer*)> m_cb; uv_timer_t *_timer;
std::function<void(Timer*)> _cb;
}; };
} }
+2 -2
View File
@@ -17,7 +17,7 @@
*/ */
// WHY IS THIS UP HERE // WHY IS THIS UP HERE
#if defined(_DEBUG) && defined(WIN32) #if defined(_DEBUG) && defined(_WIN32)
#ifndef _CRTDBG_MAP_ALLOC #ifndef _CRTDBG_MAP_ALLOC
#include <stdlib.h> #include <stdlib.h>
#include <crtdbg.h> #include <crtdbg.h>
@@ -27,7 +27,7 @@
#ifndef EQDEBUG_H #ifndef EQDEBUG_H
#define EQDEBUG_H #define EQDEBUG_H
#ifdef _WINDOWS #ifdef _WIN32
#include <winsock2.h> #include <winsock2.h>
#include <windows.h> #include <windows.h>
#endif #endif
+1 -1
View File
@@ -23,6 +23,6 @@
#include "eq_packet_structs.h" #include "eq_packet_structs.h"
#ifndef WIN32 #ifndef _WIN32
#include <netinet/in.h> //for htonl #include <netinet/in.h> //for htonl
#endif #endif
+6 -6
View File
@@ -17,7 +17,7 @@
*/ */
#include "ipc_mutex.h" #include "ipc_mutex.h"
#ifdef _WINDOWS #ifdef _WIN32
#define WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN
#include <Windows.h> #include <Windows.h>
#undef WIN32_LEAN_AND_MEAN #undef WIN32_LEAN_AND_MEAN
@@ -33,7 +33,7 @@
namespace EQEmu { namespace EQEmu {
struct IPCMutex::Implementation { struct IPCMutex::Implementation {
#ifdef _WINDOWS #ifdef _WIN32
HANDLE mut_; HANDLE mut_;
#else #else
int fd_; int fd_;
@@ -42,7 +42,7 @@ namespace EQEmu {
IPCMutex::IPCMutex(std::string name) : locked_(false) { IPCMutex::IPCMutex(std::string name) : locked_(false) {
imp_ = new Implementation; imp_ = new Implementation;
#ifdef _WINDOWS #ifdef _WIN32
auto Config = EQEmuConfig::get(); auto Config = EQEmuConfig::get();
std::string final_name = Config->SharedMemDir + "EQEmuMutex_"; std::string final_name = Config->SharedMemDir + "EQEmuMutex_";
final_name += name; final_name += name;
@@ -82,7 +82,7 @@ namespace EQEmu {
} }
IPCMutex::~IPCMutex() { IPCMutex::~IPCMutex() {
#ifdef _WINDOWS #ifdef _WIN32
if(locked_) { if(locked_) {
ReleaseMutex(imp_->mut_); ReleaseMutex(imp_->mut_);
} }
@@ -103,7 +103,7 @@ namespace EQEmu {
return false; return false;
} }
#ifdef _WINDOWS #ifdef _WIN32
DWORD wait_result = WaitForSingleObject(imp_->mut_, INFINITE); DWORD wait_result = WaitForSingleObject(imp_->mut_, INFINITE);
if(wait_result != WAIT_OBJECT_0) { if(wait_result != WAIT_OBJECT_0) {
return false; return false;
@@ -121,7 +121,7 @@ namespace EQEmu {
if(!locked_) { if(!locked_) {
return false; return false;
} }
#ifdef _WINDOWS #ifdef _WIN32
if(!ReleaseMutex(imp_->mut_)) { if(!ReleaseMutex(imp_->mut_)) {
return false; return false;
} }
+5 -5
View File
@@ -17,7 +17,7 @@
*/ */
#include "memory_mapped_file.h" #include "memory_mapped_file.h"
#ifdef _WINDOWS #ifdef _WIN32
#include <windows.h> #include <windows.h>
#else #else
#include <sys/types.h> #include <sys/types.h>
@@ -36,7 +36,7 @@
namespace EQEmu { namespace EQEmu {
struct MemoryMappedFile::Implementation { struct MemoryMappedFile::Implementation {
#ifdef _WINDOWS #ifdef _WIN32
HANDLE mapped_object_; HANDLE mapped_object_;
#else #else
int fd_; int fd_;
@@ -47,7 +47,7 @@ namespace EQEmu {
: filename_(filename), size_(size) { : filename_(filename), size_(size) {
imp_ = new Implementation; imp_ = new Implementation;
#ifdef _WINDOWS #ifdef _WIN32
DWORD total_size = size + sizeof(shared_memory_struct); DWORD total_size = size + sizeof(shared_memory_struct);
HANDLE file = CreateFile(filename.c_str(), HANDLE file = CreateFile(filename.c_str(),
GENERIC_READ | GENERIC_WRITE, GENERIC_READ | GENERIC_WRITE,
@@ -116,7 +116,7 @@ namespace EQEmu {
size_ = size; size_ = size;
fclose(f); fclose(f);
#ifdef _WINDOWS #ifdef _WIN32
DWORD total_size = size + sizeof(shared_memory_struct); DWORD total_size = size + sizeof(shared_memory_struct);
HANDLE file = CreateFile(filename.c_str(), HANDLE file = CreateFile(filename.c_str(),
GENERIC_READ | GENERIC_WRITE, GENERIC_READ | GENERIC_WRITE,
@@ -172,7 +172,7 @@ namespace EQEmu {
} }
MemoryMappedFile::~MemoryMappedFile() { MemoryMappedFile::~MemoryMappedFile() {
#ifdef _WINDOWS #ifdef _WIN32
if(imp_->mapped_object_) { if(imp_->mapped_object_) {
CloseHandle(imp_->mapped_object_); CloseHandle(imp_->mapped_object_);
} }
+4 -4
View File
@@ -1,4 +1,4 @@
#ifdef _WINDOWS #ifdef _WIN32
// VS6 doesn't like the length of STL generated names: disabling // VS6 doesn't like the length of STL generated names: disabling
#pragma warning(disable:4786) #pragma warning(disable:4786)
#endif #endif
@@ -10,7 +10,7 @@
#include <iostream> #include <iostream>
#include <zlib.h> #include <zlib.h>
#ifndef WIN32 #ifndef _WIN32
#include <sys/time.h> #include <sys/time.h>
#endif #endif
@@ -24,7 +24,7 @@
std::map<int,std::string> DBFieldNames; std::map<int,std::string> DBFieldNames;
#ifndef WIN32 #ifndef _WIN32
#if defined(FREEBSD) || defined(__CYGWIN__) #if defined(FREEBSD) || defined(__CYGWIN__)
int print_stacktrace() int print_stacktrace()
{ {
@@ -526,7 +526,7 @@ std::string generate_key(int length)
{ {
std::string key; std::string key;
//TODO: write this for win32... //TODO: write this for win32...
#ifndef WIN32 #ifndef _WIN32
int i; int i;
timeval now; timeval now;
static const char *chars="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; static const char *chars="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
+1 -1
View File
@@ -24,7 +24,7 @@ void decode(char *in, char *out);
void encode_chunk(char *in, int len, char *out); void encode_chunk(char *in, int len, char *out);
void decode_chunk(char *in, char *out); void decode_chunk(char *in, char *out);
#ifndef WIN32 #ifndef _WIN32
int print_stacktrace(); int print_stacktrace();
#endif #endif
+10 -10
View File
@@ -22,19 +22,19 @@
#include <string.h> #include <string.h>
#include <time.h> #include <time.h>
#ifndef WIN32 #ifndef _WIN32
#include <netinet/in.h> #include <netinet/in.h>
#include <sys/socket.h> #include <sys/socket.h>
#endif #endif
#include <iostream> #include <iostream>
#include <iomanip> #include <iomanip>
#ifdef _WINDOWS #ifdef _WIN32
#include <io.h> #include <io.h>
#endif #endif
#include "../common/timer.h" #include "../common/timer.h"
#include "../common/seperator.h" #include "../common/seperator.h"
#ifdef _WINDOWS #ifdef _WIN32
#include <windows.h> #include <windows.h>
#define snprintf _snprintf #define snprintf _snprintf
@@ -73,7 +73,7 @@ void CoutTimestamp(bool ms) {
int32 filesize(FILE* fp) { int32 filesize(FILE* fp) {
#ifdef _WINDOWS #ifdef _WIN32
return _filelength(_fileno(fp)); return _filelength(_fileno(fp));
#else #else
struct stat file_stat; struct stat file_stat;
@@ -88,7 +88,7 @@ int32 filesize(FILE* fp) {
} }
uint32 ResolveIP(const char* hostname, char* errbuf) { uint32 ResolveIP(const char* hostname, char* errbuf) {
#ifdef _WINDOWS #ifdef _WIN32
static InitWinsock ws; static InitWinsock ws;
#endif #endif
if (errbuf) if (errbuf)
@@ -99,14 +99,14 @@ uint32 ResolveIP(const char* hostname, char* errbuf) {
return 0; return 0;
} }
struct sockaddr_in server_sin; struct sockaddr_in server_sin;
#ifdef _WINDOWS #ifdef _WIN32
PHOSTENT phostent = nullptr; PHOSTENT phostent = nullptr;
#else #else
struct hostent *phostent = nullptr; struct hostent *phostent = nullptr;
#endif #endif
server_sin.sin_family = AF_INET; server_sin.sin_family = AF_INET;
if ((phostent = gethostbyname(hostname)) == nullptr) { if ((phostent = gethostbyname(hostname)) == nullptr) {
#ifdef _WINDOWS #ifdef _WIN32
if (errbuf) if (errbuf)
snprintf(errbuf, ERRBUF_SIZE, "Unable to get the host name. Error: %i", WSAGetLastError()); snprintf(errbuf, ERRBUF_SIZE, "Unable to get the host name. Error: %i", WSAGetLastError());
#else #else
@@ -115,7 +115,7 @@ uint32 ResolveIP(const char* hostname, char* errbuf) {
#endif #endif
return 0; return 0;
} }
#ifdef _WINDOWS #ifdef _WIN32
memcpy ((char FAR *)&(server_sin.sin_addr), phostent->h_addr, phostent->h_length); memcpy ((char FAR *)&(server_sin.sin_addr), phostent->h_addr, phostent->h_length);
#else #else
memcpy ((char*)&(server_sin.sin_addr), phostent->h_addr, phostent->h_length); memcpy ((char*)&(server_sin.sin_addr), phostent->h_addr, phostent->h_length);
@@ -136,7 +136,7 @@ bool ParseAddress(const char* iAddress, uint32* oIP, uint16* oPort, char* errbuf
return false; return false;
} }
#ifdef _WINDOWS #ifdef _WIN32
InitWinsock::InitWinsock() { InitWinsock::InitWinsock() {
WORD version = MAKEWORD (1,1); WORD version = MAKEWORD (1,1);
WSADATA wsadata; WSADATA wsadata;
@@ -157,7 +157,7 @@ const char * itoa(int num) {
return temp; return temp;
} }
#ifndef WIN32 #ifndef _WIN32
const char * itoa(int num, char* a,int b) { const char * itoa(int num, char* a,int b) {
static char temp[_ITOA_BUFLEN]; static char temp[_ITOA_BUFLEN];
memset(temp,0,_ITOA_BUFLEN); memset(temp,0,_ITOA_BUFLEN);
+1 -1
View File
@@ -77,7 +77,7 @@ uint32 Catch22(uint32 mask);
#define _ITOA_BUFLEN 25 #define _ITOA_BUFLEN 25
const char *itoa(int num); //not thread safe const char *itoa(int num); //not thread safe
#ifndef _WINDOWS #ifndef _WIN32
const char *itoa(int num, char* a,int b); const char *itoa(int num, char* a,int b);
#endif #endif
+7 -7
View File
@@ -25,7 +25,7 @@
#endif #endif
#ifdef _WINDOWS #ifdef _WIN32
bool IsTryLockSupported(); bool IsTryLockSupported();
bool TrylockSupported = IsTryLockSupported(); bool TrylockSupported = IsTryLockSupported();
@@ -69,7 +69,7 @@ Mutex::Mutex() {
#if DEBUG_MUTEX_CLASS >= 7 #if DEBUG_MUTEX_CLASS >= 7
std::cout << "Constructing Mutex" << std::endl; std::cout << "Constructing Mutex" << std::endl;
#endif #endif
#ifdef _WINDOWS #ifdef _WIN32
InitializeCriticalSection(&CSMutex); InitializeCriticalSection(&CSMutex);
#else #else
pthread_mutexattr_t attr; pthread_mutexattr_t attr;
@@ -85,7 +85,7 @@ Mutex::Mutex() {
} }
Mutex::~Mutex() { Mutex::~Mutex() {
#ifdef _WINDOWS #ifdef _WIN32
DeleteCriticalSection(&CSMutex); DeleteCriticalSection(&CSMutex);
#else #else
#endif #endif
@@ -95,14 +95,14 @@ void Mutex::lock() {
#if DEBUG_MUTEX_CLASS >= 5 #if DEBUG_MUTEX_CLASS >= 5
if (!trylock()) { if (!trylock()) {
std::cout << "Locking Mutex: Having to wait" << std::endl; std::cout << "Locking Mutex: Having to wait" << std::endl;
#ifdef _WINDOWS #ifdef _WIN32
EnterCriticalSection(&CSMutex); EnterCriticalSection(&CSMutex);
#else #else
pthread_mutex_lock(&CSMutex); pthread_mutex_lock(&CSMutex);
#endif #endif
} }
#else #else
#ifdef _WINDOWS #ifdef _WIN32
EnterCriticalSection(&CSMutex); EnterCriticalSection(&CSMutex);
#else #else
pthread_mutex_lock(&CSMutex); pthread_mutex_lock(&CSMutex);
@@ -111,7 +111,7 @@ void Mutex::lock() {
} }
bool Mutex::trylock() { bool Mutex::trylock() {
#ifdef _WINDOWS #ifdef _WIN32
#if(_WIN32_WINNT >= 0x0400) #if(_WIN32_WINNT >= 0x0400)
if (TrylockSupported) if (TrylockSupported)
return TryEnterCriticalSection(&CSMutex); return TryEnterCriticalSection(&CSMutex);
@@ -129,7 +129,7 @@ bool Mutex::trylock() {
} }
void Mutex::unlock() { void Mutex::unlock() {
#ifdef _WINDOWS #ifdef _WIN32
LeaveCriticalSection(&CSMutex); LeaveCriticalSection(&CSMutex);
#else #else
pthread_mutex_unlock(&CSMutex); pthread_mutex_unlock(&CSMutex);
+2 -2
View File
@@ -17,7 +17,7 @@
*/ */
#ifndef MYMUTEX_H #ifndef MYMUTEX_H
#define MYMUTEX_H #define MYMUTEX_H
#ifdef _WINDOWS #ifdef _WIN32
#include <winsock2.h> #include <winsock2.h>
#include <windows.h> #include <windows.h>
#else #else
@@ -36,7 +36,7 @@ public:
bool trylock(); bool trylock();
protected: protected:
private: private:
#if defined WIN32 || defined WIN64 #if defined _WIN32
CRITICAL_SECTION CSMutex; CRITICAL_SECTION CSMutex;
#else #else
pthread_mutex_t CSMutex; pthread_mutex_t CSMutex;
+1 -1
View File
@@ -1,7 +1,7 @@
#ifndef MYSQL_REQUEST_RESULT_H #ifndef MYSQL_REQUEST_RESULT_H
#define MYSQL_REQUEST_RESULT_H #define MYSQL_REQUEST_RESULT_H
#ifdef _WINDOWS #ifdef _WIN32
#include <winsock2.h> #include <winsock2.h>
#include <windows.h> #include <windows.h>
#endif #endif
+1 -1
View File
@@ -1,7 +1,7 @@
#ifndef MYSQL_REQUEST_ROW_H #ifndef MYSQL_REQUEST_ROW_H
#define MYSQL_REQUEST_ROW_H #define MYSQL_REQUEST_ROW_H
#ifdef _WINDOWS #ifdef _WIN32
#include <winsock2.h> #include <winsock2.h>
#include <windows.h> #include <windows.h>
#endif #endif
+2 -2
View File
@@ -13,7 +13,7 @@ EQ::Net::DaybreakConnectionManager::DaybreakConnectionManager()
memset(&m_timer, 0, sizeof(uv_timer_t)); memset(&m_timer, 0, sizeof(uv_timer_t));
memset(&m_socket, 0, sizeof(uv_udp_t)); memset(&m_socket, 0, sizeof(uv_udp_t));
Attach(EQ::EventLoop::Get().Handle()); Attach(EQ::EventLoop::GetDefault().Handle());
} }
EQ::Net::DaybreakConnectionManager::DaybreakConnectionManager(const DaybreakConnectionManagerOptions &opts) EQ::Net::DaybreakConnectionManager::DaybreakConnectionManager(const DaybreakConnectionManagerOptions &opts)
@@ -23,7 +23,7 @@ EQ::Net::DaybreakConnectionManager::DaybreakConnectionManager(const DaybreakConn
memset(&m_timer, 0, sizeof(uv_timer_t)); memset(&m_timer, 0, sizeof(uv_timer_t));
memset(&m_socket, 0, sizeof(uv_udp_t)); memset(&m_socket, 0, sizeof(uv_udp_t));
Attach(EQ::EventLoop::Get().Handle()); Attach(EQ::EventLoop::GetDefault().Handle());
} }
EQ::Net::DaybreakConnectionManager::~DaybreakConnectionManager() EQ::Net::DaybreakConnectionManager::~DaybreakConnectionManager()
+1 -1
View File
@@ -21,7 +21,7 @@ namespace EQ
hints.ai_socktype = SOCK_STREAM; hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP; hints.ai_protocol = IPPROTO_TCP;
auto loop = EQ::EventLoop::Get().Handle(); auto loop = EQ::EventLoop::GetDefault().Handle();
uv_getaddrinfo_t *resolver = new uv_getaddrinfo_t(); uv_getaddrinfo_t *resolver = new uv_getaddrinfo_t();
memset(resolver, 0, sizeof(uv_getaddrinfo_t)); memset(resolver, 0, sizeof(uv_getaddrinfo_t));
auto port_str = std::to_string(port); auto port_str = std::to_string(port);
+6 -279
View File
@@ -1,279 +1,16 @@
#include "packet.h" #include "packet.h"
#include "endian.h" #include <fmt/format.h>
#include <cctype> #include <cctype>
#include <fmt/format.h> #include <fmt/format.h>
void EQ::Net::Packet::PutInt8(size_t offset, int8_t value) bool EQ::Net::StaticPacket::Resize(size_t new_size)
{ {
if (Length() < offset + 1) { if (new_size > _max_len) {
if (!Resize(offset + 1)) { return false;
throw std::out_of_range("Packet::PutInt8(), could not resize packet and would of written past the end.");
}
} }
*(int8_t*)((char*)Data() + offset) = value; _len = new_size;
} return true;
void EQ::Net::Packet::PutInt16(size_t offset, int16_t value)
{
if (Length() < offset + 2) {
if (!Resize(offset + 2)) {
throw std::out_of_range("Packet::PutInt16(), could not resize packet and would of written past the end.");
}
}
*(int16_t*)((char*)Data() + offset) = value;
}
void EQ::Net::Packet::PutInt32(size_t offset, int32_t value)
{
if (Length() < offset + 4) {
if (!Resize(offset + 4)) {
throw std::out_of_range("Packet::PutInt32(), could not resize packet and would of written past the end.");
}
}
*(int32_t*)((char*)Data() + offset) = value;
}
void EQ::Net::Packet::PutInt64(size_t offset, int64_t value)
{
if (Length() < offset + 8) {
if (!Resize(offset + 8)) {
throw std::out_of_range("Packet::PutInt64(), could not resize packet and would of written past the end.");
}
}
*(int64_t*)((char*)Data() + offset) = value;
}
void EQ::Net::Packet::PutUInt8(size_t offset, uint8_t value)
{
if (Length() < offset + 1) {
if (!Resize(offset + 1)) {
throw std::out_of_range("Packet::PutUInt8(), could not resize packet and would of written past the end.");
}
}
*(uint8_t*)((char*)Data() + offset) = value;
}
void EQ::Net::Packet::PutUInt16(size_t offset, uint16_t value)
{
if (Length() < offset + 2) {
if (!Resize(offset + 2)) {
throw std::out_of_range("Packet::PutUInt16(), could not resize packet and would of written past the end.");
}
}
*(uint16_t*)((char*)Data() + offset) = value;
}
void EQ::Net::Packet::PutUInt32(size_t offset, uint32_t value)
{
if (Length() < offset + 4) {
if (!Resize(offset + 4)) {
throw std::out_of_range("Packet::PutUInt32(), could not resize packet and would of written past the end.");
}
}
*(uint32_t*)((char*)Data() + offset) = value;
}
void EQ::Net::Packet::PutUInt64(size_t offset, uint64_t value)
{
if (Length() < offset + 8) {
if (!Resize(offset + 8)) {
throw std::out_of_range("Packet::PutUInt64(), could not resize packet and would of written past the end.");
}
}
*(uint64_t*)((char*)Data() + offset) = value;
}
void EQ::Net::Packet::PutFloat(size_t offset, float value)
{
if (Length() < offset + 4) {
if (!Resize(offset + 4)) {
throw std::out_of_range("Packet::PutFloat(), could not resize packet and would of written past the end.");
}
}
*(float*)((char*)Data() + offset) = value;
}
void EQ::Net::Packet::PutDouble(size_t offset, double value)
{
if (Length() < offset + 8) {
if (!Resize(offset + 8)) {
throw std::out_of_range("Packet::PutDouble(), could not resize packet and would of written past the end.");
}
}
*(double*)((char*)Data() + offset) = value;
}
void EQ::Net::Packet::PutString(size_t offset, const std::string &str)
{
if (Length() < offset + str.length()) {
if (!Resize(offset + str.length())) {
throw std::out_of_range("Packet::PutString(), could not resize packet and would of written past the end.");
}
}
memcpy(((char*)Data() + offset), str.c_str(), str.length());
}
void EQ::Net::Packet::PutCString(size_t offset, const char *str)
{
size_t sz = strlen(str);
if (Length() < offset + sz + 1) {
if (!Resize(offset + sz + 1)) {
throw std::out_of_range("Packet::PutCString(), could not resize packet and would of written past the end.");
}
}
memcpy(((char*)Data() + offset), str, sz);
*((char*)Data() + offset + sz) = 0;
}
void EQ::Net::Packet::PutPacket(size_t offset, const Packet &p)
{
if (p.Length() == 0) {
return;
}
if (Length() < offset + p.Length()) {
if (!Resize(offset + p.Length())) {
throw std::out_of_range("Packet::PutPacket(), could not resize packet and would of written past the end.");
}
}
memcpy(((char*)Data() + offset), p.Data(), p.Length());
}
void EQ::Net::Packet::PutData(size_t offset, void *data, size_t length)
{
if (length == 0) {
return;
}
if (Length() < offset + length) {
if (!Resize(offset + length)) {
throw std::out_of_range("Packet::PutData(), could not resize packet and would of written past the end.");
}
}
memcpy(((char*)Data() + offset), data, length);
}
int8_t EQ::Net::Packet::GetInt8(size_t offset) const
{
if (Length() < offset + 1) {
throw std::out_of_range("Packet read out of range.");
}
return *(int8_t*)((char*)Data() + offset);
}
int16_t EQ::Net::Packet::GetInt16(size_t offset) const
{
if (Length() < offset + 2) {
throw std::out_of_range("Packet read out of range.");
}
return *(int16_t*)((char*)Data() + offset);
}
int32_t EQ::Net::Packet::GetInt32(size_t offset) const
{
if (Length() < offset + 4) {
throw std::out_of_range("Packet read out of range.");
}
return *(int32_t*)((char*)Data() + offset);
}
int64_t EQ::Net::Packet::GetInt64(size_t offset) const
{
if (Length() < offset + 8) {
throw std::out_of_range("Packet read out of range.");
}
return *(int64_t*)((char*)Data() + offset);
}
uint8_t EQ::Net::Packet::GetUInt8(size_t offset) const
{
if (Length() < offset + 1) {
throw std::out_of_range("Packet read out of range.");
}
return *(uint8_t*)((char*)Data() + offset);
}
uint16_t EQ::Net::Packet::GetUInt16(size_t offset) const
{
if (Length() < offset + 2) {
throw std::out_of_range("Packet read out of range.");
}
return *(uint16_t*)((char*)Data() + offset);
}
uint32_t EQ::Net::Packet::GetUInt32(size_t offset) const
{
if (Length() < offset + 4) {
throw std::out_of_range("Packet read out of range.");
}
return *(uint32_t*)((char*)Data() + offset);
}
uint64_t EQ::Net::Packet::GetUInt64(size_t offset) const
{
if (Length() < offset + 8) {
throw std::out_of_range("Packet read out of range.");
}
return *(uint64_t*)((char*)Data() + offset);
}
float EQ::Net::Packet::GetFloat(size_t offset) const
{
if (Length() < offset + 4) {
throw std::out_of_range("Packet read out of range.");
}
return *(float*)((char*)Data() + offset);
}
double EQ::Net::Packet::GetDouble(size_t offset) const
{
if (Length() < offset + 8) {
throw std::out_of_range("Packet read out of range.");
}
return *(double*)((char*)Data() + offset);
}
std::string EQ::Net::Packet::GetString(size_t offset, size_t length) const
{
if (Length() < offset + length) {
throw std::out_of_range("Packet read out of range.");
}
return std::string((char*)Data() + offset, (char*)Data() + offset + length);
}
std::string EQ::Net::Packet::GetCString(size_t offset) const
{
if (Length() < offset + 1) {
throw std::out_of_range("Packet read out of range.");
}
char *str = ((char*)Data() + offset);
return std::string(str);
} }
char ToSafePrint(unsigned char in) { char ToSafePrint(unsigned char in) {
@@ -342,13 +79,3 @@ std::string EQ::Net::Packet::ToString(size_t line_length) const
return ret; return ret;
} }
bool EQ::Net::StaticPacket::Resize(size_t new_size)
{
if (new_size > m_max_data_length) {
return false;
}
m_data_length = new_size;
return true;
}
+691 -67
View File
@@ -13,8 +13,7 @@ namespace EQ {
class Packet class Packet
{ {
public: public:
Packet() : m_stream(std::ios::out | std::ios::binary) { } Packet() = default;
virtual ~Packet() { }
virtual const void *Data() const = 0; virtual const void *Data() const = 0;
virtual void *Data() = 0; virtual void *Data() = 0;
@@ -24,6 +23,617 @@ namespace EQ {
virtual bool Resize(size_t new_size) = 0; virtual bool Resize(size_t new_size) = 0;
virtual void Reserve(size_t new_size) = 0; virtual void Reserve(size_t new_size) = 0;
std::string ToString() const;
std::string ToString(size_t line_length) const;
void SetWritePos(size_t offset) { _wpos = offset; }
void SetReadPos(size_t offset) { _rpos = offset; }
//Position Independent Output Interface
void PutInt8(size_t offset, int8_t value) {
if (Length() < offset + sizeof(int8_t)) {
if (!Resize(offset + sizeof(int8_t))) {
throw std::out_of_range("Packet::PutInt8(), could not resize packet and would of written past the end.");
}
}
*reinterpret_cast<int8_t*>(static_cast<char*>(Data()) + offset) = value;
_wpos = offset + sizeof(int8_t);
}
void PutInt16(size_t offset, int16_t value) {
if (Length() < offset + sizeof(int16_t)) {
if (!Resize(offset + sizeof(int16_t))) {
throw std::out_of_range("Packet::PutInt16(), could not resize packet and would of written past the end.");
}
}
*reinterpret_cast<int16_t*>(static_cast<char*>(Data()) + offset) = value;
_wpos = offset + sizeof(int16_t);
}
void PutInt32(size_t offset, int32_t value) {
if (Length() < offset + sizeof(int32_t)) {
if (!Resize(offset + sizeof(int32_t))) {
throw std::out_of_range("Packet::PutInt32(), could not resize packet and would of written past the end.");
}
}
*reinterpret_cast<int32_t*>(static_cast<char*>(Data()) + offset) = value;
_wpos = offset + sizeof(int32_t);
}
void PutInt64(size_t offset, int64_t value) {
if (Length() < offset + sizeof(int64_t)) {
if (!Resize(offset + sizeof(int64_t))) {
throw std::out_of_range("Packet::PutInt64(), could not resize packet and would of written past the end.");
}
}
*reinterpret_cast<int64_t*>(static_cast<char*>(Data()) + offset) = value;
_wpos = offset + sizeof(int64_t);
}
void PutUInt8(size_t offset, uint8_t value) {
if (Length() < offset + sizeof(uint8_t)) {
if (!Resize(offset + sizeof(uint8_t))) {
throw std::out_of_range("Packet::PutUInt8(), could not resize packet and would of written past the end.");
}
}
*reinterpret_cast<uint8_t*>(static_cast<char*>(Data()) + offset) = value;
_wpos = offset + sizeof(uint8_t);
}
void PutUInt16(size_t offset, uint16_t value) {
if (Length() < offset + sizeof(uint16_t)) {
if (!Resize(offset + sizeof(uint16_t))) {
throw std::out_of_range("Packet::PutUInt16(), could not resize packet and would of written past the end.");
}
}
*reinterpret_cast<uint16_t*>(static_cast<char*>(Data()) + offset) = value;
_wpos = offset + sizeof(uint16_t);
}
void PutUInt32(size_t offset, uint32_t value) {
if (Length() < offset + sizeof(uint32_t)) {
if (!Resize(offset + sizeof(uint32_t))) {
throw std::out_of_range("Packet::PutUInt32(), could not resize packet and would of written past the end.");
}
}
*reinterpret_cast<uint32_t*>(static_cast<char*>(Data()) + offset) = value;
_wpos = offset + sizeof(uint32_t);
}
void PutUInt64(size_t offset, uint64_t value) {
if (Length() < offset + sizeof(uint64_t)) {
if (!Resize(offset + sizeof(uint64_t))) {
throw std::out_of_range("Packet::PutUInt64(), could not resize packet and would of written past the end.");
}
}
*reinterpret_cast<uint64_t*>(static_cast<char*>(Data()) + offset) = value;
_wpos = offset + sizeof(uint64_t);
}
void PutFloat(size_t offset, float value) {
if (Length() < offset + sizeof(float)) {
if (!Resize(offset + sizeof(float))) {
throw std::out_of_range("Packet::PutFloat(), could not resize packet and would of written past the end.");
}
}
*reinterpret_cast<float*>(static_cast<char*>(Data()) + offset) = value;
_wpos = offset + sizeof(float);
}
void PutDouble(size_t offset, double value) {
if (Length() < offset + sizeof(double)) {
if (!Resize(offset + sizeof(double))) {
throw std::out_of_range("Packet::PutDouble(), could not resize packet and would of written past the end.");
}
}
*reinterpret_cast<double*>(static_cast<char*>(Data()) + offset) = value;
_wpos = offset + sizeof(double);
}
void PutString(size_t offset, const std::string &str) {
if (Length() < offset + str.length()) {
if (!Resize(offset + str.length())) {
throw std::out_of_range("Packet::PutString(), could not resize packet and would of written past the end.");
}
}
std::memcpy((static_cast<char*>(Data()) + offset), str.c_str(), str.length());
_wpos = offset + str.length();
}
void PutCString(size_t offset, const char *str) {
size_t sz = strlen(str);
if (Length() < offset + sz + sizeof(int8_t)) {
if (!Resize(offset + sz + sizeof(int8_t))) {
throw std::out_of_range("Packet::PutCString(), could not resize packet and would of written past the end.");
}
}
std::memcpy((static_cast<char*>(Data()) + offset), str, sz);
*(static_cast<char*>(Data()) + offset + sz) = 0;
_wpos = offset + sz + sizeof(int8_t);
}
void PutPacket(size_t offset, const Packet &p) {
if (p.Length() == 0) {
return;
}
if (Length() < offset + p.Length()) {
if (!Resize(offset + p.Length())) {
throw std::out_of_range("Packet::PutPacket(), could not resize packet and would of written past the end.");
}
}
std::memcpy((static_cast<char*>(Data()) + offset), p.Data(), p.Length());
_wpos = offset + p.Length();
}
void PutData(size_t offset, void *data, size_t length) {
if (length == 0) {
return;
}
if (Length() < offset + length) {
if (!Resize(offset + length)) {
throw std::out_of_range("Packet::PutData(), could not resize packet and would of written past the end.");
}
}
std::memcpy((static_cast<char*>(Data()) + offset), data, length);
_wpos = offset + length;
}
//Position Dependent Output Interface
void PutInt8(int8_t value) {
PutInt8(_wpos, value);
}
void PutInt16(int16_t value) {
PutInt16(_wpos, value);
}
void PutInt32(int32_t value) {
PutInt32(_wpos, value);
}
void PutInt64(int64_t value) {
PutInt64(_wpos, value);
}
void PutUInt8(uint8_t value) {
PutUInt8(_wpos, value);
}
void PutUInt16(uint16_t value) {
PutUInt16(_wpos, value);
}
void PutUInt32(uint32_t value) {
PutUInt32(_wpos, value);
}
void PutUInt64(uint64_t value) {
PutUInt64(_wpos, value);
}
void PutFloat(float value) {
PutFloat(_wpos, value);
}
void PutDouble(double value) {
PutDouble(_wpos, value);
}
void PutString(const std::string &str) {
PutString(_wpos, str);
}
void PutCString(const char *str) {
PutCString(_wpos, str);
}
void PutPacket(const Packet &p) {
PutPacket(_wpos, p);
}
void PutData(void *data, size_t length) {
PutData(_wpos, data, length);
}
//Position Independent Input Interface
int8_t GetInt8(size_t offset) const {
if (Length() < offset + sizeof(int8_t)) {
throw std::out_of_range("Packet read out of range.");
}
return *reinterpret_cast<const int8_t*>(reinterpret_cast<const int8_t*>(Data()) + offset);
}
int16_t GetInt16(size_t offset) const {
if (Length() < offset + sizeof(int16_t)) {
throw std::out_of_range("Packet read out of range.");
}
return *reinterpret_cast<const int16_t*>(reinterpret_cast<const int8_t*>(Data()) + offset);
}
int32_t GetInt32(size_t offset) const {
if (Length() < offset + sizeof(int32_t)) {
throw std::out_of_range("Packet read out of range.");
}
return *reinterpret_cast<const int32_t*>(reinterpret_cast<const int8_t*>(Data()) + offset);
}
int64_t GetInt64(size_t offset) const {
if (Length() < offset + sizeof(int64_t)) {
throw std::out_of_range("Packet read out of range.");
}
return *reinterpret_cast<const int64_t*>(reinterpret_cast<const int8_t*>(Data()) + offset);
}
uint8_t GetUInt8(size_t offset) const {
if (Length() < offset + sizeof(uint8_t)) {
throw std::out_of_range("Packet read out of range.");
}
return *reinterpret_cast<const uint8_t*>(reinterpret_cast<const int8_t*>(Data()) + offset);
}
uint16_t GetUInt16(size_t offset) const {
if (Length() < offset + sizeof(uint16_t)) {
throw std::out_of_range("Packet read out of range.");
}
return *reinterpret_cast<const uint16_t*>(reinterpret_cast<const int8_t*>(Data()) + offset);
}
uint32_t GetUInt32(size_t offset) const {
if (Length() < offset + sizeof(uint32_t)) {
throw std::out_of_range("Packet read out of range.");
}
return *reinterpret_cast<const uint32_t*>(reinterpret_cast<const int8_t*>(Data()) + offset);
}
uint64_t GetUInt64(size_t offset) const {
if (Length() < offset + sizeof(uint64_t)) {
throw std::out_of_range("Packet read out of range.");
}
return *reinterpret_cast<const uint64_t*>(reinterpret_cast<const int8_t*>(Data()) + offset);
}
float GetFloat(size_t offset) const {
if (Length() < offset + sizeof(float)) {
throw std::out_of_range("Packet read out of range.");
}
return *reinterpret_cast<const float*>(reinterpret_cast<const int8_t*>(Data()) + offset);
}
double GetDouble(size_t offset) const {
if (Length() < offset + sizeof(double)) {
throw std::out_of_range("Packet read out of range.");
}
return *reinterpret_cast<const double*>(reinterpret_cast<const int8_t*>(Data()) + offset);
}
std::string GetString(size_t offset, size_t length) const {
if (Length() < offset + length) {
throw std::out_of_range("Packet read out of range.");
}
return std::string(reinterpret_cast<const int8_t*>(Data()) + offset, reinterpret_cast<const int8_t*>(Data()) + offset + length);
}
std::string GetCString(size_t offset) const {
if (Length() < offset) {
throw std::out_of_range("Packet read out of range.");
}
auto sz = strlen(static_cast<const char*>(Data()));
if (Length() < offset + sz + sizeof(int8_t)) {
throw std::out_of_range("Packet read out of range.");
}
const char *str = reinterpret_cast<const char*>(reinterpret_cast<const int8_t*>(Data()) + offset);
return std::string(str);
}
//Position Dependent Input Interface
int8_t GetInt8() {
auto offset = _rpos;
if (Length() < offset + sizeof(int8_t)) {
throw std::out_of_range("Packet read out of range.");
}
_rpos = offset + sizeof(int8_t);
return *reinterpret_cast<int8_t*>(static_cast<char*>(Data()) + offset);
}
int16_t GetInt16() {
auto offset = _rpos;
if (Length() < offset + sizeof(int16_t)) {
throw std::out_of_range("Packet read out of range.");
}
_rpos = offset + sizeof(int16_t);
return *reinterpret_cast<int16_t*>(static_cast<char*>(Data()) + offset);
}
int32_t GetInt32() {
auto offset = _rpos;
if (Length() < offset + sizeof(int32_t)) {
throw std::out_of_range("Packet read out of range.");
}
_rpos = offset + sizeof(int32_t);
return *reinterpret_cast<int32_t*>(static_cast<char*>(Data()) + offset);
}
int64_t GetInt64() {
auto offset = _rpos;
if (Length() < offset + sizeof(int64_t)) {
throw std::out_of_range("Packet read out of range.");
}
_rpos = offset + sizeof(int64_t);
return *reinterpret_cast<int64_t*>(static_cast<char*>(Data()) + offset);
}
uint8_t GetUInt8() {
auto offset = _rpos;
if (Length() < offset + sizeof(uint8_t)) {
throw std::out_of_range("Packet read out of range.");
}
_rpos = offset + sizeof(uint8_t);
return *reinterpret_cast<uint8_t*>(static_cast<char*>(Data()) + offset);
}
uint16_t GetUInt16() {
auto offset = _rpos;
if (Length() < offset + sizeof(uint16_t)) {
throw std::out_of_range("Packet read out of range.");
}
_rpos = offset + sizeof(uint16_t);
return *reinterpret_cast<uint16_t*>(static_cast<char*>(Data()) + offset);
}
uint32_t GetUInt32() {
auto offset = _rpos;
if (Length() < offset + sizeof(uint32_t)) {
throw std::out_of_range("Packet read out of range.");
}
_rpos = offset + sizeof(uint32_t);
return *reinterpret_cast<uint32_t*>(static_cast<char*>(Data()) + offset);
}
uint64_t GetUInt64() {
auto offset = _rpos;
if (Length() < offset + sizeof(uint64_t)) {
throw std::out_of_range("Packet read out of range.");
}
_rpos = offset + sizeof(uint64_t);
return *reinterpret_cast<uint64_t*>(static_cast<char*>(Data()) + offset);
}
float GetFloat() {
auto offset = _rpos;
if (Length() < offset + sizeof(float)) {
throw std::out_of_range("Packet read out of range.");
}
_rpos = offset + sizeof(float);
return *reinterpret_cast<float*>(static_cast<char*>(Data()) + offset);
}
double GetDouble() {
auto offset = _rpos;
if (Length() < offset + sizeof(double)) {
throw std::out_of_range("Packet read out of range.");
}
_rpos = offset + sizeof(double);
return *reinterpret_cast<double*>(static_cast<char*>(Data()) + offset);
}
std::string GetString(size_t length) {
auto offset = _rpos;
if (Length() < offset + length) {
throw std::out_of_range("Packet read out of range.");
}
_rpos = offset + length;
return std::string(static_cast<char*>(Data()) + offset, static_cast<char*>(Data()) + offset + length);
}
std::string GetCString() {
auto offset = _rpos;
if (Length() < offset + sizeof(int8_t)) {
throw std::out_of_range("Packet read out of range.");
}
auto sz = strlen(static_cast<const char*>(Data()));
if (Length() < offset + sz + sizeof(int8_t)) {
throw std::out_of_range("Packet read out of range.");
}
_rpos = offset + sz + sizeof(int8_t);
char *str = (static_cast<char*>(Data()) + offset);
return std::string(str);
}
int8_t& operator[](size_t offset) {
if (Length() < offset + sizeof(int8_t)) {
throw std::out_of_range("Packet read out of range.");
}
return *reinterpret_cast<int8_t*>(static_cast<char*>(Data()) + offset);
}
const int8_t& operator[](size_t offset) const {
if (Length() < offset + sizeof(int8_t)) {
throw std::out_of_range("Packet read out of range.");
}
return *reinterpret_cast<const int8_t*>(static_cast<const char*>(Data()) + offset);
}
//Stream Output Interface
Packet &operator<<(int8_t v) {
PutInt8(v);
return *this;
}
Packet &operator<<(int16_t v) {
PutInt16(v);
return *this;
}
Packet &operator<<(int32_t v) {
PutInt32(v);
return *this;
}
Packet &operator<<(int64_t v) {
PutInt64(v);
return *this;
}
Packet &operator<<(uint8_t v) {
PutUInt8(v);
return *this;
}
Packet &operator<<(uint16_t v) {
PutUInt16(v);
return *this;
}
Packet &operator<<(uint32_t v) {
PutUInt32(v);
return *this;
}
Packet &operator<<(uint64_t v) {
PutUInt64(v);
return *this;
}
Packet &operator<<(float v) {
PutFloat(v);
return *this;
}
Packet &operator<<(double v) {
PutDouble(v);
return *this;
}
Packet &operator<<(const std::string &v) {
PutString(v.data());
return *this;
}
Packet &operator<<(const char *v) {
PutCString(v);
return *this;
}
Packet &operator<<(const Packet &v) {
PutPacket(v);
return *this;
}
//Stream Input Interface
Packet &operator>>(int8_t &v) {
v = GetInt8();
return *this;
}
Packet &operator>>(int16_t &v) {
v = GetInt16();
return *this;
}
Packet &operator>>(int32_t &v) {
v = GetInt32();
return *this;
}
Packet &operator>>(int64_t &v) {
v = GetInt64();
return *this;
}
Packet &operator>>(uint8_t &v) {
v = GetUInt8();
return *this;
}
Packet &operator>>(uint16_t &v) {
v = GetUInt16();
return *this;
}
Packet &operator>>(uint32_t &v) {
v = GetUInt32();
return *this;
}
Packet &operator>>(uint64_t &v) {
v = GetUInt64();
return *this;
}
Packet &operator>>(float &v) {
v = GetFloat();
return *this;
}
Packet &operator>>(double &v) {
v = GetDouble();
return *this;
}
Packet &operator>>(std::string &v) {
v = GetCString();
return *this;
}
// Seriliazation
template<typename T> template<typename T>
T GetSerialize(size_t offset) const T GetSerialize(size_t offset) const
{ {
@@ -36,11 +646,12 @@ namespace EQ {
template<typename T> template<typename T>
void PutSerialize(size_t offset, const T &value) { void PutSerialize(size_t offset, const T &value) {
m_stream.clear(); std::stringstream stream;
cereal::BinaryOutputArchive output(m_stream);
cereal::BinaryOutputArchive output(stream);
output(value); output(value);
auto str = m_stream.str(); auto str = stream.str();
if (Length() < offset + str.length()) { if (Length() < offset + str.length()) {
if (!Resize(offset + str.length())) { if (!Resize(offset + str.length())) {
throw std::out_of_range("Packet::PutSerialize(), could not resize packet and would of written past the end."); throw std::out_of_range("Packet::PutSerialize(), could not resize packet and would of written past the end.");
@@ -49,82 +660,95 @@ namespace EQ {
memcpy((char*)Data() + offset, &str[0], str.length()); memcpy((char*)Data() + offset, &str[0], str.length());
} }
void PutInt8(size_t offset, int8_t value);
void PutInt16(size_t offset, int16_t value);
void PutInt32(size_t offset, int32_t value);
void PutInt64(size_t offset, int64_t value);
void PutUInt8(size_t offset, uint8_t value);
void PutUInt16(size_t offset, uint16_t value);
void PutUInt32(size_t offset, uint32_t value);
void PutUInt64(size_t offset, uint64_t value);
void PutFloat(size_t offset, float value);
void PutDouble(size_t offset, double value);
void PutString(size_t offset, const std::string &str);
void PutCString(size_t offset, const char *str);
void PutPacket(size_t offset, const Packet &p);
void PutData(size_t offset, void *data, size_t length);
int8_t GetInt8(size_t offset) const;
int16_t GetInt16(size_t offset) const;
int32_t GetInt32(size_t offset) const;
int64_t GetInt64(size_t offset) const;
uint8_t GetUInt8(size_t offset) const;
uint16_t GetUInt16(size_t offset) const;
uint32_t GetUInt32(size_t offset) const;
uint64_t GetUInt64(size_t offset) const;
float GetFloat(size_t offset) const;
double GetDouble(size_t offset) const;
std::string GetString(size_t offset, size_t length) const;
std::string GetCString(size_t offset) const;
std::string ToString() const;
std::string ToString(size_t line_length) const;
protected: protected:
std::stringstream m_stream; size_t _rpos{ 0 };
size_t _wpos{ 0 };
}; };
class StaticPacket : public Packet class StaticPacket : public Packet
{ {
public: public:
StaticPacket(void *data, size_t size) { m_data = data; m_data_length = size; m_max_data_length = size; } StaticPacket(void *data, size_t len) : _data(data), _len(len), _max_len(len) {
virtual ~StaticPacket() { } }
StaticPacket(const StaticPacket &o) { m_data = o.m_data; m_data_length = o.m_data_length; }
StaticPacket& operator=(const StaticPacket &o) { m_data = o.m_data; m_data_length = o.m_data_length; return *this; }
StaticPacket(StaticPacket &&o) { m_data = o.m_data; m_data_length = o.m_data_length; }
virtual const void *Data() const { return m_data; } StaticPacket(const StaticPacket &o) : _data(o._data), _len(o._len), _max_len(o._max_len) {
virtual void *Data() { return m_data; } _rpos = o._rpos;
virtual size_t Length() const { return m_data_length; } _wpos = o._wpos;
virtual size_t Length() { return m_data_length; } }
virtual bool Clear() { return false; }
virtual bool Resize(size_t new_size); StaticPacket& operator=(const StaticPacket& o) {
virtual void Reserve(size_t new_size) { } _data = o._data;
_len = o._len;
_max_len = o._max_len;
_rpos = o._rpos;
_wpos = o._wpos;
return *this;
}
StaticPacket(StaticPacket &&o) noexcept : _data(o._data), _len(o._len), _max_len(o._max_len) {
_rpos = o._rpos;
_wpos = o._wpos;
}
const void *Data() const override { return _data; }
void *Data() override { return _data; }
size_t Length() const override { return _len; }
size_t Length() override { return _len; }
bool Clear() override { return false; }
bool Resize(size_t new_size) override;
void Reserve(size_t new_size) override { }
protected: protected:
void *m_data; void *_data;
size_t m_data_length; size_t _len;
size_t m_max_data_length; size_t _max_len;
}; };
class DynamicPacket : public Packet class DynamicPacket : public Packet
{ {
public: public:
DynamicPacket() { } const static size_t DefaultSize = 4096;
virtual ~DynamicPacket() { }
DynamicPacket(DynamicPacket &&o) { m_data = std::move(o.m_data); } DynamicPacket() {
DynamicPacket(const DynamicPacket &o) { m_data = o.m_data; } _data.reserve(DefaultSize);
DynamicPacket& operator=(const DynamicPacket &o) { m_data = o.m_data; return *this; } }
DynamicPacket(size_t size) {
_data.reserve(size);
}
DynamicPacket(const DynamicPacket& o) : _data(o._data) {
_rpos = o._rpos;
_wpos = o._wpos;
}
DynamicPacket& operator=(const DynamicPacket& o) {
_data = o._data;
_rpos = o._rpos;
_wpos = o._wpos;
}
DynamicPacket(DynamicPacket &&o) noexcept : _data(o.MoveData()) {
_rpos = o._rpos;
_wpos = o._wpos;
}
std::vector<int8_t>&& MoveData() {
_rpos = 0;
_wpos = 0;
return std::move(_data);
}
const void *Data() const override { return _data.data(); }
void *Data() override { return _data.data(); }
size_t Length() const override { return _data.size(); }
size_t Length() override { return _data.size(); }
bool Clear() override { _data.clear(); return true; }
bool Resize(size_t new_size) override { _data.resize(new_size); return true; }
void Reserve(size_t new_size) override { _data.reserve(new_size); }
virtual const void *Data() const { return &m_data[0]; }
virtual void *Data() { return &m_data[0]; }
virtual size_t Length() const { return m_data.size(); }
virtual size_t Length() { return m_data.size(); }
virtual bool Clear() { m_data.clear(); return true; }
virtual bool Resize(size_t new_size) { m_data.resize(new_size, 0); return true; }
virtual void Reserve(size_t new_size) { m_data.reserve(new_size); }
protected: protected:
std::vector<char> m_data; std::vector<int8_t> _data;
}; };
} } // namespace Net
} } // namespace EQ
+2 -2
View File
@@ -23,7 +23,7 @@ void EQ::Net::TCPConnection::Connect(const std::string &addr, int port, bool ipv
std::function<void(std::shared_ptr<EQ::Net::TCPConnection>)> cb; std::function<void(std::shared_ptr<EQ::Net::TCPConnection>)> cb;
}; };
auto loop = EQ::EventLoop::Get().Handle(); auto loop = EQ::EventLoop::GetDefault().Handle();
uv_tcp_t *socket = new uv_tcp_t; uv_tcp_t *socket = new uv_tcp_t;
memset(socket, 0, sizeof(uv_tcp_t)); memset(socket, 0, sizeof(uv_tcp_t));
uv_tcp_init(loop, socket); uv_tcp_init(loop, socket);
@@ -142,7 +142,7 @@ void EQ::Net::TCPConnection::Write(const char *data, size_t count)
WriteBaton *baton = new WriteBaton; WriteBaton *baton = new WriteBaton;
baton->connection = this; baton->connection = this;
baton->buffer = new char[count];; baton->buffer = new char[count];
uv_write_t *write_req = new uv_write_t; uv_write_t *write_req = new uv_write_t;
memset(write_req, 0, sizeof(uv_write_t)); memset(write_req, 0, sizeof(uv_write_t));
+2 -2
View File
@@ -32,7 +32,7 @@ void EQ::Net::TCPServer::Listen(const std::string &addr, int port, bool ipv6, st
m_on_new_connection = cb; m_on_new_connection = cb;
auto loop = EQ::EventLoop::Get().Handle(); auto loop = EQ::EventLoop::GetDefault().Handle();
m_socket = new uv_tcp_t; m_socket = new uv_tcp_t;
memset(m_socket, 0, sizeof(uv_tcp_t)); memset(m_socket, 0, sizeof(uv_tcp_t));
uv_tcp_init(loop, m_socket); uv_tcp_init(loop, m_socket);
@@ -53,7 +53,7 @@ void EQ::Net::TCPServer::Listen(const std::string &addr, int port, bool ipv6, st
return; return;
} }
auto loop = EQ::EventLoop::Get().Handle(); auto loop = EQ::EventLoop::GetDefault().Handle();
uv_tcp_t *client = new uv_tcp_t; uv_tcp_t *client = new uv_tcp_t;
memset(client, 0, sizeof(uv_tcp_t)); memset(client, 0, sizeof(uv_tcp_t));
uv_tcp_init(loop, client); uv_tcp_init(loop, client);
+1 -1
View File
@@ -29,7 +29,7 @@
//#endif //#endif
#include <string.h> #include <string.h>
#ifdef _WINDOWS #ifdef _WIN32
#define snprintf _snprintf #define snprintf _snprintf
#define strncasecmp _strnicmp #define strncasecmp _strnicmp
#define strcasecmp _stricmp #define strcasecmp _stricmp
+1 -1
View File
@@ -23,7 +23,7 @@
#include "packet_dump.h" #include "packet_dump.h"
#include "packet_functions.h" #include "packet_functions.h"
#ifndef WIN32 #ifndef _WIN32
#include <netinet/in.h> #include <netinet/in.h>
#endif #endif
+8 -8
View File
@@ -22,7 +22,7 @@
#include "global_define.h" #include "global_define.h"
#include "types.h" #include "types.h"
#include "proc_launcher.h" #include "proc_launcher.h"
#ifdef _WINDOWS #ifdef _WIN32
#include <windows.h> #include <windows.h>
#else #else
#include <sys/types.h> #include <sys/types.h>
@@ -39,7 +39,7 @@
ProcLauncher ProcLauncher::s_launcher; ProcLauncher ProcLauncher::s_launcher;
#ifdef _WINDOWS #ifdef _WIN32
const ProcLauncher::ProcRef ProcLauncher::ProcError = 0xFFFFFFFF; const ProcLauncher::ProcRef ProcLauncher::ProcError = 0xFFFFFFFF;
#else #else
const ProcLauncher::ProcRef ProcLauncher::ProcError = -1; const ProcLauncher::ProcRef ProcLauncher::ProcError = -1;
@@ -47,7 +47,7 @@ const ProcLauncher::ProcRef ProcLauncher::ProcError = -1;
ProcLauncher::ProcLauncher() ProcLauncher::ProcLauncher()
{ {
#ifndef WIN32 #ifndef _WIN32
if(signal(SIGCHLD, ProcLauncher::HandleSigChild) == SIG_ERR) if(signal(SIGCHLD, ProcLauncher::HandleSigChild) == SIG_ERR)
fprintf(stderr, "Unable to register child signal handler. Thats bad."); fprintf(stderr, "Unable to register child signal handler. Thats bad.");
m_signalCount = 0; m_signalCount = 0;
@@ -55,7 +55,7 @@ ProcLauncher::ProcLauncher()
} }
void ProcLauncher::Process() { void ProcLauncher::Process() {
#ifdef _WINDOWS #ifdef _WIN32
std::map<ProcRef, Spec *>::iterator cur, end, tmp; std::map<ProcRef, Spec *>::iterator cur, end, tmp;
cur = m_running.begin(); cur = m_running.begin();
end = m_running.end(); end = m_running.end();
@@ -112,7 +112,7 @@ void ProcLauncher::ProcessTerminated(std::map<ProcRef, Spec *>::iterator &it) {
if(it->second->handler != nullptr) if(it->second->handler != nullptr)
it->second->handler->OnTerminate(it->first, it->second); it->second->handler->OnTerminate(it->first, it->second);
#ifdef _WINDOWS #ifdef _WIN32
CloseHandle(it->second->proc_info.hProcess); CloseHandle(it->second->proc_info.hProcess);
#else //!WIN32 #else //!WIN32
#endif //!WIN32 #endif //!WIN32
@@ -125,7 +125,7 @@ ProcLauncher::ProcRef ProcLauncher::Launch(Spec *&to_launch) {
Spec *it = to_launch; Spec *it = to_launch;
to_launch = nullptr; to_launch = nullptr;
#ifdef _WINDOWS #ifdef _WIN32
STARTUPINFO siStartInfo; STARTUPINFO siStartInfo;
BOOL bFuncRetn = FALSE; BOOL bFuncRetn = FALSE;
@@ -283,7 +283,7 @@ bool ProcLauncher::Terminate(const ProcRef &proc, bool graceful) {
//we do not remove it from the list until we have been notified //we do not remove it from the list until we have been notified
//that they have been terminated. //that they have been terminated.
#ifdef _WINDOWS #ifdef _WIN32
if(!TerminateProcess(res->second->proc_info.hProcess, 0)) { if(!TerminateProcess(res->second->proc_info.hProcess, 0)) {
return(false); return(false);
} }
@@ -325,7 +325,7 @@ void ProcLauncher::TerminateAll(bool final) {
} }
#ifndef WIN32 #ifndef _WIN32
void ProcLauncher::HandleSigChild(int signum) { void ProcLauncher::HandleSigChild(int signum) {
if(signum == SIGCHLD) { if(signum == SIGCHLD) {
ProcLauncher::get()->m_signalCount++; ProcLauncher::get()->m_signalCount++;
+3 -3
View File
@@ -33,7 +33,7 @@ public:
static ProcLauncher *get() { return(&s_launcher); } static ProcLauncher *get() { return(&s_launcher); }
static void ProcessInThisThread(); static void ProcessInThisThread();
#ifdef WIN32 #ifdef _WIN32
typedef DWORD ProcRef; typedef DWORD ProcRef;
static const ProcRef ProcError; static const ProcRef ProcError;
#else #else
@@ -55,7 +55,7 @@ public:
std::string logFile; //empty = do not redirect output. std::string logFile; //empty = do not redirect output.
protected: protected:
//None of these fields get copied around //None of these fields get copied around
#ifdef WIN32 #ifdef _WIN32
PROCESS_INFORMATION proc_info; PROCESS_INFORMATION proc_info;
#endif #endif
}; };
@@ -83,7 +83,7 @@ protected:
private: private:
static ProcLauncher s_launcher; static ProcLauncher s_launcher;
#ifndef WIN32 #ifndef _WIN32
uint32 m_signalCount; uint32 m_signalCount;
static void HandleSigChild(int signum); static void HandleSigChild(int signum);
#endif #endif
+1 -1
View File
@@ -23,7 +23,7 @@
#include "database.h" #include "database.h"
#include "string_util.h" #include "string_util.h"
#ifdef _WINDOWS #ifdef _WIN32
#include <winsock2.h> #include <winsock2.h>
#include <windows.h> #include <windows.h>
int gettimeofday (timeval *tp, ...); int gettimeofday (timeval *tp, ...);
+2 -5
View File
@@ -121,11 +121,8 @@ private:
int m_activeRuleset; int m_activeRuleset;
std::string m_activeName; std::string m_activeName;
#ifdef WIN64
uint32 m_RuleIntValues [_IntRuleCount ]; int32 m_RuleIntValues [_IntRuleCount ];
#else
int m_RuleIntValues [_IntRuleCount ];
#endif
float m_RuleRealValues[_RealRuleCount]; float m_RuleRealValues[_RealRuleCount];
uint32 m_RuleBoolValues[_BoolRuleCount]; uint32 m_RuleBoolValues[_BoolRuleCount];
+1 -1
View File
@@ -77,7 +77,7 @@
#include "classes.h" #include "classes.h"
#include "spdat.h" #include "spdat.h"
#ifndef WIN32 #ifndef _WIN32
#include <stdlib.h> #include <stdlib.h>
#include "unix.h" #include "unix.h"
#endif #endif
+1 -1
View File
@@ -17,7 +17,7 @@
#include "string_util.h" #include "string_util.h"
#include <algorithm> #include <algorithm>
#ifdef _WINDOWS #ifdef _WIN32
#include <windows.h> #include <windows.h>
#define snprintf _snprintf #define snprintf _snprintf
+2 -2
View File
@@ -18,7 +18,7 @@
// Disgrace: for windows compile // Disgrace: for windows compile
#ifndef WIN32 #ifndef _WIN32
#include <sys/time.h> #include <sys/time.h>
#else #else
#include <sys/timeb.h> #include <sys/timeb.h>
@@ -64,7 +64,7 @@ Timer::Timer(uint32 start, uint32 timer, bool iUseAcurateTiming = false) {
} }
/* Reimplemented for MSVC - Bounce */ /* Reimplemented for MSVC - Bounce */
#ifdef _WINDOWS #ifdef _WIN32
int gettimeofday (timeval *tp, ...) int gettimeofday (timeval *tp, ...)
{ {
timeb tb; timeb tb;
+1 -1
View File
@@ -22,7 +22,7 @@
#include <chrono> #include <chrono>
// Disgrace: for windows compile // Disgrace: for windows compile
#ifdef _WINDOWS #ifdef _WIN32
#include "global_define.h" #include "global_define.h"
int gettimeofday (timeval *tp, ...); int gettimeofday (timeval *tp, ...);
#endif #endif
+5 -5
View File
@@ -29,7 +29,7 @@ typedef int16_t int16;
typedef int32_t int32; typedef int32_t int32;
typedef int64_t int64; typedef int64_t int64;
#ifdef _WINDOWS #ifdef _WIN32
#pragma warning( disable : 4200 ) #pragma warning( disable : 4200 )
#endif #endif
@@ -42,7 +42,7 @@ typedef unsigned short ushort;
typedef unsigned char uchar; typedef unsigned char uchar;
typedef const char Const_char; //for perl XS typedef const char Const_char; //for perl XS
#ifdef _WINDOWS #ifdef _WIN32
#if (!defined(_MSC_VER) || (defined(_MSC_VER) && _MSC_VER < 1900)) #if (!defined(_MSC_VER) || (defined(_MSC_VER) && _MSC_VER < 1900))
#define snprintf _snprintf #define snprintf _snprintf
#endif #endif
@@ -61,7 +61,7 @@ typedef const char Const_char; //for perl XS
#define H32(i) ((uint32) (i >> 32)) #define H32(i) ((uint32) (i >> 32))
#define L16(i) ((uint16) i) #define L16(i) ((uint16) i)
#ifndef WIN32 #ifndef _WIN32
// More WIN32 compatability // More WIN32 compatability
typedef unsigned long DWORD; typedef unsigned long DWORD;
typedef unsigned char BYTE; typedef unsigned char BYTE;
@@ -79,14 +79,14 @@ typedef const char Const_char; //for perl XS
#endif #endif
#ifdef _WINDOWS #ifdef _WIN32
#define DLLFUNC extern "C" __declspec(dllexport) #define DLLFUNC extern "C" __declspec(dllexport)
#else #else
#define DLLFUNC extern "C" #define DLLFUNC extern "C"
#endif #endif
// htonll and ntohll already defined on windows // htonll and ntohll already defined on windows
#ifndef WIN32 #ifndef _WIN32
# if defined(__linux__) # if defined(__linux__)
# include <endian.h> # include <endian.h>
# elif defined(__FreeBSD__) || defined(__NetBSD__) # elif defined(__FreeBSD__) || defined(__NetBSD__)
+1 -1
View File
@@ -15,7 +15,7 @@
along with this program; if not, write to the Free Software along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/ */
#ifndef _WINDOWS #ifndef _WIN32
#include "unix.h" #include "unix.h"
#include <string.h> #include <string.h>
+1 -1
View File
@@ -15,7 +15,7 @@
along with this program; if not, write to the Free Software along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/ */
#ifndef _WINDOWS #ifndef _WIN32
#ifndef __UNIX_H__ #ifndef __UNIX_H__
#define __UNIX_H__ #define __UNIX_H__
#include <unistd.h> #include <unistd.h>
+3 -3
View File
@@ -10,16 +10,16 @@
// this doesn't do shit for C++ but libc++ and GCC 6.1+ use it to define some macros // this doesn't do shit for C++ but libc++ and GCC 6.1+ use it to define some macros
#include <ciso646> #include <ciso646>
#ifndef WIN32 #ifndef _WIN32
extern "C" { //the perl headers dont do this for us... extern "C" { //the perl headers dont do this for us...
#endif #endif
#include <perl.h> #include <perl.h>
#include <XSUB.h> #include <XSUB.h>
#ifndef WIN32 #ifndef _WIN32
}; };
#endif #endif
#ifdef WIN32 #ifdef _WIN32
#ifndef snprintf #ifndef snprintf
#define snprintf _snprintf #define snprintf _snprintf
#endif #endif
+1 -1
View File
@@ -40,7 +40,7 @@
#endif #endif
#define COMPILE_DATE __DATE__ #define COMPILE_DATE __DATE__
#define COMPILE_TIME __TIME__ #define COMPILE_TIME __TIME__
#ifndef WIN32 #ifndef _WIN32
#define LAST_MODIFIED __TIME__ #define LAST_MODIFIED __TIME__
#else #else
#define LAST_MODIFIED __TIMESTAMP__ #define LAST_MODIFIED __TIMESTAMP__
-2
View File
@@ -1,2 +0,0 @@
*.*
*
+1 -1
View File
@@ -1,4 +1,4 @@
CMAKE_MINIMUM_REQUIRED(VERSION 2.8) CMAKE_MINIMUM_REQUIRED(VERSION 3.10)
SET(eqlaunch_sources SET(eqlaunch_sources
eqlaunch.cpp eqlaunch.cpp
+2 -2
View File
@@ -70,7 +70,7 @@ int main(int argc, char *argv[]) {
Log(Logs::Detail, Logs::Launcher, "Could not set signal handler"); Log(Logs::Detail, Logs::Launcher, "Could not set signal handler");
return 1; return 1;
} }
#ifndef WIN32 #ifndef _WIN32
if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) { if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) {
Log(Logs::Detail, Logs::Launcher, "Could not set signal handler"); Log(Logs::Detail, Logs::Launcher, "Could not set signal handler");
return 1; return 1;
@@ -136,7 +136,7 @@ int main(int argc, char *argv[]) {
zones.erase(rem); zones.erase(rem);
} }
EQ::EventLoop::Get().Process(); EQ::EventLoop::GetDefault().Process();
Sleep(5); Sleep(5);
} }
+1 -1
View File
@@ -1,4 +1,4 @@
CMAKE_MINIMUM_REQUIRED(VERSION 2.8) CMAKE_MINIMUM_REQUIRED(VERSION 3.10)
SET(hc_sources SET(hc_sources
eq.cpp eq.cpp
+55 -32
View File
@@ -1,38 +1,61 @@
CMAKE_MINIMUM_REQUIRED(VERSION 2.8) # Build for LuaBind
# Ryan Pavlik <rpavlik@iastate.edu>
# http://academic.cleardefinition.com/
# Iowa State University HCI Graduate Program/VRAC
SET(lb_sources cmake_minimum_required(VERSION 3.0)
src/class.cpp project(LuaBind)
src/class_info.cpp
src/class_registry.cpp set(CPACK_PACKAGE_VERSION_MAJOR "0")
src/class_rep.cpp set(CPACK_PACKAGE_VERSION_MINOR "9")
src/create_class.cpp set(CPACK_PACKAGE_VERSION_PATCH "1")
src/error.cpp set(CPACK_PACKAGE_VERSION "${CPACK_PACKAGE_VERSION_MAJOR}.${CPACK_PACKAGE_VERSION_MINOR}.${CPACK_PACKAGE_VERSION_PATCH}")
src/exception_handler.cpp
src/function.cpp set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
src/inheritance.cpp set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
src/link_compatibility.cpp set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
src/object_rep.cpp
src/open.cpp if(NOT LUA_FOUND AND NOT LUA51_FOUND)
src/pcall.cpp find_package(Lua51 REQUIRED)
src/scope.cpp set(LUA_INCLUDE_DIRS "${LUA_INCLUDE_DIR}")
src/stack_content_by_name.cpp endif()
src/weak_ref.cpp
src/wrapper_base.cpp if(CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR)
# We are the top-level project
include(CTest)
option(LUABIND_INSTALL "Install the LuaBind library and headers" ON)
option(LUABIND_BUILD_DOCS "Build documentation files" OFF)
option(LUABIND_BUILD_SHARED "Build luabind as a shared library?" OFF)
endif()
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU" OR CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
# Requiring C++11
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
endif()
if(MSVC)
# Requiring C++11
# set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /std:c++11")
# set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /std:c++11")
endif()
set(BUILD_SHARED_LIBS ${LUABIND_BUILD_SHARED})
if(BUILD_SHARED_LIBS)
add_definitions(-DLUABIND_DYNAMIC_LINK)
endif()
include_directories(
"${CMAKE_CURRENT_SOURCE_DIR}"
${LUA_INCLUDE_DIRS}
) )
SET(lb_headers add_subdirectory(src)
) if(BUILD_TESTING)
add_subdirectory(test)
endif()
ADD_LIBRARY(luabind ${lb_sources} ${lb_headers}) if(LUABIND_BUILD_DOCS)
add_subdirectory(doc)
endif()
IF(UNIX)
set_source_files_properties(${lb_sources} PROPERTY COMPILE_FLAGS -Wno-deprecated-declarations)
ENDIF(UNIX)
IF(MSVC)
set_source_files_properties(${lb_sources} PROPERTY COMPILE_FLAGS " /W0 " )
ENDIF(MSVC)
SET(LIBRARY_OUTPUT_PATH ${PROJECT_BINARY_DIR}/bin)
+54
View File
@@ -0,0 +1,54 @@
{
"configurations": [
{
"name": "x32-debug",
"generator": "Visual Studio 15 2017",
"buildRoot": "${projectDir}/temp/x32-debug",
"cmakeCommandArgs": "",
"configurationType": "Debug",
"variables": [
{
"name": "LUA_INCLUDE_DIR",
"value": "C:/gitprojects/LuaJIT-2.1.0-beta3/src"
},
{
"name": "LUA_LIBRARIES",
"value": "C:/gitprojects/LuaJIT-2.1.0-beta3/src/lua51.lib"
},
{
"name": "LUABIND_INSTALL",
"value": "ON"
},
{
"name": "CMAKE_INSTALL_PREFIX",
"value": "${projectDir}/build/debug"
}
]
},
{
"name": "x32-release",
"generator": "Visual Studio 15 2017",
"buildRoot": "${projectDir}/temp/x32-release",
"cmakeCommandArgs": "",
"configurationType": "Release",
"variables": [
{
"name": "LUA_INCLUDE_DIR",
"value": "C:/gitprojects/LuaJIT-2.1.0-beta3/src"
},
{
"name": "LUA_LIBRARIES",
"value": "C:/gitprojects/LuaJIT-2.1.0-beta3/src/lua51.lib"
},
{
"name": "LUABIND_INSTALL",
"value": "ON"
},
{
"name": "CMAKE_INSTALL_PREFIX",
"value": "${projectDir}/build/release"
}
]
}
]
}
+42 -45
View File
@@ -28,13 +28,12 @@
#include <luabind/wrapper_base.hpp> #include <luabind/wrapper_base.hpp>
#include <luabind/detail/policy.hpp> #include <luabind/detail/policy.hpp>
#include <luabind/back_reference_fwd.hpp> #include <luabind/back_reference_fwd.hpp>
#include <luabind/wrapper_base.hpp>
#include <boost/type_traits/is_polymorphic.hpp>
namespace luabind { namespace detail namespace luabind {
{ namespace detail {
template <class T> template <class T>
void adjust_backref_ownership(T* ptr, mpl::true_) void adjust_backref_ownership(T* ptr, std::true_type)
{ {
if(wrap_base* p = dynamic_cast<wrap_base*>(ptr)) if(wrap_base* p = dynamic_cast<wrap_base*>(ptr))
{ {
@@ -44,30 +43,25 @@ namespace luabind { namespace detail
} }
} }
inline void adjust_backref_ownership(void*, mpl::false_) inline void adjust_backref_ownership(void*, std::false_type)
{} {}
template<class Direction = lua_to_cpp> template <class Pointer, class Direction = lua_to_cpp>
struct adopt_pointer : pointer_converter struct adopt_pointer : pointer_converter
{ {
typedef adopt_pointer type; using type = adopt_pointer;
int const consumed_args(...) enum { consumed_args = 1 };
{
return 1;
}
template<class T> template<class T>
T* apply(lua_State* L, by_pointer<T>, int index) T* to_cpp(lua_State* L, by_pointer<T>, int index)
{ {
T* ptr = pointer_converter::apply( T* ptr = pointer_converter::to_cpp(L, decorate_type_t<T*>(), index);
L, LUABIND_DECORATE_TYPE(T*), index);
object_rep* obj = static_cast<object_rep*>( object_rep* obj = static_cast<object_rep*>(lua_touserdata(L, index));
lua_touserdata(L, index));
obj->release(); obj->release();
adjust_backref_ownership(ptr, boost::is_polymorphic<T>()); adjust_backref_ownership(ptr, std::is_polymorphic<T>());
return ptr; return ptr;
} }
@@ -75,21 +69,32 @@ namespace luabind { namespace detail
template<class T> template<class T>
int match(lua_State* L, by_pointer<T>, int index) int match(lua_State* L, by_pointer<T>, int index)
{ {
return pointer_converter::match( return pointer_converter::match(L, decorate_type_t<T*>(), index);
L, LUABIND_DECORATE_TYPE(T*), index);
} }
template<class T> template<class T>
void converter_postcall(lua_State*, T, int) {} void converter_postcall(lua_State*, T, int) {}
}; };
template<> template <class Pointer, class T>
struct adopt_pointer<cpp_to_lua> struct pointer_or_default
{ {
typedef adopt_pointer type; using type = Pointer;
};
template <class T> template <class T>
void apply(lua_State* L, T* ptr) struct pointer_or_default<void, T>
{
using type = std::unique_ptr<T>;
};
template <class Pointer>
struct adopt_pointer<Pointer, cpp_to_lua>
{
using type = adopt_pointer;
template<class T>
void to_lua(lua_State* L, T* ptr)
{ {
if(ptr == 0) if(ptr == 0)
{ {
@@ -103,39 +108,31 @@ namespace luabind { namespace detail
if(luabind::move_back_reference(L, ptr)) if(luabind::move_back_reference(L, ptr))
return; return;
make_instance(L, std::auto_ptr<T>(ptr)); using pointer_type = typename pointer_or_default<Pointer, T>::type;
make_pointer_instance(L, pointer_type(ptr));
} }
}; };
template<int N> template <class Pointer>
// struct adopt_policy : converter_policy_tag struct adopt_policy_impl
struct adopt_policy : conversion_policy<N>
{ {
// BOOST_STATIC_CONSTANT(int, index = N);
static void precall(lua_State*, const index_map&) {}
static void postcall(lua_State*, const index_map&) {}
struct only_accepts_nonconst_pointers {};
template<class T, class Direction> template<class T, class Direction>
struct apply struct specialize
{ {
typedef luabind::detail::is_nonconst_pointer<T> is_nonconst_p; static_assert(detail::is_nonconst_pointer<T>::value, "Adopt policy only accepts non-const pointers");
typedef typename boost::mpl::if_<is_nonconst_p, adopt_pointer<Direction>, only_accepts_nonconst_pointers>::type type; using type = adopt_pointer<Pointer, Direction>;
}; };
}; };
}} }
}
namespace luabind namespace luabind
{ {
template<int N> // Caution: if we use the aliased type "policy_list" here, MSVC crashes.
detail::policy_cons<detail::adopt_policy<N>, detail::null_type> template<unsigned int N, typename Pointer = void>
adopt(LUABIND_PLACEHOLDER_ARG(N)) using adopt_policy = meta::type_list<converter_policy_injector<N, detail::adopt_policy_impl<Pointer>>>;
{
return detail::policy_cons<detail::adopt_policy<N>, detail::null_type>();
}
} }
#endif // LUABIND_ADOPT_POLICY_HPP_INCLUDE #endif // LUABIND_ADOPT_POLICY_HPP_INCLUDE
+15 -17
View File
@@ -23,28 +23,29 @@
#ifndef LUABIND_BACK_REFERENCE_040510_HPP #ifndef LUABIND_BACK_REFERENCE_040510_HPP
#define LUABIND_BACK_REFERENCE_040510_HPP #define LUABIND_BACK_REFERENCE_040510_HPP
#include <luabind/lua_include.hpp> #include <luabind/config.hpp>
#include <luabind/lua_state_fwd.hpp>
#include <type_traits>
#if !defined(LUABIND_NO_RTTI) && !defined(LUABIND_WRAPPER_BASE_HPP_INCLUDED)
#include <luabind/wrapper_base.hpp> #include <luabind/wrapper_base.hpp>
#include <luabind/detail/has_get_pointer.hpp> #endif
#include <luabind/get_pointer.hpp>
#include <boost/type_traits/is_polymorphic.hpp> #include <luabind/pointer_traits.hpp>
#include <boost/type_traits/is_const.hpp>
#include <boost/mpl/if.hpp>
namespace luabind { namespace luabind {
struct wrap_base;
namespace detail namespace detail
{ {
namespace mpl = boost::mpl;
template<class T> template<class T>
wrap_base const* get_back_reference_aux0(T const* p, mpl::true_) wrap_base const* get_back_reference_aux0(T const* p, std::true_type)
{ {
return dynamic_cast<wrap_base const*>(p); return dynamic_cast<wrap_base const*>(p);
} }
template<class T> template<class T>
wrap_base const* get_back_reference_aux0(T const*, mpl::false_) wrap_base const* get_back_reference_aux0(T const*, std::false_type)
{ {
return 0; return 0;
} }
@@ -52,17 +53,17 @@ namespace detail
template<class T> template<class T>
wrap_base const* get_back_reference_aux1(T const* p) wrap_base const* get_back_reference_aux1(T const* p)
{ {
return get_back_reference_aux0(p, boost::is_polymorphic<T>()); return get_back_reference_aux0(p, std::is_polymorphic<T>());
} }
template<class T> template<class T>
wrap_base const* get_back_reference_aux2(T const& x, mpl::true_) wrap_base const* get_back_reference_aux2(T const& x, std::true_type)
{ {
return get_back_reference_aux1(get_pointer(x)); return get_back_reference_aux1(get_pointer(x));
} }
template<class T> template<class T>
wrap_base const* get_back_reference_aux2(T const& x, mpl::false_) wrap_base const* get_back_reference_aux2(T const& x, std::false_type)
{ {
return get_back_reference_aux1(&x); return get_back_reference_aux1(&x);
} }
@@ -70,10 +71,7 @@ namespace detail
template<class T> template<class T>
wrap_base const* get_back_reference(T const& x) wrap_base const* get_back_reference(T const& x)
{ {
return detail::get_back_reference_aux2( return detail::get_back_reference_aux2(x, has_get_pointer<T>());
x
, has_get_pointer<T>()
);
} }
} // namespace detail } // namespace detail
@@ -23,6 +23,8 @@
#ifndef LUABIND_BACK_REFERENCE_FWD_040510_HPP #ifndef LUABIND_BACK_REFERENCE_FWD_040510_HPP
#define LUABIND_BACK_REFERENCE_FWD_040510_HPP #define LUABIND_BACK_REFERENCE_FWD_040510_HPP
#include <luabind/lua_state_fwd.hpp>
namespace luabind { namespace luabind {
template<class T> template<class T>
+243 -524
View File
@@ -75,42 +75,27 @@
#include <vector> #include <vector>
#include <cassert> #include <cassert>
#include <boost/bind.hpp>
#include <boost/preprocessor/repetition/enum_params.hpp>
#include <boost/preprocessor/repetition/enum_params_with_a_default.hpp>
#include <boost/preprocessor/repetition/repeat.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/type_traits/is_member_object_pointer.hpp>
#include <boost/mpl/apply.hpp>
#include <boost/mpl/lambda.hpp>
#include <boost/mpl/logical.hpp>
#include <boost/mpl/find_if.hpp>
#include <boost/mpl/eval_if.hpp>
#include <boost/mpl/logical.hpp>
#include <luabind/config.hpp> #include <luabind/config.hpp>
#include <luabind/scope.hpp> #include <luabind/scope.hpp>
#include <luabind/back_reference.hpp> #include <luabind/back_reference.hpp>
#include <luabind/function.hpp> #include <luabind/function.hpp> // -> object.hpp
#include <luabind/dependency_policy.hpp> #include <luabind/dependency_policy.hpp>
#include <luabind/detail/constructor.hpp> #include <luabind/detail/constructor.hpp> // -> object.hpp
#include <luabind/detail/call.hpp>
#include <luabind/detail/deduce_signature.hpp>
#include <luabind/detail/compute_score.hpp>
#include <luabind/detail/primitives.hpp> #include <luabind/detail/primitives.hpp>
#include <luabind/detail/property.hpp> #include <luabind/detail/property.hpp>
#include <luabind/detail/typetraits.hpp> #include <luabind/detail/type_traits.hpp>
#include <luabind/detail/class_rep.hpp> #include <luabind/detail/class_rep.hpp>
#include <luabind/detail/call.hpp>
#include <luabind/detail/object_rep.hpp> #include <luabind/detail/object_rep.hpp>
#include <luabind/detail/calc_arity.hpp> #include <luabind/detail/call.hpp>
#include <luabind/detail/call_member.hpp> #include <luabind/detail/call_member.hpp>
#include <luabind/detail/enum_maker.hpp> #include <luabind/detail/enum_maker.hpp>
#include <luabind/detail/operator_id.hpp> #include <luabind/detail/operator_id.hpp>
#include <luabind/detail/pointee_typeid.hpp>
#include <luabind/detail/link_compatibility.hpp> #include <luabind/detail/link_compatibility.hpp>
#include <luabind/detail/inheritance.hpp> #include <luabind/detail/inheritance.hpp>
#include <luabind/detail/signature_match.hpp>
#include <luabind/no_dependency.hpp>
#include <luabind/typeid.hpp> #include <luabind/typeid.hpp>
#include <luabind/detail/meta.hpp>
// to remove the 'this' used in initialization list-warning // to remove the 'this' used in initialization list-warning
#ifdef _MSC_VER #ifdef _MSC_VER
@@ -118,17 +103,8 @@
#pragma warning(disable: 4355) #pragma warning(disable: 4355)
#endif #endif
namespace boost namespace luabind {
{ namespace detail {
template <class T> class shared_ptr;
} // namespace boost
namespace luabind
{
namespace detail
{
struct unspecified {}; struct unspecified {};
template<class Derived> struct operator_; template<class Derived> struct operator_;
@@ -136,7 +112,62 @@ namespace luabind
struct you_need_to_define_a_get_const_holder_function_for_your_smart_ptr {}; struct you_need_to_define_a_get_const_holder_function_for_your_smart_ptr {};
} }
template<class T, class X1 = detail::unspecified, class X2 = detail::unspecified, class X3 = detail::unspecified> template < typename... BaseClasses >
struct bases { };
using no_bases = bases< >;
using default_holder = null_type;
namespace detail {
template < typename T >
struct make_bases {
using type = bases< T >;
};
template< typename... Bases >
struct make_bases< bases< Bases... > > {
using type = bases< Bases... >;
};
}
template< typename T >
using make_bases = typename detail::make_bases< T >::type;
template< typename... Args >
struct constructor
{};
// helper for overloaded methods, only need to provide argument types (IntelliSense bug squiggles the code, but it does compile!)
template< typename... Args >
struct meth {
template< typename Class, typename Ret >
static auto use_nonconst(Ret(Class::*fn)(Args...)) -> decltype(fn)
{
return fn;
}
template< typename Class, typename Ret >
static auto use_const(Ret(Class::*fn)(Args...) const) -> decltype(fn)
{
return fn;
}
template< typename Class, typename Ret >
static auto use_auto(Ret(Class::*fn)(Args...) const) -> decltype(fn)
{
return fn;
}
template< typename Class, typename Ret >
static auto use_auto(Ret(Class::*fn)(Args...)) -> decltype(fn)
{
return fn;
}
};
// TODO: Could specialize for certain base classes to make the interface "type safe".
template<typename T, typename BaseOrBases = no_bases, typename HolderType = null_type, typename WrapperType = null_type>
struct class_; struct class_;
// TODO: this function will only be invoked if the user hasn't defined a correct overload // TODO: this function will only be invoked if the user hasn't defined a correct overload
@@ -148,79 +179,14 @@ namespace luabind
} }
template <class T> template <class T>
boost::shared_ptr<T const>* get_const_holder(boost::shared_ptr<T>*) std::shared_ptr<T const>* get_const_holder(std::shared_ptr<T>*)
{ {
return 0; return 0;
} }
template <
BOOST_PP_ENUM_PARAMS_WITH_A_DEFAULT(
LUABIND_MAX_BASES, class A, detail::null_type)
>
struct bases
{};
typedef bases<detail::null_type> no_bases;
namespace detail
{
template <class T>
struct is_bases
: mpl::false_
{};
template <BOOST_PP_ENUM_PARAMS(LUABIND_MAX_BASES, class A)>
struct is_bases<bases<BOOST_PP_ENUM_PARAMS(LUABIND_MAX_BASES, A)> >
: mpl::true_
{};
template <class T, class P>
struct is_unspecified
: mpl::apply1<P, T>
{};
template <class P>
struct is_unspecified<unspecified, P>
: mpl::true_
{};
template <class P>
struct is_unspecified_mfn
{
template <class T>
struct apply
: is_unspecified<T, P>
{};
};
template<class Predicate>
struct get_predicate
{
typedef mpl::protect<is_unspecified_mfn<Predicate> > type;
};
template <class Result, class Default>
struct result_or_default
{
typedef Result type;
};
template <class Default>
struct result_or_default<unspecified, Default>
{
typedef Default type;
};
template<class Parameters, class Predicate, class DefaultValue>
struct extract_parameter
{
typedef typename get_predicate<Predicate>::type pred;
typedef typename boost::mpl::find_if<Parameters, pred>::type iterator;
typedef typename result_or_default<
typename iterator::type, DefaultValue
>::type type;
};
namespace detail {
// prints the types of the values on the stack, in the // prints the types of the values on the stack, in the
// range [start_index, lua_gettop()] // range [start_index, lua_gettop()]
@@ -291,7 +257,7 @@ namespace luabind
// MSVC complains about member being sensitive to alignment (C4121) // MSVC complains about member being sensitive to alignment (C4121)
// when F is a pointer to member of a class with virtual bases. // when F is a pointer to member of a class with virtual bases.
# ifdef BOOST_MSVC # ifdef _MSC_VER
# pragma pack(push) # pragma pack(push)
# pragma pack(16) # pragma pack(16)
# endif # endif
@@ -299,266 +265,147 @@ namespace luabind
template <class Class, class F, class Policies> template <class Class, class F, class Policies>
struct memfun_registration : registration struct memfun_registration : registration
{ {
memfun_registration(char const* name, F f, Policies const& policies) memfun_registration(char const* name, F f)
: name(name) : name(name), f(f)
, f(f)
, policies(policies)
{} {}
void register_(lua_State* L) const void register_(lua_State* L) const
{ {
object fn = make_function( // Need to check if the class type of the signature is a base of this class
L, f, deduce_signature(f, (Class*)0), policies); object fn = make_function(L, f, deduce_signature_t<F, Class>(), Policies());
add_overload(object(from_stack(L, -1)), name, fn);
add_overload(
object(from_stack(L, -1))
, name
, fn
);
} }
char const* name; char const* name;
F f; F f;
Policies policies;
}; };
# ifdef BOOST_MSVC # ifdef _MSC_VER
# pragma pack(pop) # pragma pack(pop)
# endif # endif
template <class P, class T> template <class P, class T>
struct default_pointer struct default_pointer
{ {
typedef P type; using type = P;
}; };
template <class T> template <class T>
struct default_pointer<null_type, T> struct default_pointer<null_type, T>
{ {
typedef std::auto_ptr<T> type; using type = std::unique_ptr<T>;
}; };
template <class Class, class Pointer, class Signature, class Policies> template <class Class, class Pointer, class Signature, class Policies>
struct constructor_registration : registration struct constructor_registration : registration
{ {
constructor_registration(Policies const& policies) constructor_registration()
: policies(policies)
{} {}
void register_(lua_State* L) const void register_(lua_State* L) const
{ {
typedef typename default_pointer<Pointer, Class>::type pointer; using pointer = typename default_pointer<Pointer, Class>::type;
object fn = make_function(L, construct<Class, pointer, Signature>(), Signature(), Policies());
object fn = make_function( add_overload(object(from_stack(L, -1)), "__init", fn);
L
, construct<Class, pointer, Signature>(), Signature()
, policies
);
add_overload(
object(from_stack(L, -1))
, "__init"
, fn
);
} }
Policies policies;
}; };
template <class T> template <class T>
struct reference_result struct reference_result
: mpl::if_< : std::conditional< std::is_pointer<T>::value || is_primitive<T>::value, T, typename std::add_lvalue_reference< T >::type >
mpl::or_<boost::is_pointer<T>, is_primitive<T> > {};
, T
, typename boost::add_reference<T>::type template <class T>
> struct reference_argument
: std::conditional< std::is_pointer<T>::value || is_primitive<T>::value, T, typename std::add_lvalue_reference< typename std::add_const<T>::type >::type >
{}; {};
template <class T, class Policies> template <class T, class Policies>
struct inject_dependency_policy struct inject_dependency_policy
: mpl::if_< {
is_primitive<T> using type = typename std::conditional <
, Policies is_primitive<T>::value || meta::contains<Policies, call_policy_injector< detail::no_dependency_policy > >::value,
, policy_cons<dependency_policy<0, 1>, Policies> Policies,
> typename meta::push_back< Policies, call_policy_injector< dependency_policy<0, 1> > >::type
{}; >::type;
};
template < template <class Class, class Get, class GetPolicies, class Set = null_type, class SetPolicies = no_policies >
class Class
, class Get, class GetPolicies
, class Set = null_type, class SetPolicies = null_type
>
struct property_registration : registration struct property_registration : registration
{ {
property_registration( property_registration(char const* name, Get const& get, Set const& set = null_type())
char const* name : name(name), get(get), set(set)
, Get const& get
, GetPolicies const& get_policies
, Set const& set = Set()
, SetPolicies const& set_policies = SetPolicies()
)
: name(name)
, get(get)
, get_policies(get_policies)
, set(set)
, set_policies(set_policies)
{} {}
void register_(lua_State* L) const
{
object context(from_stack(L, -1));
register_aux(
L
, context
, make_get(L, get, boost::is_member_object_pointer<Get>())
, set
);
}
template <class F> template <class F>
object make_get(lua_State* L, F const& f, mpl::false_) const object make_get(lua_State* L, F const& f, std::false_type /*member_ptr*/) const
{ {
return make_function( return make_function(L, f, GetPolicies());
L, f, deduce_signature(f, (Class*)0), get_policies);
} }
template <class T, class D> template <class T, class D>
object make_get(lua_State* L, D T::* mem_ptr, mpl::true_) const object make_get(lua_State* L, D T::* mem_ptr, std::true_type /*member_ptr*/) const
{ {
typedef typename reference_result<D>::type result_type; using result_type = typename reference_result<D>::type;
typedef typename inject_dependency_policy< using get_signature = meta::type_list<result_type, Class const&>;
D, GetPolicies>::type policies; using injected_list = typename inject_dependency_policy< D, GetPolicies >::type;
return make_function( return make_function(L, access_member_ptr<T, D, result_type>(mem_ptr), get_signature(), injected_list());
L
, access_member_ptr<T, D, result_type>(mem_ptr)
, mpl::vector2<result_type, Class const&>()
, policies()
);
} }
template <class F> template <class F>
object make_set(lua_State* L, F const& f, mpl::false_) const object make_set(lua_State* L, F const& f, std::false_type /*member_ptr*/) const
{ {
return make_function( return make_function(L, f, deduce_signature_t<F>(), SetPolicies());
L, f, deduce_signature(f, (Class*)0), set_policies);
} }
template <class T, class D> template <class T, class D>
object make_set(lua_State* L, D T::* mem_ptr, mpl::true_) const object make_set(lua_State* L, D T::* mem_ptr, std::true_type /*member_ptr*/) const
{ {
return make_function( using argument_type = typename reference_argument<D>::type;
L using signature_type = meta::type_list<void, Class&, argument_type>;
, access_member_ptr<T, D>(mem_ptr)
, mpl::vector3<void, Class&, D const&>() return make_function(L, access_member_ptr<T, D>(mem_ptr), signature_type(), SetPolicies());
, set_policies
);
} }
template <class S> // if a setter was given
void register_aux( template <class SetterType>
lua_State* L, object const& context void register_aux(lua_State* L, object const& context, object const& get_, SetterType const&) const
, object const& get_, S const&) const
{ {
context[name] = property( context[name] = property(get_, make_set(L, set, std::is_member_object_pointer<Set>()));
get_
, make_set(L, set, boost::is_member_object_pointer<Set>())
);
} }
void register_aux( // if no setter was given
lua_State*, object const& context void register_aux(lua_State*, object const& context, object const& get_, null_type) const
, object const& get_, null_type) const
{ {
context[name] = property(get_); context[name] = property(get_);
} }
// register entry
void register_(lua_State* L) const
{
object context(from_stack(L, -1));
register_aux(L, context, make_get(L, get, std::is_member_object_pointer<Get>()), set);
}
char const* name; char const* name;
Get get; Get get;
GetPolicies get_policies;
Set set; Set set;
SetPolicies set_policies;
}; };
} // namespace detail } // namespace detail
// registers a class in the lua environment // registers a class in the lua environment
template<class T, class X1, class X2, class X3> template<class T, typename BaseOrBases, typename HolderType, typename WrapperType >
struct class_: detail::class_base struct class_
: detail::class_base
{ {
typedef class_<T, X1, X2, X3> self_t; using self_t = class_<T, BaseOrBases, HolderType, WrapperType>;
using BaseList = make_bases< BaseOrBases >;
private:
template<class A, class B, class C, class D>
class_(const class_<A,B,C,D>&);
public: public:
typedef boost::mpl::vector4<X1, X2, X3, detail::unspecified> parameters_type;
// WrappedType MUST inherit from T
typedef typename detail::extract_parameter<
parameters_type
, boost::is_base_and_derived<T, boost::mpl::_>
, detail::null_type
>::type WrappedType;
typedef typename detail::extract_parameter<
parameters_type
, boost::mpl::not_<
boost::mpl::or_<
detail::is_bases<boost::mpl::_>
, boost::is_base_and_derived<boost::mpl::_, T>
, boost::is_base_and_derived<T, boost::mpl::_>
>
>
, detail::null_type
>::type HeldType;
template <class Src, class Target>
void add_downcast(Src*, Target*, boost::mpl::true_)
{
add_cast(
detail::registered_class<Src>::id
, detail::registered_class<Target>::id
, detail::dynamic_cast_<Src, Target>::execute
);
}
template <class Src, class Target>
void add_downcast(Src*, Target*, boost::mpl::false_)
{}
// this function generates conversion information
// in the given class_rep structure. It will be able
// to implicitly cast to the given template type
template<class To>
void gen_base_info(detail::type_<To>)
{
add_base(typeid(To), detail::static_cast_<T, To>::execute);
add_cast(
detail::registered_class<T>::id
, detail::registered_class<To>::id
, detail::static_cast_<T, To>::execute
);
add_downcast((To*)0, (T*)0, boost::is_polymorphic<To>());
}
void gen_base_info(detail::type_<detail::null_type>)
{}
#define LUABIND_GEN_BASE_INFO(z, n, text) gen_base_info(detail::type_<BaseClass##n>());
template<BOOST_PP_ENUM_PARAMS(LUABIND_MAX_BASES, class BaseClass)>
void generate_baseclass_list(detail::type_<bases<BOOST_PP_ENUM_PARAMS(LUABIND_MAX_BASES, BaseClass)> >)
{
BOOST_PP_REPEAT(LUABIND_MAX_BASES, LUABIND_GEN_BASE_INFO, _)
}
#undef LUABIND_GEN_BASE_INFO
class_(const char* name) : class_base(name), scope(*this) class_(const char* name) : class_base(name), scope(*this)
{ {
#ifndef NDEBUG #ifndef NDEBUG
@@ -567,174 +414,78 @@ namespace luabind
init(); init();
} }
template<class F>
class_& def(const char* name, F f)
{
return this->virtual_def(
name, f, detail::null_type()
, detail::null_type(), boost::mpl::true_());
}
// virtual functions // virtual functions
template<class F, class DefaultOrPolicies> template<class F, typename... Injectors>
class_& def(char const* name, F fn, DefaultOrPolicies default_or_policies) class_& def(char const* name, F fn, policy_list< Injectors... > policies = no_policies())
{ {
return this->virtual_def( return this->virtual_def(name, fn, policies, null_type());
name, fn, default_or_policies, detail::null_type()
, LUABIND_MSVC_TYPENAME detail::is_policy_cons<DefaultOrPolicies>::type());
} }
template<class F, class Default, class Policies> // IntelliSense bug squiggles the code, but it does compile!
class_& def(char const* name, F fn template<typename Ret, typename C, typename... Args, typename... Injectors>
, Default default_, Policies const& policies) class_& def_nonconst(char const* name, Ret(C::*fn)(Args...), policy_list<Injectors...> policies = no_policies())
{ {
return this->virtual_def( return def(name, fn, policies);
name, fn, default_
, policies, boost::mpl::false_());
} }
template<BOOST_PP_ENUM_PARAMS(LUABIND_MAX_ARITY, class A)> // IntelliSense bug squiggles the code, but it does compile!
class_& def(constructor<BOOST_PP_ENUM_PARAMS(LUABIND_MAX_ARITY, A)> sig) template<typename Ret, typename C, typename... Args, typename... Injectors>
class_& def_const(char const* name, Ret(C::*fn)(Args...) const, policy_list<Injectors...> policies = no_policies())
{ {
return this->def_constructor(&sig, detail::null_type()); return def(name, fn, policies);
} }
template<BOOST_PP_ENUM_PARAMS(LUABIND_MAX_ARITY, class A), class Policies> template<class F, class Default, typename... Injectors>
class_& def(constructor<BOOST_PP_ENUM_PARAMS(LUABIND_MAX_ARITY, A)> sig, const Policies& policies) class_& def(char const* name, F fn, Default default_, policy_list< Injectors... > policies = no_policies())
{ {
return this->def_constructor(&sig, policies); return this->virtual_def(name, fn, policies, default_);
} }
template <class Getter> template<typename... Args, typename... Injectors>
class_& property(const char* name, Getter g) class_& def(constructor<Args...> sig, policy_list< Injectors... > policies = no_policies())
{ {
this->add_member( return this->def_constructor(sig, policies);
new detail::property_registration<T, Getter, detail::null_type>( }
name, g, detail::null_type()));
// ======================
// Start of reworked property overloads
// ======================
template <class Getter, typename... Injectors>
class_& property(const char* name, Getter g, policy_list< Injectors... > get_injectors = no_policies())
{
return property(name, g, null_type(), get_injectors);
}
template <class Getter, class Setter, typename... GetInjectors, typename... SetInjectors>
class_& property(const char* name, Getter g, Setter s, policy_list<GetInjectors...> = no_policies(), policy_list<SetInjectors...> = no_policies())
{
using registration_type = detail::property_registration<T, Getter, policy_list<GetInjectors...>, Setter, policy_list<SetInjectors...>>;
this->add_member(new registration_type(name, g, s));
return *this; return *this;
} }
template <class Getter, class MaybeSetter> template <class C, class D, typename... Injectors>
class_& property(const char* name, Getter g, MaybeSetter s) class_& def_readonly(const char* name, D C::*mem_ptr, policy_list<Injectors...> policies = no_policies())
{ {
return property_impl( return property(name, mem_ptr, policies);
name, g, s
, boost::mpl::bool_<detail::is_policy_cons<MaybeSetter>::value>()
);
} }
template<class Getter, class Setter, class GetPolicies> template <class C, class D, typename... GetInjectors, typename... SetInjectors>
class_& property(const char* name, Getter g, Setter s, const GetPolicies& get_policies) class_& def_readwrite(const char* name, D C::*mem_ptr, policy_list<GetInjectors...> get_injectors = no_policies(), policy_list<SetInjectors...> set_injectors = no_policies())
{ {
typedef detail::property_registration< return property(name, mem_ptr, mem_ptr, get_injectors, set_injectors);
T, Getter, GetPolicies, Setter, detail::null_type
> registration_type;
this->add_member(
new registration_type(name, g, get_policies, s));
return *this;
} }
template<class Getter, class Setter, class GetPolicies, class SetPolicies> // =====================
class_& property( // End of reworked property overloads
const char* name // =====================
, Getter g, Setter s
, GetPolicies const& get_policies template<class Derived, typename... Injectors>
, SetPolicies const& set_policies) class_& def(detail::operator_<Derived>, policy_list<Injectors...> policies = no_policies())
{ {
typedef detail::property_registration< using policy_list_type = policy_list<Injectors...>;
T, Getter, GetPolicies, Setter, SetPolicies return this->def(Derived::name(), &Derived::template apply<T, policy_list_type>::execute, policies);
> registration_type;
this->add_member(
new registration_type(name, g, get_policies, s, set_policies));
return *this;
}
template <class C, class D>
class_& def_readonly(const char* name, D C::*mem_ptr)
{
typedef detail::property_registration<T, D C::*, detail::null_type>
registration_type;
this->add_member(
new registration_type(name, mem_ptr, detail::null_type()));
return *this;
}
template <class C, class D, class Policies>
class_& def_readonly(const char* name, D C::*mem_ptr, Policies const& policies)
{
typedef detail::property_registration<T, D C::*, Policies>
registration_type;
this->add_member(
new registration_type(name, mem_ptr, policies));
return *this;
}
template <class C, class D>
class_& def_readwrite(const char* name, D C::*mem_ptr)
{
typedef detail::property_registration<
T, D C::*, detail::null_type, D C::*
> registration_type;
this->add_member(
new registration_type(
name, mem_ptr, detail::null_type(), mem_ptr));
return *this;
}
template <class C, class D, class GetPolicies>
class_& def_readwrite(
const char* name, D C::*mem_ptr, GetPolicies const& get_policies)
{
typedef detail::property_registration<
T, D C::*, GetPolicies, D C::*
> registration_type;
this->add_member(
new registration_type(
name, mem_ptr, get_policies, mem_ptr));
return *this;
}
template <class C, class D, class GetPolicies, class SetPolicies>
class_& def_readwrite(
const char* name
, D C::*mem_ptr
, GetPolicies const& get_policies
, SetPolicies const& set_policies
)
{
typedef detail::property_registration<
T, D C::*, GetPolicies, D C::*, SetPolicies
> registration_type;
this->add_member(
new registration_type(
name, mem_ptr, get_policies, mem_ptr, set_policies));
return *this;
}
template<class Derived, class Policies>
class_& def(detail::operator_<Derived>, Policies const& policies)
{
return this->def(
Derived::name()
, &Derived::template apply<T, Policies>::execute
, policies
);
}
template<class Derived>
class_& def(detail::operator_<Derived>)
{
return this->def(
Derived::name()
, &Derived::template apply<T, detail::null_type>::execute
);
} }
detail::enum_maker<self_t> enum_(const char*) detail::enum_maker<self_t> enum_(const char*)
@@ -745,125 +496,93 @@ namespace luabind
detail::static_scope<self_t> scope; detail::static_scope<self_t> scope;
private: private:
void init()
{
class_base::init(typeid(T), detail::registered_class<T>::id, typeid(WrapperType), detail::registered_class<WrapperType>::id);
add_wrapper_cast((WrapperType*)0);
generate_baseclass_list();
}
template<class S, typename OtherBaseOrBases, typename OtherWrapper >
class_(const class_<S, OtherBaseOrBases, OtherWrapper>&);
template <class Src, class Target>
void add_downcast(Src*, Target*, std::true_type)
{
add_cast(detail::registered_class<Src>::id, detail::registered_class<Target>::id, detail::dynamic_cast_<Src, Target>::execute);
}
template <class Src, class Target>
void add_downcast(Src*, Target*, std::false_type)
{}
// this function generates conversion information
// in the given class_rep structure. It will be able
// to implicitly cast to the given template type
template<typename Class0, typename... Classes>
void gen_base_info(bases<Class0, Classes...>)
{
add_base(typeid(Class0), detail::static_cast_<T, Class0>::execute);
add_cast(detail::registered_class<T>::id, detail::registered_class<Class0>::id, detail::static_cast_<T, Class0>::execute);
add_downcast((Class0*)0, (T*)0, std::is_polymorphic<Class0>());
gen_base_info(bases<Classes...>());
}
void gen_base_info(bases<>)
{
}
void generate_baseclass_list()
{
gen_base_info(BaseList());
}
void operator=(class_ const&); void operator=(class_ const&);
void add_wrapper_cast(detail::null_type*) void add_wrapper_cast(null_type*)
{} {}
template <class U> template <class U>
void add_wrapper_cast(U*) void add_wrapper_cast(U*)
{ {
add_cast( add_cast(detail::registered_class<U>::id, detail::registered_class<T>::id, detail::static_cast_<U, T>::execute);
detail::registered_class<U>::id add_downcast((T*)0, (U*)0, std::is_polymorphic<T>());
, detail::registered_class<T>::id
, detail::static_cast_<U,T>::execute
);
add_downcast((T*)0, (U*)0, boost::is_polymorphic<T>());
}
void init()
{
typedef typename detail::extract_parameter<
parameters_type
, boost::mpl::or_<
detail::is_bases<boost::mpl::_>
, boost::is_base_and_derived<boost::mpl::_, T>
>
, no_bases
>::type bases_t;
typedef typename
boost::mpl::if_<detail::is_bases<bases_t>
, bases_t
, bases<bases_t>
>::type Base;
class_base::init(
typeid(T)
, detail::registered_class<T>::id
, typeid(WrappedType)
, detail::registered_class<WrappedType>::id
);
add_wrapper_cast((WrappedType*)0);
generate_baseclass_list(detail::type_<Base>());
}
template<class Getter, class GetPolicies>
class_& property_impl(const char* name,
Getter g,
GetPolicies policies,
boost::mpl::bool_<true>)
{
this->add_member(
new detail::property_registration<T, Getter, GetPolicies>(
name, g, policies));
return *this;
}
template<class Getter, class Setter>
class_& property_impl(const char* name,
Getter g,
Setter s,
boost::mpl::bool_<false>)
{
typedef detail::property_registration<
T, Getter, detail::null_type, Setter, detail::null_type
> registration_type;
this->add_member(
new registration_type(name, g, detail::null_type(), s));
return *this;
} }
// these handle default implementation of virtual functions // these handle default implementation of virtual functions
template<class F, class Policies> template<class F, class Default, typename... Injectors>
class_& virtual_def(char const* name, F const& fn class_& virtual_def(char const* name, F const& fn, policy_list< Injectors... >, Default default_)
, Policies const&, detail::null_type, boost::mpl::true_)
{ {
this->add_member( using policy_list_type = policy_list< Injectors... >;
new detail::memfun_registration<T, F, Policies>( this->add_member(new detail::memfun_registration<T, F, policy_list_type >(name, fn));
name, fn, Policies())); this->add_default_member(new detail::memfun_registration<T, Default, policy_list_type>(name, default_));
return *this; return *this;
} }
template<class F, class Default, class Policies> template<class F, typename... Injectors>
class_& virtual_def(char const* name, F const& fn class_& virtual_def(char const* name, F const& fn, policy_list< Injectors... >, null_type)
, Default const& default_, Policies const&, boost::mpl::false_)
{ {
this->add_member( using policy_list_type = policy_list< Injectors... >;
new detail::memfun_registration<T, F, Policies>( this->add_member(new detail::memfun_registration<T, F, policy_list_type>(name, fn));
name, fn, Policies()));
this->add_default_member(
new detail::memfun_registration<T, Default, Policies>(
name, default_, Policies()));
return *this; return *this;
} }
template<class Signature, class Policies> template<typename... SignatureElements, typename... Injectors>
class_& def_constructor(Signature*, Policies const&) class_& def_constructor(constructor<SignatureElements...> const&, policy_list< Injectors... > const&)
{ {
typedef typename Signature::signature signature; using signature_type = meta::type_list<void, argument const&, SignatureElements...>;
using policy_list_type = policy_list< Injectors... >;
typedef typename boost::mpl::if_< using construct_type = typename std::conditional<
boost::is_same<WrappedType, detail::null_type> is_null_type<WrapperType>::value,
, T T,
, WrappedType WrapperType
>::type construct_type; >::type;
this->add_member( using registration_type = detail::constructor_registration<construct_type, HolderType, signature_type, policy_list_type>;
new detail::constructor_registration< this->add_member(new registration_type());
construct_type, HeldType, signature, Policies>( this->add_default_member(new registration_type());
Policies()));
this->add_default_member(
new detail::constructor_registration<
construct_type, HeldType, signature, Policies>(
Policies()));
return *this; return *this;
} }
-1
View File
@@ -20,7 +20,6 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
// OR OTHER DEALINGS IN THE SOFTWARE. // OR OTHER DEALINGS IN THE SOFTWARE.
#ifndef LUABIND_CLASS_INFO_HPP_INCLUDED #ifndef LUABIND_CLASS_INFO_HPP_INCLUDED
#define LUABIND_CLASS_INFO_HPP_INCLUDED #define LUABIND_CLASS_INFO_HPP_INCLUDED
+19 -34
View File
@@ -20,44 +20,13 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
// OR OTHER DEALINGS IN THE SOFTWARE. // OR OTHER DEALINGS IN THE SOFTWARE.
#ifndef LUABIND_CONFIG_HPP_INCLUDED #ifndef LUABIND_CONFIG_HPP_INCLUDED
#define LUABIND_CONFIG_HPP_INCLUDED #define LUABIND_CONFIG_HPP_INCLUDED
#include <boost/config.hpp>
#ifdef BOOST_MSVC
#define LUABIND_ANONYMOUS_FIX static
#else
#define LUABIND_ANONYMOUS_FIX
#endif
#if defined (BOOST_MSVC) && (BOOST_MSVC <= 1200)
#define for if (false) {} else for
#include <cstring>
namespace std
{
using ::strlen;
using ::strcmp;
using ::type_info;
}
#endif
#if defined (BOOST_MSVC) && (BOOST_MSVC <= 1300)
#define LUABIND_MSVC_TYPENAME
#else
#define LUABIND_MSVC_TYPENAME typename
#endif
// the maximum number of arguments of functions that's // the maximum number of arguments of functions that's
// registered. Must at least be 2 // registered. Must at least be 2
#ifndef LUABIND_MAX_ARITY #ifndef LUABIND_MAX_ARITY
#define LUABIND_MAX_ARITY 10 #define LUABIND_MAX_ARITY 100
#elif LUABIND_MAX_ARITY <= 1 #elif LUABIND_MAX_ARITY <= 1
#undef LUABIND_MAX_ARITY #undef LUABIND_MAX_ARITY
#define LUABIND_MAX_ARITY 2 #define LUABIND_MAX_ARITY 2
@@ -67,7 +36,7 @@ namespace std
// can derive from // can derive from
// max bases must at least be 1 // max bases must at least be 1
#ifndef LUABIND_MAX_BASES #ifndef LUABIND_MAX_BASES
#define LUABIND_MAX_BASES 4 #define LUABIND_MAX_BASES 100
#elif LUABIND_MAX_BASES <= 0 #elif LUABIND_MAX_BASES <= 0
#undef LUABIND_MAX_BASES #undef LUABIND_MAX_BASES
#define LUABIND_MAX_BASES 1 #define LUABIND_MAX_BASES 1
@@ -101,12 +70,18 @@ namespace std
// C code has undefined behavior, lua is written in C). // C code has undefined behavior, lua is written in C).
#ifdef LUABIND_DYNAMIC_LINK #ifdef LUABIND_DYNAMIC_LINK
# ifdef BOOST_WINDOWS # if defined (_WIN32)
# ifdef LUABIND_BUILDING # ifdef LUABIND_BUILDING
# define LUABIND_API __declspec(dllexport) # define LUABIND_API __declspec(dllexport)
# else # else
# define LUABIND_API __declspec(dllimport) # define LUABIND_API __declspec(dllimport)
# endif # endif
# elif defined (__CYGWIN__)
# ifdef LUABIND_BUILDING
# define LUABIND_API __attribute__ ((dllexport))
# else
# define LUABIND_API __attribute__ ((dllimport))
# endif
# else # else
# if defined(_GNUC_) && _GNUC_ >=4 # if defined(_GNUC_) && _GNUC_ >=4
# define LUABIND_API __attribute__ ((visibility("default"))) # define LUABIND_API __attribute__ ((visibility("default")))
@@ -118,10 +93,20 @@ namespace std
# define LUABIND_API # define LUABIND_API
#endif #endif
// This switches between using tag arguments / structure specialization for code size tests
#define LUABIND_NO_INTERNAL_TAG_ARGUMENTS
namespace luabind { namespace luabind {
LUABIND_API void disable_super_deprecation(); LUABIND_API void disable_super_deprecation();
namespace detail {
const int max_argument_count = 100;
const int max_hierarchy_depth = 100;
}
const int no_match = -(detail::max_argument_count*detail::max_hierarchy_depth + 1);
} // namespace luabind } // namespace luabind
#endif // LUABIND_CONFIG_HPP_INCLUDED #endif // LUABIND_CONFIG_HPP_INCLUDED
+41 -54
View File
@@ -20,40 +20,34 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
// OR OTHER DEALINGS IN THE SOFTWARE. // OR OTHER DEALINGS IN THE SOFTWARE.
#ifndef LUABIND_CONTAINER_POLICY_HPP_INCLUDED #ifndef LUABIND_CONTAINER_POLICY_HPP_INCLUDED
#define LUABIND_CONTAINER_POLICY_HPP_INCLUDED #define LUABIND_CONTAINER_POLICY_HPP_INCLUDED
#include <luabind/config.hpp> #include <luabind/config.hpp>
#include <luabind/detail/policy.hpp> #include <luabind/detail/policy.hpp>
#include <boost/mpl/apply_wrap.hpp> #include <luabind/detail/decorate_type.hpp> // for decorated_type
#include <luabind/detail/primitives.hpp> // for null_type (ptr only), etc
namespace luabind { namespace detail { namespace luabind {
namespace detail {
namespace mpl = boost::mpl;
template<class Policies> template<class Policies>
struct container_converter_lua_to_cpp struct container_converter_lua_to_cpp
{ {
int const consumed_args(...) enum { consumed_args = 1 };
{
return 1;
}
template<class T> template<class T>
T apply(lua_State* L, by_const_reference<T>, int index) T to_cpp(lua_State* L, by_const_reference<T>, int index)
{ {
typedef typename T::value_type value_type; using value_type = typename T::value_type;
specialized_converter_policy_n<1, Policies, value_type, lua_to_cpp> converter;
typedef typename find_conversion_policy<1, Policies>::type converter_policy;
typename mpl::apply_wrap2<converter_policy,value_type,lua_to_cpp>::type converter;
T container; T container;
lua_pushnil(L); lua_pushnil(L);
while (lua_next(L, index)) while(lua_next(L, index - 1))
{ {
container.push_back(converter.apply(L, LUABIND_DECORATE_TYPE(value_type), -1)); container.push_back(converter.apply(L, decorated_type<value_type>(), -1));
lua_pop(L, 1); // pop value lua_pop(L, 1); // pop value
} }
@@ -61,15 +55,21 @@ namespace luabind { namespace detail {
} }
template<class T> template<class T>
T apply(lua_State* L, by_value<T>, int index) T to_cpp(lua_State* L, by_value<T>, int index)
{ {
return apply(L, by_const_reference<T>(), index); return to_cpp(L, by_const_reference<T>(), index);
} }
template<class T> template<class T>
static int match(lua_State* L, by_const_reference<T>, int index) static int match(lua_State* L, by_const_reference<T>, int index)
{ {
if (lua_istable(L, index)) return 0; else return -1; if(lua_istable(L, index)) return 0; else return no_match;
}
template<class T>
static int match(lua_State* L, by_value<T>, int index)
{
return match(L, by_const_reference<T>(), index);
} }
template<class T> template<class T>
@@ -80,64 +80,51 @@ namespace luabind { namespace detail {
struct container_converter_cpp_to_lua struct container_converter_cpp_to_lua
{ {
template<class T> template<class T>
void apply(lua_State* L, const T& container) void to_lua(lua_State* L, const T& container)
{ {
typedef typename T::value_type value_type; using value_type = typename T::value_type;
specialized_converter_policy_n<1, Policies, value_type, lua_to_cpp> converter;
typedef typename find_conversion_policy<1, Policies>::type converter_policy;
typename mpl::apply_wrap2<converter_policy,value_type,lua_to_cpp>::type converter;
lua_newtable(L); lua_newtable(L);
int index = 1; int index = 1;
for (typename T::const_iterator i = container.begin(); i != container.end(); ++i) for(const auto& element : container)
{ {
converter.apply(L, *i); converter.apply(L, element);
lua_rawseti(L, -2, index); lua_rawseti(L, -2, index);
++index; ++index;
} }
} }
}; };
template<int N, class Policies> template<class Policies = no_policies>
// struct container_policy : converter_policy_tag struct container_policy
struct container_policy : conversion_policy<N>
{ {
// BOOST_STATIC_CONSTANT(int, index = N);
static void precall(lua_State*, const index_map&) {}
static void postcall(lua_State*, const index_map&) {}
struct only_accepts_nonconst_pointers {}; struct only_accepts_nonconst_pointers {};
template<class T, class Direction> template<class T, class Direction>
struct apply struct specialize;
{
typedef typename boost::mpl::if_<boost::is_same<lua_to_cpp, Direction> template<class T>
, container_converter_lua_to_cpp<Policies> struct specialize<T, lua_to_cpp> {
, container_converter_cpp_to_lua<Policies> using type = container_converter_lua_to_cpp<Policies>;
>::type type; };
template<class T>
struct specialize<T, cpp_to_lua> {
using type = container_converter_cpp_to_lua<Policies>;
}; };
}; };
}} }
}
namespace luabind namespace luabind
{ {
template<int N> template<unsigned int N, typename ElementPolicies = no_policies >
detail::policy_cons<detail::container_policy<N, detail::null_type>, detail::null_type> using container_policy = meta::type_list<converter_policy_injector<N, detail::container_policy<ElementPolicies>>>;
container(LUABIND_PLACEHOLDER_ARG(N))
{
return detail::policy_cons<detail::container_policy<N, detail::null_type>, detail::null_type>();
}
template<int N, class Policies>
detail::policy_cons<detail::container_policy<N, Policies>, detail::null_type>
container(LUABIND_PLACEHOLDER_ARG(N), const Policies&)
{
return detail::policy_cons<detail::container_policy<N, Policies>, detail::null_type>();
}
} }
#endif // LUABIND_CONTAINER_POLICY_HPP_INCLUDED #endif // LUABIND_CONTAINER_POLICY_HPP_INCLUDED
+12 -23
View File
@@ -8,52 +8,41 @@
# include <luabind/detail/policy.hpp> # include <luabind/detail/policy.hpp>
namespace luabind { namespace luabind {
namespace detail {
namespace detail
{
struct copy_converter struct copy_converter
{ {
template <class T> template <class T>
void apply(lua_State* L, T const& x) void to_lua(lua_State* L, T const& x)
{ {
value_converter().apply(L, x); value_converter().to_lua(L, x);
} }
template <class T> template <class T>
void apply(lua_State* L, T* x) void to_lua(lua_State* L, T* x)
{ {
if(!x) if(!x)
lua_pushnil(L); lua_pushnil(L);
else else
apply(L, *x); to_lua(L, *x);
} }
}; };
template <int N> struct copy_policy
struct copy_policy : conversion_policy<N>
{ {
static void precall(lua_State*, index_map const&)
{}
static void postcall(lua_State*, index_map const&)
{}
template <class T, class Direction> template <class T, class Direction>
struct apply struct specialize
{ {
typedef copy_converter type; static_assert(std::is_same<Direction, cpp_to_lua>::value, "Copy policy only supports cpp -> lua");
using type = copy_converter;
}; };
}; };
} // namespace detail } // namespace detail
template <int N> // Caution: If we use the aliased type "policy_list" here, MSVC crashes.
detail::policy_cons<detail::copy_policy<N>, detail::null_type> template< unsigned int N >
copy(LUABIND_PLACEHOLDER_ARG(N)) using copy_policy = meta::type_list< converter_policy_injector< N, detail::copy_policy > >;
{
return detail::policy_cons<detail::copy_policy<N>, detail::null_type>();
}
} // namespace luabind } // namespace luabind
+45 -65
View File
@@ -25,95 +25,75 @@
#define LUABIND_DEPENDENCY_POLICY_HPP_INCLUDED #define LUABIND_DEPENDENCY_POLICY_HPP_INCLUDED
#include <luabind/config.hpp> #include <luabind/config.hpp>
#include <luabind/detail/policy.hpp> #include <luabind/detail/policy.hpp> // for policy_cons, etc
#include <luabind/detail/object_rep.hpp> // for object_rep
#include <luabind/detail/primitives.hpp> // for null_type
namespace luabind {
namespace detail {
namespace luabind { namespace detail
{
// makes A dependent on B, meaning B will outlive A. // makes A dependent on B, meaning B will outlive A.
// internally A stores a reference to B // internally A stores a reference to B
template<int A, int B> template<int A, int B>
struct dependency_policy struct dependency_policy
{ {
static void postcall(lua_State* L, const index_map& indices) template< unsigned int... StackIndices >
static void postcall(lua_State* L, int results, meta::index_list<StackIndices...>)
{ {
int nurse_index = indices[A]; object_rep* nurse = static_cast<object_rep*>(lua_touserdata(L, meta::get<meta::index_list<StackIndices...>, A>::value));
int patient = indices[B];
object_rep* nurse = static_cast<object_rep*>(lua_touserdata(L, nurse_index));
// If the nurse isn't an object_rep, just make this a nop. // If the nurse isn't an object_rep, just make this a nop.
if(nurse == 0) if(nurse == 0)
return; return;
nurse->add_dependency(L, patient); nurse->add_dependency(L, meta::get<meta::index_list<StackIndices...>, B>::value);
} }
}; };
}} template<int B>
struct dependency_policy<0, B>
{
template< unsigned int... StackIndices >
static void postcall(lua_State* L, int results, meta::index_list<StackIndices...>)
{
object_rep* nurse = static_cast<object_rep*>(lua_touserdata(L, meta::get<meta::index_list<StackIndices...>, 0>::value + results));
#if defined (BOOST_MSVC) && (BOOST_MSVC <= 1200) // If the nurse isn't an object_rep, just make this a nop.
if(nurse == 0)
return;
namespace luabind nurse->add_dependency(L, meta::get<meta::index_list<StackIndices...>, B>::value);
{ }
// most absurd workaround of all time?
namespace detail
{
template<int N>
struct size_char_array
{
char storage[N + 2];
}; };
template<int N>
size_char_array<N> deduce_size(LUABIND_PLACEHOLDER_ARG(N));
template<class T>
struct get_index_workaround
{
static T t;
BOOST_STATIC_CONSTANT(int, value = sizeof(deduce_size(t)) - 2);
};
}
template<class A, class B>
detail::policy_cons<detail::dependency_policy<detail::get_index_workaround<A>::value
, detail::get_index_workaround<B>::value>, detail::null_type> dependency(A,B)
{
return detail::policy_cons<detail::dependency_policy<
detail::get_index_workaround<A>::value, detail::get_index_workaround<B>::value>
, detail::null_type>();
}
template<class A>
detail::policy_cons<detail::dependency_policy<0
, detail::get_index_workaround<A>::value>, detail::null_type>
return_internal_reference(A)
{
return detail::policy_cons<detail::dependency_policy<0
, detail::get_index_workaround<A>::value>, detail::null_type>();
}
}
#else
namespace luabind
{
template<int A, int B>
detail::policy_cons<detail::dependency_policy<A, B>, detail::null_type>
dependency(LUABIND_PLACEHOLDER_ARG(A), LUABIND_PLACEHOLDER_ARG(B))
{
return detail::policy_cons<detail::dependency_policy<A, B>, detail::null_type>();
}
template<int A> template<int A>
detail::policy_cons<detail::dependency_policy<0, A>, detail::null_type> struct dependency_policy<A, 0>
return_internal_reference(LUABIND_PLACEHOLDER_ARG(A))
{ {
return detail::policy_cons<detail::dependency_policy<0, A>, detail::null_type>(); template< unsigned int... StackIndices >
static void postcall(lua_State* L, int results, meta::index_list<StackIndices...>)
{
object_rep* nurse = static_cast<object_rep*>(lua_touserdata(L, meta::get<meta::index_list<StackIndices...>, A>::value));
// If the nurse isn't an object_rep, just make this a nop.
if(nurse == 0)
return;
nurse->add_dependency(L, meta::get<meta::index_list<StackIndices...>, 0>::value + results);
}
};
} }
} }
#endif namespace luabind
{
// Caution: If we use the aliased type "policy_list" here, MSVC crashes.
template<unsigned int A, unsigned int B>
using dependency_policy = meta::type_list<call_policy_injector<detail::dependency_policy<A, B>>>;
template<unsigned int A>
using return_internal_reference = meta::type_list<call_policy_injector<detail::dependency_policy<0, A>>>;
}
#endif // LUABIND_DEPENDENCY_POLICY_HPP_INCLUDED #endif // LUABIND_DEPENDENCY_POLICY_HPP_INCLUDED
+467 -243
View File
@@ -1,30 +1,24 @@
// Copyright Daniel Wallin 2008. Use, modification and distribution is // Copyright Daniel Wallin 208.Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying // subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#if !BOOST_PP_IS_ITERATING
#ifndef LUABIND_CALL2_080911_HPP #ifndef LUABIND_CALL2_080911_HPP
#define LUABIND_CALL2_080911_HPP #define LUABIND_CALL2_080911_HPP
# include <boost/mpl/apply_wrap.hpp>
# include <boost/mpl/begin_end.hpp>
# include <boost/mpl/deref.hpp>
# include <boost/mpl/front.hpp>
# include <boost/mpl/long.hpp>
# include <boost/mpl/size.hpp>
# include <boost/preprocessor/control/if.hpp>
# include <boost/preprocessor/iteration/iterate.hpp>
# include <boost/preprocessor/iteration/local.hpp>
# include <boost/preprocessor/repetition/enum.hpp>
# include <boost/preprocessor/repetition/enum_trailing_params.hpp>
# include <boost/type_traits/is_void.hpp>
#include <luabind/config.hpp> #include <luabind/config.hpp>
#include <typeinfo>
#include <luabind/detail/meta.hpp>
#include <luabind/detail/policy.hpp> #include <luabind/detail/policy.hpp>
#include <luabind/yield_policy.hpp> #include <luabind/yield_policy.hpp>
#include <luabind/detail/decorate_type.hpp>
#include <luabind/detail/object.hpp>
namespace luabind { namespace detail { #ifdef LUABIND_NO_INTERNAL_TAG_ARGUMENTS
#include <tuple>
#endif
namespace luabind {
namespace detail {
struct invoke_context; struct invoke_context;
@@ -38,8 +32,7 @@ struct LUABIND_API function_object
virtual ~function_object() virtual ~function_object()
{} {}
virtual int call( virtual int call(lua_State* L, invoke_context& ctx) /* const */ = 0;
lua_State* L, invoke_context& ctx) const = 0;
virtual void format_signature(lua_State* L, char const* function) const = 0; virtual void format_signature(lua_State* L, char const* function) const = 0;
lua_CFunction entry; lua_CFunction entry;
@@ -52,6 +45,9 @@ struct LUABIND_API invoke_context
{ {
invoke_context() invoke_context()
: best_score((std::numeric_limits<int>::max)()) : best_score((std::numeric_limits<int>::max)())
//This need to avoid static analyzer's treats
, candidates{ nullptr,nullptr,nullptr,nullptr,nullptr,
nullptr,nullptr,nullptr,nullptr,nullptr }
, candidate_index(0) , candidate_index(0)
{} {}
@@ -63,210 +59,198 @@ struct LUABIND_API invoke_context
void format_error(lua_State* L, function_object const* overloads) const; void format_error(lua_State* L, function_object const* overloads) const;
int best_score; int best_score;
function_object const* candidates[10]; function_object const* candidates[10]; // This looks like it could crash if you provide too many overloads?
int candidate_index; int candidate_index;
}; };
template <class F, class Signature, class Policies, class IsVoid> namespace call_detail_new {
inline int invoke0(
lua_State* L, function_object const& self, invoke_context& ctx /*
, F const& f, Signature, Policies const& policies, IsVoid, mpl::true_) Compute Stack Indices
Given the list of argument converter arities, computes the stack indices that each converter addresses.
*/
template< typename ConsumedList, unsigned int CurrentSum, unsigned int... StackIndices >
struct compute_stack_indices;
template< unsigned int Consumed0, unsigned int... Consumeds, unsigned int CurrentSum, unsigned int... StackIndices >
struct compute_stack_indices< meta::index_list< Consumed0, Consumeds... >, CurrentSum, StackIndices... >
{ {
return invoke_member( using type = typename compute_stack_indices< meta::index_list< Consumeds... >, CurrentSum + Consumed0, StackIndices..., CurrentSum >::type;
L, self, ctx, f, Signature(), policies
, mpl::long_<mpl::size<Signature>::value - 1>(), IsVoid()
);
}
template <class F, class Signature, class Policies, class IsVoid>
inline int invoke0(
lua_State* L, function_object const& self, invoke_context& ctx,
F const& f, Signature, Policies const& policies, IsVoid, mpl::false_)
{
return invoke_normal(
L, self, ctx, f, Signature(), policies
, mpl::long_<mpl::size<Signature>::value - 1>(), IsVoid()
);
}
template <class F, class Signature, class Policies>
inline int invoke(
lua_State* L, function_object const& self, invoke_context& ctx
, F const& f, Signature, Policies const& policies)
{
return invoke0(
L, self, ctx, f, Signature(), policies
, boost::is_void<typename mpl::front<Signature>::type>()
, boost::is_member_function_pointer<F>()
);
}
inline int maybe_yield_aux(lua_State*, int results, mpl::false_)
{
return results;
}
inline int maybe_yield_aux(lua_State* L, int results, mpl::true_)
{
return lua_yield(L, results);
}
template <class Policies>
int maybe_yield(lua_State* L, int results, Policies*)
{
return maybe_yield_aux(
L, results, mpl::bool_<has_yield<Policies>::value>());
}
inline int sum_scores(int const* first, int const* last)
{
int result = 0;
for (; first != last; ++first)
{
if (*first < 0)
return *first;
result += *first;
}
return result;
}
# define LUABIND_INVOKE_NEXT_ITER(n) \
typename mpl::next< \
BOOST_PP_IF( \
n, BOOST_PP_CAT(iter,BOOST_PP_DEC(n)), first) \
>::type
# define LUABIND_INVOKE_NEXT_INDEX(n) \
BOOST_PP_IF( \
n \
, BOOST_PP_CAT(index,BOOST_PP_DEC(n)) + \
BOOST_PP_CAT(c,BOOST_PP_DEC(n)).consumed_args() \
, 1 \
)
# define LUABIND_INVOKE_COMPUTE_ARITY(n) + BOOST_PP_CAT(c,n).consumed_args()
# define LUABIND_INVOKE_DECLARE_CONVERTER(n) \
typedef LUABIND_INVOKE_NEXT_ITER(n) BOOST_PP_CAT(iter,n); \
typedef typename mpl::deref<BOOST_PP_CAT(iter,n)>::type \
BOOST_PP_CAT(a,n); \
typedef typename find_conversion_policy<n + 1, Policies>::type \
BOOST_PP_CAT(p,n); \
typename mpl::apply_wrap2< \
BOOST_PP_CAT(p,n), BOOST_PP_CAT(a,n), lua_to_cpp>::type BOOST_PP_CAT(c,n); \
int const BOOST_PP_CAT(index,n) = LUABIND_INVOKE_NEXT_INDEX(n);
# define LUABIND_INVOKE_COMPUTE_SCORE(n) \
, BOOST_PP_CAT(c,n).match( \
L, LUABIND_DECORATE_TYPE(BOOST_PP_CAT(a,n)), BOOST_PP_CAT(index,n))
# define LUABIND_INVOKE_ARG(z, n, base) \
BOOST_PP_CAT(c,base(n)).apply( \
L, LUABIND_DECORATE_TYPE(BOOST_PP_CAT(a,base(n))), BOOST_PP_CAT(index,base(n)))
# define LUABIND_INVOKE_CONVERTER_POSTCALL(n) \
BOOST_PP_CAT(c,n).converter_postcall( \
L, LUABIND_DECORATE_TYPE(BOOST_PP_CAT(a,n)), BOOST_PP_CAT(index,n));
# define BOOST_PP_ITERATION_PARAMS_1 \
(3, (0, LUABIND_MAX_ARITY, <luabind/detail/call.hpp>))
# include BOOST_PP_ITERATE()
# define LUABIND_INVOKE_VOID
# define BOOST_PP_ITERATION_PARAMS_1 \
(3, (0, LUABIND_MAX_ARITY, <luabind/detail/call.hpp>))
# include BOOST_PP_ITERATE()
# undef LUABIND_INVOKE_VOID
# define LUABIND_INVOKE_MEMBER
# define BOOST_PP_ITERATION_PARAMS_1 \
(3, (0, LUABIND_MAX_ARITY, <luabind/detail/call.hpp>))
# include BOOST_PP_ITERATE()
# define LUABIND_INVOKE_VOID
# define BOOST_PP_ITERATION_PARAMS_1 \
(3, (0, LUABIND_MAX_ARITY, <luabind/detail/call.hpp>))
# include BOOST_PP_ITERATE()
}} // namespace luabind::detail
# endif // LUABIND_CALL2_080911_HPP
#else // BOOST_PP_IS_ITERATING
# ifdef LUABIND_INVOKE_MEMBER
# define N BOOST_PP_INC(BOOST_PP_ITERATION())
# else
# define N BOOST_PP_ITERATION()
# endif
template <class F, class Signature, class Policies>
inline int
# ifdef LUABIND_INVOKE_MEMBER
invoke_member
# else
invoke_normal
# endif
(
lua_State* L, function_object const& self, invoke_context& ctx
, F const& f, Signature, Policies const&, mpl::long_<N>
# ifdef LUABIND_INVOKE_VOID
, mpl::true_
# else
, mpl::false_
# endif
)
{
typedef typename mpl::begin<Signature>::type first;
# ifndef LUABIND_INVOKE_VOID
typedef typename mpl::deref<first>::type result_type;
typedef typename find_conversion_policy<0, Policies>::type result_policy;
typename mpl::apply_wrap2<
result_policy, result_type, cpp_to_lua>::type result_converter;
# endif
# if N > 0
# define BOOST_PP_LOCAL_MACRO(n) LUABIND_INVOKE_DECLARE_CONVERTER(n)
# define BOOST_PP_LOCAL_LIMITS (0,N-1)
# include BOOST_PP_LOCAL_ITERATE()
# endif
int const arity = 0
# if N > 0
# define BOOST_PP_LOCAL_MACRO(n) LUABIND_INVOKE_COMPUTE_ARITY(n)
# define BOOST_PP_LOCAL_LIMITS (0,N-1)
# include BOOST_PP_LOCAL_ITERATE()
# endif
;
int const arguments = lua_gettop(L);
int score = -1;
if (arity == arguments)
{
int const scores[] = {
0
# if N > 0
# define BOOST_PP_LOCAL_MACRO(n) LUABIND_INVOKE_COMPUTE_SCORE(n)
# define BOOST_PP_LOCAL_LIMITS (0,N-1)
# include BOOST_PP_LOCAL_ITERATE()
# endif
}; };
score = sum_scores(scores + 1, scores + 1 + N); template< unsigned int CurrentSum, unsigned int... StackIndices >
struct compute_stack_indices< meta::index_list< >, CurrentSum, StackIndices... >
{
using type = meta::index_list< StackIndices... >;
};
template< typename Foo >
struct FooFoo { // Foo!
enum { consumed_args = Foo::consumed_args };
};
template< typename PolicyList, typename StackIndexList >
struct policy_list_postcall;
template< typename Policy0, typename... Policies, typename StackIndexList >
struct policy_list_postcall< meta::type_list< call_policy_injector<Policy0>, Policies... >, StackIndexList > {
static void postcall(lua_State* L, int results) {
Policy0::postcall(L, results, StackIndexList());
policy_list_postcall< meta::type_list< Policies... >, StackIndexList >::postcall(L, results);
}
};
template< typename ConverterPolicy, typename StackIndexList, bool has_postcall >
struct converter_policy_postcall {
static void postcall(lua_State* L, int results) {
ConverterPolicy::postcall(L, results, StackIndexList());
}
};
template< typename ConverterPolicy, typename StackIndexList >
struct converter_policy_postcall< ConverterPolicy, StackIndexList, false > {
static void postcall(lua_State* /*L*/, int /*results*/) {
}
};
template< unsigned int Index, typename Policy, typename... Policies, typename StackIndexList >
struct policy_list_postcall< meta::type_list< converter_policy_injector< Index, Policy >, Policies... >, StackIndexList > {
static void postcall(lua_State* L, int results) {
converter_policy_postcall < Policy, StackIndexList, converter_policy_injector< Index, Policy >::has_postcall >::postcall(L, results);
policy_list_postcall< meta::type_list< Policies... >, StackIndexList >::postcall(L, results);
}
};
template< typename StackIndexList >
struct policy_list_postcall< meta::type_list< >, StackIndexList > {
static void postcall(lua_State* /*L*/, int /*results*/) {}
};
#ifndef LUABIND_NO_INTERNAL_TAG_ARGUMENTS
template< typename... ArgumentConverters >
struct compute_invoke_values {
using consumed_list = meta::index_list< FooFoo<ArgumentConverters>::consumed_args... >;
using stack_index_list = typename compute_stack_indices< consumed_list, 1 >::type;
enum { arity = meta::sum<consumed_list>::value };
};
#endif
} }
if (score >= 0 && score < ctx.best_score) #ifndef LUABIND_NO_INTERNAL_TAG_ARGUMENTS
inline int match_deferred(lua_State* L, meta::index_list<>, meta::type_list<>)
{ {
return 0;
}
template< unsigned int StackIndex0, unsigned int... StackIndices,
typename ArgumentType0, typename... ArgumentTypes,
typename ArgumentConverter0, typename... ArgumentConverters >
int match_deferred(lua_State* L,
meta::index_list< StackIndex0, StackIndices... >,
meta::type_list< ArgumentType0, ArgumentTypes... >,
ArgumentConverter0& converter0, ArgumentConverters&... converters
)
{
const int this_match = converter0.match(L, decorated_type<ArgumentType0>(), StackIndex0);
const int other_match = match_deferred(L, meta::index_list<StackIndices...>(), meta::type_list<ArgumentTypes...>(), converters...);
return (this_match >= 0) ? // could also sum them all up unconditionally
this_match + match_deferred(L, meta::index_list<StackIndices...>(), meta::type_list<ArgumentTypes...>(), converters...)
: no_match;
}
template< typename T, bool isvoid, bool memfun = std::is_member_function_pointer<T>::value > struct do_call_struct;
template< typename T >
struct do_call_struct< T, true, true /*memfun*/> {
template< typename F, typename ArgumentType0, typename... ArgumentTypes, unsigned int StackIndex0, unsigned int... StackIndices, typename ReturnConverter, typename Argument0Converter, typename... ArgumentConverters >
static void do_call(lua_State* L, F& f,
meta::index_list<StackIndex0, StackIndices...>, meta::type_list<ArgumentType0, ArgumentTypes...>,
ReturnConverter& result_converter, Argument0Converter& arg0_converter, ArgumentConverters&... arg_converters
)
{
((arg0_converter.to_cpp(L, decorated_type<ArgumentType0>(), StackIndex0)).*f)(
arg_converters.to_cpp(L, decorated_type<ArgumentTypes>(), StackIndices)...
);
}
};
template< typename T >
struct do_call_struct< T, false, true /*memfun*/> {
template< typename F, typename ArgumentType0, typename... ArgumentTypes, unsigned int StackIndex0, unsigned int... StackIndices, typename ReturnConverter, typename Argument0Converter, typename... ArgumentConverters >
static void do_call(lua_State* L, F& f,
meta::index_list<StackIndex0, StackIndices...>, meta::type_list<ArgumentType0, ArgumentTypes...>,
ReturnConverter& result_converter, Argument0Converter& arg0_converter, ArgumentConverters&... arg_converters
)
{
result_converter.to_lua(L,
((arg0_converter.to_cpp(L, decorated_type<ArgumentType0>(), StackIndex0)).*f)(
arg_converters.to_cpp(L, decorated_type<ArgumentTypes>(), StackIndices)...
)
);
}
};
template< typename T >
struct do_call_struct< T, true, false > {
template<
typename F,
typename... ArgumentTypes, unsigned int... StackIndices,
typename ReturnConverter, typename... ArgumentConverters
>
static void do_call(lua_State* L, F& f,
meta::index_list<StackIndices...>, meta::type_list<ArgumentTypes...>,
ReturnConverter& result_converter, ArgumentConverters&... arg_converters)
{
f(arg_converters.to_cpp(L, decorated_type<ArgumentTypes>(), StackIndices)...);
}
};
template< typename T >
struct do_call_struct< T, false, false > {
template<
typename F,
typename... ArgumentTypes, unsigned int... StackIndices,
typename ReturnConverter, typename... ArgumentConverters
>
static void do_call(lua_State* L, F& f,
meta::index_list<StackIndices...>, meta::type_list<ArgumentTypes...>,
ReturnConverter& result_converter, ArgumentConverters&... arg_converters)
{
result_converter.to_lua(L,
f(arg_converters.to_cpp(L, decorated_type<ArgumentTypes>(), StackIndices)...)
);
}
};
template< typename F, typename ReturnType, typename... Arguments,
typename ReturnConverter, typename... ArgumentConverters,
unsigned int Index0, unsigned int... Indices, typename PolicyList
>
int invoke3(lua_State* L, function_object const& self, invoke_context& ctx, F& f,
PolicyList, meta::index_list< Index0, Indices... > index_list, meta::type_list<ReturnType, Arguments...> signature_list,
ReturnConverter return_converter, ArgumentConverters... argument_converters)
{
using invoke_values = typename call_detail_new::compute_invoke_values< ArgumentConverters... >;
using argument_list_type = meta::type_list<Arguments...>;
using argument_index_list = meta::index_list<Indices...>;
int const arguments = lua_gettop(L);
int score = no_match;
if(invoke_values::arity == arguments) {
score = match_deferred(L, typename invoke_values::stack_index_list(), argument_list_type(), argument_converters...);
}
if(score >= 0 && score < ctx.best_score) {
ctx.best_score = score; ctx.best_score = score;
ctx.candidates[0] = &self; ctx.candidates[0] = &self;
ctx.candidate_index = 1; ctx.candidate_index = 1;
} } else if(score == ctx.best_score) {
else if (score == ctx.best_score)
{
ctx.candidates[ctx.candidate_index++] = &self; ctx.candidates[ctx.candidate_index++] = &self;
} }
@@ -279,45 +263,285 @@ invoke_normal
if(score == ctx.best_score && ctx.candidate_index == 1) if(score == ctx.best_score && ctx.candidate_index == 1)
{ {
# ifndef LUABIND_INVOKE_VOID do_call_struct<F, std::is_void<ReturnType>::value>::do_call(L, f, typename invoke_values::stack_index_list(), argument_list_type(), return_converter, argument_converters...);
result_converter.apply( meta::init_order{ (argument_converters.converter_postcall(L, decorated_type<Arguments>(), meta::get< typename invoke_values::stack_index_list, Indices - 1 >::value), 0)... };
L,
# endif
# ifdef LUABIND_INVOKE_MEMBER
(c0.apply(L, LUABIND_DECORATE_TYPE(a0), index0).*f)(
BOOST_PP_ENUM(BOOST_PP_DEC(N), LUABIND_INVOKE_ARG, BOOST_PP_INC)
)
# else
# define LUABIND_INVOKE_IDENTITY(x) x
f(
BOOST_PP_ENUM(N, LUABIND_INVOKE_ARG, LUABIND_INVOKE_IDENTITY)
)
# undef LUABIND_INVOKE_IDENTITY
# endif
# ifndef LUABIND_INVOKE_VOID
)
# endif
;
# if N > 0 results = lua_gettop(L) - invoke_values::arity;
# define BOOST_PP_LOCAL_MACRO(n) LUABIND_INVOKE_CONVERTER_POSTCALL(n) if(has_call_policy<PolicyList, yield_policy>::value) {
# define BOOST_PP_LOCAL_LIMITS (0,N-1) results = lua_yield(L, results);
# include BOOST_PP_LOCAL_ITERATE() }
# endif
results = maybe_yield(L, lua_gettop(L) - arguments, (Policies*)0); // call policiy list postcall
call_detail_new::policy_list_postcall < PolicyList, typename meta::push_front< typename invoke_values::stack_index_list, meta::index<invoke_values::arity> >::type >::postcall(L, results);
int const indices[] = {
arguments + results BOOST_PP_ENUM_TRAILING_PARAMS(N, index)
};
policy_list_postcall<Policies>::apply(L, indices);
} }
return results; return results;
} }
# undef N template< typename F, typename ReturnType, typename... Arguments, unsigned int Index0, unsigned int... Indices, typename PolicyList >
int invoke2(lua_State* L, function_object const& self, invoke_context& ctx, F& f,
meta::type_list<ReturnType, Arguments...> signature, meta::index_list<Index0, Indices...>, PolicyList)
{
using signature_type = meta::type_list<ReturnType, Arguments...>;
using return_converter = specialized_converter_policy_n<0, PolicyList, ReturnType, cpp_to_lua>;
return invoke3(L, self, ctx, f,
PolicyList(), meta::index_list<Index0, Indices...>(), signature,
return_converter(), specialized_converter_policy_n<Indices, PolicyList, Arguments, lua_to_cpp>()...
);
}
template <class F, class Signature, typename... PolicyInjectors>
// boost::bind's operator() is const, std::bind's is not
inline int invoke(lua_State* L, function_object const& self, invoke_context& ctx, F& f, Signature,
meta::type_list< PolicyInjectors... > const& injectors)
{
return invoke2(L, self, ctx, f, Signature(), typename meta::make_index_range<0, meta::size<Signature>::value>::type(), injectors);
}
#endif #endif
#ifdef LUABIND_NO_INTERNAL_TAG_ARGUMENTS
// VC2013RC doesn't support expanding a template and its member template in one expression, that's why we have to to incrementally build
// the converter list instead of a single combined expansion.
template< typename ArgumentList, typename PolicyList, typename CurrentList = meta::type_list<>, unsigned int Counter = 1 >
struct compute_argument_converter_list;
template< typename Argument0, typename... Arguments, typename PolicyList, typename... CurrentConverters, unsigned int Counter >
struct compute_argument_converter_list< meta::type_list<Argument0, Arguments... >, PolicyList, meta::type_list<CurrentConverters...>, Counter >
{
using converter_type = typename policy_detail::get_converter_policy<Counter, PolicyList>::type;
using this_specialized = typename converter_type::template specialize<Argument0, lua_to_cpp >::type;
using type = typename compute_argument_converter_list<meta::type_list<Arguments...>, PolicyList, meta::type_list<CurrentConverters..., this_specialized>, Counter + 1>::type;
};
template<typename PolicyList, typename... CurrentConverters, unsigned int Counter >
struct compute_argument_converter_list< meta::type_list<>, PolicyList, meta::type_list<CurrentConverters...>, Counter >
{
using type = meta::type_list<CurrentConverters...>;
};
template< typename ConverterList >
struct build_consumed_list;
template< typename... Converters >
struct build_consumed_list< meta::type_list< Converters... > > {
using consumed_list = meta::index_list< call_detail_new::FooFoo<Converters>::consumed_args... >;
};
template< typename SignatureList, typename PolicyList >
struct invoke_traits;
// Specialization for free functions
template< typename ResultType, typename... Arguments, typename PolicyList >
struct invoke_traits< meta::type_list<ResultType, Arguments... >, PolicyList >
{
using signature_list = meta::type_list<ResultType, Arguments...>;
using policy_list = PolicyList;
using result_type = ResultType;
using result_converter = specialized_converter_policy_n<0, PolicyList, result_type, cpp_to_lua >;
using argument_list = meta::type_list<Arguments...>;
using decorated_argument_list = meta::type_list< decorate_type_t<Arguments>... >;
// note that this is 0-based, so whenever you want to fetch from the converter list, you need to add 1
using argument_index_list = typename meta::make_index_range< 0, sizeof...(Arguments) >::type;
using argument_converter_list = typename compute_argument_converter_list<argument_list, PolicyList>::type;
using argument_converter_tuple_type = typename meta::make_tuple<argument_converter_list>::type;
using consumed_list = typename build_consumed_list<argument_converter_list>::consumed_list;
using stack_index_list = typename call_detail_new::compute_stack_indices< consumed_list, 1 >::type;
enum { arity = meta::sum<consumed_list>::value };
};
template< typename StackIndexList, typename SignatureList, unsigned int End = meta::size<SignatureList>::value, unsigned int Index = 1 >
struct match_struct {
template< typename TupleType >
static int match(lua_State* L, TupleType& tuple)
{
const int this_match = std::get<Index - 1>(tuple).match(L, decorate_type_t<typename SignatureList::template at<Index>>(), meta::get<StackIndexList, Index - 1>::value);
return this_match >= 0 ? // could also sum them up unconditionally
this_match + match_struct<StackIndexList, SignatureList, End, Index + 1>::match(L, tuple)
: no_match;
}
};
template< typename StackIndexList, typename SignatureList, unsigned int Index >
struct match_struct< StackIndexList, SignatureList, Index, Index >
{
template< typename TupleType >
static int match(lua_State* /*L*/, TupleType&) {
return 0;
}
};
template< typename PolicyList, typename Signature, typename F >
struct invoke_struct
{
using traits = invoke_traits< Signature, PolicyList >;
template< bool IsMember, bool IsVoid, typename IndexList >
struct call_struct;
template< unsigned int... ArgumentIndices >
struct call_struct< false /*member*/, false /*void*/, meta::index_list<ArgumentIndices...> >
{
static void call(lua_State* L, F& f, typename traits::argument_converter_tuple_type& argument_tuple)
{
using decorated_list = typename traits::decorated_argument_list;
using stack_indices = typename traits::stack_index_list;
using result_converter = typename traits::result_converter;
result_converter().to_lua(L,
f((std::get<ArgumentIndices>(argument_tuple).to_cpp(L,
typename meta::get<decorated_list, ArgumentIndices>::type(),
meta::get<stack_indices, ArgumentIndices>::value))...
)
);
meta::init_order{
(std::get<ArgumentIndices>(argument_tuple).converter_postcall(L,
typename meta::get<typename traits::decorated_argument_list, ArgumentIndices>::type(),
meta::get<typename traits::stack_index_list, ArgumentIndices>::value), 0)...
};
}
};
template< unsigned int... ArgumentIndices >
struct call_struct< false /*member*/, true /*void*/, meta::index_list<ArgumentIndices...> >
{
static void call(lua_State* L, F& f, typename traits::argument_converter_tuple_type& argument_tuple)
{
using decorated_list = typename traits::decorated_argument_list;
using stack_indices = typename traits::stack_index_list;
// This prevents unused warnings with empty parameter lists
(void)L;
f(std::get<ArgumentIndices>(argument_tuple).to_cpp(L,
typename meta::get<decorated_list, ArgumentIndices>::type(),
meta::get<stack_indices, ArgumentIndices>::value)...
);
meta::init_order{
(std::get<ArgumentIndices>(argument_tuple).converter_postcall(L,
typename meta::get<typename traits::decorated_argument_list, ArgumentIndices>::type(),
meta::get<typename traits::stack_index_list, ArgumentIndices>::value), 0)...
};
}
};
template< unsigned int ClassIndex, unsigned int... ArgumentIndices >
struct call_struct< true /*member*/, false /*void*/, meta::index_list<ClassIndex, ArgumentIndices...> >
{
static void call(lua_State* L, F& f, typename traits::argument_converter_tuple_type& argument_tuple)
{
using decorated_list = typename traits::decorated_argument_list;
using stack_indices = typename traits::stack_index_list;
using result_converter = typename traits::result_converter;
auto& object = std::get<0>(argument_tuple).to_cpp(L,
typename meta::get<typename traits::decorated_argument_list, 0>::type(), 1);
result_converter().to_lua(L,
(object.*f)(std::get<ArgumentIndices>(argument_tuple).to_cpp(L,
typename meta::get<decorated_list, ArgumentIndices>::type(),
meta::get<stack_indices, ArgumentIndices>::value)...
)
);
meta::init_order{
(std::get<ArgumentIndices>(argument_tuple).converter_postcall(L,
typename meta::get<typename traits::decorated_argument_list, ArgumentIndices>::type(),
meta::get<typename traits::stack_index_list, ArgumentIndices>::value), 0)...
};
}
};
template< unsigned int ClassIndex, unsigned int... ArgumentIndices >
struct call_struct< true /*member*/, true /*void*/, meta::index_list<ClassIndex, ArgumentIndices...> >
{
static void call(lua_State* L, F& f, typename traits::argument_converter_tuple_type& argument_tuple)
{
using decorated_list = typename traits::decorated_argument_list;
using stack_indices = typename traits::stack_index_list;
auto& object = std::get<0>(argument_tuple).to_cpp(L, typename meta::get<typename traits::decorated_argument_list, 0>::type(), 1);
(object.*f)(std::get<ArgumentIndices>(argument_tuple).to_cpp(L,
typename meta::get<decorated_list, ArgumentIndices>::type(),
meta::get<stack_indices, ArgumentIndices>::value)...
);
meta::init_order{
(std::get<ArgumentIndices>(argument_tuple).converter_postcall(L,
typename meta::get<typename traits::decorated_argument_list, ArgumentIndices>::type(),
meta::get<typename traits::stack_index_list, ArgumentIndices>::value), 0)...
};
}
};
static int invoke(lua_State* L, function_object const& self, invoke_context& ctx, F& f) {
int const arguments = lua_gettop(L);
int score = no_match;
// Even match needs the tuple, since pointer_converters buffer the cast result
typename traits::argument_converter_tuple_type converter_tuple;
if(traits::arity == arguments) {
// Things to remember:
// 0 is the perfect match. match > 0 means that objects had to be casted, where the value
// is the total distance of all arguments to their given types (graph distance).
// This is why we can say MaxArguments = 100, MaxDerivationDepth = 100, so no match will be > 100*100=10k and -10k1 absorbs every match.
// This gets rid of the awkward checks during converter match traversal.
using struct_type = match_struct< typename traits::stack_index_list, typename traits::signature_list >;
score = struct_type::match(L, converter_tuple);
}
if(score >= 0 && score < ctx.best_score) {
ctx.best_score = score;
ctx.candidates[0] = &self;
ctx.candidate_index = 1;
} else if(score == ctx.best_score) {
ctx.candidates[ctx.candidate_index++] = &self;
}
int results = 0;
if(self.next)
{
results = self.next->call(L, ctx);
}
if(score == ctx.best_score && ctx.candidate_index == 1)
{
call_struct<
std::is_member_function_pointer<F>::value,
std::is_void<typename traits::result_type>::value,
typename traits::argument_index_list
>::call(L, f, converter_tuple);
results = lua_gettop(L) - traits::arity;
if(has_call_policy<PolicyList, yield_policy>::value) {
results = lua_yield(L, results);
}
call_detail_new::policy_list_postcall < PolicyList, typename meta::push_front< typename traits::stack_index_list, meta::index<traits::arity> >::type >::postcall(L, results);
}
return results;
}
};
template< typename PolicyList, typename Signature, typename F>
inline int invoke(lua_State* L, function_object const& self, invoke_context& ctx, F& f)
{
return invoke_struct<PolicyList, Signature, F>::invoke(L, self, ctx, f);
}
#endif
}
} // namespace luabind::detail
# endif // LUABIND_CALL2_080911_HPP
+111 -359
View File
@@ -20,423 +20,175 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
// OR OTHER DEALINGS IN THE SOFTWARE. // OR OTHER DEALINGS IN THE SOFTWARE.
#if !BOOST_PP_IS_ITERATING
#ifndef LUABIND_CALL_FUNCTION_HPP_INCLUDED #ifndef LUABIND_CALL_FUNCTION_HPP_INCLUDED
#define LUABIND_CALL_FUNCTION_HPP_INCLUDED #define LUABIND_CALL_FUNCTION_HPP_INCLUDED
#include <luabind/config.hpp> #include <luabind/config.hpp>
#include <boost/mpl/if.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/mpl/or.hpp>
#include <boost/preprocessor/repeat.hpp>
#include <boost/preprocessor/iteration/iterate.hpp>
#include <boost/preprocessor/repetition/enum.hpp>
#include <boost/preprocessor/repetition/enum_params.hpp>
#include <boost/preprocessor/repetition/enum_binary_params.hpp>
#include <boost/preprocessor/punctuation/comma_if.hpp>
#include <luabind/error.hpp> #include <luabind/error.hpp>
#include <luabind/detail/convert_to_lua.hpp> #include <luabind/detail/push_to_lua.hpp>
#include <luabind/detail/pcall.hpp> #include <luabind/detail/pcall.hpp>
#include <luabind/detail/call_shared.hpp>
#include <luabind/detail/stack_utils.hpp>
namespace luabind namespace luabind
{ {
namespace detail namespace adl {
{ class object;
// if the proxy_function_caller returns non-void
template<class Ret, class Tuple>
class proxy_function_caller
{
// friend class luabind::object;
public:
typedef int(*function_t)(lua_State*, int, int);
proxy_function_caller(
lua_State* L
, int params
, function_t fun
, const Tuple args)
: m_state(L)
, m_params(params)
, m_fun(fun)
, m_args(args)
, m_called(false)
{
} }
proxy_function_caller(const proxy_function_caller& rhs) using adl::object;
: m_state(rhs.m_state)
, m_params(rhs.m_params) namespace detail {
, m_fun(rhs.m_fun)
, m_args(rhs.m_args) template< typename PolicyList, unsigned int pos >
, m_called(rhs.m_called) void push_arguments(lua_State* /*L*/) {}
template< typename PolicyList, unsigned int Pos, typename Arg0, typename... Args >
void push_arguments(lua_State* L, Arg0&& arg0, Args&&... args)
{ {
rhs.m_called = true; using converter_type = specialized_converter_policy< fetched_converter_policy<Pos, PolicyList>, Arg0, cpp_to_lua >;
converter_type().to_lua(L, unwrapped<Arg0>::get(std::forward<Arg0>(arg0)));
push_arguments<PolicyList, Pos + 1>(L, std::forward<Args>(args)...);
} }
~proxy_function_caller() #ifndef LUABIND_NO_INTERNAL_TAG_ARGUMENTS
template<typename Ret, typename PolicyList, typename... Args, unsigned int... Indices, typename Fn>
void call_function_impl(lua_State* L, int m_params, Fn fn, std::true_type /* void */, meta::index_list<Indices...>, Args&&... args)
{ {
if (m_called) return;
m_called = true;
lua_State* L = m_state;
int top = lua_gettop(L); int top = lua_gettop(L);
push_args_from_tuple<1>::apply(L, m_args); push_arguments<PolicyList, 1>(L, std::forward<Args>(args)...);
if (m_fun(L, boost::tuples::length<Tuple>::value, 0))
{ if(fn(L, sizeof...(Args), 0)) {
assert(lua_gettop(L) == top - m_params + 1); assert(lua_gettop(L) == top - m_params + 1);
#ifndef LUABIND_NO_EXCEPTIONS call_error(L);
throw luabind::error(L);
#else
error_callback_fun e = get_error_callback();
if (e) e(L);
assert(0 && "the lua function threw an error and exceptions are disabled."
" If you want to handle the error you can use luabind::set_error_callback()");
std::terminate();
#endif
} }
// pops the return values from the function call // pops the return values from the function call
stack_pop pop(L, lua_gettop(L) - top + m_params); stack_pop pop(L, lua_gettop(L) - top + m_params);
} }
operator Ret() template<typename Ret, typename PolicyList, typename... Args, unsigned int... Indices, typename Fn>
Ret call_function_impl(lua_State* L, int m_params, Fn fn, std::false_type /* void */, meta::index_list<Indices...>, Args&&... args)
{ {
typename mpl::apply_wrap2<default_policy,Ret,lua_to_cpp>::type converter;
m_called = true;
lua_State* L = m_state;
int top = lua_gettop(L); int top = lua_gettop(L);
push_args_from_tuple<1>::apply(L, m_args); push_arguments<PolicyList, 1>(L, std::forward<Args>(args)...);
if (m_fun(L, boost::tuples::length<Tuple>::value, 1))
{ if(fn(L, sizeof...(Args), 1)) {
assert(lua_gettop(L) == top - m_params + 1); assert(lua_gettop(L) == top - m_params + 1);
#ifndef LUABIND_NO_EXCEPTIONS call_error(L);
throw luabind::error(L);
#else
error_callback_fun e = get_error_callback();
if (e) e(L);
assert(0 && "the lua function threw an error and exceptions are disabled."
" If you want to handle the error you can use luabind::set_error_callback()");
std::terminate();
#endif
} }
// pops the return values from the function call // pops the return values from the function call
stack_pop pop(L, lua_gettop(L) - top + m_params); stack_pop pop(L, lua_gettop(L) - top + m_params);
#ifndef LUABIND_NO_ERROR_CHECKING specialized_converter_policy_n<0, PolicyList, Ret, lua_to_cpp> converter;
if(converter.match(L, decorate_type_t<Ret>(), -1) < 0) {
cast_error<Ret>(L);
}
if (converter.match(L, LUABIND_DECORATE_TYPE(Ret), -1) < 0) return converter.to_cpp(L, decorate_type_t<Ret>(), -1);
{ }
#ifndef LUABIND_NO_EXCEPTIONS
throw cast_failed(L, typeid(Ret));
#else #else
cast_failed_callback_fun e = get_cast_failed_callback(); template<typename Ret, typename PolicyList, typename IndexList, unsigned int NumParams, int(*Function)(lua_State*, int, int), bool IsVoid = std::is_void<Ret>::value>
if (e) e(L, typeid(Ret)); struct call_function_struct;
assert(0 && "the lua function's return value could not be converted." template<typename Ret, typename PolicyList, unsigned int NumParams, int(*Function)(lua_State*, int, int), unsigned int... Indices >
" If you want to handle the error you can use luabind::set_error_callback()"); struct call_function_struct< Ret, PolicyList, meta::index_list<Indices...>, NumParams, Function, true /* void */ >
std::terminate();
#endif
}
#endif
return converter.apply(L, LUABIND_DECORATE_TYPE(Ret), -1);
}
template<class Policies>
Ret operator[](const Policies& p)
{ {
typedef typename detail::find_conversion_policy<0, Policies>::type converter_policy; template< typename... Args >
typename mpl::apply_wrap2<converter_policy,Ret,lua_to_cpp>::type converter; static void call(lua_State* L, Args&&... args) {
m_called = true;
lua_State* L = m_state;
int top = lua_gettop(L); int top = lua_gettop(L);
detail::push_args_from_tuple<1>::apply(L, m_args, p); push_arguments<PolicyList, 1>(L, std::forward<Args>(args)...);
if (m_fun(L, boost::tuples::length<Tuple>::value, 1))
{
assert(lua_gettop(L) == top - m_params + 1);
#ifndef LUABIND_NO_EXCEPTIONS
throw error(L);
#else
error_callback_fun e = get_error_callback();
if (e) e(L);
assert(0 && "the lua function threw an error and exceptions are disabled." if(Function(L, sizeof...(Args), 0)) {
" If you want to handle the error you can use luabind::set_error_callback()"); if(Function == &detail::pcall) {
std::terminate(); assert(lua_gettop(L) == static_cast<int>(top - NumParams + 1));
#endif }
call_error(L);
} }
// pops the return values from the function call // pops the return values from the function call
stack_pop pop(L, lua_gettop(L) - top + m_params); stack_pop pop(L, lua_gettop(L) - top + NumParams);
#ifndef LUABIND_NO_ERROR_CHECKING
if (converter.match(L, LUABIND_DECORATE_TYPE(Ret), -1) < 0)
{
#ifndef LUABIND_NO_EXCEPTIONS
throw cast_failed(L, typeid(Ret));
#else
cast_failed_callback_fun e = get_cast_failed_callback();
if (e) e(L, typeid(Ret));
assert(0 && "the lua function's return value could not be converted."
" If you want to handle the error you can use luabind::set_error_callback()");
std::terminate();
#endif
} }
#endif
return converter.apply(L, LUABIND_DECORATE_TYPE(Ret), -1);
}
private:
lua_State* m_state;
int m_params;
function_t m_fun;
Tuple m_args;
mutable bool m_called;
}; };
// if the proxy_member_caller returns void template<typename Ret, typename PolicyList, unsigned int NumParams, int(*Function)(lua_State*, int, int), unsigned int... Indices >
template<class Tuple> struct call_function_struct< Ret, PolicyList, meta::index_list<Indices...>, NumParams, Function, false /* void */ >
class proxy_function_void_caller
{ {
friend class luabind::object; template< typename... Args >
public: static Ret call(lua_State* L, Args&&... args) {
typedef int(*function_t)(lua_State*, int, int);
proxy_function_void_caller(
lua_State* L
, int params
, function_t fun
, const Tuple args)
: m_state(L)
, m_params(params)
, m_fun(fun)
, m_args(args)
, m_called(false)
{
}
proxy_function_void_caller(const proxy_function_void_caller& rhs)
: m_state(rhs.m_state)
, m_params(rhs.m_params)
, m_fun(rhs.m_fun)
, m_args(rhs.m_args)
, m_called(rhs.m_called)
{
rhs.m_called = true;
}
~proxy_function_void_caller()
{
if (m_called) return;
m_called = true;
lua_State* L = m_state;
int top = lua_gettop(L); int top = lua_gettop(L);
push_args_from_tuple<1>::apply(L, m_args); push_arguments<PolicyList, 1>(L, std::forward<Args>(args)...);
if (m_fun(L, boost::tuples::length<Tuple>::value, 0))
{
assert(lua_gettop(L) == top - m_params + 1);
#ifndef LUABIND_NO_EXCEPTIONS
throw luabind::error(L);
#else
error_callback_fun e = get_error_callback();
if (e) e(L);
assert(0 && "the lua function threw an error and exceptions are disabled." if(Function(L, sizeof...(Args), 1)) {
" If you want to handle the error you can use luabind::set_error_callback()"); if(Function == &detail::pcall) {
std::terminate(); assert(lua_gettop(L) == static_cast<int>(top - NumParams + 1));
#endif }
call_error(L);
} }
// pops the return values from the function call // pops the return values from the function call
stack_pop pop(L, lua_gettop(L) - top + m_params); stack_pop pop(L, lua_gettop(L) - top + NumParams);
specialized_converter_policy_n<0, PolicyList, Ret, lua_to_cpp> converter;
if(converter.match(L, decorate_type_t<Ret>(), -1) < 0) {
cast_error<Ret>(L);
} }
template<class Policies> return converter.to_cpp(L, decorate_type_t<Ret>(), -1);
void operator[](const Policies& p)
{
m_called = true;
lua_State* L = m_state;
int top = lua_gettop(L);
detail::push_args_from_tuple<1>::apply(L, m_args, p);
if (m_fun(L, boost::tuples::length<Tuple>::value, 0))
{
assert(lua_gettop(L) == top - m_params + 1);
#ifndef LUABIND_NO_EXCEPTIONS
throw error(L);
#else
error_callback_fun e = get_error_callback();
if (e) e(L);
assert(0 && "the lua function threw an error and exceptions are disabled."
" If you want to handle the error you can use luabind::set_error_callback()");
std::terminate();
#endif
} }
// pops the return values from the function call
stack_pop pop(L, lua_gettop(L) - top + m_params);
}
private:
lua_State* m_state;
int m_params;
function_t m_fun;
Tuple m_args;
mutable bool m_called;
}; };
#endif
} }
#define BOOST_PP_ITERATION_PARAMS_1 (4, (0, LUABIND_MAX_ARITY, <luabind/detail/call_function.hpp>, 1)) template<class R, typename PolicyList = no_policies, typename... Args>
#include BOOST_PP_ITERATE() R call_pushed_function(lua_State* L, Args&&... args)
{
#ifndef LUABIND_NO_INTERNAL_TAG_ARGUMENTS
return detail::call_function_impl<R, PolicyList>(L, 1, &detail::pcall, std::is_void<R>(), meta::index_range<1, sizeof...(Args)+1>(), std::forward<Args>(args)...);
#else
return detail::call_function_struct<R, PolicyList, meta::index_range<1, sizeof...(Args)+1>, 1, &detail::pcall >::call(L, std::forward<Args>(args)...);
#endif
}
template<class R, typename PolicyList = no_policies, typename... Args>
R call_function(lua_State* L, const char* name, Args&&... args)
{
assert(name && "luabind::call_function() expects a function name");
lua_getglobal(L, name);
return call_pushed_function<R, PolicyList>(L, std::forward<Args>(args)...);
}
template<class R, typename PolicyList = no_policies, typename... Args>
R resume_pushed_function(lua_State* L, Args&&... args)
{
#ifndef LUABIND_NO_INTERNAL_TAG_ARGUMENTS
return detail::call_function_impl<R, PolicyList>(L, 1, &detail::resume_impl, std::is_void<R>(), meta::index_range<1, sizeof...(Args)+1>(), std::forward<Args>(args)...);
#else
return detail::call_function_struct<R, PolicyList, meta::index_range<1, sizeof...(Args)+1>, 1, &detail::resume_impl >::call(L, std::forward<Args>(args)...);
#endif
}
template<class R, typename PolicyList = no_policies, typename... Args>
R resume_function(lua_State* L, const char* name, Args&&... args)
{
assert(name && "luabind::resume_function() expects a function name");
lua_getglobal(L, name);
return resume_pushed_function<R, PolicyList>(L, std::forward<Args>(args)...);
}
template<class R, typename PolicyList = no_policies, typename... Args>
R resume(lua_State* L, Args&&... args)
{
#ifndef LUABIND_NO_INTERNAL_TAG_ARGUMENTS
return detail::call_function_impl<R, PolicyList>(L, 0, &detail::resume_impl, std::is_void<R>(), meta::index_range<1, sizeof...(Args)+1>(), std::forward<Args>(args)...);
#else
return detail::call_function_struct<R, PolicyList, meta::index_range<1, sizeof...(Args)+1>, 0, &detail::resume_impl >::call(L, std::forward<Args>(args)...);
#endif
}
} }
#endif // LUABIND_CALL_FUNCTION_HPP_INCLUDED #endif // LUABIND_CALL_FUNCTION_HPP_INCLUDED
#else
#if BOOST_PP_ITERATION_FLAGS() == 1
#define LUABIND_TUPLE_PARAMS(z, n, data) const A##n *
#define LUABIND_OPERATOR_PARAMS(z, n, data) const A##n & a##n
template<class Ret BOOST_PP_COMMA_IF(BOOST_PP_ITERATION()) BOOST_PP_ENUM_PARAMS(BOOST_PP_ITERATION(), class A)>
typename boost::mpl::if_<boost::is_void<Ret>
, luabind::detail::proxy_function_void_caller<boost::tuples::tuple<BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_TUPLE_PARAMS, _)> >
, luabind::detail::proxy_function_caller<Ret, boost::tuples::tuple<BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_TUPLE_PARAMS, _)> > >::type
call_function(lua_State* L, const char* name BOOST_PP_COMMA_IF(BOOST_PP_ITERATION()) BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_OPERATOR_PARAMS, _) )
{
assert(name && "luabind::call_function() expects a function name");
typedef boost::tuples::tuple<BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_TUPLE_PARAMS, _)> tuple_t;
#if BOOST_PP_ITERATION() == 0
tuple_t args;
#else
tuple_t args(BOOST_PP_ENUM_PARAMS(BOOST_PP_ITERATION(), &a));
#endif
typedef typename boost::mpl::if_<boost::is_void<Ret>
, luabind::detail::proxy_function_void_caller<boost::tuples::tuple<BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_TUPLE_PARAMS, _)> >
, luabind::detail::proxy_function_caller<Ret, boost::tuples::tuple<BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_TUPLE_PARAMS, _)> > >::type proxy_type;
lua_getglobal(L, name);
return proxy_type(L, 1, &detail::pcall, args);
}
template<class Ret BOOST_PP_COMMA_IF(BOOST_PP_ITERATION()) BOOST_PP_ENUM_PARAMS(BOOST_PP_ITERATION(), class A)>
typename boost::mpl::if_<boost::is_void<Ret>
, luabind::detail::proxy_function_void_caller<boost::tuples::tuple<BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_TUPLE_PARAMS, _)> >
, luabind::detail::proxy_function_caller<Ret, boost::tuples::tuple<BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_TUPLE_PARAMS, _)> > >::type
call_function(luabind::object const& obj BOOST_PP_COMMA_IF(BOOST_PP_ITERATION()) BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_OPERATOR_PARAMS, _) )
{
typedef boost::tuples::tuple<BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_TUPLE_PARAMS, _)> tuple_t;
#if BOOST_PP_ITERATION() == 0
tuple_t args;
#else
tuple_t args(BOOST_PP_ENUM_PARAMS(BOOST_PP_ITERATION(), &a));
#endif
typedef typename boost::mpl::if_<boost::is_void<Ret>
, luabind::detail::proxy_function_void_caller<boost::tuples::tuple<BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_TUPLE_PARAMS, _)> >
, luabind::detail::proxy_function_caller<Ret, boost::tuples::tuple<BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_TUPLE_PARAMS, _)> > >::type proxy_type;
obj.push(obj.interpreter());
return proxy_type(obj.interpreter(), 1, &detail::pcall, args);
}
template<class Ret BOOST_PP_COMMA_IF(BOOST_PP_ITERATION()) BOOST_PP_ENUM_PARAMS(BOOST_PP_ITERATION(), class A)>
typename boost::mpl::if_<boost::is_void<Ret>
, luabind::detail::proxy_function_void_caller<boost::tuples::tuple<BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_TUPLE_PARAMS, _)> >
, luabind::detail::proxy_function_caller<Ret, boost::tuples::tuple<BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_TUPLE_PARAMS, _)> > >::type
resume_function(lua_State* L, const char* name BOOST_PP_COMMA_IF(BOOST_PP_ITERATION()) BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_OPERATOR_PARAMS, _) )
{
assert(name && "luabind::resume_function() expects a function name");
typedef boost::tuples::tuple<BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_TUPLE_PARAMS, _)> tuple_t;
#if BOOST_PP_ITERATION() == 0
tuple_t args;
#else
tuple_t args(BOOST_PP_ENUM_PARAMS(BOOST_PP_ITERATION(), &a));
#endif
typedef typename boost::mpl::if_<boost::is_void<Ret>
, luabind::detail::proxy_function_void_caller<boost::tuples::tuple<BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_TUPLE_PARAMS, _)> >
, luabind::detail::proxy_function_caller<Ret, boost::tuples::tuple<BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_TUPLE_PARAMS, _)> > >::type proxy_type;
lua_getglobal(L, name);
return proxy_type(L, 1, &detail::resume_impl, args);
}
template<class Ret BOOST_PP_COMMA_IF(BOOST_PP_ITERATION()) BOOST_PP_ENUM_PARAMS(BOOST_PP_ITERATION(), class A)>
typename boost::mpl::if_<boost::is_void<Ret>
, luabind::detail::proxy_function_void_caller<boost::tuples::tuple<BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_TUPLE_PARAMS, _)> >
, luabind::detail::proxy_function_caller<Ret, boost::tuples::tuple<BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_TUPLE_PARAMS, _)> > >::type
resume_function(luabind::object const& obj BOOST_PP_COMMA_IF(BOOST_PP_ITERATION()) BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_OPERATOR_PARAMS, _) )
{
typedef boost::tuples::tuple<BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_TUPLE_PARAMS, _)> tuple_t;
#if BOOST_PP_ITERATION() == 0
tuple_t args;
#else
tuple_t args(BOOST_PP_ENUM_PARAMS(BOOST_PP_ITERATION(), &a));
#endif
typedef typename boost::mpl::if_<boost::is_void<Ret>
, luabind::detail::proxy_function_void_caller<boost::tuples::tuple<BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_TUPLE_PARAMS, _)> >
, luabind::detail::proxy_function_caller<Ret, boost::tuples::tuple<BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_TUPLE_PARAMS, _)> > >::type proxy_type;
obj.push(obj.interpreter());
return proxy_type(obj.interpreter(), 1, &detail::resume_impl, args);
}
template<class Ret BOOST_PP_COMMA_IF(BOOST_PP_ITERATION()) BOOST_PP_ENUM_PARAMS(BOOST_PP_ITERATION(), class A)>
typename boost::mpl::if_<boost::is_void<Ret>
, luabind::detail::proxy_function_void_caller<boost::tuples::tuple<BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_TUPLE_PARAMS, _)> >
, luabind::detail::proxy_function_caller<Ret, boost::tuples::tuple<BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_TUPLE_PARAMS, _)> > >::type
resume(lua_State* L BOOST_PP_COMMA_IF(BOOST_PP_ITERATION()) BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_OPERATOR_PARAMS, _) )
{
typedef boost::tuples::tuple<BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_TUPLE_PARAMS, _)> tuple_t;
#if BOOST_PP_ITERATION() == 0
tuple_t args;
#else
tuple_t args(BOOST_PP_ENUM_PARAMS(BOOST_PP_ITERATION(), &a));
#endif
typedef typename boost::mpl::if_<boost::is_void<Ret>
, luabind::detail::proxy_function_void_caller<boost::tuples::tuple<BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_TUPLE_PARAMS, _)> >
, luabind::detail::proxy_function_caller<Ret, boost::tuples::tuple<BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_TUPLE_PARAMS, _)> > >::type proxy_type;
return proxy_type(L, 0, &detail::resume_impl, args);
}
#undef LUABIND_OPERATOR_PARAMS
#undef LUABIND_TUPLE_PARAMS
#endif
#endif
+50 -288
View File
@@ -20,62 +20,26 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
// OR OTHER DEALINGS IN THE SOFTWARE. // OR OTHER DEALINGS IN THE SOFTWARE.
#if !BOOST_PP_IS_ITERATING
#ifndef LUABIND_CALL_MEMBER_HPP_INCLUDED #ifndef LUABIND_CALL_MEMBER_HPP_INCLUDED
#define LUABIND_CALL_MEMBER_HPP_INCLUDED #define LUABIND_CALL_MEMBER_HPP_INCLUDED
#include <luabind/config.hpp> #include <luabind/config.hpp>
#include <luabind/detail/convert_to_lua.hpp> #include <luabind/detail/push_to_lua.hpp>
#include <luabind/detail/pcall.hpp> #include <luabind/detail/pcall.hpp>
#include <luabind/error.hpp> #include <luabind/error.hpp>
#include <luabind/detail/stack_utils.hpp> #include <luabind/detail/stack_utils.hpp>
#include <luabind/object.hpp> // TODO: REMOVE DEPENDENCY #include <luabind/detail/call_shared.hpp>
#include <luabind/object.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/preprocessor/control/if.hpp>
#include <boost/preprocessor/facilities/expand.hpp>
#include <boost/preprocessor/repetition/enum.hpp>
#include <boost/mpl/apply_wrap.hpp>
namespace luabind namespace luabind
{ {
namespace detail using adl::object;
namespace detail {
template<class R, typename PolicyList, unsigned int... Indices, typename... Args>
R call_member_impl(lua_State* L, std::true_type /*void*/, meta::index_list<Indices...>, Args&&... args)
{ {
namespace mpl = boost::mpl;
// if the proxy_member_caller returns non-void
template<class Ret, class Tuple>
class proxy_member_caller
{
// friend class luabind::object;
public:
proxy_member_caller(lua_State* L_, const Tuple args)
: L(L_)
, m_args(args)
, m_called(false)
{
}
proxy_member_caller(const proxy_member_caller& rhs)
: L(rhs.L)
, m_args(rhs.m_args)
, m_called(rhs.m_called)
{
rhs.m_called = true;
}
~proxy_member_caller()
{
if (m_called) return;
m_called = true;
// don't count the function and self-reference // don't count the function and self-reference
// since those will be popped by pcall // since those will be popped by pcall
int top = lua_gettop(L) - 2; int top = lua_gettop(L) - 2;
@@ -83,166 +47,22 @@ namespace luabind
// pcall will pop the function and self reference // pcall will pop the function and self reference
// and all the parameters // and all the parameters
push_args_from_tuple<1>::apply(L, m_args); meta::init_order{ (
if (pcall(L, boost::tuples::length<Tuple>::value + 1, 0)) specialized_converter_policy_n<Indices, PolicyList, typename unwrapped<Args>::type, cpp_to_lua>().to_lua(L, unwrapped<Args>::get(std::forward<Args>(args))), 0)...
{
assert(lua_gettop(L) == top + 1);
#ifndef LUABIND_NO_EXCEPTIONS
throw luabind::error(L);
#else
error_callback_fun e = get_error_callback();
if (e) e(L);
assert(0 && "the lua function threw an error and exceptions are disabled."
"If you want to handle this error use luabind::set_error_callback()");
std::terminate();
#endif
}
// pops the return values from the function
stack_pop pop(L, lua_gettop(L) - top);
}
operator Ret()
{
typename mpl::apply_wrap2<default_policy,Ret,lua_to_cpp>::type converter;
m_called = true;
// don't count the function and self-reference
// since those will be popped by pcall
int top = lua_gettop(L) - 2;
// pcall will pop the function and self reference
// and all the parameters
push_args_from_tuple<1>::apply(L, m_args);
if (pcall(L, boost::tuples::length<Tuple>::value + 1, 1))
{
assert(lua_gettop(L) == top + 1);
#ifndef LUABIND_NO_EXCEPTIONS
throw luabind::error(L);
#else
error_callback_fun e = get_error_callback();
if (e) e(L);
assert(0 && "the lua function threw an error and exceptions are disabled."
"If you want to handle this error use luabind::set_error_callback()");
std::terminate();
#endif
}
// pops the return values from the function
stack_pop pop(L, lua_gettop(L) - top);
#ifndef LUABIND_NO_ERROR_CHECKING
if (converter.match(L, LUABIND_DECORATE_TYPE(Ret), -1) < 0)
{
assert(lua_gettop(L) == top + 1);
#ifndef LUABIND_NO_EXCEPTIONS
throw cast_failed(L, typeid(Ret));
#else
cast_failed_callback_fun e = get_cast_failed_callback();
if (e) e(L, typeid(Ret));
assert(0 && "the lua function's return value could not be converted."
"If you want to handle this error use luabind::set_error_callback()");
std::terminate();
#endif
}
#endif
return converter.apply(L, LUABIND_DECORATE_TYPE(Ret), -1);
}
template<class Policies>
Ret operator[](const Policies& p)
{
typedef typename find_conversion_policy<0, Policies>::type converter_policy;
typename mpl::apply_wrap2<converter_policy,Ret,lua_to_cpp>::type converter;
m_called = true;
// don't count the function and self-reference
// since those will be popped by pcall
int top = lua_gettop(L) - 2;
// pcall will pop the function and self reference
// and all the parameters
detail::push_args_from_tuple<1>::apply(L, m_args, p);
if (pcall(L, boost::tuples::length<Tuple>::value + 1, 1))
{
assert(lua_gettop(L) == top + 1);
#ifndef LUABIND_NO_EXCEPTIONS
throw error(L);
#else
error_callback_fun e = get_error_callback();
if (e) e(L);
assert(0 && "the lua function threw an error and exceptions are disabled."
"If you want to handle this error use luabind::set_error_callback()");
std::terminate();
#endif
}
// pops the return values from the function
stack_pop pop(L, lua_gettop(L) - top);
#ifndef LUABIND_NO_ERROR_CHECKING
if (converter.match(L, LUABIND_DECORATE_TYPE(Ret), -1) < 0)
{
assert(lua_gettop(L) == top + 1);
#ifndef LUABIND_NO_EXCEPTIONS
throw cast_failed(L, typeid(Ret));
#else
cast_failed_callback_fun e = get_cast_failed_callback();
if (e) e(L, typeid(Ret));
assert(0 && "the lua function's return value could not be converted."
"If you want to handle this error use luabind::set_error_callback()");
std::terminate();
#endif
}
#endif
return converter.apply(L, LUABIND_DECORATE_TYPE(Ret), -1);
}
private:
lua_State* L;
Tuple m_args;
mutable bool m_called;
}; };
// if the proxy_member_caller returns void if(pcall(L, sizeof...(Args)+1, 0))
template<class Tuple>
class proxy_member_void_caller
{
friend class luabind::object;
public:
proxy_member_void_caller(lua_State* L_, const Tuple args)
: L(L_)
, m_args(args)
, m_called(false)
{ {
assert(lua_gettop(L) == top + 1);
call_error(L);
}
// pops the return values from the function
stack_pop pop(L, lua_gettop(L) - top);
} }
proxy_member_void_caller(const proxy_member_void_caller& rhs) template<class R, typename PolicyList, unsigned int... Indices, typename... Args>
: L(rhs.L) R call_member_impl(lua_State* L, std::false_type /*void*/, meta::index_list<Indices...>, Args&&... args)
, m_args(rhs.m_args)
, m_called(rhs.m_called)
{ {
rhs.m_called = true;
}
~proxy_member_void_caller()
{
if (m_called) return;
m_called = true;
// don't count the function and self-reference // don't count the function and self-reference
// since those will be popped by pcall // since those will be popped by pcall
int top = lua_gettop(L) - 2; int top = lua_gettop(L) - 2;
@@ -250,95 +70,32 @@ namespace luabind
// pcall will pop the function and self reference // pcall will pop the function and self reference
// and all the parameters // and all the parameters
push_args_from_tuple<1>::apply(L, m_args); meta::init_order{ (
if (pcall(L, boost::tuples::length<Tuple>::value + 1, 0)) specialized_converter_policy_n<Indices, PolicyList, typename unwrapped<Args>::type, cpp_to_lua>().to_lua(L, unwrapped<Args>::get(std::forward<Args>(args))), 0)...
{
assert(lua_gettop(L) == top + 1);
#ifndef LUABIND_NO_EXCEPTIONS
throw luabind::error(L);
#else
error_callback_fun e = get_error_callback();
if (e) e(L);
assert(0 && "the lua function threw an error and exceptions are disabled."
"If you want to handle this error use luabind::set_error_callback()");
std::terminate();
#endif
}
// pops the return values from the function
stack_pop pop(L, lua_gettop(L) - top);
}
template<class Policies>
void operator[](const Policies& p)
{
m_called = true;
// don't count the function and self-reference
// since those will be popped by pcall
int top = lua_gettop(L) - 2;
// pcall will pop the function and self reference
// and all the parameters
detail::push_args_from_tuple<1>::apply(L, m_args, p);
if (pcall(L, boost::tuples::length<Tuple>::value + 1, 0))
{
assert(lua_gettop(L) == top + 1);
#ifndef LUABIND_NO_EXCEPTIONS
throw error(L);
#else
error_callback_fun e = get_error_callback();
if (e) e(L);
assert(0 && "the lua function threw an error and exceptions are disabled."
"If you want to handle this error use luabind::set_error_callback()");
std::terminate();
#endif
}
// pops the return values from the function
stack_pop pop(L, lua_gettop(L) - top);
}
private:
lua_State* L;
Tuple m_args;
mutable bool m_called;
}; };
if(pcall(L, sizeof...(Args)+1, 1))
{
assert(lua_gettop(L) == top + 1);
call_error(L);
}
// pops the return values from the function
stack_pop pop(L, lua_gettop(L) - top);
specialized_converter_policy_n<0, PolicyList, R, lua_to_cpp> converter;
if(converter.match(L, decorate_type_t<R>(), -1) < 0) {
cast_error<R>(L);
}
return converter.to_cpp(L, decorate_type_t<R>(), -1);
}
} // detail } // detail
#define BOOST_PP_ITERATION_PARAMS_1 (4, (0, LUABIND_MAX_ARITY, <luabind/detail/call_member.hpp>, 1)) template<class R, typename PolicyList = no_policies, typename... Args>
#include BOOST_PP_ITERATE() R call_member(object const& obj, const char* name, Args&&... args)
}
#endif // LUABIND_CALL_MEMBER_HPP_INCLUDED
#else
#if BOOST_PP_ITERATION_FLAGS() == 1
#define LUABIND_TUPLE_PARAMS(z, n, data) const A##n *
#define LUABIND_OPERATOR_PARAMS(z, n, data) const A##n & a##n
template<class R BOOST_PP_COMMA_IF(BOOST_PP_ITERATION()) BOOST_PP_ENUM_PARAMS(BOOST_PP_ITERATION(), class A)>
typename boost::mpl::if_<boost::is_void<R>
, luabind::detail::proxy_member_void_caller<boost::tuples::tuple<BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_TUPLE_PARAMS, _)> >
, luabind::detail::proxy_member_caller<R, boost::tuples::tuple<BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_TUPLE_PARAMS, _)> > >::type
call_member(object const& obj, const char* name BOOST_PP_COMMA_IF(BOOST_PP_ITERATION()) BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_OPERATOR_PARAMS, _))
{ {
typedef boost::tuples::tuple<BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_TUPLE_PARAMS, _)> tuple_t;
#if BOOST_PP_ITERATION() == 0
tuple_t args;
#else
tuple_t args(BOOST_PP_ENUM_PARAMS(BOOST_PP_ITERATION(), &a));
#endif
typedef typename boost::mpl::if_<boost::is_void<R>
, luabind::detail::proxy_member_void_caller<boost::tuples::tuple<BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_TUPLE_PARAMS, _)> >
, luabind::detail::proxy_member_caller<R, boost::tuples::tuple<BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_TUPLE_PARAMS, _)> > >::type proxy_type;
// this will be cleaned up by the proxy object // this will be cleaned up by the proxy object
// once the call has been made // once the call has been made
@@ -354,12 +111,17 @@ namespace luabind
// now the function and self objects // now the function and self objects
// are on the stack. These will both // are on the stack. These will both
// be popped by pcall // be popped by pcall
return proxy_type(obj.interpreter(), args);
return detail::call_member_impl<R, PolicyList>(obj.interpreter(), std::is_void<R>(), meta::index_range<1, sizeof...(Args)+1>(), std::forward<Args>(args)...);
} }
#undef LUABIND_OPERATOR_PARAMS template <class R, typename... Args>
#undef LUABIND_TUPLE_PARAMS R call_member(wrap_base const* self, char const* fn, Args&&... args)
{
return self->call<R>(fn, std::forward<Args>(args)...);
}
#endif }
#endif
#endif // LUABIND_CALL_MEMBER_HPP_INCLUDED
@@ -1,66 +0,0 @@
// Copyright (c) 2004 Daniel Wallin and Arvid Norberg
// 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.
#define N BOOST_PP_ITERATION()
#define LUABIND_UNWRAP_PARAMETER(z, n, _) \
typename detail::unwrap_parameter_type<T, BOOST_PP_CAT(A, n)>::type \
BOOST_PP_CAT(_, n)
template<class Self BOOST_PP_ENUM_TRAILING_PARAMS(N, class A)>
struct BOOST_PP_CAT(call_operator, N)
: detail::operator_<
BOOST_PP_CAT(call_operator, N)<
Self BOOST_PP_ENUM_TRAILING_PARAMS(N, A)
>
>
{
BOOST_PP_CAT(call_operator, N)(int) {}
template<class T, class Policies>
struct apply
{
static void execute(
lua_State* L
, typename detail::unwrap_parameter_type<T, Self>::type self
BOOST_PP_ENUM_TRAILING(N, LUABIND_UNWRAP_PARAMETER, _)
)
{
using namespace detail;
operator_result(
L
#if BOOST_WORKAROUND(BOOST_MSVC, <= 1300)
, self(BOOST_PP_ENUM_PARAMS(N, _))
#else
, (self(BOOST_PP_ENUM_PARAMS(N, _)), detail::operator_void_return())
#endif
, (Policies*)0
);
}
};
static char const* name() { return "__call"; }
};
#undef LUABIND_UNWRAP_PARAMETER
#undef N
@@ -20,42 +20,46 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
// OR OTHER DEALINGS IN THE SOFTWARE. // OR OTHER DEALINGS IN THE SOFTWARE.
#if !BOOST_PP_IS_ITERATING #ifndef LUABIND_CALL_SHARED_HPP_INCLUDED
#define LUABIND_CALL_SHARED_HPP_INCLUDED
# include <luabind/detail/signature_match.hpp> namespace luabind {
namespace detail {
#ifndef LUABIND_CALC_ARITY_HPP_INCLUDED inline void call_error(lua_State* L)
#define LUABIND_CALC_ARITY_HPP_INCLUDED
#define LUABIND_FIND_CONV(z,n,text) typedef typename find_conversion_policy<n + 1, Policies>::type p##n;
#define LUABIND_CALC_ARITY(z,n,text) + BOOST_PP_CAT(p,n)::has_arg
namespace luabind { namespace detail
{ {
template<int N> struct calc_arity; #ifndef LUABIND_NO_EXCEPTIONS
throw luabind::error(L);
#else
error_callback_fun e = get_error_callback();
if(e) e(L);
#define BOOST_PP_ITERATION_PARAMS_1 (4, (0, LUABIND_MAX_ARITY, <luabind/detail/calc_arity.hpp>, 1)) assert(0 && "the lua function threw an error and exceptions are disabled."
#include BOOST_PP_ITERATE() " If you want to handle the error you can use luabind::set_error_callback()");
}} std::terminate();
#endif
#undef LUABIND_CALC_ARITY }
#undef LUABIND_FIND_CONV
template<typename T>
void cast_error(lua_State* L)
#endif // LUABIND_CALC_ARITY_HPP_INCLUDED {
#ifndef LUABIND_NO_EXCEPTIONS
#else // BOOST_PP_ITERATE throw cast_failed(L, typeid(T));
#else
template<> cast_failed_callback_fun e = get_cast_failed_callback();
struct calc_arity<BOOST_PP_ITERATION()> if(e) e(L, typeid(T));
{
template<BOOST_PP_ENUM_PARAMS(LUABIND_MAX_ARITY, class A), class Policies> assert(0 && "the lua function's return value could not be converted."
static int apply(constructor<BOOST_PP_ENUM_PARAMS(LUABIND_MAX_ARITY, A)>, Policies*) " If you want to handle the error you can use luabind::set_cast_failed_callback()");
{ std::terminate();
BOOST_PP_REPEAT(BOOST_PP_ITERATION(), LUABIND_FIND_CONV, _) #endif
return 0 BOOST_PP_REPEAT(BOOST_PP_ITERATION(), LUABIND_CALC_ARITY, _); }
template< typename... Args >
void expand_hack(Args... /*args*/)
{}
}
} }
};
#endif #endif
+113
View File
@@ -0,0 +1,113 @@
// This has been stripped from boost minus the compatibility for borland etc.
// (C) Copyright Steve Cleary, Beman Dawes, Howard Hinnant & John Maddock 2000.
// Use, modification and distribution are subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt).
//
// See http://www.boost.org/libs/utility for most recent version including documentation.
// call_traits: defines typedefs for function usage
// (see libs/utility/call_traits.htm)
/* Release notes:
23rd July 2000:
Fixed array specialization. (JM)
Added Borland specific fixes for reference types
(issue raised by Steve Cleary).
*/
#ifndef LUABIND_CALL_TRAITS_HPP_INCLUDED
#define LUABIND_CALL_TRAITS_HPP_INCLUDED
namespace luabind {
namespace detail {
template <typename T, bool small_>
struct ct_imp2
{
using param_type = const T&;
};
template <typename T>
struct ct_imp2<T, true>
{
using param_type = const T;
};
template <typename T, bool isp, bool b1, bool b2>
struct ct_imp
{
using param_type = const T&;
};
template <typename T, bool isp, bool b2>
struct ct_imp<T, isp, true, b2>
{
using param_type = typename ct_imp2<T, sizeof(T) <= sizeof(void*)>::param_type;
};
template <typename T, bool isp, bool b1>
struct ct_imp<T, isp, b1, true>
{
using param_type = typename ct_imp2<T, sizeof(T) <= sizeof(void*)>::param_type;
};
template <typename T, bool b1, bool b2>
struct ct_imp<T, true, b1, b2>
{
using param_type = const T;
};
template <typename T>
struct call_traits
{
public:
using value_type = T;
using reference = T&;
using const_reference = const T&;
using param_type = typename ct_imp<
T,
std::is_pointer<T>::value,
std::is_integral<T>::value || std::is_floating_point<T>::value,
std::is_enum<T>::value
>::param_type;
};
template <typename T>
struct call_traits<T&>
{
using value_type = T&;
using reference = T&;
using const_reference = const T&;
using param_type = T&;
};
template <typename T, std::size_t N>
struct call_traits<T[N]>
{
private:
using array_type = T[N];
public:
using value_type = const T*;
using reference = array_type&;
using const_reference = const array_type&;
using param_type = const T* const;
};
template <typename T, std::size_t N>
struct call_traits<const T[N]>
{
private:
using array_type = const T[N];
public:
using value_type = const T*;
using reference = array_type&;
using const_reference = const array_type&;
using param_type = const T* const;
};
}
}
#endif
@@ -1,89 +0,0 @@
// Copyright (c) 2004 Daniel Wallin
// 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 CLASS_CACHE_040218_HPP
#define CLASS_CACHE_040218_HPP
#include <luabind/prefix.hpp>
#include <boost/type_traits/add_reference.hpp>
#include <boost/type_traits/add_const.hpp>
namespace luabind { namespace detail {
#ifdef LUABIND_NOT_THREADSAFE
class class_rep;
template<class T>
struct class_cache_impl
{
static lua_State* state;
static class_rep* class_;
};
template<class T>
lua_State* class_cache_impl<T>::state = 0;
template<class T>
class_rep* class_cache_impl<T>::class_ = 0;
template<class T>
struct class_cache
: class_cache_impl<
typename boost::add_reference<
typename boost::add_const<
T
>::type
>::type
>
{
};
template<class T>
class_rep* get_class_rep(lua_State* L, void(*)(T*) = 0)
{
if (class_cache<T>::state != L)
{
class_cache<T>::state = L;
class_registry* registry = class_registry::get_registry(L);
class_cache<T>::class_ = registry->find_class(typeid(T));
}
return class_cache<T>::class_;
}
#else
template<class T>
class_rep* get_class_rep(lua_State* L, void(*)(T*) = 0)
{
class_registry* registry = class_registry::get_registry(L);
return registry->find_class(typeid(T));
}
#endif
}} // namespace luabind::detail
#endif // CLASS_CACHE_040218_HPP
@@ -30,8 +30,9 @@
#include <luabind/open.hpp> #include <luabind/open.hpp>
#include <luabind/typeid.hpp> #include <luabind/typeid.hpp>
namespace luabind { namespace detail namespace luabind {
{ namespace detail {
class class_rep; class class_rep;
struct LUABIND_API class_registry struct LUABIND_API class_registry
@@ -79,7 +80,8 @@ namespace luabind { namespace detail
}; };
}} }
}
#endif // LUABIND_CLASS_REGISTRY_HPP_INCLUDED #endif // LUABIND_CLASS_REGISTRY_HPP_INCLUDED
+10 -11
View File
@@ -1,4 +1,4 @@
// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // Copyright (c) 2003 Daniel Wallin and Arvid Norberg
// Permission is hereby granted, free of charge, to any person obtaining a // Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"), // copy of this software and associated documentation files (the "Software"),
@@ -24,16 +24,12 @@
#ifndef LUABIND_CLASS_REP_HPP_INCLUDED #ifndef LUABIND_CLASS_REP_HPP_INCLUDED
#define LUABIND_CLASS_REP_HPP_INCLUDED #define LUABIND_CLASS_REP_HPP_INCLUDED
#include <boost/limits.hpp>
#include <boost/preprocessor/repetition/enum_params_with_a_default.hpp>
#include <string> #include <string>
#include <utility> #include <utility>
#include <vector> #include <vector>
#include <luabind/config.hpp> #include <luabind/config.hpp>
#include <luabind/lua_include.hpp> #include <luabind/lua_include.hpp>
#include <luabind/detail/object_rep.hpp>
#include <luabind/detail/garbage_collector.hpp> #include <luabind/detail/garbage_collector.hpp>
#include <luabind/detail/operator_id.hpp> #include <luabind/detail/operator_id.hpp>
#include <luabind/detail/class_registry.hpp> #include <luabind/detail/class_registry.hpp>
@@ -43,8 +39,8 @@
#include <luabind/typeid.hpp> #include <luabind/typeid.hpp>
#include <luabind/detail/ref.hpp> #include <luabind/detail/ref.hpp>
namespace luabind { namespace detail namespace luabind {
{ namespace detail {
LUABIND_API std::string stack_content_by_name(lua_State* L, int start_index); LUABIND_API std::string stack_content_by_name(lua_State* L, int start_index);
@@ -151,6 +147,9 @@ namespace luabind { namespace detail
private: private:
// Code common to both constructors
void shared_init(lua_State * L);
void cache_operators(lua_State*); void cache_operators(lua_State*);
// this is a pointer to the type_info structure for // this is a pointer to the type_info structure for
@@ -204,10 +203,10 @@ namespace luabind { namespace detail
class_id_map* m_classes; class_id_map* m_classes;
}; };
bool is_class_rep(lua_State* L, int index); LUABIND_API bool is_class_rep(lua_State* L, int index);
}} }
}
//#include <luabind/detail/overload_rep_impl.hpp>
#endif // LUABIND_CLASS_REP_HPP_INCLUDED #endif // LUABIND_CLASS_REP_HPP_INCLUDED
@@ -1,73 +0,0 @@
// Copyright Daniel Wallin 2008. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef LUABIND_COMPUTE_RANK_081006_HPP
# define LUABIND_COMPUTE_RANK_081006_HPP
# include <luabind/config.hpp>
# include <luabind/detail/policy.hpp>
# include <boost/mpl/apply_wrap.hpp>
# include <boost/mpl/begin_end.hpp>
# include <boost/mpl/int.hpp>
# include <boost/mpl/next.hpp>
namespace luabind { namespace detail {
namespace mpl = boost::mpl;
template <class Idx, class Iter, class End, class Policies>
int compute_score_aux(
lua_State*L, int index, Idx, Iter, End end, Policies const& policies)
{
typedef typename Iter::type arg_type;
typedef typename find_conversion_policy<Idx::value, Policies>::type
conversion_policy;
typedef typename mpl::apply_wrap2<
conversion_policy, arg_type, lua_to_cpp>::type converter;
int score = converter::match(L, LUABIND_DECORATE_TYPE(arg_type), index);
if (score < 0)
return score;
if (conversion_policy::has_arg)
++index;
int next = compute_score_aux(
L
, index
, typename mpl::next<Idx>::type()
, typename mpl::next<Iter>::type()
, end
, policies
);
if (next < 0)
return next;
return score + next;
}
template <class Idx, class End, class Policies>
int compute_score_aux(lua_State*, int, Idx, End, End, Policies const&)
{
return 0;
}
template <class Signature, class Policies>
int compute_score(lua_State* L, Signature, Policies const& policies)
{
return compute_score_aux(
L
, 1
, mpl::int_<1>()
, typename mpl::next<typename mpl::begin<Signature>::type>::type()
, typename mpl::end<Signature>::type()
, policies
);
}
}} // namespace luabind::detail
#endif // LUABIND_COMPUTE_RANK_081006_HPP
+24 -70
View File
@@ -2,22 +2,16 @@
// subject to the Boost Software License, Version 1.0. (See accompanying // subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#if !BOOST_PP_IS_ITERATING
#ifndef LUABIND_DETAIL_CONSTRUCTOR_081018_HPP #ifndef LUABIND_DETAIL_CONSTRUCTOR_081018_HPP
#define LUABIND_DETAIL_CONSTRUCTOR_081018_HPP #define LUABIND_DETAIL_CONSTRUCTOR_081018_HPP
#include <luabind/get_main_thread.hpp> #include <luabind/get_main_thread.hpp>
# include <luabind/object.hpp> #include <luabind/lua_argument_proxy.hpp>
#include <luabind/wrapper_base.hpp> #include <luabind/wrapper_base.hpp>
#include <luabind/detail/inheritance.hpp> #include <luabind/detail/inheritance.hpp>
# include <boost/preprocessor/iteration/iterate.hpp> namespace luabind {
# include <boost/preprocessor/iteration/local.hpp> namespace detail {
# include <boost/preprocessor/repetition/enum_params.hpp>
# include <boost/preprocessor/repetition/enum_binary_params.hpp>
namespace luabind { namespace detail {
inline void inject_backref(lua_State*, void*, void*) inline void inject_backref(lua_State*, void*, void*)
{} {}
@@ -28,25 +22,19 @@ void inject_backref(lua_State* L, T* p, wrap_base*)
weak_ref(get_main_thread(L), L, 1).swap(wrap_access::ref(*p)); weak_ref(get_main_thread(L), L, 1).swap(wrap_access::ref(*p));
} }
template <std::size_t Arity, class T, class Pointer, class Signature> template< class T, class Pointer, class Signature, class Arguments, class ArgumentIndices >
struct construct_aux; struct construct_aux_helper;
template <class T, class Pointer, class Signature> template< class T, class Pointer, class Signature, typename... Arguments, unsigned int... ArgumentIndices >
struct construct struct construct_aux_helper< T, Pointer, Signature, meta::type_list< Arguments... >, meta::index_list< ArgumentIndices... > >
: construct_aux<mpl::size<Signature>::value - 2, T, Pointer, Signature>
{};
template <class T, class Pointer, class Signature>
struct construct_aux<0, T, Pointer, Signature>
{ {
typedef pointer_holder<Pointer, T> holder_type; using holder_type = pointer_holder<Pointer, T>;
void operator()(argument const& self_) const void operator()(argument const& self_, Arguments... args) const
{ {
object_rep* self = touserdata<object_rep>(self_); object_rep* self = touserdata<object_rep>(self_);
class_rep* cls = self->crep();
std::auto_ptr<T> instance(new T); std::unique_ptr<T> instance(new T(args...));
inject_backref(self_.interpreter(), instance.get(), instance.get()); inject_backref(self_.interpreter(), instance.get(), instance.get());
void* naked_ptr = instance.get(); void* naked_ptr = instance.get();
@@ -54,58 +42,24 @@ struct construct_aux<0, T, Pointer, Signature>
void* storage = self->allocate(sizeof(holder_type)); void* storage = self->allocate(sizeof(holder_type));
self->set_instance(new (storage) holder_type( self->set_instance(new (storage) holder_type(std::move(ptr), registered_class<T>::id, naked_ptr));
ptr, registered_class<T>::id, naked_ptr, cls));
} }
}; };
# define BOOST_PP_ITERATION_PARAMS_1 \
(3, (1, LUABIND_MAX_ARITY, <luabind/detail/constructor.hpp>))
# include BOOST_PP_ITERATE()
}} // namespace luabind::detail template< class T, class Pointer, class Signature >
struct construct :
public construct_aux_helper <
T,
Pointer,
Signature, typename meta::sub_range< Signature, 2, meta::size<Signature>::value >::type,
typename meta::make_index_range<0, meta::size<Signature>::value - 2>::type >
{
};
} // namespace detail
} // namespace luabind
# endif // LUABIND_DETAIL_CONSTRUCTOR_081018_HPP # endif // LUABIND_DETAIL_CONSTRUCTOR_081018_HPP
#else // !BOOST_PP_IS_ITERATING
# define N BOOST_PP_ITERATION()
template <class T, class Pointer, class Signature>
struct construct_aux<N, T, Pointer, Signature>
{
typedef typename mpl::begin<Signature>::type first;
typedef typename mpl::next<first>::type iter0;
# define BOOST_PP_LOCAL_MACRO(n) \
typedef typename mpl::next< \
BOOST_PP_CAT(iter,BOOST_PP_DEC(n))>::type BOOST_PP_CAT(iter,n); \
typedef typename BOOST_PP_CAT(iter,n)::type BOOST_PP_CAT(a,BOOST_PP_DEC(n));
# define BOOST_PP_LOCAL_LIMITS (1,N)
# include BOOST_PP_LOCAL_ITERATE()
typedef pointer_holder<Pointer, T> holder_type;
void operator()(argument const& self_, BOOST_PP_ENUM_BINARY_PARAMS(N,a,_)) const
{
object_rep* self = touserdata<object_rep>(self_);
class_rep* cls = self->crep();
std::auto_ptr<T> instance(new T(BOOST_PP_ENUM_PARAMS(N,_)));
inject_backref(self_.interpreter(), instance.get(), instance.get());
void* naked_ptr = instance.get();
Pointer ptr(instance.release());
void* storage = self->allocate(sizeof(holder_type));
self->set_instance(new (storage) holder_type(
ptr, registered_class<T>::id, naked_ptr, cls));
}
};
# undef N
#endif
@@ -0,0 +1,81 @@
// Copyright (c) 2003 Daniel Wallin and Arvid Norberg
// 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 LUABIND_CONVERSION_BASE_HPP_INCLUDED
#define LUABIND_CONVERSION_BASE_HPP_INCLUDED
#include <type_traits>
#include <luabind/lua_include.hpp>
#include <luabind/detail/decorate_type.hpp>
#include <luabind/detail/make_instance.hpp>
#include <luabind/pointer_traits.hpp>
#include <luabind/from_stack.hpp>
namespace luabind {
namespace detail {
// Something's strange with the references here... need to know when to copy :(
template <class T, class Clone>
void make_pointee_instance(lua_State* L, T&& x, std::true_type, Clone)
{
if(get_pointer(x))
{
make_pointer_instance(L, std::forward<T>(x));
}
else
{
lua_pushnil(L);
}
}
template <class T>
void make_pointee_instance(lua_State* L, T&& x, std::false_type, std::true_type)
{
using value_type = typename std::remove_reference<T>::type;
std::unique_ptr<value_type> ptr(new value_type(std::move(x)));
make_pointer_instance(L, std::move(ptr));
}
template <class T>
void make_pointee_instance(lua_State* L, T&& x, std::false_type, std::false_type)
{
// need a second make_instance that moves x into place
make_pointer_instance(L, &x);
}
template <class T, class Clone>
void make_pointee_instance(lua_State* L, T&& x, Clone)
{
make_pointee_instance(L, std::forward<T>(x), has_get_pointer<T>(), Clone());
}
}
template <class T, class Enable>
struct default_converter;
}
#endif
@@ -0,0 +1,89 @@
// Copyright (c) 2003 Daniel Wallin and Arvid Norberg
// 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 LUABIND_CONVERSION_POLICIES_HPP_INCLUDED
#define LUABIND_CONVERSION_POLICIES_HPP_INCLUDED
#include <luabind/detail/type_traits.hpp>
#include <luabind/detail/meta.hpp>
#include <luabind/detail/policy.hpp>
#include <luabind/detail/conversion_policies/conversion_base.hpp>
#include <luabind/detail/conversion_policies/enum_converter.hpp>
#include <luabind/detail/conversion_policies/pointer_converter.hpp>
#include <luabind/detail/conversion_policies/reference_converter.hpp>
#include <luabind/detail/conversion_policies/value_converter.hpp>
#include <luabind/detail/conversion_policies/lua_proxy_converter.hpp>
#include <luabind/detail/conversion_policies/native_converter.hpp>
#include <luabind/detail/conversion_policies/function_converter.hpp>
#include <luabind/shared_ptr_converter.hpp>
namespace luabind {
template <>
struct default_converter<lua_State*>
{
enum { consumed_args = 0 };
template <class U>
lua_State* to_cpp(lua_State* L, U, int /*index*/)
{
return L;
}
template <class U>
static int match(lua_State*, U, int /*index*/)
{
return 0;
}
template <class U>
void converter_postcall(lua_State*, U, int) {}
};
namespace detail {
// This is the one that gets hit, if default_policy doesn't hit one of the specializations defined all over the place
template< class T >
struct default_converter_generator
: public meta::select_ <
meta::case_< is_lua_proxy_arg<T>, lua_proxy_converter<T> >,
meta::case_< std::is_enum<typename std::remove_reference<T>::type>, enum_converter >,
meta::case_< is_nonconst_pointer<T>, pointer_converter >,
meta::case_< is_const_pointer<T>, const_pointer_converter >,
meta::case_< is_nonconst_reference<T>, ref_converter >,
meta::case_< is_const_reference<T>, const_ref_converter >,
meta::default_< value_converter >
> ::type
{
};
}
template <class T, class Enable>
struct default_converter
: detail::default_converter_generator<T>::type
{};
}
#endif
@@ -0,0 +1,82 @@
// Copyright (c) 2003 Daniel Wallin and Arvid Norberg
// 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 LUABIND_ENUM_CONVERTER_HPP_INCLUDED
#define LUABIND_ENUM_CONVERTER_HPP_INCLUDED
#include <type_traits>
#include <luabind/detail/type_traits.hpp>
#include <luabind/detail/conversion_policies/conversion_base.hpp>
namespace luabind {
namespace detail {
struct enum_converter
{
using type = enum_converter;
using is_native = std::false_type;
enum { consumed_args = 1 };
void to_lua(lua_State* L, int val)
{
lua_pushnumber(L, val);
}
template<class T>
T to_cpp(lua_State* L, by_value<T>, int index)
{
return static_cast<T>(static_cast<int>(lua_tonumber(L, index)));
}
template<class T>
static int match(lua_State* L, by_value<T>, int index)
{
if(lua_isnumber(L, index)) {
return 0;
} else {
return no_match;
}
}
template<class T>
T to_cpp(lua_State* L, by_const_reference<T>, int index)
{
return static_cast<T>(static_cast<int>(lua_tonumber(L, index)));
}
template<class T>
static int match(lua_State* L, by_const_reference<T>, int index)
{
if(lua_isnumber(L, index)) return 0; else return no_match;
}
template<class T>
void converter_postcall(lua_State*, T, int) {}
};
}
}
#endif
@@ -0,0 +1,93 @@
// Copyright Christian Neumüller 2013. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef LUABIND_FUNCTION_CONVERTER_HPP_INCLUDED
#define LUABIND_FUNCTION_CONVERTER_HPP_INCLUDED
#include <functional>
#include <luabind/detail/deduce_signature.hpp>
#include <luabind/detail/conversion_policies/conversion_base.hpp>
#include <luabind/make_function.hpp>
#include <luabind/detail/call_function.hpp>
namespace luabind {
template <typename R = object>
struct function
{
using result_type = R;
function(luabind::object const& obj)
: m_func(obj)
{
}
template< typename... Args>
R operator() (Args&&... args)
{
return call_function<R>(m_func, std::forward<Args>(args)...);
}
private:
object m_func;
};
namespace detail {
template< typename T >
struct is_function : public std::false_type {};
template< typename T >
struct is_function< std::function< T > > : public std::true_type {};
}
template< typename R, typename... Args, typename WrappedType >
struct deduce_signature <std::function< R(Args...) >, WrappedType >
{
using type = meta::type_list< R, Args... >;
};
template <typename F>
struct default_converter<F, typename std::enable_if<detail::is_function<remove_const_reference_t<F>>::value>::type>
{
using is_native = std::true_type;
enum { consumed_args = 1 };
template <class U>
void converter_postcall(lua_State*, U const&, int)
{}
template <class U>
static int match(lua_State* L, U, int index)
{
if(lua_type(L, index) == LUA_TFUNCTION)
return 0;
if(luaL_getmetafield(L, index, "__call")) {
lua_pop(L, 1);
return 1;
}
return no_match;
}
template <class U>
F to_cpp(lua_State* L, U, int index)
{
// If you get a compiler error here, you are probably trying to
// get a function pointer from Lua. This is not supported:
// you must use a type which is constructible from a
// luabind::function, e.g. std::function or boost::function.
return function<typename F::result_type>(object(from_stack(L, index)));
}
void to_lua(lua_State* L, F value)
{
make_function(L, value).push(L);
}
};
} // namespace luabind
#endif // LUABIND_FUNCTION_CONVERTER_HPP_INCLUDED
@@ -0,0 +1,73 @@
// 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 LUABIND_VALUE_WRAPPER_CONVERTER_HPP_INCLUDED
#define LUABIND_VALUE_WRAPPER_CONVERTER_HPP_INCLUDED
#include <luabind/lua_proxy.hpp>
#include <type_traits>
namespace luabind {
namespace detail {
template <class U>
struct lua_proxy_converter
{
using type = lua_proxy_converter<U>;
using is_native = std::true_type;
enum { consumed_args = 1 };
template<class T>
T to_cpp(lua_State* L, by_const_reference<T>, int index)
{
return T(from_stack(L, index));
}
template<class T>
T to_cpp(lua_State* L, by_value<T>, int index)
{
return to_cpp(L, by_const_reference<T>(), index);
}
template<class T>
static int match(lua_State* L, by_const_reference<T>, int index)
{
return lua_proxy_traits<T>::check(L, index)
? max_hierarchy_depth
: no_match;
}
template<class T>
static int match(lua_State* L, by_value<T>, int index)
{
return match(L, by_const_reference<T>(), index);
}
void converter_postcall(...) {}
template<class T>
void to_lua(lua_State* interpreter, T const& value_wrapper)
{
lua_proxy_traits<T>::unwrap(interpreter, value_wrapper);
}
};
}
}
#endif
@@ -0,0 +1,302 @@
// Copyright (c) 2003 Daniel Wallin and Arvid Norberg
// 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 LUABIND_NATIVE_CONVERTER_HPP_INCLUDED
#define LUABIND_NATIVE_CONVERTER_HPP_INCLUDED
#include <type_traits>
#include <string>
#include <luabind/detail/policy.hpp>
#include <luabind/detail/conversion_policies/conversion_base.hpp>
#include <luabind/detail/type_traits.hpp>
#include <luabind/detail/call_traits.hpp>
#include <luabind/lua_include.hpp>
#if LUA_VERSION_NUM < 502
# define lua_rawlen lua_objlen
#endif
namespace luabind {
template <class T, class Derived = default_converter<T> >
struct native_converter_base
{
using is_native = std::true_type;
using value_type = typename detail::call_traits<T>::value_type;
using param_type = typename detail::call_traits<T>::param_type;
enum { consumed_args = 1 };
template <class U>
void converter_postcall(lua_State*, U const&, int)
{}
int match(lua_State* L, by_value<T>, int index)
{
return Derived::compute_score(L, index);
}
int match(lua_State* L, by_value<T const>, int index)
{
return Derived::compute_score(L, index);
}
int match(lua_State* L, by_const_reference<T>, int index)
{
return Derived::compute_score(L, index);
}
value_type to_cpp(lua_State* L, by_value<T>, int index)
{
return derived().to_cpp_deferred(L, index);
}
value_type to_cpp(lua_State* L, by_const_reference<T>, int index)
{
return derived().to_cpp_deferred(L, index);
}
void to_lua(lua_State* L, param_type value)
{
derived().to_lua_deferred(L, value);
}
Derived& derived()
{
return static_cast<Derived&>(*this);
}
};
template <typename QualifiedT>
struct integer_converter
: native_converter_base<remove_const_reference_t<QualifiedT>>
{
using T = remove_const_reference_t<QualifiedT>;
using value_type = typename native_converter_base<T>::value_type;
using param_type = typename native_converter_base<T>::param_type;
static int compute_score(lua_State* L, int index)
{
return lua_type(L, index) == LUA_TNUMBER ? 0 : no_match;
}
static value_type to_cpp_deferred(lua_State* L, int index)
{
if((std::is_unsigned<value_type>::value && sizeof(value_type) >= sizeof(lua_Integer)) || (sizeof(value_type) > sizeof(lua_Integer))) {
return static_cast<T>(lua_tonumber(L, index));
} else {
return static_cast<T>(lua_tointeger(L, index));
}
}
void to_lua_deferred(lua_State* L, param_type value)
{
if((std::is_unsigned<value_type>::value && sizeof(value_type) >= sizeof(lua_Integer)) || (sizeof(value_type) > sizeof(lua_Integer)))
{
lua_pushnumber(L, (lua_Number)value);
} else {
lua_pushinteger(L, static_cast<lua_Integer>(value));
}
}
};
template <typename QualifiedT>
struct number_converter
: native_converter_base<remove_const_reference_t<QualifiedT>>
{
using T = remove_const_reference_t<QualifiedT>;
using value_type = typename native_converter_base<T>::value_type;
using param_type = typename native_converter_base<T>::param_type;
static int compute_score(lua_State* L, int index)
{
return lua_type(L, index) == LUA_TNUMBER ? 0 : no_match;
}
static value_type to_cpp_deferred(lua_State* L, int index)
{
return static_cast<T>(lua_tonumber(L, index));
}
static void to_lua_deferred(lua_State* L, param_type value)
{
lua_pushnumber(L, static_cast<lua_Number>(value));
}
};
template <>
struct default_converter<bool>
: native_converter_base<bool>
{
static int compute_score(lua_State* L, int index)
{
return lua_type(L, index) == LUA_TBOOLEAN ? 0 : no_match;
}
static bool to_cpp_deferred(lua_State* L, int index)
{
return lua_toboolean(L, index) == 1;
}
static void to_lua_deferred(lua_State* L, bool value)
{
lua_pushboolean(L, value);
}
};
template <>
struct default_converter<bool const>
: default_converter<bool>
{};
template <>
struct default_converter<bool const&>
: default_converter<bool>
{};
template <>
struct default_converter<std::string>
: native_converter_base<std::string>
{
static int compute_score(lua_State* L, int index)
{
return lua_type(L, index) == LUA_TSTRING ? 0 : no_match;
}
static std::string to_cpp_deferred(lua_State* L, int index)
{
return std::string(lua_tostring(L, index), lua_rawlen(L, index));
}
static void to_lua_deferred(lua_State* L, std::string const& value)
{
lua_pushlstring(L, value.data(), value.size());
}
};
template <>
struct default_converter<std::string&>
: default_converter<std::string>
{};
template <>
struct default_converter<std::string const>
: default_converter<std::string>
{};
template <>
struct default_converter<std::string const&>
: default_converter<std::string>
{};
template <>
struct default_converter<char const*>
{
using is_native = std::true_type;
enum { consumed_args = 1 };
template <class U>
static int match(lua_State* L, U, int index)
{
int type = lua_type(L, index);
return (type == LUA_TSTRING || type == LUA_TNIL) ? 0 : no_match;
}
template <class U>
static char const* to_cpp(lua_State* L, U, int index)
{
return lua_tostring(L, index);
}
static void to_lua(lua_State* L, char const* str)
{
lua_pushstring(L, str);
}
template <class U>
void converter_postcall(lua_State*, U, int)
{}
};
template <>
struct default_converter<const char* const>
: default_converter<char const*>
{};
template <>
struct default_converter<const char* const&>
: default_converter<char const*>
{};
template <>
struct default_converter<const char*&>
: default_converter<char const*>
{};
template <>
struct default_converter<char*>
: default_converter<char const*>
{};
template <std::size_t N>
struct default_converter<char const[N]>
: default_converter<char const*>
{};
template <std::size_t N>
struct default_converter<char[N]>
: default_converter<char const*>
{};
template <std::size_t N>
struct default_converter <char(&)[N]>
: default_converter<char const*>
{};
template <std::size_t N>
struct default_converter <const char(&)[N]>
: default_converter<char const*>
{};
template <typename T>
struct default_converter < T, typename std::enable_if< std::is_integral<remove_const_reference_t<T>>::value >::type >
: integer_converter<T>
{
};
template <typename T>
struct default_converter < T, typename std::enable_if< std::is_floating_point<remove_const_reference_t<T>>::value >::type >
: number_converter<T>
{
};
}
#if LUA_VERSION_NUM < 502
# undef lua_rawlen
#endif
#endif
@@ -0,0 +1,143 @@
// 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 LUABIND_POINTER_CONVERTER_HPP_INCLUDED
#define LUABIND_POINTER_CONVERTER_HPP_INCLUDED
#include <type_traits>
#include <luabind/lua_include.hpp>
#include <luabind/detail/make_instance.hpp>
#include <luabind/back_reference.hpp>
namespace luabind {
/*
Todo: Remove code duplication
*/
namespace detail {
struct pointer_converter
{
using type = pointer_converter;
using is_native = std::false_type;
pointer_converter()
: result(0)
{}
void* result;
enum { consumed_args = 1 };
template<class T>
static void to_lua(lua_State* L, T* ptr)
{
if(ptr == 0)
{
lua_pushnil(L);
return;
}
if(luabind::get_back_reference(L, ptr))
return;
make_pointer_instance(L, ptr);
}
template<class T>
T* to_cpp(lua_State*, by_pointer<T>, int /*index*/)
{
return static_cast<T*>(result);
}
template<class T>
int match(lua_State* L, by_pointer<T>, int index)
{
if(lua_isnil(L, index)) return 0;
object_rep* obj = get_instance(L, index);
if(obj == 0) return no_match;
if(obj->is_const())
return no_match;
std::pair<void*, int> s = obj->get_instance(registered_class<T>::id);
result = s.first;
return s.second;
}
template<class T>
void converter_postcall(lua_State*, by_pointer<T>, int /*index*/)
{}
};
struct const_pointer_converter
{
using type = const_pointer_converter;
using is_native = std::false_type;
enum { consumed_args = 1 };
const_pointer_converter()
: result(0)
{}
void* result;
template<class T>
void to_lua(lua_State* L, const T* ptr)
{
if(ptr == 0)
{
lua_pushnil(L);
return;
}
if(luabind::get_back_reference(L, ptr))
return;
make_pointer_instance(L, ptr);
}
template<class T>
T const* to_cpp(lua_State*, by_const_pointer<T>, int)
{
return static_cast<T const*>(result);
}
template<class T>
int match(lua_State* L, by_const_pointer<T>, int index)
{
if(lua_isnil(L, index)) return 0;
object_rep* obj = get_instance(L, index);
if(obj == 0) return no_match; // if the type is not one of our own registered types, classify it as a non-match
std::pair<void*, int> s = obj->get_instance(registered_class<T>::id);
if(s.second >= 0 && !obj->is_const())
s.second += 10;
result = s.first;
return s.second;
}
template<class T>
void converter_postcall(lua_State*, T, int) {}
};
}
}
#endif
@@ -0,0 +1,124 @@
// 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 LUABIND_REFERENCE_CONVERTER_HPP_INCLUDED
#define LUABIND_REFERENCE_CONVERTER_HPP_INCLUDED
#include <type_traits>
#include <luabind/detail/conversion_policies/conversion_base.hpp>
#include <luabind/detail/conversion_policies/pointer_converter.hpp>
#include <luabind/back_reference.hpp>
namespace luabind {
/*
TODO: Remove code duplication
*/
namespace detail {
struct ref_converter : pointer_converter
{
using type = ref_converter;
using is_native = std::false_type;
enum { consumed_args = 1 };
template<class T>
void to_lua(lua_State* L, T& ref)
{
if(luabind::get_back_reference(L, ref))
return;
make_pointee_instance(L, ref, std::false_type());
}
template<class T>
T& to_cpp(lua_State* L, by_reference<T>, int index)
{
assert(!lua_isnil(L, index));
return *pointer_converter::to_cpp(L, by_pointer<T>(), index);
}
template<class T>
int match(lua_State* L, by_reference<T>, int index)
{
object_rep* obj = get_instance(L, index);
if(obj == 0) return no_match;
if(obj->is_const())
return no_match;
std::pair<void*, int> s = obj->get_instance(registered_class<T>::id);
result = s.first;
return s.second;
}
template<class T>
void converter_postcall(lua_State*, T, int) {}
};
struct const_ref_converter
{
using type = const_ref_converter;
using is_native = std::false_type;
enum { consumed_args = 1 };
const_ref_converter()
: result(0)
{}
void* result;
template<class T>
void to_lua(lua_State* L, T const& ref)
{
if(luabind::get_back_reference(L, ref))
return;
make_pointee_instance(L, ref, std::false_type());
}
template<class T>
T const& to_cpp(lua_State*, by_const_reference<T>, int)
{
return *static_cast<T*>(result);
}
template<class T>
int match(lua_State* L, by_const_reference<T>, int index)
{
object_rep* obj = get_instance(L, index);
if(obj == 0) return no_match; // if the type is not one of our own registered types, classify it as a non-match
std::pair<void*, int> s = obj->get_instance(registered_class<T>::id);
if(s.second >= 0 && !obj->is_const())
s.second += 10;
result = s.first;
return s.second;
}
template<class T>
void converter_postcall(lua_State*, by_const_reference<T>, int)
{
}
};
}
}
#endif
@@ -0,0 +1,79 @@
// 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 LUABIND_VALUE_CONVERTER_HPP_INCLUDED
#define LUABIND_VALUE_CONVERTER_HPP_INCLUDED
#include <type_traits>
#include <luabind/lua_include.hpp>
#include <luabind/back_reference.hpp>
#include <luabind/detail/object_rep.hpp>
namespace luabind {
namespace detail {
struct value_converter
{
using type = value_converter;
using is_native = std::false_type;
enum { consumed_args = 1 };
value_converter()
: result(0)
{}
void* result;
template<class T>
void to_lua(lua_State* L, T&& x)
{
if(luabind::get_back_reference(L, x))
return;
make_value_instance(L, std::forward<T>(x));
}
template<class T>
T to_cpp(lua_State*, by_value<T>, int)
{
return *static_cast<T*>(result);
}
template<class T>
int match(lua_State* L, by_value<T>, int index)
{
// special case if we get nil in, try to match the holder type
if(lua_isnil(L, index))
return no_match;
object_rep* obj = get_instance(L, index);
if(obj == 0) return no_match;
std::pair<void*, int> s = obj->get_instance(registered_class<T>::id);
result = s.first;
return s.second;
}
template<class T>
void converter_postcall(lua_State*, T, int) {}
};
}
}
#endif
@@ -6,11 +6,12 @@
# define LUABIND_CONVERSION_STORAGE_080930_HPP # define LUABIND_CONVERSION_STORAGE_080930_HPP
# include <luabind/config.hpp> # include <luabind/config.hpp>
# include <boost/aligned_storage.hpp> # include <type_traits>
namespace luabind { namespace detail { namespace luabind {
namespace detail {
typedef void(*destruction_function)(void*); using destruction_function = void(*)(void*);
// This is used by the converters in policy.hpp, and // This is used by the converters in policy.hpp, and
// class_rep::convert_to as temporary storage when constructing // class_rep::convert_to as temporary storage when constructing
@@ -31,11 +32,12 @@ struct conversion_storage
// Unfortunately the converters currently doesn't have access to // Unfortunately the converters currently doesn't have access to
// the actual type being converted when this is instantiated, so // the actual type being converted when this is instantiated, so
// we have to guess a max size. // we have to guess a max size.
boost::aligned_storage<128> data; std::aligned_storage<128> data;
destruction_function destructor; destruction_function destructor;
}; };
}} // namespace luabind::detail }
} // namespace luabind::detail
#endif // LUABIND_CONVERSION_STORAGE_080930_HPP #endif // LUABIND_CONVERSION_STORAGE_080930_HPP
@@ -1,92 +0,0 @@
// Copyright (c) 2003 Daniel Wallin and Arvid Norberg
// 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 LUABIND_CONVERT_TO_LUA_HPP_INCLUDED
#define LUABIND_CONVERT_TO_LUA_HPP_INCLUDED
#include <luabind/config.hpp>
#include <luabind/detail/policy.hpp>
#include <boost/ref.hpp>
#include <boost/mpl/apply_wrap.hpp>
namespace luabind { namespace detail
{
template<bool IsReferenceWrapper = false>
struct unwrap_ref
{
template<class T>
static const T& get(const T& r) { return r; }
template<class T>
struct apply
{
typedef T type;
};
};
template<>
struct unwrap_ref<true>
{
template<class T>
static T& get(const boost::reference_wrapper<T>& r) { return r.get(); }
template<class T>
struct apply
{
typedef typename T::type& type;
};
};
namespace mpl = boost::mpl;
template<class T>
void convert_to_lua(lua_State* L, const T& v)
{
typedef typename mpl::apply_wrap1<
unwrap_ref<boost::is_reference_wrapper<T>::value>
, T
>::type value_type;
typename mpl::apply_wrap2<default_policy,value_type,cpp_to_lua>::type converter;
converter.apply(L, unwrap_ref<boost::is_reference_wrapper<T>::value>::get(v));
}
template<int Index, class T, class Policies>
void convert_to_lua_p(lua_State* L, const T& v, const Policies&)
{
typedef typename mpl::apply_wrap1<
unwrap_ref<boost::is_reference_wrapper<T>::value>
, T
>::type value_type;
typedef typename find_conversion_policy<Index, Policies>::type converter_policy;
typename mpl::apply_wrap2<converter_policy,value_type,cpp_to_lua>::type converter;
converter.apply(L, unwrap_ref<boost::is_reference_wrapper<T>::value>::get(v));
}
}}
#endif
@@ -0,0 +1,58 @@
#ifndef LUABIND_CRTP_ITERATOR_HPP_INCLUDED
#define LUABIND_CRTP_ITERATOR_HPP_INCLUDED
#include <iterator>
namespace luabind {
namespace detail {
template< typename CRTP, typename Category, typename ValueType, typename ReferenceType = ValueType&, typename DifferenceType = ptrdiff_t >
class crtp_iterator :
public std::iterator<Category, ValueType, DifferenceType, ValueType*, ReferenceType >
{
public:
using base_type = std::iterator<Category, ValueType, DifferenceType, ValueType*, ReferenceType >;
CRTP& operator++()
{
upcast().increment();
return upcast();
}
CRTP operator++(int)
{
CRTP tmp(upcast());
upcast().increment();
return tmp;
}
bool operator==(const CRTP& rhs)
{
return upcast().equal(rhs);
}
bool operator!=(const CRTP& rhs)
{
return !upcast().equal(rhs);
}
typename base_type::reference operator*()
{
return upcast().dereference();
}
typename base_type::reference operator->()
{
return upcast().dereference();
}
private:
CRTP& upcast() { return static_cast<CRTP&>(*this); }
const CRTP& upcast() const { return static_cast<const CRTP&>(*this); }
};
}
}
#endif

Some files were not shown because too many files have changed in this diff Show More