# Copyright (c) 2026 Jakub Juszczakiewicz
# All rights reserved.

cmake_minimum_required(VERSION 3.19...3.21)
project(kit-bigints C ASM)

set(WITH_TESTS TRUE CACHE BOOL true)

include_directories(
  include
)

include(CheckSourceCompiles)

set(HEADER_FILES include/kitbigints/version.h)
set(SOURCE_FILES src/version.c)

include (TestBigEndian)
TEST_BIG_ENDIAN(IS_BIG_ENDIAN)
if(IS_BIG_ENDIAN)
 add_definitions(-DBIG_ENDIAN)
else()
 add_definitions(-DLITTLE_ENDIAN)
endif()

if(MINGW)
add_definitions(-DUSE_WINAPI)
add_definitions(-DIS_MINGW)
set(WINDOWS True CACHE BOOL "Window OS")
elseif(WIN32)
add_definitions(-DUSE_WINAPI)
set(WINDOWS True CACHE BOOL "Window OS")
else()
set(WINDOWS False CACHE BOOL "Window OS")
endif()

if(CMAKE_SIZEOF_VOID_P EQUAL 8)
  add_definitions(-DSIZE_T_BITS=64)
elseif(CMAKE_SIZEOF_VOID_P EQUAL 4)
  add_definitions(-DSIZE_T_BITS=32)
else()
  message(FATAL_ERROR "Unsupported architecture")
endif()
check_type_size(__int128 INT_128)
if (HAVE_INT_128)
  add_definitions(-DHAVE_INT_128)
endif()

check_include_file("unistd.h" HAVE_UNISTD_H)
if(HAVE_UNISTD_H)
 add_definitions(-DHAVE_UNISTD_H)
endif()

if (HAVE_UNISTD_H)
check_source_compiles(C "
#include <stdint.h>
#include <stddef.h>
#include <unistd.h>

int main()
{
  ssize_t a = 10;
  return 0;
}
" HAVE_SSIZE_T)
else()
check_source_compiles(C "
#include <stdint.h>
#include <stddef.h>

int main()
{
  ssize_t a = 10;
  return 0;
}
" HAVE_SSIZE_T)
endif()
if(HAVE_SSIZE_T)
 add_definitions(-DHAVE_SSIZE_T)
endif()

set(ALG_NASM False CACHE BOOL "Add support for assembler code compiled by nasm")
if (ALG_NASM)
  enable_language(ASM_NASM)
endif()

set(ALG_ARCH "C" CACHE STRING "Compile architecture specific code")

list(APPEND HEADER_FILES include/kitbigints/bigint.h)
include(src/CMakeLists.txt)

add_library(kitbigints SHARED ${SOURCE_FILES})
set_property(TARGET kitbigints PROPERTY C_STANDARD 23)
set_property(TARGET kitbigints PROPERTY POSITION_INDEPENDENT_CODE 1)
install(TARGETS kitbigints LIBRARY DESTINATION lib)

install(FILES ${HEADER_FILES} DESTINATION include/kitbigints)

if (${WITH_TESTS})
  include(CTest)
  add_subdirectory(tests)
endif()
