-
-
\ No newline at end of file
diff --git a/solvitaire/.idea/codeStyles/Project.xml b/solvitaire/.idea/codeStyles/Project.xml
deleted file mode 100644
index 30aa626..0000000
--- a/solvitaire/.idea/codeStyles/Project.xml
+++ /dev/null
@@ -1,29 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/solvitaire/.idea/codeStyles/codeStyleConfig.xml b/solvitaire/.idea/codeStyles/codeStyleConfig.xml
deleted file mode 100644
index a55e7a1..0000000
--- a/solvitaire/.idea/codeStyles/codeStyleConfig.xml
+++ /dev/null
@@ -1,5 +0,0 @@
-
-
-
-
-
\ No newline at end of file
diff --git a/solvitaire/.idea/misc.xml b/solvitaire/.idea/misc.xml
deleted file mode 100644
index 79b3c94..0000000
--- a/solvitaire/.idea/misc.xml
+++ /dev/null
@@ -1,4 +0,0 @@
-
-
-
-
\ No newline at end of file
diff --git a/solvitaire/.idea/modules.xml b/solvitaire/.idea/modules.xml
deleted file mode 100644
index 6bef8dd..0000000
--- a/solvitaire/.idea/modules.xml
+++ /dev/null
@@ -1,8 +0,0 @@
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/solvitaire/.idea/statistic.xml b/solvitaire/.idea/statistic.xml
deleted file mode 100644
index 1f847e3..0000000
--- a/solvitaire/.idea/statistic.xml
+++ /dev/null
@@ -1,14 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/solvitaire/.idea/vcs.xml b/solvitaire/.idea/vcs.xml
deleted file mode 100644
index 94a25f7..0000000
--- a/solvitaire/.idea/vcs.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-
-
-
-
\ No newline at end of file
diff --git a/solvitaire/CMakeLists.txt b/solvitaire/CMakeLists.txt
deleted file mode 100644
index 3d85ae5..0000000
--- a/solvitaire/CMakeLists.txt
+++ /dev/null
@@ -1,224 +0,0 @@
-# File based on https://stackoverflow.com/questions/21163188/most-simple-but-complete-cmake-example
-
-cmake_minimum_required(VERSION 3.9.4)
-project(solvitaire)
-
-set(CMAKE_CXX_STANDARD 14)
-set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
-
-# For -flto flag
-include(CheckIPOSupported)
-check_ipo_supported(RESULT supported OUTPUT error)
-
-###############################################################################
-## source files ###############################################################
-###############################################################################
-
-set(main src/main/main.cpp)
-set(sources src/main/input-output/input/command_line_helper.cpp
- src/main/api.cpp
- src/main/input-output/input/command_line_helper.h
- src/main/input-output/output/log_helper.h
- src/main/game/card.h
- src/main/game/card.cpp
- src/main/input-output/input/json-parsing/deal_parser.h
- src/main/input-output/input/json-parsing/deal_parser.cpp
- src/main/solver/solver.cpp
- src/main/solver/solver.h
- src/main/game/search-state/game_state.cpp
- src/main/game/search-state/game_state.h
- src/main/game/sol_rules.h
- src/main/game/pile.cpp
- src/main/game/pile.h
- src/main/input-output/input/json-parsing/json_helper.cpp
- src/main/input-output/input/json-parsing/json_helper.h
- src/main/input-output/input/sol_preset_types.h
- src/main/input-output/input/sol_preset_types.cpp
- src/main/input-output/input/json-parsing/rules_parser.cpp
- src/main/input-output/input/json-parsing/rules_parser.h
- src/main/input-output/output/state_printer.cpp
- src/main/input-output/output/state_printer.h
- src/main/game/global_cache.cpp
- src/main/game/global_cache.h
- src/main/game/sol_rules.cpp
- src/main/evaluation/solvability_calc.cpp
- src/main/evaluation/solvability_calc.h
- src/main/evaluation/benchmark.cpp
- src/main/evaluation/benchmark.h
- lib/rapidjson/document.h
- lib/rapidjson/schema.h
- lib/rapidjson/stringbuffer.h
- src/main/game/search-state/game_state.legal_moves.cpp
- src/main/game/search-state/game_state.dominance_moves.cpp
- src/main/game/search-state/game_state.pile_order.cpp
- src/main/game/move.cpp
- src/main/game/move.h src/main/evaluation/binomial_ci.cpp src/main/evaluation/binomial_ci.h)
-set(sources_test
- src/test/test_helper.cpp
- src/test/test_helper.h
- src/test/integration_tests/spanish_patience_test.cpp
- src/test/integration_tests/black_hole_test.cpp
- src/test/integration_tests/free_cell_test.cpp
- src/test/integration_tests/bakers_dozen_test.cpp
- src/test/integration_tests/fortunes_favor_test.cpp
- src/test/integration_tests/flower_garden_test.cpp
- src/test/integration_tests/canfield_test.cpp
- src/test/integration_tests/somerset_test.cpp
- src/test/integration_tests/alpha_star_test.cpp
- src/test/integration_tests/spider_test.cpp
- src/test/integration_tests/klondike_test.cpp
- src/test/integration_tests/gaps_test.cpp
- src/test/integration_tests/accordion_test.cpp
- src/test/unit_tests/global_cache_test.cpp
- src/test/unit_tests/foundations_dominance_test.cpp
- src/test/unit_tests/deal_parser_test.cpp
- src/test/unit_tests/card_test.cpp
- src/test/unit_tests/pile_test.cpp
- src/test/unit_tests/legal_move_gen_test.cpp
- src/test/unit_tests/built_group_move_gen_test.cpp
- src/test/unit_tests/face_up_cards_test.cpp
- src/test/unit_tests/k_plus_stock_test.cpp)
-
-###############################################################################
-## Rapid JSON setup ###########################################################
-###############################################################################
-
-include_directories(lib/rapidjson)
-
-###############################################################################
-## Boost setup ################################################################
-###############################################################################
-
-set(Boost_USE_STATIC_LIBS ON)
-set(Boost_USE_MULTITHREADED ON)
-set(Boost_USE_STATIC_RUNTIME OFF)
-
-set(boost_components program_options)
-
-find_package(Boost 1.53.0 REQUIRED COMPONENTS ${boost_components})
-
-if(Boost_FOUND)
- include_directories(${Boost_INCLUDE_DIRS})
-else()
- message(WARNING "Must install Boost libraries")
-endif()
-
-###############################################################################
-## GTest setup ################################################################
-###############################################################################
-
-# Download and unpack googletest at configure time
-configure_file(CMakeLists.txt.in googletest-download/CMakeLists.txt)
-execute_process(COMMAND ${CMAKE_COMMAND} -G "${CMAKE_GENERATOR}" .
- RESULT_VARIABLE result
- WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/googletest-download )
-if(result)
- message(FATAL_ERROR "CMake step for googletest failed: ${result}")
-endif()
-execute_process(COMMAND ${CMAKE_COMMAND} --build .
- RESULT_VARIABLE result
- WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/googletest-download )
-if(result)
- message(FATAL_ERROR "Build step for googletest failed: ${result}")
-endif()
-
-# Add googletest directly to our build. This defines
-# the gtest and gtest_main targets.
-add_subdirectory(${CMAKE_BINARY_DIR}/googletest-src
- ${CMAKE_BINARY_DIR}/googletest-build)
-
-# The gtest/gtest_main targets carry header search path
-# dependencies automatically when using CMake 2.8.11 or
-# later. Otherwise we have to add them here ourselves.
-if (CMAKE_VERSION VERSION_LESS 2.8.11)
- include_directories("${gtest_SOURCE_DIR}/include")
-endif()
-
-###############################################################################
-## compile options ############################################################
-###############################################################################
-
-set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14 -DBOOST_LOG_DYN_LINK \
--lboost_system -pthread -pedantic -Wall -Wextra \
--Wcast-align -Wcast-qual -Wformat=2 -Winit-self \
--Wlogical-op -Wmissing-declarations -Wmissing-include-dirs -Wnoexcept \
--Wno-old-style-cast -Woverloaded-virtual -Wredundant-decls -Wno-shadow \
--Wno-error=catch-value= \
--Wstrict-null-sentinel -Werror")
-set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -O0 -g")
-#set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -O -fno-inline -fno-inline-functions -g -Wl,-O1") # uncomment for profiling
-set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -O3 -flto -s -DNDEBUG -Wl,-O1") # uncomment otherwise
-
-###############################################################################
-## target definitions #########################################################
-###############################################################################
-
-# Default to building the 'Debug' configuration
-if(NOT CMAKE_BUILD_TYPE)
- set(CMAKE_BUILD_TYPE Debug CACHE STRING "The build configuration" FORCE)
-endif()
-
-# add the data to the target, so it becomes visible in some IDE
-add_executable(solvitaire ${main} ${sources})
-set_property(TARGET solvitaire PROPERTY INTERPROCEDURAL_OPTIMIZATION TRUE) # For -flto flag
-target_link_libraries(solvitaire LINK_PUBLIC ${Boost_LIBRARIES})
-
-add_library(sol STATIC ${sources})
-set_target_properties(sol PROPERTIES PUBLIC_HEADER src/main/api.h)
-set_property(TARGET sol PROPERTY INTERPROCEDURAL_OPTIMIZATION TRUE) # For -flto flag
-target_link_libraries(sol LINK_PUBLIC ${Boost_LIBRARIES})
-
-# add a separete executable for the 'no pile symmetry' version of the solver
-#add_executable(solvitaire-no-pile-symmetry ${main} ${sources})
-#target_link_libraries(solvitaire-no-pile-symmetry LINK_PUBLIC ${Boost_LIBRARIES})
-#set_target_properties(solvitaire-no-pile-symmetry PROPERTIES COMPILE_FLAGS -DNO_PILE_SYMMETRY)
-
-# add a separete executable for the 'no suit symmetry' version of the solver
-#add_executable(solvitaire-no-suit-symmetry ${main} ${sources})
-#target_link_libraries(solvitaire-no-suit-symmetry LINK_PUBLIC ${Boost_LIBRARIES})
-#set_target_properties(solvitaire-no-suit-symmetry PROPERTIES COMPILE_FLAGS -DNO_SUIT_SYMMETRY)
-
-# add a separete executable for the 'no symmetry' version of the solver
-#add_executable(solvitaire-no-symmetry ${main} ${sources})
-#target_link_libraries(solvitaire-no-symmetry LINK_PUBLIC ${Boost_LIBRARIES})
-#set_target_properties(solvitaire-no-symmetry PROPERTIES COMPILE_FLAGS "-DNO_SUIT_SYMMETRY -DNO_PILE_SYMMETRY")
-
-# add a separete executable for the 'no auto foundations' version of the solver
-#add_executable(solvitaire-no-auto-foundations ${main} ${sources})
-#target_link_libraries(solvitaire-no-auto-foundations LINK_PUBLIC ${Boost_LIBRARIES})
-#set_target_properties(solvitaire-no-auto-foundations PROPERTIES COMPILE_FLAGS -DNO_AUTO_FOUNDATIONS)
-
-
-###############################################################################
-## testing ####################################################################
-###############################################################################
-
-add_executable(unit_tests ${sources_test} ${sources})
-
-# this allows us to use our executable as a link library
-# therefore we can inherit all compiler options and library dependencies
-set_target_properties(solvitaire PROPERTIES ENABLE_EXPORTS on)
-
-target_link_libraries(unit_tests gtest_main ${Boost_LIBRARIES})
-
-ENABLE_TESTING()
-ADD_TEST(NAME unit_tests
- WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/bin
- COMMAND unit_tests)
-
-###############################################################################
-## packaging ##################################################################
-###############################################################################
-
-# all install commands get the same destination. this allows us to use paths
-# relative to the executable.
-install(TARGETS solvitaire DESTINATION solvitaire)
-
-set(CPACK_OUTPUT_FILE_PREFIX installer)
-set(CPACK_PACKAGE_VERSION "1.0.0")
-
-# we don't want to split our program up into several things
-set(CPACK_MONOLITHIC_INSTALL 1)
-
-# This must be last
-include(CPack)
diff --git a/solvitaire/CMakeLists.txt.in b/solvitaire/CMakeLists.txt.in
deleted file mode 100644
index 4c67ef5..0000000
--- a/solvitaire/CMakeLists.txt.in
+++ /dev/null
@@ -1,15 +0,0 @@
-cmake_minimum_required(VERSION 2.8.2)
-
-project(googletest-download NONE)
-
-include(ExternalProject)
-ExternalProject_Add(googletest
- GIT_REPOSITORY https://github.com/google/googletest.git
- GIT_TAG master
- SOURCE_DIR "${CMAKE_BINARY_DIR}/googletest-src"
- BINARY_DIR "${CMAKE_BINARY_DIR}/googletest-build"
- CONFIGURE_COMMAND ""
- BUILD_COMMAND ""
- INSTALL_COMMAND ""
- TEST_COMMAND ""
-)
diff --git a/solvitaire/Dockerfile b/solvitaire/Dockerfile
deleted file mode 100644
index 7a63b5b..0000000
--- a/solvitaire/Dockerfile
+++ /dev/null
@@ -1,31 +0,0 @@
-FROM ubuntu:18.04
-
-WORKDIR /home/Solvitaire/
-
-COPY . /home/Solvitaire/
-
-RUN apt-get update \
-&& apt-get install -y \
-gcc-6 \
-cmake \
-libboost-all-dev \
-git \
-python3 \
-vim \
-parallel
-
-RUN cmake [-G "CodeBlocks - Unix Makefiles"] \
--DCMAKE_BUILD_TYPE=RELEASE \
--Bcmake-build-release -H. \
-&& cmake [-G "CodeBlocks - Unix Makefiles"] \
--DCMAKE_BUILD_TYPE=DEBUG \
--Bcmake-build-debug -H.
-
-RUN cmake --build cmake-build-release \
-&& cmake --build cmake-build-debug
-
-WORKDIR /home/
-RUN mv /home/Solvitaire/ /home/.install/
-WORKDIR /home/Solvitaire/
-
-CMD /bin/bash
diff --git a/solvitaire/README.md b/solvitaire/README.md
deleted file mode 100644
index 8644da4..0000000
--- a/solvitaire/README.md
+++ /dev/null
@@ -1,113 +0,0 @@
-# Solvitaire: A general solver for perfect-information solitaire games
-
-## Install
-
-The easiest way to install (and run) Solvitaire is by using the supplied
-Docker image. For more information about installing Docker, head to
-
-
-With Docker installed, simply run:
-
-```
-$ ./docker-install.sh
-```
-
-This command downloads a docker image containing an environment in which
-Solvitaire can be built and run, without the user needing to worry about having
-the correct dependencies/versions.
-
-It also adds a pre-made CMake build system and a built binary to your directory
-so you don't have to wait for an initial build to compile. Rather convenient!
-
-The downside to this approach is that the Docker image is unfortunately quite
-large, and pulling it may take a minute or two (although you only have to do
-this once!) If you don't wish to use docker, the steps contained in
-_Dockerfile_ should be a good guide to the required dependencies, although bear
-in mind that on older Linux systems the required versions of dependencies may
-not be available through _rpm_ / _deb_.
-
-(Note: on one system I had to run `sudo usermod -aG docker $USER`
-and then restart my machine before docker would allow me sufficient
-permissions. Just making a note of this here in case others encounter a similar
-problem)
-
-## Using the Docker image
-
-To use the docker image, simply run:
-
-```
-$ ./enter-container.sh
-```
-
-This command will start the docker container and enter an interactive session
-within the container's filesystem. The files you'll see there are simply a
-mounted version of the root directory, so any changes you make in the
-container will be reflected in your filesystem, and vice versa. When
-you exit the interactive session the container will automatically be stopped.
-
-If you don't wish to enter an interactive session, you can run:
-
-```
-$ ./enter-container.sh "command_to_be_run"
-```
-
-This will spin up a container, run the command, and tear the container down,
-with no noticeable overhead. Combining this with the fact that the repo's
-files are mounted in the Docker image, means that a user can edit
-Solvitaire's files on their local system using their own tools/editor, and
-then build/execute Solvitaire in the controlled Docker environment - the
-best of both worlds!
-
-For more information on Docker images, see
-
-
-## Build
-
-If the above instructions have been followed, you should already have a
-built binary in the root directory.
-
-To (re-)build Solvitaire within the container, simply run:
-
-```
-$ ./build.sh [--release|--debug] [--solvitaire|--unit-tests]
-(default args = "--release" "--solvitaire")
-```
-
-If you wish to run a build from outside the container, run:
-
-```
-$ ./enter-container.sh ./build.sh
-```
-
-For more build information and options, examine _build.sh_ and
-_CMakeLists.txt._
-
-## Run
-
-To run Solvitaire from within the container, simply run either:
-
-```
-$ ./solvitaire
-$ ./solvitaire-debug
-```
-
-and for the unit tests (note, these must be
-run inside src/test for the integration tests to pass):
-
-```
-$ cd src/test
-$ ../../unit-tests
-$ ../../unit-tests-debug
-```
-
-Or from outside the container:
-
-```
-$ ./enter-container.sh "cd src/test; ../../unit-tests"
-```
-
-## Help
-
-If you have any problems getting these steps to work, don't hesitate to get in
-touch via
-
diff --git a/solvitaire/archive/README.md b/solvitaire/archive/README.md
deleted file mode 100644
index f31f44a..0000000
--- a/solvitaire/archive/README.md
+++ /dev/null
@@ -1,4 +0,0 @@
-# Archive
-
-A place to store old files which are no longer directly relevant to the
-project, but shouldn't be discarded quite yet
diff --git a/solvitaire/archive/build-notes.md b/solvitaire/archive/build-notes.md
deleted file mode 100644
index c7aca09..0000000
--- a/solvitaire/archive/build-notes.md
+++ /dev/null
@@ -1,56 +0,0 @@
-# How to build / run the project
-
-The project uses the CMake build system generator. there are several stages for
-building the project, running the program, and creating an installer.
-
-### Installing dependencies
-
-#### Upgrade GCC (if you don't have version 6)
-`sudo add-apt-repository ppa:ubuntu-toolchain-r/test -y`
-
-`sudo apt-get update -qq`
-
-`sudo apt-get install -qq g++-6`
-
-`sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-6 60 --slave /usr/bin/g++ g++ /usr/bin/g++-6`
-
-#### Boost
-
-Note: this doesn't have to (and probably shouldn't) be run from within the project, unlike the other commands listed here.
-
-`sudo wget -O boost_1_63_0.tar.gz http://sourceforge.net/projects/boost/files/boost/1.63.0/boost_1_63_0.tar.gz/download`
-
-`sudo tar xzvf boost_1_63_0.tar.gz`
-
-`cd boost_1_63_0/`
-
-`sudo ./bootstrap.sh --with-libraries=log`
-
-`sudo ./b2 link=shared threading=multi toolset=gcc optimization=space`
-
-`sudo ./b2 install`
-
-`cd ..`
-
-### Generate Build System
-
-`cmake [-G "CodeBlocks - Unix Makefiles"] -D CMAKE_CXX_COMPILER=g++-6 -DCMAKE_BUILD_TYPE=[DEBUG|RELEASE] -Bcmake-build-[debug|release] -H.`
-
-### Build project
-
-`cmake --build cmake-build-[debug|release]`
-
-### Run executable
-
-`./cmake-build-[debug|release]/bin/solvitaire`
-
-### Create project installer
-
-`cpack --config cmake-build-[debug|release]/CPackConfig.cmake`
-
-## Profiling
-
-To get line numbers, you will first need to change the release build from -03 to -02
-
-valgrind --tool=callgrind --log-file=callgrind.log cmake-build-release/bin/solvitaire ...
-kcachegrind callgrind.out._
diff --git a/solvitaire/archive/canfield-check.py b/solvitaire/archive/canfield-check.py
deleted file mode 100644
index 2bfd974..0000000
--- a/solvitaire/archive/canfield-check.py
+++ /dev/null
@@ -1,40 +0,0 @@
-import subprocess
-import json
-import re
-
-with open('sample100.txt', 'r') as myfile:
- data = myfile.read()
-
-lines = data.splitlines()
-deals = []
-for (i, line) in enumerate(lines):
- # Get stuck starting positions
- if line[:8] == "Canfield" and lines[i+12][:5] == "Stuck":
- foundations = []
- reserve = []
- tableau = []
- stock = []
- for (j, line) in enumerate(lines[i+1:i+12]):
- cards = line[6:].replace("T", "10")
-
- # Reserve
- if j < 4 and cards != '':
- foundations.append(cards)
- elif j == 4:
- reserve = list(filter(None, re.compile("\x1b\[[0-9]m ?").split(cards)))
- elif j > 4 and j < 9:
- tableau.append([cards])
- elif j == 9 or j == 10:
- stock += cards.split(' ')
- deals.append({
- "foundations": foundations,
- "reserve": reserve,
- "tableau piles": tableau,
- "stock": stock
- })
-
-for (i, deal) in enumerate(deals):
- print(json.dumps(deal), file=open("tmp.json", "wt"))
- print("Attempting deal " + str(i))
- subprocess.run(["./cmake-build-release/bin/solvitaire", "--type", "canfield", "tmp.json", "--class", "--timeout", "600000"])
-
diff --git a/solvitaire/archive/clean-build.sh b/solvitaire/archive/clean-build.sh
deleted file mode 100755
index ce17b8a..0000000
--- a/solvitaire/archive/clean-build.sh
+++ /dev/null
@@ -1,13 +0,0 @@
-#!/bin/sh
-
-echo "Cleaning..."
-rm -rf cmake-build-debug; mkdir cmake-build-debug;
-rm -rf cmake-build-release; mkdir cmake-build-release;
-
-echo "Generating build..."
-cmake -G "CodeBlocks - Unix Makefiles" -D CMAKE_CXX_COMPILER=g++ -DCMAKE_BUILD_TYPE=DEBUG --target solvitaire -Bcmake-build-debug -H.
-cmake -G "CodeBlocks - Unix Makefiles" -D CMAKE_CXX_COMPILER=g++ -DCMAKE_BUILD_TYPE=RELEASE --target solvitaire -Bcmake-build-release -H.
-
-echo "Building..."
-cmake --build cmake-build-debug
-cmake --build cmake-build-release
diff --git a/solvitaire/archive/docs/DOER-document/main.tex b/solvitaire/archive/docs/DOER-document/main.tex
deleted file mode 100644
index 400c6b6..0000000
--- a/solvitaire/archive/docs/DOER-document/main.tex
+++ /dev/null
@@ -1,107 +0,0 @@
-\documentclass{article}
-\usepackage[utf8]{inputenc}
-\usepackage[margin=1in]{geometry}
-\usepackage{hyperref}
-\usepackage[
-backend=biber,
-style=alphabetic,
-sorting=ynt
-]{biblatex}
-\addbibresource{references.bib}
-
-\title{Description, Objectives, Ethics, Resources}
-\author{Matriculation Number: 150012297}
-\date{September 2017}
-
-\begin{document}
-
-\maketitle
-
-\section{Description}
-
-\subsection{Title}
-
-\vspace{2mm}
-
-\emph{\large{A Solver for Solitaire Games of Perfect Information}}
-
-\subsection{Overview}
-
-The aim of this project is to create a solver for a variety of single-player,
-perfect information solitaire card games. The solver should be able to
-correctly provide solutions for some instances of solitaire games, and be able
-to report other instances as unsolvable, minimising the number of instances
-that are deemed `intractable' (cannot be classified as solvable or unsolvable
-within a reasonable time period). A key study for this project will be how to
-do this efficiently for a \emph{variety} of solitaire games.
-
-Perfect information games are an especially important domain in artificial
-intelligence, and some of the most high-profile successes in the field of AI
-have been creating good players for games like Chess, Checkers and Go, all of
-which are perfect information games. However, relatively little work has been
-done on creating programs to play single-player perfect information games, and
-good solvers do not yet exist for most solitaire games.
-
-Hence, this project will focus on creating a solver which is general enough to
-be able to play a wide range of solitaire games, whilst also maintaining a high
-level of efficiency. This efficiency will be achieved through a combination of
-language-level optimisation, and through exploring different AI search
-techniques. A specialised solver will be written to accomplish this, in code
-rather than using an existing constraint solving or planning programs.
-
-\section{Objectives}
-
-\subsection{Primary Objectives}
-
-\begin{enumerate}
- \item An application for solving single-player, perfect information solitaire
-instances (software artefact).
- \item Some kind of schema or language for describing a \emph{wide} range of
-solitaire games.
- \item The application must be able to solve valid games expressed using the
-schema/language.
- \item Automated testing to demonstrate the correctness of my classifications.
- \item An implementation of search techniques such as `meta-moves'/`super
-moves'\cite{SolLab} and eliminating symmetrical states.
- \item An implementation of language-level/design optimisations to improve the
-efficiency of my search.
- \item An analysis in my report of the effects of the above search techniques
-and implementation choices on the performance of the solver.
-\end{enumerate}
-
-\subsection{Secondary Objectives}
-
-\begin{enumerate}
- \item Optimise the search algorithm to eliminate searching states in which
-certain moves/states `dominate'\cite{WikDom} others.
- \item Implement and evaluate more than one different type of search (e.g.
-best first, iterative deepening).
- \item Experiment with and evaluate different designs for the general
-heuristic for best-first search, that works across a variety of games.
-\end{enumerate}
-
-\subsection{Tertiary Objectives}
-
-Other tertiary objectives that satisfy the core aims of the project would be
-reasonable additions. Below are two particular instances of interesting routes
-down which this project could be taken:
-
-\begin{enumerate}
- \item An extension of the algorithm that aims to provide shortened solutions
-(i.e. ones that minimise the number of moves taken).
- \item Calculating the solvability ratio for some the games my application can
-solve.
-\end{enumerate}
-
-\section{Ethics}
-
-There are no ethical considerations for this project.
-
-\section{Resources}
-
-This project can be completed using standard school equipment.
-
-\printbibliography
-
-\end{document}
-
diff --git a/solvitaire/archive/docs/DOER-document/references.bib b/solvitaire/archive/docs/DOER-document/references.bib
deleted file mode 100644
index ae852d6..0000000
--- a/solvitaire/archive/docs/DOER-document/references.bib
+++ /dev/null
@@ -1,16 +0,0 @@
-@online{SolLab,
- author = "Michael Keller",
- title = "FreeCell -- Frequently Asked Questions (FAQ)",
- year = "2015",
- url = "http://solitairelaboratory.com/fcfaq.html#Supermove",
- urldate = "2017-09-20"
-}
-
-@online{WikDom,
- author = "Wikipedia",
- title = "Stochastic dominance",
- year = "2017",
- url = "https://en.wikipedia.org/wiki/Stochastic_dominance",
- urldate = "2017-09-20"
-}
-
diff --git a/solvitaire/archive/docs/project-tools.md b/solvitaire/archive/docs/project-tools.md
deleted file mode 100644
index 4bbfed8..0000000
--- a/solvitaire/archive/docs/project-tools.md
+++ /dev/null
@@ -1,27 +0,0 @@
-# Project Tools
-
-**Language:** C++
-
-**IDE:** CLion
-
-**Build Tool:** CMake
-
-**Dependency Management:** Conan.io
-
-**Unit Testing:** GTest
-
-**Logging:** Boost logging library
-
-**Documentation:** Doxygen
-
-**Profiling:** Gperftools
-
-**Debugging:** GDB
-
-**Continuous Integration:** TravisCI
-
-**Version Control:** Git
-
-**Agile Tracking:** Trello / Kanban
-
-**Documentation:** Doxygen
diff --git a/solvitaire/archive/docs/supervisor-meetings/2017-09-12.md b/solvitaire/archive/docs/supervisor-meetings/2017-09-12.md
deleted file mode 100644
index 0124022..0000000
--- a/solvitaire/archive/docs/supervisor-meetings/2017-09-12.md
+++ /dev/null
@@ -1,64 +0,0 @@
-# Supervisor Meeting: 2017-09-12
-
-We had discussed the project briefly at the end of the 2016-17 academic year.
-Having officially confirmed that I was undertaking this project at the start
-of the 2017-18 academic year, this is a record of my first supervisor meeting.
-
-## Done since last meeting
-
-### Background reading
-
-I undertook a small amount of background reading over the summer, in
-anticipation for signing up to this project at the start of the year. This
-reading mainly consisted of a few papers related to solitaire solvers, and to
-Monte Carlo Tree Search (a particular method used for AI search).
-
-### Playing Solitaires
-
-I also played a wide variety of solitaire games, using the Android App
-250+ Solitaire Collection
-
-
-## Discussion Points
-
-### Objectives
-
-Much of the meeting revolved around the objectives of the project. It was
-agreed that it would be more fruitful to create a single solver that could
-play a variety of solitares well, rather than multiple different solvers. One
-of the challenges of the project is to explore and attempt to mitigate the
-tradeoff between the generality and efficiency of the solver.
-
-### AI Search Techniques
-
-Some brief discussion took place regarding AI search techniques, and the use of
-AI Paradigms (e.g. Constraint Programming) versus specialised solvers. It was
-decided that a specialised solver would be the most rewarding approach to
-creating a solver, and possibly the most effective. The notion of 'dominance'
-in constraints was also discussed, and scenarios in certain solitaires in which
-this could be used to search more efficiently, as well as symmetries and state
-representation.
-
-### Monte Carlo Tree Search
-
-A previous SH project by Laura Brewis had focussed on imperfect information
-solitaire games, and made heavy use of the Monte Carlo Tree Search algorithm.
-Although this method is typically used for imperfect information domains,
-it was suggested that it could also be of use here. However, it was agreed
-that this was perhaps not a primary objective, and other aveues would be better
-off explored first.
-
-### Technologies
-Given the premium placed on efficiency for this project, C++ was agreed upon
-as a good candidate for a language to write the application in. Possibly using
-Python for any parts of the application that are not search-related.
-
-
-## Future Work
-
-- Read Laura Brewis' project report as a guide for how one might approach the
- project
-- Define more clearly my project objectives, both primary and secondary
-- Write a literature review of the current material on the subject of solitaie
- solvers, as a basis for planning my own work in the area
-
diff --git a/solvitaire/archive/docs/supervisor-meetings/2017-09-19.md b/solvitaire/archive/docs/supervisor-meetings/2017-09-19.md
deleted file mode 100644
index 0e39748..0000000
--- a/solvitaire/archive/docs/supervisor-meetings/2017-09-19.md
+++ /dev/null
@@ -1,78 +0,0 @@
-# Supervisor Meeting: 2017-09-19
-
-## Done since last meeting
-
-### Read Laura Brewis' Project Report
-
-This gave me a better understanding of what is expected from an SH project, as
-well as how one might approach designing a solitaire solving application. Noted
-several of the solitaire-related references Laura used in her report, and added
-them to my list of articles/papers to be reviewed.
-
-### Begin defining objectives
-
-Some work has been done on defining the primary, secondary and tertiary
-objectives for the project. This still needs to be typed up formally and
-confirmed.
-
-### List of articles for context review
-
-A list of 15 or so relevant articles and projects has been compiled as a basis
-for my ongoing context review.
-
-### Preliminary work on solitaire schema
-
-Some preliminary work has been done on a JSON schema for defining different
-types of solitaire games. Again, this still needs to be written up formally.
-
-## Discussion Points
-
-### FC-Solve Project
-
-We spent some time looking at Shlomi Fish's _fc-solve_ project, and the
-relationship my project might have to the work he's done. His solver seems
-quite advanced, but the approach he's taken is not particularly academic and
-there are not good measures of the way in which various features affect
-performance.
-
-Moreover his code and documentation are not particularly well organised.
-As a consequence it was decided that attention wouldn't be paid too closely to
-his project in general, but perhaps for individual features his implementation
-could serve as a good reference.
-
-### Project Objectives
-
-The objectives for the project will likely be broken down into primary,
-secondary and tertiary objectives, representing the essential features, the
-more important additional features, and the less important additional features
-respectively.
-
-The ability to accurately determine solutions, or classify instances as
-insolvable are of course core features, and an implementation of meta-moves is
-also probably a core feature. By contrast implementing some notion of
-'dominance' might be a secondary objective, and a monte-carlo tree search might
-be a tertiary objective.
-
-### Range of games
-
-Having a solver that is able to solve a wide variety of solitaire games is also
-a very important feature for the project. We decided that this was one of the
-features that differentiates this project from, say, _fc-solve_. Generality
-will be at the core of the project. It is up to me now to decide which range of
-features to target, and which types of games to target.
-
-### Where to start
-
-It was suggested that the project would benefit from targeting generality right
-from the start, adding this across the implementation as soon as feasible,
-rather than as an addition towards the end of the project. This advice will
-be taken on board when planning the work to be done in the initial stages
-of the project.
-
-## Future Work
-
-- Formally define Primary, Secondary and Tertiary objectives for project
-- This will be done as part of the overall DOER document
-- Begin reviewing articles & projects as part of an ongoing context review
-- Write up ideas for JSON solitaire schema
-- Create project design plan
diff --git a/solvitaire/archive/docs/supervisor-meetings/2017-09-25.md b/solvitaire/archive/docs/supervisor-meetings/2017-09-25.md
deleted file mode 100644
index b7c3a6e..0000000
--- a/solvitaire/archive/docs/supervisor-meetings/2017-09-25.md
+++ /dev/null
@@ -1,52 +0,0 @@
-# Supervisor Meeting: 2017-09-19
-
-## Done since last meeting
-
-### Write first draft of DOER document
-
-First draft completed. See DOER branch for details. Primary, secondary and
-tertiary objectives written up and will need discussion with supervisor.
-
-### Create draft JSON schema for describing card games
-
-Draft schema written for describing a number of games from the 250+ Solitaire
-app.
-
-## Discussion Points
-
-### DOER form changes
-
-#### Primary objectives:
-- Schema/language has been moved to objective 2
-- Testing for correctness of classifications has been made into its own
- objective
-- Symmetry checking has been added to meta-moves objective
-- Objective added for language-level/design optimisations
-- Analysis objective moved to end of list of primary objectives
-
-#### Secondary objectives:
-- Added need to evaluate as well as implement different types of search
- (objective 2)
-- Best-first heuristic objective rewritten to make more sense (given previous
- objective required a basic for of this heuristic anyway)
-
-#### Tertiary objectives:
-- Removed MCTS and added solvability ratio objective
-
-### JSON Schema
-
-It was suggested that although it was sensible to limit the number of features
-to some reasonable limit, it may be beneficial to make my schema more
-expressive, so that almost anything that my implementation could in theory
-process, is able to be expressed in my language.
-
-For example, if a game uses 'any suit' to build downwards, that could
-actually just be shorthand for the following sequence 'K,Q,J,10,9,8,...',
-which can optionally be supplied in full.
-
-## Future Work
-
-- Create project design plan
-- Decide on technologies/ecosystem for project
-- Create very basic app using the above
-
diff --git a/solvitaire/archive/docs/supervisor-meetings/2017-10-03.md b/solvitaire/archive/docs/supervisor-meetings/2017-10-03.md
deleted file mode 100644
index f43b9aa..0000000
--- a/solvitaire/archive/docs/supervisor-meetings/2017-10-03.md
+++ /dev/null
@@ -1,21 +0,0 @@
-# Supervisor Meeting: 2017-09-19
-
-## Done since last meeting
-
-### Project initial plan
-
-Created first few Trello backlog tasks for setting up the project.
-
-### Tools / ecosystem plan
-
-Decided on and partially set up project ecosystem for Java
-
-## Discussion Points
-
-The relative merits of implementing the project in Java and C++. It was felt that whilst a different language would probably not make a huge difference a) C++ would run faster and would probably be more suited to the task at hand, and b) it would be a worthwhile endeavor from a personal perspective to improve my C++ skills. Therefor I decided to switch (back) from Java to C++
-
-## Future Work
-
-- Redo my tools/ecosystem plan for C++
-- Set up my tools and ecosystem for the project with a template of each element working
-- Create a very basic solver for one of the solitaire games
diff --git a/solvitaire/archive/docs/supervisor-meetings/2017-10-12.md b/solvitaire/archive/docs/supervisor-meetings/2017-10-12.md
deleted file mode 100644
index 6360a6d..0000000
--- a/solvitaire/archive/docs/supervisor-meetings/2017-10-12.md
+++ /dev/null
@@ -1,53 +0,0 @@
-# Supervisor Meeting: 2017-10-12
-
-## Done since last meeting
-
-### Tools / ecosystem plan for C++
-
-Tools and ecosystem decided upon. They are detailed in their own document but at the time of writing they are as follows:
-
-**Language:** C++
-
-**IDE:** CLion
-
-**Build Tool:** CMake
-
-**Dependency Management:** Conan.io
-
-**Unit Testing:** GTest
-
-**Logging:** Boost logging library
-
-**Documentation:** Doxygen
-
-**Profiling:** Gperftools
-
-**Debugging:** GDB
-
-**Continuous Integration:** TravisCI
-
-**Version Control:** Git
-
-**Agile Tracking:** Trello / Kanban
-
-**Documentation:** Doxygen
-
-Most of these have been implemented and work properly. The only one left to do before development can begin properly is TravisCI.
-
-### Simplified Black Hole solver
-
-I have created a simple solver for a small version of Black Hole. This compiles and runs successfully.
-
-## Discussion Points
-
-Demonstrated the Black Hole solver and several parts of the tools setup. Much of the discussion focused on the structure of the project in terms of classes and inheritance. It was discussed that I reflect the different functionality of different game features through subclassing, and abstract common functionality into superclasses.
-
-We also talked about the possibility of abstracting the _way_ in which searches generate new states (changing pointers to existing states or creating whole new data structures), and the potential usefulness of this. It was also suggested not to take for granted the notion that copying the whole state every time was less efficient, due to system-level memory optimisations.
-
-Finally, we spoke about where to go from here, and good next steps. To avoid premature optimisation, optimisation will not be focused on for now. Instead, the first step was to clean up the code I have now and put it in nice object-oriented classes, in a way that lends itself to being expanded to other solitaire features. Then to create the relevant command-line interactions, logging and output to have a fully-working program (agile). And then to think about incrementally adding new features.
-
-## Future Work
-
-- Finish the work I need to do in terms of tools-setup (i.e. TravisCI)
-- Tidy up my code and refactor it in good, object-oriented style
-- Add the necessary features to have a program that is 'ready for release' (agile).
diff --git a/solvitaire/archive/docs/supervisor-meetings/2017-10-17.md b/solvitaire/archive/docs/supervisor-meetings/2017-10-17.md
deleted file mode 100644
index 99ecd47..0000000
--- a/solvitaire/archive/docs/supervisor-meetings/2017-10-17.md
+++ /dev/null
@@ -1,29 +0,0 @@
-# Supervisor Meeting: 2017-10-17
-
-## Done since last meeting
-
-### Finish Core Tools Setup work
-
-TravisCI now tested and working
-
-### Add user input handling
-
-Added command line parsing library logic and also added a library to scan the
-user's JSON relative to a validation schema.
-
-### Finish C++ book
-
-Whilst there is still more I can learn about the language, the main job of
-getting up to speed is complete.
-
-## Discussion Points
-
-We spoke about the potential to use object-orientation to handle different
-types of games. Possibly having one abstract game class which the specific
-game types could be subclasses of.
-
-## Future Work
-
-- Converting my existing solving code into a more tidy and object-oriented set
- of classes
-- Having a finished and polished black hole solver
diff --git a/solvitaire/archive/docs/supervisor-meetings/2017-10-24.md b/solvitaire/archive/docs/supervisor-meetings/2017-10-24.md
deleted file mode 100644
index 80ad93f..0000000
--- a/solvitaire/archive/docs/supervisor-meetings/2017-10-24.md
+++ /dev/null
@@ -1,30 +0,0 @@
-# Supervisor Meeting: 2017-10-24
-
-## Done since last meeting
-
-Worked on rewriting the solving and state representation logic in a more
-object-oriented fashion, using abstract classes which could be subclassed for
-different game types. Currently all of my state representation is immutable
-and is copied between functions (no heap used).
-
-## Discussion Points
-
-### Depth First Search
-
-We spoke about methods of tracking where you've been using depth-first search,
-and the efficiency of different implementations.
-
-### Object Orientaiton
-
-We examined some of the problems I was facing using O-O. Specifically, the idea
-that I would use different subclasses for different game types. This would mean
-that my solver could only handle the preset games, which did not fulfill the
-requirement for my solver to be able to handle games described using a game
-description language.
-
-## Future Work
-
-- Finish the Black Hole Solver (tidy)
-- Rework the OO in the solver to make it more general
-- Add a new game to the solver. One without a fixed solution length, but without
- loops.
diff --git a/solvitaire/archive/docs/supervisor-meetings/2017-10-31.md b/solvitaire/archive/docs/supervisor-meetings/2017-10-31.md
deleted file mode 100644
index 2083af0..0000000
--- a/solvitaire/archive/docs/supervisor-meetings/2017-10-31.md
+++ /dev/null
@@ -1,43 +0,0 @@
-# Supervisor Meeting: 2017-10-31
-
-## Done since last meeting
-
-### Finished Black Hole solver
-
-I finished work on the Black Hole solver and tidied up my code sufficiently to
-make it extendable to other game types.
-
-### Reworked Object-Orientation
-
-I reworked the object-orientation used in the solver so that classes for Black
-Hole were general enough to be able to represent other game types.
-
-### Added Spanish patience
-
-I added the game of Spanish Patience to the solver which used the core logic
-of the Black Hole search to solve this new (and quite different) game. I also
-added a simplified version of the game (as I have done with Black Hole) where
-the problem size is small enough that at this stage a solution can actually be
-found.
-
-## Discussion Points
-
-when to optimise + below
-
-Some quite extensive demonstrations of my code took place at this meeting,
-presenting the various features of my solver for both Black Hole and Spanish
-Patience. Progress is going well and what I have thus far represents a good
-basis for the rest of the project going forward.
-
-We explored what the best features to implement next would be. We agreed that
-adding new game features would be a good thing to do next, just so that a) my
-solver has a little more range, and b) it enforces strong generality on my
-solver.
-
-It was also suggested that getting a general and reliable solver should be the
-next main goal, after which optimisations should be considered.
-
-## Future Work
-
-- Add another solitaire with "cells" as part of the game rules
-- Add another solitaire with a "stock" as part of the game rules
diff --git a/solvitaire/archive/docs/supervisor-meetings/2017-11-07.md b/solvitaire/archive/docs/supervisor-meetings/2017-11-07.md
deleted file mode 100644
index 9dae911..0000000
--- a/solvitaire/archive/docs/supervisor-meetings/2017-11-07.md
+++ /dev/null
@@ -1,39 +0,0 @@
-# Supervisor Meeting: 2017-11-07
-
-## Done since last meeting
-
-### Add States Searched
-When my solver prints out a solution, it now also outputs the number of states
-searched.
-
-### Add Free Cell
-I have added the game Free Cell to the solver, which involved implementing the
-"cell" feature.
-
-### Almost Completed Canfield
-I have almost finished adding the game Canfield to the solver, which involves
-implementing the "stock/waste" feature, and the "reserve" feature.
-
-## Discussion Points
-
-We spoke about the usefulness of having some kind of script to evaluate at what
-"level" my solver can currently solve a range of basic game types. To do this
-it may be necessary to implement the feature whereby game rules are interpreted
-according to a user-supplied JSON schema.
-
-We also discussed the fact that it might be worth quickly implementing some
-kind of hash table to store states seen so far, just because the current
-naive implementation has performance so bad it makes the solver painfully slow.
-
-It was also discussed that in the longer term, it would be worth thinking about
-some heuristics that might help in getting to correct solutions quicker.
-
-## Future Work
-
-- Finish implementing Canfield
-- Add another two games: one to specifically target the stock, and one for the
-reserve
-- Add some basic unit testing for each "core" game type
-- Clean up and refactor the code a little
-- Add reading in the game rules from JSON
-- Create a performance benchmark script
diff --git a/solvitaire/archive/docs/supervisor-meetings/2017-11-14.md b/solvitaire/archive/docs/supervisor-meetings/2017-11-14.md
deleted file mode 100644
index b112a99..0000000
--- a/solvitaire/archive/docs/supervisor-meetings/2017-11-14.md
+++ /dev/null
@@ -1,36 +0,0 @@
-# Supervisor Meeting: 2017-11-14
-
-## Done since last meeting
-
-### Completed Canfield
-Canfield is completed and there exists a simple variant which my application
-can solve.
-
-### Refactor Code
-I underwent a major refactoring of my code, in order to a) clean up parts that
-were messy/not clear, b) simplify things that were overly complex, and c) make
-everything more generic.
-
-### Implement reading rule descriptions from JSON
-My solver now reads rule descriptions from a JSON file and runs its solutions
-based on those descriptions. These JSON files can either be specified by the
-user, or retrieveed internally when one of the presets is specified.
-
-## Discussion Points
-
-We spoke about the possibility of making my JSON representations of game rules
-as rich as possible, to allow it to essentially represent anything my solver
-can solve. In addition, we discussed further the plan to make deals
-representable in JSON too, which I will have to implement before I do my
-testing.
-
-In addition, there was discussion of the performance benchmarking, which is now
-possible for me to implement properly because I have the JSON rules description
-implemented. We also spoke about the best approaches to optimising code. It was
-suggested that I focus particularly on data structures and algorithms here,
-rather than, say, compiler optimisations etc.
-
-## Future Work
-
-- Create a performance benchmark script
-- Implement some basic optimisations for my code
diff --git a/solvitaire/archive/docs/supervisor-meetings/2017-11-28.md b/solvitaire/archive/docs/supervisor-meetings/2017-11-28.md
deleted file mode 100644
index 8d927ee..0000000
--- a/solvitaire/archive/docs/supervisor-meetings/2017-11-28.md
+++ /dev/null
@@ -1,26 +0,0 @@
-# Supervisor Meeting: 2017-11-28
-
-## Done since last meeting
-
-### Performance Benchmark script
-
-I've written a script to run my solver on random instances at different
-difficulty levels, of several solitaire games, to give me an overview of how
-well my solver is performing.
-
-### Basic Optimisations
-
-I've changed the way in which my program stores its own move history so that
-it can run with a better theoretical time complexity.
-
-### Code Profiling
-I've set up and documented how to run a profiler on my code to identify which
-areas are slowing down performance.
-
-## Discussion Points
-We discussed in very general terms strategy for improving the internal
-representation in my program, and what could be done in terms of caching state.
-
-## Future Work
-- Generally over the break, just focus on getting the solver running as
-efficiently as possible
diff --git a/solvitaire/archive/docs/supervisor-meetings/2018-02-01.md b/solvitaire/archive/docs/supervisor-meetings/2018-02-01.md
deleted file mode 100644
index bd141ba..0000000
--- a/solvitaire/archive/docs/supervisor-meetings/2018-02-01.md
+++ /dev/null
@@ -1,27 +0,0 @@
-# Supervisor Meeting: 2018-02-01
-
-## Done since last meeting
-
-- Added deal description and testing to existing games
-- Altered the implementation to make it more efficient
-- Added cache symmetries
-- Added 7 more games/features to the solver with accompanying tests
-- Profiled the code and identified inefficiencies
-- Improved performance by changing the way state is cached
-- Reduced the size of the cached state to improve performance
-- Added multiple versions of application to show effect of certain optimisations
-
-## Discussion Points
-
-Much of the discussion focused on reviewing the work done over the break. Then
-attention turned to dominances and the potential for them to improve my solver.
-We spoke about the foundations dominance which I still have yet to implement,
-as well as a number of black-hole specific dominances, along with one or two
-more general ones. I demonstrated the performance of my current solver, and we
-spoke about the game Spider, and the challenges of creating a solver that would
-work well for that larger 2-deck game.
-
-## Future Work
-
-- Foundations dominance
-- Review project objectives
diff --git a/solvitaire/archive/docs/supervisor-meetings/2018-02-08.md b/solvitaire/archive/docs/supervisor-meetings/2018-02-08.md
deleted file mode 100644
index fd43fbe..0000000
--- a/solvitaire/archive/docs/supervisor-meetings/2018-02-08.md
+++ /dev/null
@@ -1,37 +0,0 @@
-# Supervisor Meeting: 2018-02-01
-
-## Done since last meeting
-
-### Foundations dominance
-
-I fixed a bug with some of my game types where it would allow you to move cards
-from the foundations when it shouldn't have. I then added this dominance and
-adjusted my solver accordingly.
-
-### Review project objectives
-
-See trello card for more details. Still need to type up proper adjusted version
-now it has been discussed.
-
-## Discussion Points
-
-- We discussed what would need to be done for games where you can 'worry back',
-and how I would implement this.
-- We discovered a bug in the way I was caching states which was giving false
-results.
-- We spoke about the idea of 'streamlining' optimisations in this context.
-- We spoke about writing tests to make sure optimisations weren't giving false
-results.
-
-## Future Work
-
-- Properly type up adjusted project objectives
-- Finish admin and testing for dominance moves
-- Implement dominance for 'worrying back' games
-- Test performance of this
-- Write script for different optimisations to make sure none of them changed
-the solvability of games
-- Fix caching bug
-- Think about 'streamlining' moves and possibly add symmetry flag for this
-- Profile code
-
diff --git a/solvitaire/archive/generate-results-optimisations-off.sh b/solvitaire/archive/generate-results-optimisations-off.sh
deleted file mode 100755
index 510fa50..0000000
--- a/solvitaire/archive/generate-results-optimisations-off.sh
+++ /dev/null
@@ -1,91 +0,0 @@
-#!/bin/bash
-
-trap 'exit 130' INT
-
-if [ "$#" != 4 ]; then
- echo "Usage: "
- exit 1
-fi
-
-seeds="$1"
-cores="$2"
-timeout="$3"
-cache="$4"
-
-declare -a arr=(
-"alpha-star"
-"bakers-game"
-"black-hole"
-"castles-of-spain"
-"delta-star"
-"eight-off-any-card-spaces"
-"eight-off"
-"fan"
-"fore-cell"
-"fortunes-favor"
-"king-albert"
-"northwest-territory"
-"one-cell"
-"raglan"
-"sea-towers"
-"somerset"
-"spiderette"
-"two-cell"
-"will-o-the-wisp"
-"free-cell"
-"east-haven"
-"klondike"
-"klondike-deal-1"
-"canfield"
-"penguin"
-"free-cell-0-cell"
-"free-cell-1-cell"
-"free-cell-2-cell"
-"free-cell-3-cell"
-"free-cell-4-pile"
-"free-cell-5-pile"
-"free-cell-6-pile"
-"free-cell-7-pile"
-"flower-garden"
-"spanish-patience"
-)
-
-
-### Presets not attempted:
-### Rules wrong?
-# "martha"
-
-
-## Too difficult (?)
-
-# "alina"
-# "blind-alleys"
-# "bakers-dozen"
-# "scotch-patience"
-# "chameleon"
-# "duchess"
-# "spider"
-
-
-## Stock games
-
-
-
-DATE=`date +%Y-%m-%d-%H-%M-%S`
-
-out_dir=results/comparisons-$DATE
-
-mkdir -p "$out_dir"
-echo "Writing to $out_dir/"
-
-for i in "${arr[@]}"
-do
- echo "Running $i ..."
- ./solvability.sh "$seeds" "$cores" "./cmake-build-release/bin/solvitaire --type $i --timeout $timeout --cache $cache --str none" "$out_dir"/$i-normal
- ./solvability.sh "$seeds" "$cores" "./cmake-build-release/bin/solvitaire-no-auto-foundations --type $i --timeout $timeout --cache $cache --str none" "$out_dir"/$i-no-auto-foundations
- ./solvability.sh "$seeds" "$cores" "./cmake-build-release/bin/solvitaire-no-pile-symmetry --type $i --timeout $timeout --cache $cache --str none" "$out_dir"/$i-no-pile-symmetry
- ./solvability.sh "$seeds" "$cores" "./cmake-build-release/bin/solvitaire-no-suit-symmetry --type $i --timeout $timeout --cache $cache --str none" "$out_dir"/$i-no-suit-symmetry
- ./solvability.sh "$seeds" "$cores" "./cmake-build-release/bin/solvitaire-no-symmetry --type $i --timeout $timeout --cache $cache --str none" "$out_dir"/$i-no-symmetry
-done
-
-echo "Done!"
diff --git a/solvitaire/archive/optimisation-test.py b/solvitaire/archive/optimisation-test.py
deleted file mode 100644
index 594b9eb..0000000
--- a/solvitaire/archive/optimisation-test.py
+++ /dev/null
@@ -1,75 +0,0 @@
-import sys
-from subprocess import run, CalledProcessError, DEVNULL, PIPE, Popen
-
-runCount = 100
-
-# Loops through each canonical solitaire
-
-for optimisation in [
- "-no-reduced-state",
- "-no-pile-symmetry",
- "-no-auto-foundations",
- "-no-symmetry"
-]:
-
- for preset in [
- "simple-alpha-star",
- "simple-bakers-dozen",
- "simple-black-hole",
- "simple-canfield",
- "simple-flower-garden",
- "simple-fortunes-favor",
- "simple-free-cell",
- "simple-somerset",
- "simple-spanish-patience"
- ]:
-
- differs = []
-
- for attempt in range(runCount):
- try:
- op_p = Popen("./cmake-build-release/bin/solvitaire" + optimisation
- + " --type " + preset + " --random " + str(attempt)
- + " --classify",
- shell=True,
- stdout=PIPE,
- stderr=DEVNULL)
- out_str = op_p.stdout.readline()
- if out_str == b'Solved\n':
- op_res = True
- elif out_str == b'No Possible Solution\n':
- op_res = False
- else:
- raise Exception('Invalid return value!')
-
- no_op_p = Popen("./cmake-build-release/bin/solvitaire"
- + " --type " + preset + " --random " + str(attempt)
- + " --classify",
- shell=True,
- stdout=PIPE,
- stderr=DEVNULL)
- out_str = no_op_p.stdout.readline()
- if out_str == b'Solved\n':
- no_op_res = True
- elif out_str == b'No Possible Solution\n':
- no_op_res = False
- else:
- raise Exception('Invalid return value!')
-
- if op_res != no_op_res:
- differs.append(attempt)
-
- except CalledProcessError:
- print("Error running " + preset + " with seed " + str(attempt) + "!")
- sys.exit()
- except Exception as e:
- print("Unknown error in script: ", e)
- sys.exit()
-
- run("pkill solvitaire", shell=True)
-
- if not differs :
- print(preset + ": No difference in solutions for " + optimisation)
- else :
- print(preset + ": Optimisation " + optimisation + " differs for the following seeds:")
- print(differs)
diff --git a/solvitaire/archive/real-benchmark.sh b/solvitaire/archive/real-benchmark.sh
deleted file mode 100755
index 1e7f7b3..0000000
--- a/solvitaire/archive/real-benchmark.sh
+++ /dev/null
@@ -1,4 +0,0 @@
-time (for i in $(seq 1 $2);
-do
- ./cmake-build-release/bin/solvitaire --type "$1" --classify --random "$i"
-done)
diff --git a/solvitaire/archive/repeat_deal.sh b/solvitaire/archive/repeat_deal.sh
deleted file mode 100755
index f33440f..0000000
--- a/solvitaire/archive/repeat_deal.sh
+++ /dev/null
@@ -1,4 +0,0 @@
-time (for i in $(seq 1 $3);
-do
- ./cmake-build-release/bin/solvitaire --type "$1" --classify --random "$2" > /dev/null 2>&1
-done)
diff --git a/solvitaire/build.sh b/solvitaire/build.sh
deleted file mode 100755
index 58b846b..0000000
--- a/solvitaire/build.sh
+++ /dev/null
@@ -1,54 +0,0 @@
-#!/bin/bash
-
-build="release"
-target="solvitaire"
-error=false
-
-if [ "$#" == 1 ]; then
- if [ "$1" == "--debug" ]; then
- build="debug"
- elif [ "$1" == "--release" ]; then
- build="release"
- elif [ "$1" == "--unit-tests" ]; then
- target="unit_tests"
- elif [ "$1" == "--solvitaire" ]; then
- target="solvitaire"
- else
- error=true
- fi
-fi
-
-if [ "$#" == 2 ]; then
- if [ "$1" == "--debug" ]; then
- build="debug"
- elif [ "$1" == "--release" ]; then
- build="release"
- else
- error=true
- fi
-
- if [ "$2" == "--unit-tests" ]; then
- target="unit_tests"
- elif [ "$2" == "--solvitaire" ]; then
- target="solvitaire"
- else
- error=true
- fi
-fi
-
-if [ "$#" -gt 2 ]; then
- error=true
-fi
-
-if [ "$error" = true ]; then
- echo "Usage: ./build.sh [--release|--debug] [--solvitaire|--unit-tests]"
- echo "(default args = --release --solvitaire)"
- exit 1
-else
- cmake [-G "CodeBlocks - Unix Makefiles"] \
- "-DCMAKE_BUILD_TYPE=${build^^}" \
- "-Bcmake-build-$build" -H.
- cmake --build "cmake-build-$build" -- "$target"
- exit 0
-fi
-
diff --git a/solvitaire/docker-install.sh b/solvitaire/docker-install.sh
deleted file mode 100755
index 9438c5d..0000000
--- a/solvitaire/docker-install.sh
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/bin/bash
-
-docker login
-
-# Downloads the image
-docker pull thecharlesblake/solvitaire:1.0
-
-# If the cmake-build-[debug/release] folders don't exist, copies pre-generated
-# versions from the docker image into the current directory (so new users
-# don't have to wait for a long build to complete!)
-if [ ! -d "cmake-build-release" ] && [ ! -d "cmake-build-debug" ]; then
- docker run -i -v ${PWD}:/home/Solvitaire --rm \
- thecharlesblake/solvitaire:1.0 bash -c \
- "cp -r ../.install/cmake-build-* ."
-fi
diff --git a/solvitaire/enter-container.sh b/solvitaire/enter-container.sh
deleted file mode 100755
index ac0c78d..0000000
--- a/solvitaire/enter-container.sh
+++ /dev/null
@@ -1,9 +0,0 @@
-#!/bin/bash
-
-if [ "$#" == 0 ]; then
- docker run -it -v$(pwd):/home/Solvitaire --rm \
- thecharlesblake/solvitaire:1.0
-else
- docker run -it -v$(pwd):/home/Solvitaire --rm \
- thecharlesblake/solvitaire:1.0 bash -c "$*"
-fi
diff --git a/solvitaire/generate-results.sh b/solvitaire/generate-results.sh
deleted file mode 100755
index 33e92de..0000000
--- a/solvitaire/generate-results.sh
+++ /dev/null
@@ -1,88 +0,0 @@
-#!/bin/bash
-
-trap 'exit 130' INT
-
-if [ "$#" != 3 ]; then
- echo "Usage: \"\""
- echo "e.g.: ./generate-results.sh 1000 40 \"./cmake-build-release/bin/solvitaire --timeout 6000 --str smart-solvability\""
- exit 1
-fi
-
-seeds="$1"
-cores="$2"
-sol_command="$3"
-
-declare -a arr=(
-"alpha-star"
-"bakers-game"
-"black-hole"
-"castles-of-spain"
-"delta-star"
-"eight-off-any-card-spaces"
-"eight-off"
-"fan"
-"flower-garden"
-"fore-cell"
-"fortunes-favor"
-"king-albert"
-"northwest-territory"
-"one-cell"
-"raglan"
-"sea-towers"
-"somerset"
-"spanish-patience"
-"spiderette"
-"two-cell"
-"will-o-the-wisp"
-"free-cell-0-cell"
-"free-cell-1-cell"
-"free-cell-2-cell"
-"free-cell-3-cell"
-"free-cell-4-pile"
-"free-cell-5-pile"
-"free-cell-6-pile"
-"free-cell-7-pile"
-"free-cell"
-"blind-alleys"
-"chameleon"
-"duchess"
-"east-haven"
-"klondike"
-"klondike-deal-1"
-"martha"
-"canfield"
-"penguin"
-"alina"
-"bakers-dozen"
-"scotch-patience"
-"spider"
-)
-
-### Presets not attempted:
-
-## Rules incorrect
-
-#"martha"
-#"penguin"
-
-## Too difficult (?)
-
-
-## Stock games
-
-
-
-DATE=`date +%Y-%m-%d-%H-%M-%S`
-
-out_dir=results/$DATE
-
-mkdir -p "$out_dir"
-echo "Writing to $out_dir/"
-
-for i in "${arr[@]}"
-do
- echo "Running $i ..."
- ./solvability.sh "$seeds" "$cores" "$sol_command --type $i" "$out_dir"/$i.csv &>/dev/null
-done
-
-echo "Done!"
diff --git a/solvitaire/headers b/solvitaire/headers
deleted file mode 120000
index f315e29..0000000
--- a/solvitaire/headers
+++ /dev/null
@@ -1 +0,0 @@
-/cs/home/trh/metasol/solvitaire/src/main
\ No newline at end of file
diff --git a/solvitaire/lib/rapidjson/allocators.h b/solvitaire/lib/rapidjson/allocators.h
deleted file mode 100644
index 655f4a3..0000000
--- a/solvitaire/lib/rapidjson/allocators.h
+++ /dev/null
@@ -1,271 +0,0 @@
-// Tencent is pleased to support the open source community by making RapidJSON available.
-//
-// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
-//
-// Licensed under the MIT License (the "License"); you may not use this file except
-// in compliance with the License. You may obtain a copy of the License at
-//
-// http://opensource.org/licenses/MIT
-//
-// Unless required by applicable law or agreed to in writing, software distributed
-// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
-// CONDITIONS OF ANY KIND, either express or implied. See the License for the
-// specific language governing permissions and limitations under the License.
-
-#ifndef RAPIDJSON_ALLOCATORS_H_
-#define RAPIDJSON_ALLOCATORS_H_
-
-#include "rapidjson.h"
-
-RAPIDJSON_NAMESPACE_BEGIN
-
-///////////////////////////////////////////////////////////////////////////////
-// Allocator
-
-/*! \class rapidjson::Allocator
- \brief Concept for allocating, resizing and freeing memory block.
-
- Note that Malloc() and Realloc() are non-static but Free() is static.
-
- So if an allocator need to support Free(), it needs to put its pointer in
- the header of memory block.
-
-\code
-concept Allocator {
- static const bool kNeedFree; //!< Whether this allocator needs to call Free().
-
- // Allocate a memory block.
- // \param size of the memory block in bytes.
- // \returns pointer to the memory block.
- void* Malloc(size_t size);
-
- // Resize a memory block.
- // \param originalPtr The pointer to current memory block. Null pointer is permitted.
- // \param originalSize The current size in bytes. (Design issue: since some allocator may not book-keep this, explicitly pass to it can save memory.)
- // \param newSize the new size in bytes.
- void* Realloc(void* originalPtr, size_t originalSize, size_t newSize);
-
- // Free a memory block.
- // \param pointer to the memory block. Null pointer is permitted.
- static void Free(void *ptr);
-};
-\endcode
-*/
-
-///////////////////////////////////////////////////////////////////////////////
-// CrtAllocator
-
-//! C-runtime library allocator.
-/*! This class is just wrapper for standard C library memory routines.
- \note implements Allocator concept
-*/
-class CrtAllocator {
-public:
- static const bool kNeedFree = true;
- void* Malloc(size_t size) {
- if (size) // behavior of malloc(0) is implementation defined.
- return std::malloc(size);
- else
- return NULL; // standardize to returning NULL.
- }
- void* Realloc(void* originalPtr, size_t originalSize, size_t newSize) {
- (void)originalSize;
- if (newSize == 0) {
- std::free(originalPtr);
- return NULL;
- }
- return std::realloc(originalPtr, newSize);
- }
- static void Free(void *ptr) { std::free(ptr); }
-};
-
-///////////////////////////////////////////////////////////////////////////////
-// MemoryPoolAllocator
-
-//! Default memory allocator used by the parser and DOM.
-/*! This allocator allocate memory blocks from pre-allocated memory chunks.
-
- It does not free memory blocks. And Realloc() only allocate new memory.
-
- The memory chunks are allocated by BaseAllocator, which is CrtAllocator by default.
-
- User may also supply a buffer as the first chunk.
-
- If the user-buffer is full then additional chunks are allocated by BaseAllocator.
-
- The user-buffer is not deallocated by this allocator.
-
- \tparam BaseAllocator the allocator type for allocating memory chunks. Default is CrtAllocator.
- \note implements Allocator concept
-*/
-template
-class MemoryPoolAllocator {
-public:
- static const bool kNeedFree = false; //!< Tell users that no need to call Free() with this allocator. (concept Allocator)
-
- //! Constructor with chunkSize.
- /*! \param chunkSize The size of memory chunk. The default is kDefaultChunkSize.
- \param baseAllocator The allocator for allocating memory chunks.
- */
- MemoryPoolAllocator(size_t chunkSize = kDefaultChunkCapacity, BaseAllocator* baseAllocator = 0) :
- chunkHead_(0), chunk_capacity_(chunkSize), userBuffer_(0), baseAllocator_(baseAllocator), ownBaseAllocator_(0)
- {
- }
-
- //! Constructor with user-supplied buffer.
- /*! The user buffer will be used firstly. When it is full, memory pool allocates new chunk with chunk size.
-
- The user buffer will not be deallocated when this allocator is destructed.
-
- \param buffer User supplied buffer.
- \param size Size of the buffer in bytes. It must at least larger than sizeof(ChunkHeader).
- \param chunkSize The size of memory chunk. The default is kDefaultChunkSize.
- \param baseAllocator The allocator for allocating memory chunks.
- */
- MemoryPoolAllocator(void *buffer, size_t size, size_t chunkSize = kDefaultChunkCapacity, BaseAllocator* baseAllocator = 0) :
- chunkHead_(0), chunk_capacity_(chunkSize), userBuffer_(buffer), baseAllocator_(baseAllocator), ownBaseAllocator_(0)
- {
- RAPIDJSON_ASSERT(buffer != 0);
- RAPIDJSON_ASSERT(size > sizeof(ChunkHeader));
- chunkHead_ = reinterpret_cast(buffer);
- chunkHead_->capacity = size - sizeof(ChunkHeader);
- chunkHead_->size = 0;
- chunkHead_->next = 0;
- }
-
- //! Destructor.
- /*! This deallocates all memory chunks, excluding the user-supplied buffer.
- */
- ~MemoryPoolAllocator() {
- Clear();
- RAPIDJSON_DELETE(ownBaseAllocator_);
- }
-
- //! Deallocates all memory chunks, excluding the user-supplied buffer.
- void Clear() {
- while (chunkHead_ && chunkHead_ != userBuffer_) {
- ChunkHeader* next = chunkHead_->next;
- baseAllocator_->Free(chunkHead_);
- chunkHead_ = next;
- }
- if (chunkHead_ && chunkHead_ == userBuffer_)
- chunkHead_->size = 0; // Clear user buffer
- }
-
- //! Computes the total capacity of allocated memory chunks.
- /*! \return total capacity in bytes.
- */
- size_t Capacity() const {
- size_t capacity = 0;
- for (ChunkHeader* c = chunkHead_; c != 0; c = c->next)
- capacity += c->capacity;
- return capacity;
- }
-
- //! Computes the memory blocks allocated.
- /*! \return total used bytes.
- */
- size_t Size() const {
- size_t size = 0;
- for (ChunkHeader* c = chunkHead_; c != 0; c = c->next)
- size += c->size;
- return size;
- }
-
- //! Allocates a memory block. (concept Allocator)
- void* Malloc(size_t size) {
- if (!size)
- return NULL;
-
- size = RAPIDJSON_ALIGN(size);
- if (chunkHead_ == 0 || chunkHead_->size + size > chunkHead_->capacity)
- if (!AddChunk(chunk_capacity_ > size ? chunk_capacity_ : size))
- return NULL;
-
- void *buffer = reinterpret_cast(chunkHead_) + RAPIDJSON_ALIGN(sizeof(ChunkHeader)) + chunkHead_->size;
- chunkHead_->size += size;
- return buffer;
- }
-
- //! Resizes a memory block (concept Allocator)
- void* Realloc(void* originalPtr, size_t originalSize, size_t newSize) {
- if (originalPtr == 0)
- return Malloc(newSize);
-
- if (newSize == 0)
- return NULL;
-
- originalSize = RAPIDJSON_ALIGN(originalSize);
- newSize = RAPIDJSON_ALIGN(newSize);
-
- // Do not shrink if new size is smaller than original
- if (originalSize >= newSize)
- return originalPtr;
-
- // Simply expand it if it is the last allocation and there is sufficient space
- if (originalPtr == reinterpret_cast(chunkHead_) + RAPIDJSON_ALIGN(sizeof(ChunkHeader)) + chunkHead_->size - originalSize) {
- size_t increment = static_cast(newSize - originalSize);
- if (chunkHead_->size + increment <= chunkHead_->capacity) {
- chunkHead_->size += increment;
- return originalPtr;
- }
- }
-
- // Realloc process: allocate and copy memory, do not free original buffer.
- if (void* newBuffer = Malloc(newSize)) {
- if (originalSize)
- std::memcpy(newBuffer, originalPtr, originalSize);
- return newBuffer;
- }
- else
- return NULL;
- }
-
- //! Frees a memory block (concept Allocator)
- static void Free(void *ptr) { (void)ptr; } // Do nothing
-
-private:
- //! Copy constructor is not permitted.
- MemoryPoolAllocator(const MemoryPoolAllocator& rhs) /* = delete */;
- //! Copy assignment operator is not permitted.
- MemoryPoolAllocator& operator=(const MemoryPoolAllocator& rhs) /* = delete */;
-
- //! Creates a new chunk.
- /*! \param capacity Capacity of the chunk in bytes.
- \return true if success.
- */
- bool AddChunk(size_t capacity) {
- if (!baseAllocator_)
- ownBaseAllocator_ = baseAllocator_ = RAPIDJSON_NEW(BaseAllocator)();
- if (ChunkHeader* chunk = reinterpret_cast(baseAllocator_->Malloc(RAPIDJSON_ALIGN(sizeof(ChunkHeader)) + capacity))) {
- chunk->capacity = capacity;
- chunk->size = 0;
- chunk->next = chunkHead_;
- chunkHead_ = chunk;
- return true;
- }
- else
- return false;
- }
-
- static const int kDefaultChunkCapacity = 64 * 1024; //!< Default chunk capacity.
-
- //! Chunk header for perpending to each chunk.
- /*! Chunks are stored as a singly linked list.
- */
- struct ChunkHeader {
- size_t capacity; //!< Capacity of the chunk in bytes (excluding the header itself).
- size_t size; //!< Current size of allocated memory in bytes.
- ChunkHeader *next; //!< Next chunk in the linked list.
- };
-
- ChunkHeader *chunkHead_; //!< Head of the chunk linked-list. Only the head chunk serves allocation.
- size_t chunk_capacity_; //!< The minimum capacity of chunk when they are allocated.
- void *userBuffer_; //!< User supplied buffer.
- BaseAllocator* baseAllocator_; //!< base allocator for allocating memory chunks.
- BaseAllocator* ownBaseAllocator_; //!< base allocator created by this object.
-};
-
-RAPIDJSON_NAMESPACE_END
-
-#endif // RAPIDJSON_ENCODINGS_H_
diff --git a/solvitaire/lib/rapidjson/cursorstreamwrapper.h b/solvitaire/lib/rapidjson/cursorstreamwrapper.h
deleted file mode 100644
index 52c11a7..0000000
--- a/solvitaire/lib/rapidjson/cursorstreamwrapper.h
+++ /dev/null
@@ -1,78 +0,0 @@
-// Tencent is pleased to support the open source community by making RapidJSON available.
-//
-// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
-//
-// Licensed under the MIT License (the "License"); you may not use this file except
-// in compliance with the License. You may obtain a copy of the License at
-//
-// http://opensource.org/licenses/MIT
-//
-// Unless required by applicable law or agreed to in writing, software distributed
-// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
-// CONDITIONS OF ANY KIND, either express or implied. See the License for the
-// specific language governing permissions and limitations under the License.
-
-#ifndef RAPIDJSON_CURSORSTREAMWRAPPER_H_
-#define RAPIDJSON_CURSORSTREAMWRAPPER_H_
-
-#include "stream.h"
-
-#if defined(__GNUC__)
-RAPIDJSON_DIAG_PUSH
-RAPIDJSON_DIAG_OFF(effc++)
-#endif
-
-#if defined(_MSC_VER) && _MSC_VER <= 1800
-RAPIDJSON_DIAG_PUSH
-RAPIDJSON_DIAG_OFF(4702) // unreachable code
-RAPIDJSON_DIAG_OFF(4512) // assignment operator could not be generated
-#endif
-
-RAPIDJSON_NAMESPACE_BEGIN
-
-
-//! Cursor stream wrapper for counting line and column number if error exists.
-/*!
- \tparam InputStream Any stream that implements Stream Concept
-*/
-template >
-class CursorStreamWrapper : public GenericStreamWrapper {
-public:
- typedef typename Encoding::Ch Ch;
-
- CursorStreamWrapper(InputStream& is):
- GenericStreamWrapper(is), line_(1), col_(0) {}
-
- // counting line and column number
- Ch Take() {
- Ch ch = this->is_.Take();
- if(ch == '\n') {
- line_ ++;
- col_ = 0;
- } else {
- col_ ++;
- }
- return ch;
- }
-
- //! Get the error line number, if error exists.
- size_t GetLine() const { return line_; }
- //! Get the error column number, if error exists.
- size_t GetColumn() const { return col_; }
-
-private:
- size_t line_; //!< Current Line
- size_t col_; //!< Current Column
-};
-
-#if defined(_MSC_VER) && _MSC_VER <= 1800
-RAPIDJSON_DIAG_POP
-#endif
-
-#if defined(__GNUC__)
-RAPIDJSON_DIAG_POP
-#endif
-
-RAPIDJSON_NAMESPACE_END
-
-#endif // RAPIDJSON_CURSORSTREAMWRAPPER_H_
diff --git a/solvitaire/lib/rapidjson/document.h b/solvitaire/lib/rapidjson/document.h
deleted file mode 100644
index a6acc24..0000000
--- a/solvitaire/lib/rapidjson/document.h
+++ /dev/null
@@ -1,2660 +0,0 @@
-// Tencent is pleased to support the open source community by making RapidJSON available.
-//
-// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
-//
-// Licensed under the MIT License (the "License"); you may not use this file except
-// in compliance with the License. You may obtain a copy of the License at
-//
-// http://opensource.org/licenses/MIT
-//
-// Unless required by applicable law or agreed to in writing, software distributed
-// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
-// CONDITIONS OF ANY KIND, either express or implied. See the License for the
-// specific language governing permissions and limitations under the License.
-
-#ifndef RAPIDJSON_DOCUMENT_H_
-#define RAPIDJSON_DOCUMENT_H_
-
-/*! \file document.h */
-
-#include "reader.h"
-#include "internal/meta.h"
-#include "internal/strfunc.h"
-#include "memorystream.h"
-#include "encodedstream.h"
-#include // placement new
-#include
-
-RAPIDJSON_DIAG_PUSH
-#ifdef _MSC_VER
-RAPIDJSON_DIAG_OFF(4127) // conditional expression is constant
-RAPIDJSON_DIAG_OFF(4244) // conversion from kXxxFlags to 'uint16_t', possible loss of data
-#endif
-
-#ifdef __clang__
-RAPIDJSON_DIAG_OFF(padded)
-RAPIDJSON_DIAG_OFF(switch-enum)
-RAPIDJSON_DIAG_OFF(c++98-compat)
-#endif
-
-#ifdef __GNUC__
-RAPIDJSON_DIAG_OFF(effc++)
-#if __GNUC__ >= 6
-RAPIDJSON_DIAG_OFF(terminate) // ignore throwing RAPIDJSON_ASSERT in RAPIDJSON_NOEXCEPT functions
-#endif
-#endif // __GNUC__
-
-#ifndef RAPIDJSON_NOMEMBERITERATORCLASS
-#include // std::random_access_iterator_tag
-#endif
-
-#if RAPIDJSON_HAS_CXX11_RVALUE_REFS
-#include // std::move
-#endif
-
-RAPIDJSON_NAMESPACE_BEGIN
-
-// Forward declaration.
-template
-class GenericValue;
-
-template
-class GenericDocument;
-
-//! Name-value pair in a JSON object value.
-/*!
- This class was internal to GenericValue. It used to be a inner struct.
- But a compiler (IBM XL C/C++ for AIX) have reported to have problem with that so it moved as a namespace scope struct.
- https://code.google.com/p/rapidjson/issues/detail?id=64
-*/
-template
-struct GenericMember {
- GenericValue name; //!< name of member (must be a string)
- GenericValue value; //!< value of member.
-};
-
-///////////////////////////////////////////////////////////////////////////////
-// GenericMemberIterator
-
-#ifndef RAPIDJSON_NOMEMBERITERATORCLASS
-
-//! (Constant) member iterator for a JSON object value
-/*!
- \tparam Const Is this a constant iterator?
- \tparam Encoding Encoding of the value. (Even non-string values need to have the same encoding in a document)
- \tparam Allocator Allocator type for allocating memory of object, array and string.
-
- This class implements a Random Access Iterator for GenericMember elements
- of a GenericValue, see ISO/IEC 14882:2003(E) C++ standard, 24.1 [lib.iterator.requirements].
-
- \note This iterator implementation is mainly intended to avoid implicit
- conversions from iterator values to \c NULL,
- e.g. from GenericValue::FindMember.
-
- \note Define \c RAPIDJSON_NOMEMBERITERATORCLASS to fall back to a
- pointer-based implementation, if your platform doesn't provide
- the C++ header.
-
- \see GenericMember, GenericValue::MemberIterator, GenericValue::ConstMemberIterator
- */
-template
-class GenericMemberIterator {
-
- friend class GenericValue;
- template friend class GenericMemberIterator;
-
- typedef GenericMember PlainType;
- typedef typename internal::MaybeAddConst::Type ValueType;
-
-public:
- //! Iterator type itself
- typedef GenericMemberIterator Iterator;
- //! Constant iterator type
- typedef GenericMemberIterator ConstIterator;
- //! Non-constant iterator type
- typedef GenericMemberIterator NonConstIterator;
-
- /** \name std::iterator_traits support */
- //@{
- typedef ValueType value_type;
- typedef ValueType * pointer;
- typedef ValueType & reference;
- typedef std::ptrdiff_t difference_type;
- typedef std::random_access_iterator_tag iterator_category;
- //@}
-
- //! Pointer to (const) GenericMember
- typedef pointer Pointer;
- //! Reference to (const) GenericMember
- typedef reference Reference;
- //! Signed integer type (e.g. \c ptrdiff_t)
- typedef difference_type DifferenceType;
-
- //! Default constructor (singular value)
- /*! Creates an iterator pointing to no element.
- \note All operations, except for comparisons, are undefined on such values.
- */
- GenericMemberIterator() : ptr_() {}
-
- //! Iterator conversions to more const
- /*!
- \param it (Non-const) iterator to copy from
-
- Allows the creation of an iterator from another GenericMemberIterator
- that is "less const". Especially, creating a non-constant iterator
- from a constant iterator are disabled:
- \li const -> non-const (not ok)
- \li const -> const (ok)
- \li non-const -> const (ok)
- \li non-const -> non-const (ok)
-
- \note If the \c Const template parameter is already \c false, this
- constructor effectively defines a regular copy-constructor.
- Otherwise, the copy constructor is implicitly defined.
- */
- GenericMemberIterator(const NonConstIterator & it) : ptr_(it.ptr_) {}
- Iterator& operator=(const NonConstIterator & it) { ptr_ = it.ptr_; return *this; }
-
- //! @name stepping
- //@{
- Iterator& operator++(){ ++ptr_; return *this; }
- Iterator& operator--(){ --ptr_; return *this; }
- Iterator operator++(int){ Iterator old(*this); ++ptr_; return old; }
- Iterator operator--(int){ Iterator old(*this); --ptr_; return old; }
- //@}
-
- //! @name increment/decrement
- //@{
- Iterator operator+(DifferenceType n) const { return Iterator(ptr_+n); }
- Iterator operator-(DifferenceType n) const { return Iterator(ptr_-n); }
-
- Iterator& operator+=(DifferenceType n) { ptr_+=n; return *this; }
- Iterator& operator-=(DifferenceType n) { ptr_-=n; return *this; }
- //@}
-
- //! @name relations
- //@{
- bool operator==(ConstIterator that) const { return ptr_ == that.ptr_; }
- bool operator!=(ConstIterator that) const { return ptr_ != that.ptr_; }
- bool operator<=(ConstIterator that) const { return ptr_ <= that.ptr_; }
- bool operator>=(ConstIterator that) const { return ptr_ >= that.ptr_; }
- bool operator< (ConstIterator that) const { return ptr_ < that.ptr_; }
- bool operator> (ConstIterator that) const { return ptr_ > that.ptr_; }
- //@}
-
- //! @name dereference
- //@{
- Reference operator*() const { return *ptr_; }
- Pointer operator->() const { return ptr_; }
- Reference operator[](DifferenceType n) const { return ptr_[n]; }
- //@}
-
- //! Distance
- DifferenceType operator-(ConstIterator that) const { return ptr_-that.ptr_; }
-
-private:
- //! Internal constructor from plain pointer
- explicit GenericMemberIterator(Pointer p) : ptr_(p) {}
-
- Pointer ptr_; //!< raw pointer
-};
-
-#else // RAPIDJSON_NOMEMBERITERATORCLASS
-
-// class-based member iterator implementation disabled, use plain pointers
-
-template
-struct GenericMemberIterator;
-
-//! non-const GenericMemberIterator
-template
-struct GenericMemberIterator {
- //! use plain pointer as iterator type
- typedef GenericMember* Iterator;
-};
-//! const GenericMemberIterator
-template
-struct GenericMemberIterator {
- //! use plain const pointer as iterator type
- typedef const GenericMember* Iterator;
-};
-
-#endif // RAPIDJSON_NOMEMBERITERATORCLASS
-
-///////////////////////////////////////////////////////////////////////////////
-// GenericStringRef
-
-//! Reference to a constant string (not taking a copy)
-/*!
- \tparam CharType character type of the string
-
- This helper class is used to automatically infer constant string
- references for string literals, especially from \c const \b (!)
- character arrays.
-
- The main use is for creating JSON string values without copying the
- source string via an \ref Allocator. This requires that the referenced
- string pointers have a sufficient lifetime, which exceeds the lifetime
- of the associated GenericValue.
-
- \b Example
- \code
- Value v("foo"); // ok, no need to copy & calculate length
- const char foo[] = "foo";
- v.SetString(foo); // ok
-
- const char* bar = foo;
- // Value x(bar); // not ok, can't rely on bar's lifetime
- Value x(StringRef(bar)); // lifetime explicitly guaranteed by user
- Value y(StringRef(bar, 3)); // ok, explicitly pass length
- \endcode
-
- \see StringRef, GenericValue::SetString
-*/
-template
-struct GenericStringRef {
- typedef CharType Ch; //!< character type of the string
-
- //! Create string reference from \c const character array
-#ifndef __clang__ // -Wdocumentation
- /*!
- This constructor implicitly creates a constant string reference from
- a \c const character array. It has better performance than
- \ref StringRef(const CharType*) by inferring the string \ref length
- from the array length, and also supports strings containing null
- characters.
-
- \tparam N length of the string, automatically inferred
-
- \param str Constant character array, lifetime assumed to be longer
- than the use of the string in e.g. a GenericValue
-
- \post \ref s == str
-
- \note Constant complexity.
- \note There is a hidden, private overload to disallow references to
- non-const character arrays to be created via this constructor.
- By this, e.g. function-scope arrays used to be filled via
- \c snprintf are excluded from consideration.
- In such cases, the referenced string should be \b copied to the
- GenericValue instead.
- */
-#endif
- template
- GenericStringRef(const CharType (&str)[N]) RAPIDJSON_NOEXCEPT
- : s(str), length(N-1) {}
-
- //! Explicitly create string reference from \c const character pointer
-#ifndef __clang__ // -Wdocumentation
- /*!
- This constructor can be used to \b explicitly create a reference to
- a constant string pointer.
-
- \see StringRef(const CharType*)
-
- \param str Constant character pointer, lifetime assumed to be longer
- than the use of the string in e.g. a GenericValue
-
- \post \ref s == str
-
- \note There is a hidden, private overload to disallow references to
- non-const character arrays to be created via this constructor.
- By this, e.g. function-scope arrays used to be filled via
- \c snprintf are excluded from consideration.
- In such cases, the referenced string should be \b copied to the
- GenericValue instead.
- */
-#endif
- explicit GenericStringRef(const CharType* str)
- : s(str), length(NotNullStrLen(str)) {}
-
- //! Create constant string reference from pointer and length
-#ifndef __clang__ // -Wdocumentation
- /*! \param str constant string, lifetime assumed to be longer than the use of the string in e.g. a GenericValue
- \param len length of the string, excluding the trailing NULL terminator
-
- \post \ref s == str && \ref length == len
- \note Constant complexity.
- */
-#endif
- GenericStringRef(const CharType* str, SizeType len)
- : s(RAPIDJSON_LIKELY(str) ? str : emptyString), length(len) { RAPIDJSON_ASSERT(str != 0 || len == 0u); }
-
- GenericStringRef(const GenericStringRef& rhs) : s(rhs.s), length(rhs.length) {}
-
- //! implicit conversion to plain CharType pointer
- operator const Ch *() const { return s; }
-
- const Ch* const s; //!< plain CharType pointer
- const SizeType length; //!< length of the string (excluding the trailing NULL terminator)
-
-private:
- SizeType NotNullStrLen(const CharType* str) {
- RAPIDJSON_ASSERT(str != 0);
- return internal::StrLen(str);
- }
-
- /// Empty string - used when passing in a NULL pointer
- static const Ch emptyString[];
-
- //! Disallow construction from non-const array
- template
- GenericStringRef(CharType (&str)[N]) /* = delete */;
- //! Copy assignment operator not permitted - immutable type
- GenericStringRef& operator=(const GenericStringRef& rhs) /* = delete */;
-};
-
-template
-const CharType GenericStringRef::emptyString[] = { CharType() };
-
-//! Mark a character pointer as constant string
-/*! Mark a plain character pointer as a "string literal". This function
- can be used to avoid copying a character string to be referenced as a
- value in a JSON GenericValue object, if the string's lifetime is known
- to be valid long enough.
- \tparam CharType Character type of the string
- \param str Constant string, lifetime assumed to be longer than the use of the string in e.g. a GenericValue
- \return GenericStringRef string reference object
- \relatesalso GenericStringRef
-
- \see GenericValue::GenericValue(StringRefType), GenericValue::operator=(StringRefType), GenericValue::SetString(StringRefType), GenericValue::PushBack(StringRefType, Allocator&), GenericValue::AddMember
-*/
-template
-inline GenericStringRef StringRef(const CharType* str) {
- return GenericStringRef(str);
-}
-
-//! Mark a character pointer as constant string
-/*! Mark a plain character pointer as a "string literal". This function
- can be used to avoid copying a character string to be referenced as a
- value in a JSON GenericValue object, if the string's lifetime is known
- to be valid long enough.
-
- This version has better performance with supplied length, and also
- supports string containing null characters.
-
- \tparam CharType character type of the string
- \param str Constant string, lifetime assumed to be longer than the use of the string in e.g. a GenericValue
- \param length The length of source string.
- \return GenericStringRef string reference object
- \relatesalso GenericStringRef
-*/
-template
-inline GenericStringRef StringRef(const CharType* str, size_t length) {
- return GenericStringRef(str, SizeType(length));
-}
-
-#if RAPIDJSON_HAS_STDSTRING
-//! Mark a string object as constant string
-/*! Mark a string object (e.g. \c std::string) as a "string literal".
- This function can be used to avoid copying a string to be referenced as a
- value in a JSON GenericValue object, if the string's lifetime is known
- to be valid long enough.
-
- \tparam CharType character type of the string
- \param str Constant string, lifetime assumed to be longer than the use of the string in e.g. a GenericValue
- \return GenericStringRef string reference object
- \relatesalso GenericStringRef
- \note Requires the definition of the preprocessor symbol \ref RAPIDJSON_HAS_STDSTRING.
-*/
-template
-inline GenericStringRef StringRef(const std::basic_string& str) {
- return GenericStringRef(str.data(), SizeType(str.size()));
-}
-#endif
-
-///////////////////////////////////////////////////////////////////////////////
-// GenericValue type traits
-namespace internal {
-
-template
-struct IsGenericValueImpl : FalseType {};
-
-// select candidates according to nested encoding and allocator types
-template struct IsGenericValueImpl::Type, typename Void::Type>
- : IsBaseOf, T>::Type {};
-
-// helper to match arbitrary GenericValue instantiations, including derived classes
-template struct IsGenericValue : IsGenericValueImpl::Type {};
-
-} // namespace internal
-
-///////////////////////////////////////////////////////////////////////////////
-// TypeHelper
-
-namespace internal {
-
-template
-struct TypeHelper {};
-
-template
-struct TypeHelper {
- static bool Is(const ValueType& v) { return v.IsBool(); }
- static bool Get(const ValueType& v) { return v.GetBool(); }
- static ValueType& Set(ValueType& v, bool data) { return v.SetBool(data); }
- static ValueType& Set(ValueType& v, bool data, typename ValueType::AllocatorType&) { return v.SetBool(data); }
-};
-
-template
-struct TypeHelper {
- static bool Is(const ValueType& v) { return v.IsInt(); }
- static int Get(const ValueType& v) { return v.GetInt(); }
- static ValueType& Set(ValueType& v, int data) { return v.SetInt(data); }
- static ValueType& Set(ValueType& v, int data, typename ValueType::AllocatorType&) { return v.SetInt(data); }
-};
-
-template
-struct TypeHelper {
- static bool Is(const ValueType& v) { return v.IsUint(); }
- static unsigned Get(const ValueType& v) { return v.GetUint(); }
- static ValueType& Set(ValueType& v, unsigned data) { return v.SetUint(data); }
- static ValueType& Set(ValueType& v, unsigned data, typename ValueType::AllocatorType&) { return v.SetUint(data); }
-};
-
-#ifdef _MSC_VER
-RAPIDJSON_STATIC_ASSERT(sizeof(long) == sizeof(int));
-template
-struct TypeHelper {
- static bool Is(const ValueType& v) { return v.IsInt(); }
- static long Get(const ValueType& v) { return v.GetInt(); }
- static ValueType& Set(ValueType& v, long data) { return v.SetInt(data); }
- static ValueType& Set(ValueType& v, long data, typename ValueType::AllocatorType&) { return v.SetInt(data); }
-};
-
-RAPIDJSON_STATIC_ASSERT(sizeof(unsigned long) == sizeof(unsigned));
-template
-struct TypeHelper {
- static bool Is(const ValueType& v) { return v.IsUint(); }
- static unsigned long Get(const ValueType& v) { return v.GetUint(); }
- static ValueType& Set(ValueType& v, unsigned long data) { return v.SetUint(data); }
- static ValueType& Set(ValueType& v, unsigned long data, typename ValueType::AllocatorType&) { return v.SetUint(data); }
-};
-#endif
-
-template
-struct TypeHelper {
- static bool Is(const ValueType& v) { return v.IsInt64(); }
- static int64_t Get(const ValueType& v) { return v.GetInt64(); }
- static ValueType& Set(ValueType& v, int64_t data) { return v.SetInt64(data); }
- static ValueType& Set(ValueType& v, int64_t data, typename ValueType::AllocatorType&) { return v.SetInt64(data); }
-};
-
-template
-struct TypeHelper {
- static bool Is(const ValueType& v) { return v.IsUint64(); }
- static uint64_t Get(const ValueType& v) { return v.GetUint64(); }
- static ValueType& Set(ValueType& v, uint64_t data) { return v.SetUint64(data); }
- static ValueType& Set(ValueType& v, uint64_t data, typename ValueType::AllocatorType&) { return v.SetUint64(data); }
-};
-
-template
-struct TypeHelper {
- static bool Is(const ValueType& v) { return v.IsDouble(); }
- static double Get(const ValueType& v) { return v.GetDouble(); }
- static ValueType& Set(ValueType& v, double data) { return v.SetDouble(data); }
- static ValueType& Set(ValueType& v, double data, typename ValueType::AllocatorType&) { return v.SetDouble(data); }
-};
-
-template
-struct TypeHelper {
- static bool Is(const ValueType& v) { return v.IsFloat(); }
- static float Get(const ValueType& v) { return v.GetFloat(); }
- static ValueType& Set(ValueType& v, float data) { return v.SetFloat(data); }
- static ValueType& Set(ValueType& v, float data, typename ValueType::AllocatorType&) { return v.SetFloat(data); }
-};
-
-template
-struct TypeHelper {
- typedef const typename ValueType::Ch* StringType;
- static bool Is(const ValueType& v) { return v.IsString(); }
- static StringType Get(const ValueType& v) { return v.GetString(); }
- static ValueType& Set(ValueType& v, const StringType data) { return v.SetString(typename ValueType::StringRefType(data)); }
- static ValueType& Set(ValueType& v, const StringType data, typename ValueType::AllocatorType& a) { return v.SetString(data, a); }
-};
-
-#if RAPIDJSON_HAS_STDSTRING
-template
-struct TypeHelper > {
- typedef std::basic_string StringType;
- static bool Is(const ValueType& v) { return v.IsString(); }
- static StringType Get(const ValueType& v) { return StringType(v.GetString(), v.GetStringLength()); }
- static ValueType& Set(ValueType& v, const StringType& data, typename ValueType::AllocatorType& a) { return v.SetString(data, a); }
-};
-#endif
-
-template
-struct TypeHelper {
- typedef typename ValueType::Array ArrayType;
- static bool Is(const ValueType& v) { return v.IsArray(); }
- static ArrayType Get(ValueType& v) { return v.GetArray(); }
- static ValueType& Set(ValueType& v, ArrayType data) { return v = data; }
- static ValueType& Set(ValueType& v, ArrayType data, typename ValueType::AllocatorType&) { return v = data; }
-};
-
-template
-struct TypeHelper {
- typedef typename ValueType::ConstArray ArrayType;
- static bool Is(const ValueType& v) { return v.IsArray(); }
- static ArrayType Get(const ValueType& v) { return v.GetArray(); }
-};
-
-template
-struct TypeHelper {
- typedef typename ValueType::Object ObjectType;
- static bool Is(const ValueType& v) { return v.IsObject(); }
- static ObjectType Get(ValueType& v) { return v.GetObject(); }
- static ValueType& Set(ValueType& v, ObjectType data) { return v = data; }
- static ValueType& Set(ValueType& v, ObjectType data, typename ValueType::AllocatorType&) { return v = data; }
-};
-
-template
-struct TypeHelper {
- typedef typename ValueType::ConstObject ObjectType;
- static bool Is(const ValueType& v) { return v.IsObject(); }
- static ObjectType Get(const ValueType& v) { return v.GetObject(); }
-};
-
-} // namespace internal
-
-// Forward declarations
-template class GenericArray;
-template class GenericObject;
-
-///////////////////////////////////////////////////////////////////////////////
-// GenericValue
-
-//! Represents a JSON value. Use Value for UTF8 encoding and default allocator.
-/*!
- A JSON value can be one of 7 types. This class is a variant type supporting
- these types.
-
- Use the Value if UTF8 and default allocator
-
- \tparam Encoding Encoding of the value. (Even non-string values need to have the same encoding in a document)
- \tparam Allocator Allocator type for allocating memory of object, array and string.
-*/
-template >
-class GenericValue {
-public:
- //! Name-value pair in an object.
- typedef GenericMember Member;
- typedef Encoding EncodingType; //!< Encoding type from template parameter.
- typedef Allocator AllocatorType; //!< Allocator type from template parameter.
- typedef typename Encoding::Ch Ch; //!< Character type derived from Encoding.
- typedef GenericStringRef StringRefType; //!< Reference to a constant string
- typedef typename GenericMemberIterator::Iterator MemberIterator; //!< Member iterator for iterating in object.
- typedef typename GenericMemberIterator::Iterator ConstMemberIterator; //!< Constant member iterator for iterating in object.
- typedef GenericValue* ValueIterator; //!< Value iterator for iterating in array.
- typedef const GenericValue* ConstValueIterator; //!< Constant value iterator for iterating in array.
- typedef GenericValue ValueType; //!< Value type of itself.
- typedef GenericArray Array;
- typedef GenericArray ConstArray;
- typedef GenericObject Object;
- typedef GenericObject ConstObject;
-
- //!@name Constructors and destructor.
- //@{
-
- //! Default constructor creates a null value.
- GenericValue() RAPIDJSON_NOEXCEPT : data_() { data_.f.flags = kNullFlag; }
-
-#if RAPIDJSON_HAS_CXX11_RVALUE_REFS
- //! Move constructor in C++11
- GenericValue(GenericValue&& rhs) RAPIDJSON_NOEXCEPT : data_(rhs.data_) {
- rhs.data_.f.flags = kNullFlag; // give up contents
- }
-#endif
-
-private:
- //! Copy constructor is not permitted.
- GenericValue(const GenericValue& rhs);
-
-#if RAPIDJSON_HAS_CXX11_RVALUE_REFS
- //! Moving from a GenericDocument is not permitted.
- template
- GenericValue(GenericDocument&& rhs);
-
- //! Move assignment from a GenericDocument is not permitted.
- template
- GenericValue& operator=(GenericDocument&& rhs);
-#endif
-
-public:
-
- //! Constructor with JSON value type.
- /*! This creates a Value of specified type with default content.
- \param type Type of the value.
- \note Default content for number is zero.
- */
- explicit GenericValue(Type type) RAPIDJSON_NOEXCEPT : data_() {
- static const uint16_t defaultFlags[7] = {
- kNullFlag, kFalseFlag, kTrueFlag, kObjectFlag, kArrayFlag, kShortStringFlag,
- kNumberAnyFlag
- };
- RAPIDJSON_ASSERT(type >= kNullType && type <= kNumberType);
- data_.f.flags = defaultFlags[type];
-
- // Use ShortString to store empty string.
- if (type == kStringType)
- data_.ss.SetLength(0);
- }
-
- //! Explicit copy constructor (with allocator)
- /*! Creates a copy of a Value by using the given Allocator
- \tparam SourceAllocator allocator of \c rhs
- \param rhs Value to copy from (read-only)
- \param allocator Allocator for allocating copied elements and buffers. Commonly use GenericDocument::GetAllocator().
- \param copyConstStrings Force copying of constant strings (e.g. referencing an in-situ buffer)
- \see CopyFrom()
- */
- template
- GenericValue(const GenericValue& rhs, Allocator& allocator, bool copyConstStrings = false) {
- switch (rhs.GetType()) {
- case kObjectType: {
- SizeType count = rhs.data_.o.size;
- Member* lm = reinterpret_cast(allocator.Malloc(count * sizeof(Member)));
- const typename GenericValue::Member* rm = rhs.GetMembersPointer();
- for (SizeType i = 0; i < count; i++) {
- new (&lm[i].name) GenericValue(rm[i].name, allocator, copyConstStrings);
- new (&lm[i].value) GenericValue(rm[i].value, allocator, copyConstStrings);
- }
- data_.f.flags = kObjectFlag;
- data_.o.size = data_.o.capacity = count;
- SetMembersPointer(lm);
- }
- break;
- case kArrayType: {
- SizeType count = rhs.data_.a.size;
- GenericValue* le = reinterpret_cast(allocator.Malloc(count * sizeof(GenericValue)));
- const GenericValue* re = rhs.GetElementsPointer();
- for (SizeType i = 0; i < count; i++)
- new (&le[i]) GenericValue(re[i], allocator, copyConstStrings);
- data_.f.flags = kArrayFlag;
- data_.a.size = data_.a.capacity = count;
- SetElementsPointer(le);
- }
- break;
- case kStringType:
- if (rhs.data_.f.flags == kConstStringFlag && !copyConstStrings) {
- data_.f.flags = rhs.data_.f.flags;
- data_ = *reinterpret_cast(&rhs.data_);
- }
- else
- SetStringRaw(StringRef(rhs.GetString(), rhs.GetStringLength()), allocator);
- break;
- default:
- data_.f.flags = rhs.data_.f.flags;
- data_ = *reinterpret_cast(&rhs.data_);
- break;
- }
- }
-
- //! Constructor for boolean value.
- /*! \param b Boolean value
- \note This constructor is limited to \em real boolean values and rejects
- implicitly converted types like arbitrary pointers. Use an explicit cast
- to \c bool, if you want to construct a boolean JSON value in such cases.
- */
-#ifndef RAPIDJSON_DOXYGEN_RUNNING // hide SFINAE from Doxygen
- template
- explicit GenericValue(T b, RAPIDJSON_ENABLEIF((internal::IsSame))) RAPIDJSON_NOEXCEPT // See #472
-#else
- explicit GenericValue(bool b) RAPIDJSON_NOEXCEPT
-#endif
- : data_() {
- // safe-guard against failing SFINAE
- RAPIDJSON_STATIC_ASSERT((internal::IsSame::Value));
- data_.f.flags = b ? kTrueFlag : kFalseFlag;
- }
-
- //! Constructor for int value.
- explicit GenericValue(int i) RAPIDJSON_NOEXCEPT : data_() {
- data_.n.i64 = i;
- data_.f.flags = (i >= 0) ? (kNumberIntFlag | kUintFlag | kUint64Flag) : kNumberIntFlag;
- }
-
- //! Constructor for unsigned value.
- explicit GenericValue(unsigned u) RAPIDJSON_NOEXCEPT : data_() {
- data_.n.u64 = u;
- data_.f.flags = (u & 0x80000000) ? kNumberUintFlag : (kNumberUintFlag | kIntFlag | kInt64Flag);
- }
-
- //! Constructor for int64_t value.
- explicit GenericValue(int64_t i64) RAPIDJSON_NOEXCEPT : data_() {
- data_.n.i64 = i64;
- data_.f.flags = kNumberInt64Flag;
- if (i64 >= 0) {
- data_.f.flags |= kNumberUint64Flag;
- if (!(static_cast(i64) & RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0x00000000)))
- data_.f.flags |= kUintFlag;
- if (!(static_cast(i64) & RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0x80000000)))
- data_.f.flags |= kIntFlag;
- }
- else if (i64 >= static_cast(RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0x80000000)))
- data_.f.flags |= kIntFlag;
- }
-
- //! Constructor for uint64_t value.
- explicit GenericValue(uint64_t u64) RAPIDJSON_NOEXCEPT : data_() {
- data_.n.u64 = u64;
- data_.f.flags = kNumberUint64Flag;
- if (!(u64 & RAPIDJSON_UINT64_C2(0x80000000, 0x00000000)))
- data_.f.flags |= kInt64Flag;
- if (!(u64 & RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0x00000000)))
- data_.f.flags |= kUintFlag;
- if (!(u64 & RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0x80000000)))
- data_.f.flags |= kIntFlag;
- }
-
- //! Constructor for double value.
- explicit GenericValue(double d) RAPIDJSON_NOEXCEPT : data_() { data_.n.d = d; data_.f.flags = kNumberDoubleFlag; }
-
- //! Constructor for float value.
- explicit GenericValue(float f) RAPIDJSON_NOEXCEPT : data_() { data_.n.d = static_cast(f); data_.f.flags = kNumberDoubleFlag; }
-
- //! Constructor for constant string (i.e. do not make a copy of string)
- GenericValue(const Ch* s, SizeType length) RAPIDJSON_NOEXCEPT : data_() { SetStringRaw(StringRef(s, length)); }
-
- //! Constructor for constant string (i.e. do not make a copy of string)
- explicit GenericValue(StringRefType s) RAPIDJSON_NOEXCEPT : data_() { SetStringRaw(s); }
-
- //! Constructor for copy-string (i.e. do make a copy of string)
- GenericValue(const Ch* s, SizeType length, Allocator& allocator) : data_() { SetStringRaw(StringRef(s, length), allocator); }
-
- //! Constructor for copy-string (i.e. do make a copy of string)
- GenericValue(const Ch*s, Allocator& allocator) : data_() { SetStringRaw(StringRef(s), allocator); }
-
-#if RAPIDJSON_HAS_STDSTRING
- //! Constructor for copy-string from a string object (i.e. do make a copy of string)
- /*! \note Requires the definition of the preprocessor symbol \ref RAPIDJSON_HAS_STDSTRING.
- */
- GenericValue(const std::basic_string& s, Allocator& allocator) : data_() { SetStringRaw(StringRef(s), allocator); }
-#endif
-
- //! Constructor for Array.
- /*!
- \param a An array obtained by \c GetArray().
- \note \c Array is always pass-by-value.
- \note the source array is moved into this value and the sourec array becomes empty.
- */
- GenericValue(Array a) RAPIDJSON_NOEXCEPT : data_(a.value_.data_) {
- a.value_.data_ = Data();
- a.value_.data_.f.flags = kArrayFlag;
- }
-
- //! Constructor for Object.
- /*!
- \param o An object obtained by \c GetObject().
- \note \c Object is always pass-by-value.
- \note the source object is moved into this value and the sourec object becomes empty.
- */
- GenericValue(Object o) RAPIDJSON_NOEXCEPT : data_(o.value_.data_) {
- o.value_.data_ = Data();
- o.value_.data_.f.flags = kObjectFlag;
- }
-
- //! Destructor.
- /*! Need to destruct elements of array, members of object, or copy-string.
- */
- ~GenericValue() {
- if (Allocator::kNeedFree) { // Shortcut by Allocator's trait
- switch(data_.f.flags) {
- case kArrayFlag:
- {
- GenericValue* e = GetElementsPointer();
- for (GenericValue* v = e; v != e + data_.a.size; ++v)
- v->~GenericValue();
- Allocator::Free(e);
- }
- break;
-
- case kObjectFlag:
- for (MemberIterator m = MemberBegin(); m != MemberEnd(); ++m)
- m->~Member();
- Allocator::Free(GetMembersPointer());
- break;
-
- case kCopyStringFlag:
- Allocator::Free(const_cast(GetStringPointer()));
- break;
-
- default:
- break; // Do nothing for other types.
- }
- }
- }
-
- //@}
-
- //!@name Assignment operators
- //@{
-
- //! Assignment with move semantics.
- /*! \param rhs Source of the assignment. It will become a null value after assignment.
- */
- GenericValue& operator=(GenericValue& rhs) RAPIDJSON_NOEXCEPT {
- RAPIDJSON_ASSERT(this != &rhs);
- this->~GenericValue();
- RawAssign(rhs);
- return *this;
- }
-
-#if RAPIDJSON_HAS_CXX11_RVALUE_REFS
- //! Move assignment in C++11
- GenericValue& operator=(GenericValue&& rhs) RAPIDJSON_NOEXCEPT {
- return *this = rhs.Move();
- }
-#endif
-
- //! Assignment of constant string reference (no copy)
- /*! \param str Constant string reference to be assigned
- \note This overload is needed to avoid clashes with the generic primitive type assignment overload below.
- \see GenericStringRef, operator=(T)
- */
- GenericValue& operator=(StringRefType str) RAPIDJSON_NOEXCEPT {
- GenericValue s(str);
- return *this = s;
- }
-
- //! Assignment with primitive types.
- /*! \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t
- \param value The value to be assigned.
-
- \note The source type \c T explicitly disallows all pointer types,
- especially (\c const) \ref Ch*. This helps avoiding implicitly
- referencing character strings with insufficient lifetime, use
- \ref SetString(const Ch*, Allocator&) (for copying) or
- \ref StringRef() (to explicitly mark the pointer as constant) instead.
- All other pointer types would implicitly convert to \c bool,
- use \ref SetBool() instead.
- */
- template
- RAPIDJSON_DISABLEIF_RETURN((internal::IsPointer), (GenericValue&))
- operator=(T value) {
- GenericValue v(value);
- return *this = v;
- }
-
- //! Deep-copy assignment from Value
- /*! Assigns a \b copy of the Value to the current Value object
- \tparam SourceAllocator Allocator type of \c rhs
- \param rhs Value to copy from (read-only)
- \param allocator Allocator to use for copying
- \param copyConstStrings Force copying of constant strings (e.g. referencing an in-situ buffer)
- */
- template
- GenericValue& CopyFrom(const GenericValue& rhs, Allocator& allocator, bool copyConstStrings = false) {
- RAPIDJSON_ASSERT(static_cast(this) != static_cast(&rhs));
- this->~GenericValue();
- new (this) GenericValue(rhs, allocator, copyConstStrings);
- return *this;
- }
-
- //! Exchange the contents of this value with those of other.
- /*!
- \param other Another value.
- \note Constant complexity.
- */
- GenericValue& Swap(GenericValue& other) RAPIDJSON_NOEXCEPT {
- GenericValue temp;
- temp.RawAssign(*this);
- RawAssign(other);
- other.RawAssign(temp);
- return *this;
- }
-
- //! free-standing swap function helper
- /*!
- Helper function to enable support for common swap implementation pattern based on \c std::swap:
- \code
- void swap(MyClass& a, MyClass& b) {
- using std::swap;
- swap(a.value, b.value);
- // ...
- }
- \endcode
- \see Swap()
- */
- friend inline void swap(GenericValue& a, GenericValue& b) RAPIDJSON_NOEXCEPT { a.Swap(b); }
-
- //! Prepare Value for move semantics
- /*! \return *this */
- GenericValue& Move() RAPIDJSON_NOEXCEPT { return *this; }
- //@}
-
- //!@name Equal-to and not-equal-to operators
- //@{
- //! Equal-to operator
- /*!
- \note If an object contains duplicated named member, comparing equality with any object is always \c false.
- \note Linear time complexity (number of all values in the subtree and total lengths of all strings).
- */
- template
- bool operator==(const GenericValue& rhs) const {
- typedef GenericValue RhsType;
- if (GetType() != rhs.GetType())
- return false;
-
- switch (GetType()) {
- case kObjectType: // Warning: O(n^2) inner-loop
- if (data_.o.size != rhs.data_.o.size)
- return false;
- for (ConstMemberIterator lhsMemberItr = MemberBegin(); lhsMemberItr != MemberEnd(); ++lhsMemberItr) {
- typename RhsType::ConstMemberIterator rhsMemberItr = rhs.FindMember(lhsMemberItr->name);
- if (rhsMemberItr == rhs.MemberEnd() || lhsMemberItr->value != rhsMemberItr->value)
- return false;
- }
- return true;
-
- case kArrayType:
- if (data_.a.size != rhs.data_.a.size)
- return false;
- for (SizeType i = 0; i < data_.a.size; i++)
- if ((*this)[i] != rhs[i])
- return false;
- return true;
-
- case kStringType:
- return StringEqual(rhs);
-
- case kNumberType:
- if (IsDouble() || rhs.IsDouble()) {
- double a = GetDouble(); // May convert from integer to double.
- double b = rhs.GetDouble(); // Ditto
- return a >= b && a <= b; // Prevent -Wfloat-equal
- }
- else
- return data_.n.u64 == rhs.data_.n.u64;
-
- default:
- return true;
- }
- }
-
- //! Equal-to operator with const C-string pointer
- bool operator==(const Ch* rhs) const { return *this == GenericValue(StringRef(rhs)); }
-
-#if RAPIDJSON_HAS_STDSTRING
- //! Equal-to operator with string object
- /*! \note Requires the definition of the preprocessor symbol \ref RAPIDJSON_HAS_STDSTRING.
- */
- bool operator==(const std::basic_string& rhs) const { return *this == GenericValue(StringRef(rhs)); }
-#endif
-
- //! Equal-to operator with primitive types
- /*! \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t, \c double, \c true, \c false
- */
- template RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr,internal::IsGenericValue >), (bool)) operator==(const T& rhs) const { return *this == GenericValue(rhs); }
-
- //! Not-equal-to operator
- /*! \return !(*this == rhs)
- */
- template
- bool operator!=(const GenericValue& rhs) const { return !(*this == rhs); }
-
- //! Not-equal-to operator with const C-string pointer
- bool operator!=(const Ch* rhs) const { return !(*this == rhs); }
-
- //! Not-equal-to operator with arbitrary types
- /*! \return !(*this == rhs)
- */
- template RAPIDJSON_DISABLEIF_RETURN((internal::IsGenericValue), (bool)) operator!=(const T& rhs) const { return !(*this == rhs); }
-
- //! Equal-to operator with arbitrary types (symmetric version)
- /*! \return (rhs == lhs)
- */
- template friend RAPIDJSON_DISABLEIF_RETURN((internal::IsGenericValue), (bool)) operator==(const T& lhs, const GenericValue& rhs) { return rhs == lhs; }
-
- //! Not-Equal-to operator with arbitrary types (symmetric version)
- /*! \return !(rhs == lhs)
- */
- template friend RAPIDJSON_DISABLEIF_RETURN((internal::IsGenericValue), (bool)) operator!=(const T& lhs, const GenericValue& rhs) { return !(rhs == lhs); }
- //@}
-
- //!@name Type
- //@{
-
- Type GetType() const { return static_cast(data_.f.flags & kTypeMask); }
- bool IsNull() const { return data_.f.flags == kNullFlag; }
- bool IsFalse() const { return data_.f.flags == kFalseFlag; }
- bool IsTrue() const { return data_.f.flags == kTrueFlag; }
- bool IsBool() const { return (data_.f.flags & kBoolFlag) != 0; }
- bool IsObject() const { return data_.f.flags == kObjectFlag; }
- bool IsArray() const { return data_.f.flags == kArrayFlag; }
- bool IsNumber() const { return (data_.f.flags & kNumberFlag) != 0; }
- bool IsInt() const { return (data_.f.flags & kIntFlag) != 0; }
- bool IsUint() const { return (data_.f.flags & kUintFlag) != 0; }
- bool IsInt64() const { return (data_.f.flags & kInt64Flag) != 0; }
- bool IsUint64() const { return (data_.f.flags & kUint64Flag) != 0; }
- bool IsDouble() const { return (data_.f.flags & kDoubleFlag) != 0; }
- bool IsString() const { return (data_.f.flags & kStringFlag) != 0; }
-
- // Checks whether a number can be losslessly converted to a double.
- bool IsLosslessDouble() const {
- if (!IsNumber()) return false;
- if (IsUint64()) {
- uint64_t u = GetUint64();
- volatile double d = static_cast(u);
- return (d >= 0.0)
- && (d < static_cast((std::numeric_limits::max)()))
- && (u == static_cast(d));
- }
- if (IsInt64()) {
- int64_t i = GetInt64();
- volatile double d = static_cast(i);
- return (d >= static_cast((std::numeric_limits::min)()))
- && (d < static_cast((std::numeric_limits::max)()))
- && (i == static_cast(d));
- }
- return true; // double, int, uint are always lossless
- }
-
- // Checks whether a number is a float (possible lossy).
- bool IsFloat() const {
- if ((data_.f.flags & kDoubleFlag) == 0)
- return false;
- double d = GetDouble();
- return d >= -3.4028234e38 && d <= 3.4028234e38;
- }
- // Checks whether a number can be losslessly converted to a float.
- bool IsLosslessFloat() const {
- if (!IsNumber()) return false;
- double a = GetDouble();
- if (a < static_cast(-(std::numeric_limits::max)())
- || a > static_cast((std::numeric_limits::max)()))
- return false;
- double b = static_cast(static_cast(a));
- return a >= b && a <= b; // Prevent -Wfloat-equal
- }
-
- //@}
-
- //!@name Null
- //@{
-
- GenericValue& SetNull() { this->~GenericValue(); new (this) GenericValue(); return *this; }
-
- //@}
-
- //!@name Bool
- //@{
-
- bool GetBool() const { RAPIDJSON_ASSERT(IsBool()); return data_.f.flags == kTrueFlag; }
- //!< Set boolean value
- /*! \post IsBool() == true */
- GenericValue& SetBool(bool b) { this->~GenericValue(); new (this) GenericValue(b); return *this; }
-
- //@}
-
- //!@name Object
- //@{
-
- //! Set this value as an empty object.
- /*! \post IsObject() == true */
- GenericValue& SetObject() { this->~GenericValue(); new (this) GenericValue(kObjectType); return *this; }
-
- //! Get the number of members in the object.
- SizeType MemberCount() const { RAPIDJSON_ASSERT(IsObject()); return data_.o.size; }
-
- //! Get the capacity of object.
- SizeType MemberCapacity() const { RAPIDJSON_ASSERT(IsObject()); return data_.o.capacity; }
-
- //! Check whether the object is empty.
- bool ObjectEmpty() const { RAPIDJSON_ASSERT(IsObject()); return data_.o.size == 0; }
-
- //! Get a value from an object associated with the name.
- /*! \pre IsObject() == true
- \tparam T Either \c Ch or \c const \c Ch (template used for disambiguation with \ref operator[](SizeType))
- \note In version 0.1x, if the member is not found, this function returns a null value. This makes issue 7.
- Since 0.2, if the name is not correct, it will assert.
- If user is unsure whether a member exists, user should use HasMember() first.
- A better approach is to use FindMember().
- \note Linear time complexity.
- */
- template
- RAPIDJSON_DISABLEIF_RETURN((internal::NotExpr::Type, Ch> >),(GenericValue&)) operator[](T* name) {
- GenericValue n(StringRef(name));
- return (*this)[n];
- }
- template
- RAPIDJSON_DISABLEIF_RETURN((internal::NotExpr::Type, Ch> >),(const GenericValue&)) operator[](T* name) const { return const_cast(*this)[name]; }
-
- //! Get a value from an object associated with the name.
- /*! \pre IsObject() == true
- \tparam SourceAllocator Allocator of the \c name value
-
- \note Compared to \ref operator[](T*), this version is faster because it does not need a StrLen().
- And it can also handle strings with embedded null characters.
-
- \note Linear time complexity.
- */
- template
- GenericValue& operator[](const GenericValue& name) {
- MemberIterator member = FindMember(name);
- if (member != MemberEnd())
- return member->value;
- else {
- RAPIDJSON_ASSERT(false); // see above note
-
- // This will generate -Wexit-time-destructors in clang
- // static GenericValue NullValue;
- // return NullValue;
-
- // Use static buffer and placement-new to prevent destruction
- static char buffer[sizeof(GenericValue)];
- return *new (buffer) GenericValue();
- }
- }
- template
- const GenericValue& operator[](const GenericValue& name) const { return const_cast(*this)[name]; }
-
-#if RAPIDJSON_HAS_STDSTRING
- //! Get a value from an object associated with name (string object).
- GenericValue& operator[](const std::basic_string& name) { return (*this)[GenericValue(StringRef(name))]; }
- const GenericValue& operator[](const std::basic_string& name) const { return (*this)[GenericValue(StringRef(name))]; }
-#endif
-
- //! Const member iterator
- /*! \pre IsObject() == true */
- ConstMemberIterator MemberBegin() const { RAPIDJSON_ASSERT(IsObject()); return ConstMemberIterator(GetMembersPointer()); }
- //! Const \em past-the-end member iterator
- /*! \pre IsObject() == true */
- ConstMemberIterator MemberEnd() const { RAPIDJSON_ASSERT(IsObject()); return ConstMemberIterator(GetMembersPointer() + data_.o.size); }
- //! Member iterator
- /*! \pre IsObject() == true */
- MemberIterator MemberBegin() { RAPIDJSON_ASSERT(IsObject()); return MemberIterator(GetMembersPointer()); }
- //! \em Past-the-end member iterator
- /*! \pre IsObject() == true */
- MemberIterator MemberEnd() { RAPIDJSON_ASSERT(IsObject()); return MemberIterator(GetMembersPointer() + data_.o.size); }
-
- //! Request the object to have enough capacity to store members.
- /*! \param newCapacity The capacity that the object at least need to have.
- \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator().
- \return The value itself for fluent API.
- \note Linear time complexity.
- */
- GenericValue& MemberReserve(SizeType newCapacity, Allocator &allocator) {
- RAPIDJSON_ASSERT(IsObject());
- if (newCapacity > data_.o.capacity) {
- SetMembersPointer(reinterpret_cast(allocator.Realloc(GetMembersPointer(), data_.o.capacity * sizeof(Member), newCapacity * sizeof(Member))));
- data_.o.capacity = newCapacity;
- }
- return *this;
- }
-
- //! Check whether a member exists in the object.
- /*!
- \param name Member name to be searched.
- \pre IsObject() == true
- \return Whether a member with that name exists.
- \note It is better to use FindMember() directly if you need the obtain the value as well.
- \note Linear time complexity.
- */
- bool HasMember(const Ch* name) const { return FindMember(name) != MemberEnd(); }
-
-#if RAPIDJSON_HAS_STDSTRING
- //! Check whether a member exists in the object with string object.
- /*!
- \param name Member name to be searched.
- \pre IsObject() == true
- \return Whether a member with that name exists.
- \note It is better to use FindMember() directly if you need the obtain the value as well.
- \note Linear time complexity.
- */
- bool HasMember(const std::basic_string& name) const { return FindMember(name) != MemberEnd(); }
-#endif
-
- //! Check whether a member exists in the object with GenericValue name.
- /*!
- This version is faster because it does not need a StrLen(). It can also handle string with null character.
- \param name Member name to be searched.
- \pre IsObject() == true
- \return Whether a member with that name exists.
- \note It is better to use FindMember() directly if you need the obtain the value as well.
- \note Linear time complexity.
- */
- template
- bool HasMember(const GenericValue& name) const { return FindMember(name) != MemberEnd(); }
-
- //! Find member by name.
- /*!
- \param name Member name to be searched.
- \pre IsObject() == true
- \return Iterator to member, if it exists.
- Otherwise returns \ref MemberEnd().
-
- \note Earlier versions of Rapidjson returned a \c NULL pointer, in case
- the requested member doesn't exist. For consistency with e.g.
- \c std::map, this has been changed to MemberEnd() now.
- \note Linear time complexity.
- */
- MemberIterator FindMember(const Ch* name) {
- GenericValue n(StringRef(name));
- return FindMember(n);
- }
-
- ConstMemberIterator FindMember(const Ch* name) const { return const_cast(*this).FindMember(name); }
-
- //! Find member by name.
- /*!
- This version is faster because it does not need a StrLen(). It can also handle string with null character.
- \param name Member name to be searched.
- \pre IsObject() == true
- \return Iterator to member, if it exists.
- Otherwise returns \ref MemberEnd().
-
- \note Earlier versions of Rapidjson returned a \c NULL pointer, in case
- the requested member doesn't exist. For consistency with e.g.
- \c std::map, this has been changed to MemberEnd() now.
- \note Linear time complexity.
- */
- template
- MemberIterator FindMember(const GenericValue& name) {
- RAPIDJSON_ASSERT(IsObject());
- RAPIDJSON_ASSERT(name.IsString());
- MemberIterator member = MemberBegin();
- for ( ; member != MemberEnd(); ++member)
- if (name.StringEqual(member->name))
- break;
- return member;
- }
- template ConstMemberIterator FindMember(const GenericValue& name) const { return const_cast(*this).FindMember(name); }
-
-#if RAPIDJSON_HAS_STDSTRING
- //! Find member by string object name.
- /*!
- \param name Member name to be searched.
- \pre IsObject() == true
- \return Iterator to member, if it exists.
- Otherwise returns \ref MemberEnd().
- */
- MemberIterator FindMember(const std::basic_string& name) { return FindMember(GenericValue(StringRef(name))); }
- ConstMemberIterator FindMember(const std::basic_string& name) const { return FindMember(GenericValue(StringRef(name))); }
-#endif
-
- //! Add a member (name-value pair) to the object.
- /*! \param name A string value as name of member.
- \param value Value of any type.
- \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator().
- \return The value itself for fluent API.
- \note The ownership of \c name and \c value will be transferred to this object on success.
- \pre IsObject() && name.IsString()
- \post name.IsNull() && value.IsNull()
- \note Amortized Constant time complexity.
- */
- GenericValue& AddMember(GenericValue& name, GenericValue& value, Allocator& allocator) {
- RAPIDJSON_ASSERT(IsObject());
- RAPIDJSON_ASSERT(name.IsString());
-
- ObjectData& o = data_.o;
- if (o.size >= o.capacity)
- MemberReserve(o.capacity == 0 ? kDefaultObjectCapacity : (o.capacity + (o.capacity + 1) / 2), allocator);
- Member* members = GetMembersPointer();
- members[o.size].name.RawAssign(name);
- members[o.size].value.RawAssign(value);
- o.size++;
- return *this;
- }
-
- //! Add a constant string value as member (name-value pair) to the object.
- /*! \param name A string value as name of member.
- \param value constant string reference as value of member.
- \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator().
- \return The value itself for fluent API.
- \pre IsObject()
- \note This overload is needed to avoid clashes with the generic primitive type AddMember(GenericValue&,T,Allocator&) overload below.
- \note Amortized Constant time complexity.
- */
- GenericValue& AddMember(GenericValue& name, StringRefType value, Allocator& allocator) {
- GenericValue v(value);
- return AddMember(name, v, allocator);
- }
-
-#if RAPIDJSON_HAS_STDSTRING
- //! Add a string object as member (name-value pair) to the object.
- /*! \param name A string value as name of member.
- \param value constant string reference as value of member.
- \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator().
- \return The value itself for fluent API.
- \pre IsObject()
- \note This overload is needed to avoid clashes with the generic primitive type AddMember(GenericValue&,T,Allocator&) overload below.
- \note Amortized Constant time complexity.
- */
- GenericValue& AddMember(GenericValue& name, std::basic_string& value, Allocator& allocator) {
- GenericValue v(value, allocator);
- return AddMember(name, v, allocator);
- }
-#endif
-
- //! Add any primitive value as member (name-value pair) to the object.
- /*! \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t
- \param name A string value as name of member.
- \param value Value of primitive type \c T as value of member
- \param allocator Allocator for reallocating memory. Commonly use GenericDocument::GetAllocator().
- \return The value itself for fluent API.
- \pre IsObject()
-
- \note The source type \c T explicitly disallows all pointer types,
- especially (\c const) \ref Ch*. This helps avoiding implicitly
- referencing character strings with insufficient lifetime, use
- \ref AddMember(StringRefType, GenericValue&, Allocator&) or \ref
- AddMember(StringRefType, StringRefType, Allocator&).
- All other pointer types would implicitly convert to \c bool,
- use an explicit cast instead, if needed.
- \note Amortized Constant time complexity.
- */
- template
- RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr, internal::IsGenericValue >), (GenericValue&))
- AddMember(GenericValue& name, T value, Allocator& allocator) {
- GenericValue v(value);
- return AddMember(name, v, allocator);
- }
-
-#if RAPIDJSON_HAS_CXX11_RVALUE_REFS
- GenericValue& AddMember(GenericValue&& name, GenericValue&& value, Allocator& allocator) {
- return AddMember(name, value, allocator);
- }
- GenericValue& AddMember(GenericValue&& name, GenericValue& value, Allocator& allocator) {
- return AddMember(name, value, allocator);
- }
- GenericValue& AddMember(GenericValue& name, GenericValue&& value, Allocator& allocator) {
- return AddMember(name, value, allocator);
- }
- GenericValue& AddMember(StringRefType name, GenericValue&& value, Allocator& allocator) {
- GenericValue n(name);
- return AddMember(n, value, allocator);
- }
-#endif // RAPIDJSON_HAS_CXX11_RVALUE_REFS
-
-
- //! Add a member (name-value pair) to the object.
- /*! \param name A constant string reference as name of member.
- \param value Value of any type.
- \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator().
- \return The value itself for fluent API.
- \note The ownership of \c value will be transferred to this object on success.
- \pre IsObject()
- \post value.IsNull()
- \note Amortized Constant time complexity.
- */
- GenericValue& AddMember(StringRefType name, GenericValue& value, Allocator& allocator) {
- GenericValue n(name);
- return AddMember(n, value, allocator);
- }
-
- //! Add a constant string value as member (name-value pair) to the object.
- /*! \param name A constant string reference as name of member.
- \param value constant string reference as value of member.
- \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator().
- \return The value itself for fluent API.
- \pre IsObject()
- \note This overload is needed to avoid clashes with the generic primitive type AddMember(StringRefType,T,Allocator&) overload below.
- \note Amortized Constant time complexity.
- */
- GenericValue& AddMember(StringRefType name, StringRefType value, Allocator& allocator) {
- GenericValue v(value);
- return AddMember(name, v, allocator);
- }
-
- //! Add any primitive value as member (name-value pair) to the object.
- /*! \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t
- \param name A constant string reference as name of member.
- \param value Value of primitive type \c T as value of member
- \param allocator Allocator for reallocating memory. Commonly use GenericDocument::GetAllocator().
- \return The value itself for fluent API.
- \pre IsObject()
-
- \note The source type \c T explicitly disallows all pointer types,
- especially (\c const) \ref Ch*. This helps avoiding implicitly
- referencing character strings with insufficient lifetime, use
- \ref AddMember(StringRefType, GenericValue&, Allocator&) or \ref
- AddMember(StringRefType, StringRefType, Allocator&).
- All other pointer types would implicitly convert to \c bool,
- use an explicit cast instead, if needed.
- \note Amortized Constant time complexity.
- */
- template
- RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr, internal::IsGenericValue >), (GenericValue&))
- AddMember(StringRefType name, T value, Allocator& allocator) {
- GenericValue n(name);
- return AddMember(n, value, allocator);
- }
-
- //! Remove all members in the object.
- /*! This function do not deallocate memory in the object, i.e. the capacity is unchanged.
- \note Linear time complexity.
- */
- void RemoveAllMembers() {
- RAPIDJSON_ASSERT(IsObject());
- for (MemberIterator m = MemberBegin(); m != MemberEnd(); ++m)
- m->~Member();
- data_.o.size = 0;
- }
-
- //! Remove a member in object by its name.
- /*! \param name Name of member to be removed.
- \return Whether the member existed.
- \note This function may reorder the object members. Use \ref
- EraseMember(ConstMemberIterator) if you need to preserve the
- relative order of the remaining members.
- \note Linear time complexity.
- */
- bool RemoveMember(const Ch* name) {
- GenericValue n(StringRef(name));
- return RemoveMember(n);
- }
-
-#if RAPIDJSON_HAS_STDSTRING
- bool RemoveMember(const std::basic_string& name) { return RemoveMember(GenericValue(StringRef(name))); }
-#endif
-
- template
- bool RemoveMember(const GenericValue& name) {
- MemberIterator m = FindMember(name);
- if (m != MemberEnd()) {
- RemoveMember(m);
- return true;
- }
- else
- return false;
- }
-
- //! Remove a member in object by iterator.
- /*! \param m member iterator (obtained by FindMember() or MemberBegin()).
- \return the new iterator after removal.
- \note This function may reorder the object members. Use \ref
- EraseMember(ConstMemberIterator) if you need to preserve the
- relative order of the remaining members.
- \note Constant time complexity.
- */
- MemberIterator RemoveMember(MemberIterator m) {
- RAPIDJSON_ASSERT(IsObject());
- RAPIDJSON_ASSERT(data_.o.size > 0);
- RAPIDJSON_ASSERT(GetMembersPointer() != 0);
- RAPIDJSON_ASSERT(m >= MemberBegin() && m < MemberEnd());
-
- MemberIterator last(GetMembersPointer() + (data_.o.size - 1));
- if (data_.o.size > 1 && m != last)
- *m = *last; // Move the last one to this place
- else
- m->~Member(); // Only one left, just destroy
- --data_.o.size;
- return m;
- }
-
- //! Remove a member from an object by iterator.
- /*! \param pos iterator to the member to remove
- \pre IsObject() == true && \ref MemberBegin() <= \c pos < \ref MemberEnd()
- \return Iterator following the removed element.
- If the iterator \c pos refers to the last element, the \ref MemberEnd() iterator is returned.
- \note This function preserves the relative order of the remaining object
- members. If you do not need this, use the more efficient \ref RemoveMember(MemberIterator).
- \note Linear time complexity.
- */
- MemberIterator EraseMember(ConstMemberIterator pos) {
- return EraseMember(pos, pos +1);
- }
-
- //! Remove members in the range [first, last) from an object.
- /*! \param first iterator to the first member to remove
- \param last iterator following the last member to remove
- \pre IsObject() == true && \ref MemberBegin() <= \c first <= \c last <= \ref MemberEnd()
- \return Iterator following the last removed element.
- \note This function preserves the relative order of the remaining object
- members.
- \note Linear time complexity.
- */
- MemberIterator EraseMember(ConstMemberIterator first, ConstMemberIterator last) {
- RAPIDJSON_ASSERT(IsObject());
- RAPIDJSON_ASSERT(data_.o.size > 0);
- RAPIDJSON_ASSERT(GetMembersPointer() != 0);
- RAPIDJSON_ASSERT(first >= MemberBegin());
- RAPIDJSON_ASSERT(first <= last);
- RAPIDJSON_ASSERT(last <= MemberEnd());
-
- MemberIterator pos = MemberBegin() + (first - MemberBegin());
- for (MemberIterator itr = pos; itr != last; ++itr)
- itr->~Member();
- std::memmove(&*pos, &*last, static_cast(MemberEnd() - last) * sizeof(Member));
- data_.o.size -= static_cast(last - first);
- return pos;
- }
-
- //! Erase a member in object by its name.
- /*! \param name Name of member to be removed.
- \return Whether the member existed.
- \note Linear time complexity.
- */
- bool EraseMember(const Ch* name) {
- GenericValue n(StringRef(name));
- return EraseMember(n);
- }
-
-#if RAPIDJSON_HAS_STDSTRING
- bool EraseMember(const std::basic_string& name) { return EraseMember(GenericValue(StringRef(name))); }
-#endif
-
- template
- bool EraseMember(const GenericValue& name) {
- MemberIterator m = FindMember(name);
- if (m != MemberEnd()) {
- EraseMember(m);
- return true;
- }
- else
- return false;
- }
-
- Object GetObject() { RAPIDJSON_ASSERT(IsObject()); return Object(*this); }
- ConstObject GetObject() const { RAPIDJSON_ASSERT(IsObject()); return ConstObject(*this); }
-
- //@}
-
- //!@name Array
- //@{
-
- //! Set this value as an empty array.
- /*! \post IsArray == true */
- GenericValue& SetArray() { this->~GenericValue(); new (this) GenericValue(kArrayType); return *this; }
-
- //! Get the number of elements in array.
- SizeType Size() const { RAPIDJSON_ASSERT(IsArray()); return data_.a.size; }
-
- //! Get the capacity of array.
- SizeType Capacity() const { RAPIDJSON_ASSERT(IsArray()); return data_.a.capacity; }
-
- //! Check whether the array is empty.
- bool Empty() const { RAPIDJSON_ASSERT(IsArray()); return data_.a.size == 0; }
-
- //! Remove all elements in the array.
- /*! This function do not deallocate memory in the array, i.e. the capacity is unchanged.
- \note Linear time complexity.
- */
- void Clear() {
- RAPIDJSON_ASSERT(IsArray());
- GenericValue* e = GetElementsPointer();
- for (GenericValue* v = e; v != e + data_.a.size; ++v)
- v->~GenericValue();
- data_.a.size = 0;
- }
-
- //! Get an element from array by index.
- /*! \pre IsArray() == true
- \param index Zero-based index of element.
- \see operator[](T*)
- */
- GenericValue& operator[](SizeType index) {
- RAPIDJSON_ASSERT(IsArray());
- RAPIDJSON_ASSERT(index < data_.a.size);
- return GetElementsPointer()[index];
- }
- const GenericValue& operator[](SizeType index) const { return const_cast(*this)[index]; }
-
- //! Element iterator
- /*! \pre IsArray() == true */
- ValueIterator Begin() { RAPIDJSON_ASSERT(IsArray()); return GetElementsPointer(); }
- //! \em Past-the-end element iterator
- /*! \pre IsArray() == true */
- ValueIterator End() { RAPIDJSON_ASSERT(IsArray()); return GetElementsPointer() + data_.a.size; }
- //! Constant element iterator
- /*! \pre IsArray() == true */
- ConstValueIterator Begin() const { return const_cast(*this).Begin(); }
- //! Constant \em past-the-end element iterator
- /*! \pre IsArray() == true */
- ConstValueIterator End() const { return const_cast(*this).End(); }
-
- //! Request the array to have enough capacity to store elements.
- /*! \param newCapacity The capacity that the array at least need to have.
- \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator().
- \return The value itself for fluent API.
- \note Linear time complexity.
- */
- GenericValue& Reserve(SizeType newCapacity, Allocator &allocator) {
- RAPIDJSON_ASSERT(IsArray());
- if (newCapacity > data_.a.capacity) {
- SetElementsPointer(reinterpret_cast(allocator.Realloc(GetElementsPointer(), data_.a.capacity * sizeof(GenericValue), newCapacity * sizeof(GenericValue))));
- data_.a.capacity = newCapacity;
- }
- return *this;
- }
-
- //! Append a GenericValue at the end of the array.
- /*! \param value Value to be appended.
- \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator().
- \pre IsArray() == true
- \post value.IsNull() == true
- \return The value itself for fluent API.
- \note The ownership of \c value will be transferred to this array on success.
- \note If the number of elements to be appended is known, calls Reserve() once first may be more efficient.
- \note Amortized constant time complexity.
- */
- GenericValue& PushBack(GenericValue& value, Allocator& allocator) {
- RAPIDJSON_ASSERT(IsArray());
- if (data_.a.size >= data_.a.capacity)
- Reserve(data_.a.capacity == 0 ? kDefaultArrayCapacity : (data_.a.capacity + (data_.a.capacity + 1) / 2), allocator);
- GetElementsPointer()[data_.a.size++].RawAssign(value);
- return *this;
- }
-
-#if RAPIDJSON_HAS_CXX11_RVALUE_REFS
- GenericValue& PushBack(GenericValue&& value, Allocator& allocator) {
- return PushBack(value, allocator);
- }
-#endif // RAPIDJSON_HAS_CXX11_RVALUE_REFS
-
- //! Append a constant string reference at the end of the array.
- /*! \param value Constant string reference to be appended.
- \param allocator Allocator for reallocating memory. It must be the same one used previously. Commonly use GenericDocument::GetAllocator().
- \pre IsArray() == true
- \return The value itself for fluent API.
- \note If the number of elements to be appended is known, calls Reserve() once first may be more efficient.
- \note Amortized constant time complexity.
- \see GenericStringRef
- */
- GenericValue& PushBack(StringRefType value, Allocator& allocator) {
- return (*this).template PushBack(value, allocator);
- }
-
- //! Append a primitive value at the end of the array.
- /*! \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t
- \param value Value of primitive type T to be appended.
- \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator().
- \pre IsArray() == true
- \return The value itself for fluent API.
- \note If the number of elements to be appended is known, calls Reserve() once first may be more efficient.
-
- \note The source type \c T explicitly disallows all pointer types,
- especially (\c const) \ref Ch*. This helps avoiding implicitly
- referencing character strings with insufficient lifetime, use
- \ref PushBack(GenericValue&, Allocator&) or \ref
- PushBack(StringRefType, Allocator&).
- All other pointer types would implicitly convert to \c bool,
- use an explicit cast instead, if needed.
- \note Amortized constant time complexity.
- */
- template
- RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr, internal::IsGenericValue >), (GenericValue&))
- PushBack(T value, Allocator& allocator) {
- GenericValue v(value);
- return PushBack(v, allocator);
- }
-
- //! Remove the last element in the array.
- /*!
- \note Constant time complexity.
- */
- GenericValue& PopBack() {
- RAPIDJSON_ASSERT(IsArray());
- RAPIDJSON_ASSERT(!Empty());
- GetElementsPointer()[--data_.a.size].~GenericValue();
- return *this;
- }
-
- //! Remove an element of array by iterator.
- /*!
- \param pos iterator to the element to remove
- \pre IsArray() == true && \ref Begin() <= \c pos < \ref End()
- \return Iterator following the removed element. If the iterator pos refers to the last element, the End() iterator is returned.
- \note Linear time complexity.
- */
- ValueIterator Erase(ConstValueIterator pos) {
- return Erase(pos, pos + 1);
- }
-
- //! Remove elements in the range [first, last) of the array.
- /*!
- \param first iterator to the first element to remove
- \param last iterator following the last element to remove
- \pre IsArray() == true && \ref Begin() <= \c first <= \c last <= \ref End()
- \return Iterator following the last removed element.
- \note Linear time complexity.
- */
- ValueIterator Erase(ConstValueIterator first, ConstValueIterator last) {
- RAPIDJSON_ASSERT(IsArray());
- RAPIDJSON_ASSERT(data_.a.size > 0);
- RAPIDJSON_ASSERT(GetElementsPointer() != 0);
- RAPIDJSON_ASSERT(first >= Begin());
- RAPIDJSON_ASSERT(first <= last);
- RAPIDJSON_ASSERT(last <= End());
- ValueIterator pos = Begin() + (first - Begin());
- for (ValueIterator itr = pos; itr != last; ++itr)
- itr->~GenericValue();
- std::memmove(pos, last, static_cast(End() - last) * sizeof(GenericValue));
- data_.a.size -= static_cast(last - first);
- return pos;
- }
-
- Array GetArray() { RAPIDJSON_ASSERT(IsArray()); return Array(*this); }
- ConstArray GetArray() const { RAPIDJSON_ASSERT(IsArray()); return ConstArray(*this); }
-
- //@}
-
- //!@name Number
- //@{
-
- int GetInt() const { RAPIDJSON_ASSERT(data_.f.flags & kIntFlag); return data_.n.i.i; }
- unsigned GetUint() const { RAPIDJSON_ASSERT(data_.f.flags & kUintFlag); return data_.n.u.u; }
- int64_t GetInt64() const { RAPIDJSON_ASSERT(data_.f.flags & kInt64Flag); return data_.n.i64; }
- uint64_t GetUint64() const { RAPIDJSON_ASSERT(data_.f.flags & kUint64Flag); return data_.n.u64; }
-
- //! Get the value as double type.
- /*! \note If the value is 64-bit integer type, it may lose precision. Use \c IsLosslessDouble() to check whether the converison is lossless.
- */
- double GetDouble() const {
- RAPIDJSON_ASSERT(IsNumber());
- if ((data_.f.flags & kDoubleFlag) != 0) return data_.n.d; // exact type, no conversion.
- if ((data_.f.flags & kIntFlag) != 0) return data_.n.i.i; // int -> double
- if ((data_.f.flags & kUintFlag) != 0) return data_.n.u.u; // unsigned -> double
- if ((data_.f.flags & kInt64Flag) != 0) return static_cast(data_.n.i64); // int64_t -> double (may lose precision)
- RAPIDJSON_ASSERT((data_.f.flags & kUint64Flag) != 0); return static_cast(data_.n.u64); // uint64_t -> double (may lose precision)
- }
-
- //! Get the value as float type.
- /*! \note If the value is 64-bit integer type, it may lose precision. Use \c IsLosslessFloat() to check whether the converison is lossless.
- */
- float GetFloat() const {
- return static_cast(GetDouble());
- }
-
- GenericValue& SetInt(int i) { this->~GenericValue(); new (this) GenericValue(i); return *this; }
- GenericValue& SetUint(unsigned u) { this->~GenericValue(); new (this) GenericValue(u); return *this; }
- GenericValue& SetInt64(int64_t i64) { this->~GenericValue(); new (this) GenericValue(i64); return *this; }
- GenericValue& SetUint64(uint64_t u64) { this->~GenericValue(); new (this) GenericValue(u64); return *this; }
- GenericValue& SetDouble(double d) { this->~GenericValue(); new (this) GenericValue(d); return *this; }
- GenericValue& SetFloat(float f) { this->~GenericValue(); new (this) GenericValue(static_cast(f)); return *this; }
-
- //@}
-
- //!@name String
- //@{
-
- const Ch* GetString() const { RAPIDJSON_ASSERT(IsString()); return (data_.f.flags & kInlineStrFlag) ? data_.ss.str : GetStringPointer(); }
-
- //! Get the length of string.
- /*! Since rapidjson permits "\\u0000" in the json string, strlen(v.GetString()) may not equal to v.GetStringLength().
- */
- SizeType GetStringLength() const { RAPIDJSON_ASSERT(IsString()); return ((data_.f.flags & kInlineStrFlag) ? (data_.ss.GetLength()) : data_.s.length); }
-
- //! Set this value as a string without copying source string.
- /*! This version has better performance with supplied length, and also support string containing null character.
- \param s source string pointer.
- \param length The length of source string, excluding the trailing null terminator.
- \return The value itself for fluent API.
- \post IsString() == true && GetString() == s && GetStringLength() == length
- \see SetString(StringRefType)
- */
- GenericValue& SetString(const Ch* s, SizeType length) { return SetString(StringRef(s, length)); }
-
- //! Set this value as a string without copying source string.
- /*! \param s source string reference
- \return The value itself for fluent API.
- \post IsString() == true && GetString() == s && GetStringLength() == s.length
- */
- GenericValue& SetString(StringRefType s) { this->~GenericValue(); SetStringRaw(s); return *this; }
-
- //! Set this value as a string by copying from source string.
- /*! This version has better performance with supplied length, and also support string containing null character.
- \param s source string.
- \param length The length of source string, excluding the trailing null terminator.
- \param allocator Allocator for allocating copied buffer. Commonly use GenericDocument::GetAllocator().
- \return The value itself for fluent API.
- \post IsString() == true && GetString() != s && strcmp(GetString(),s) == 0 && GetStringLength() == length
- */
- GenericValue& SetString(const Ch* s, SizeType length, Allocator& allocator) { return SetString(StringRef(s, length), allocator); }
-
- //! Set this value as a string by copying from source string.
- /*! \param s source string.
- \param allocator Allocator for allocating copied buffer. Commonly use GenericDocument::GetAllocator().
- \return The value itself for fluent API.
- \post IsString() == true && GetString() != s && strcmp(GetString(),s) == 0 && GetStringLength() == length
- */
- GenericValue& SetString(const Ch* s, Allocator& allocator) { return SetString(StringRef(s), allocator); }
-
- //! Set this value as a string by copying from source string.
- /*! \param s source string reference
- \param allocator Allocator for allocating copied buffer. Commonly use GenericDocument::GetAllocator().
- \return The value itself for fluent API.
- \post IsString() == true && GetString() != s.s && strcmp(GetString(),s) == 0 && GetStringLength() == length
- */
- GenericValue& SetString(StringRefType s, Allocator& allocator) { this->~GenericValue(); SetStringRaw(s, allocator); return *this; }
-
-#if RAPIDJSON_HAS_STDSTRING
- //! Set this value as a string by copying from source string.
- /*! \param s source string.
- \param allocator Allocator for allocating copied buffer. Commonly use GenericDocument::GetAllocator().
- \return The value itself for fluent API.
- \post IsString() == true && GetString() != s.data() && strcmp(GetString(),s.data() == 0 && GetStringLength() == s.size()
- \note Requires the definition of the preprocessor symbol \ref RAPIDJSON_HAS_STDSTRING.
- */
- GenericValue& SetString(const std::basic_string& s, Allocator& allocator) { return SetString(StringRef(s), allocator); }
-#endif
-
- //@}
-
- //!@name Array
- //@{
-
- //! Templated version for checking whether this value is type T.
- /*!
- \tparam T Either \c bool, \c int, \c unsigned, \c int64_t, \c uint64_t, \c double, \c float, \c const \c char*, \c std::basic_string
- */
- template
- bool Is() const { return internal::TypeHelper::Is(*this); }
-
- template
- T Get() const { return internal::TypeHelper::Get(*this); }
-
- template
- T Get() { return internal::TypeHelper::Get(*this); }
-
- template
- ValueType& Set(const T& data) { return internal::TypeHelper::Set(*this, data); }
-
- template
- ValueType& Set(const T& data, AllocatorType& allocator) { return internal::TypeHelper::Set(*this, data, allocator); }
-
- //@}
-
- //! Generate events of this value to a Handler.
- /*! This function adopts the GoF visitor pattern.
- Typical usage is to output this JSON value as JSON text via Writer, which is a Handler.
- It can also be used to deep clone this value via GenericDocument, which is also a Handler.
- \tparam Handler type of handler.
- \param handler An object implementing concept Handler.
- */
- template
- bool Accept(Handler& handler) const {
- switch(GetType()) {
- case kNullType: return handler.Null();
- case kFalseType: return handler.Bool(false);
- case kTrueType: return handler.Bool(true);
-
- case kObjectType:
- if (RAPIDJSON_UNLIKELY(!handler.StartObject()))
- return false;
- for (ConstMemberIterator m = MemberBegin(); m != MemberEnd(); ++m) {
- RAPIDJSON_ASSERT(m->name.IsString()); // User may change the type of name by MemberIterator.
- if (RAPIDJSON_UNLIKELY(!handler.Key(m->name.GetString(), m->name.GetStringLength(), (m->name.data_.f.flags & kCopyFlag) != 0)))
- return false;
- if (RAPIDJSON_UNLIKELY(!m->value.Accept(handler)))
- return false;
- }
- return handler.EndObject(data_.o.size);
-
- case kArrayType:
- if (RAPIDJSON_UNLIKELY(!handler.StartArray()))
- return false;
- for (const GenericValue* v = Begin(); v != End(); ++v)
- if (RAPIDJSON_UNLIKELY(!v->Accept(handler)))
- return false;
- return handler.EndArray(data_.a.size);
-
- case kStringType:
- return handler.String(GetString(), GetStringLength(), (data_.f.flags & kCopyFlag) != 0);
-
- default:
- RAPIDJSON_ASSERT(GetType() == kNumberType);
- if (IsDouble()) return handler.Double(data_.n.d);
- else if (IsInt()) return handler.Int(data_.n.i.i);
- else if (IsUint()) return handler.Uint(data_.n.u.u);
- else if (IsInt64()) return handler.Int64(data_.n.i64);
- else return handler.Uint64(data_.n.u64);
- }
- }
-
-private:
- template friend class GenericValue;
- template friend class GenericDocument;
-
- enum {
- kBoolFlag = 0x0008,
- kNumberFlag = 0x0010,
- kIntFlag = 0x0020,
- kUintFlag = 0x0040,
- kInt64Flag = 0x0080,
- kUint64Flag = 0x0100,
- kDoubleFlag = 0x0200,
- kStringFlag = 0x0400,
- kCopyFlag = 0x0800,
- kInlineStrFlag = 0x1000,
-
- // Initial flags of different types.
- kNullFlag = kNullType,
- kTrueFlag = kTrueType | kBoolFlag,
- kFalseFlag = kFalseType | kBoolFlag,
- kNumberIntFlag = kNumberType | kNumberFlag | kIntFlag | kInt64Flag,
- kNumberUintFlag = kNumberType | kNumberFlag | kUintFlag | kUint64Flag | kInt64Flag,
- kNumberInt64Flag = kNumberType | kNumberFlag | kInt64Flag,
- kNumberUint64Flag = kNumberType | kNumberFlag | kUint64Flag,
- kNumberDoubleFlag = kNumberType | kNumberFlag | kDoubleFlag,
- kNumberAnyFlag = kNumberType | kNumberFlag | kIntFlag | kInt64Flag | kUintFlag | kUint64Flag | kDoubleFlag,
- kConstStringFlag = kStringType | kStringFlag,
- kCopyStringFlag = kStringType | kStringFlag | kCopyFlag,
- kShortStringFlag = kStringType | kStringFlag | kCopyFlag | kInlineStrFlag,
- kObjectFlag = kObjectType,
- kArrayFlag = kArrayType,
-
- kTypeMask = 0x07
- };
-
- static const SizeType kDefaultArrayCapacity = 16;
- static const SizeType kDefaultObjectCapacity = 16;
-
- struct Flag {
-#if RAPIDJSON_48BITPOINTER_OPTIMIZATION
- char payload[sizeof(SizeType) * 2 + 6]; // 2 x SizeType + lower 48-bit pointer
-#elif RAPIDJSON_64BIT
- char payload[sizeof(SizeType) * 2 + sizeof(void*) + 6]; // 6 padding bytes
-#else
- char payload[sizeof(SizeType) * 2 + sizeof(void*) + 2]; // 2 padding bytes
-#endif
- uint16_t flags;
- };
-
- struct String {
- SizeType length;
- SizeType hashcode; //!< reserved
- const Ch* str;
- }; // 12 bytes in 32-bit mode, 16 bytes in 64-bit mode
-
- // implementation detail: ShortString can represent zero-terminated strings up to MaxSize chars
- // (excluding the terminating zero) and store a value to determine the length of the contained
- // string in the last character str[LenPos] by storing "MaxSize - length" there. If the string
- // to store has the maximal length of MaxSize then str[LenPos] will be 0 and therefore act as
- // the string terminator as well. For getting the string length back from that value just use
- // "MaxSize - str[LenPos]".
- // This allows to store 13-chars strings in 32-bit mode, 21-chars strings in 64-bit mode,
- // 13-chars strings for RAPIDJSON_48BITPOINTER_OPTIMIZATION=1 inline (for `UTF8`-encoded strings).
- struct ShortString {
- enum { MaxChars = sizeof(static_cast(0)->payload) / sizeof(Ch), MaxSize = MaxChars - 1, LenPos = MaxSize };
- Ch str[MaxChars];
-
- inline static bool Usable(SizeType len) { return (MaxSize >= len); }
- inline void SetLength(SizeType len) { str[LenPos] = static_cast(MaxSize - len); }
- inline SizeType GetLength() const { return static_cast(MaxSize - str[LenPos]); }
- }; // at most as many bytes as "String" above => 12 bytes in 32-bit mode, 16 bytes in 64-bit mode
-
- // By using proper binary layout, retrieval of different integer types do not need conversions.
- union Number {
-#if RAPIDJSON_ENDIAN == RAPIDJSON_LITTLEENDIAN
- struct I {
- int i;
- char padding[4];
- }i;
- struct U {
- unsigned u;
- char padding2[4];
- }u;
-#else
- struct I {
- char padding[4];
- int i;
- }i;
- struct U {
- char padding2[4];
- unsigned u;
- }u;
-#endif
- int64_t i64;
- uint64_t u64;
- double d;
- }; // 8 bytes
-
- struct ObjectData {
- SizeType size;
- SizeType capacity;
- Member* members;
- }; // 12 bytes in 32-bit mode, 16 bytes in 64-bit mode
-
- struct ArrayData {
- SizeType size;
- SizeType capacity;
- GenericValue* elements;
- }; // 12 bytes in 32-bit mode, 16 bytes in 64-bit mode
-
- union Data {
- String s;
- ShortString ss;
- Number n;
- ObjectData o;
- ArrayData a;
- Flag f;
- }; // 16 bytes in 32-bit mode, 24 bytes in 64-bit mode, 16 bytes in 64-bit with RAPIDJSON_48BITPOINTER_OPTIMIZATION
-
- RAPIDJSON_FORCEINLINE const Ch* GetStringPointer() const { return RAPIDJSON_GETPOINTER(Ch, data_.s.str); }
- RAPIDJSON_FORCEINLINE const Ch* SetStringPointer(const Ch* str) { return RAPIDJSON_SETPOINTER(Ch, data_.s.str, str); }
- RAPIDJSON_FORCEINLINE GenericValue* GetElementsPointer() const { return RAPIDJSON_GETPOINTER(GenericValue, data_.a.elements); }
- RAPIDJSON_FORCEINLINE GenericValue* SetElementsPointer(GenericValue* elements) { return RAPIDJSON_SETPOINTER(GenericValue, data_.a.elements, elements); }
- RAPIDJSON_FORCEINLINE Member* GetMembersPointer() const { return RAPIDJSON_GETPOINTER(Member, data_.o.members); }
- RAPIDJSON_FORCEINLINE Member* SetMembersPointer(Member* members) { return RAPIDJSON_SETPOINTER(Member, data_.o.members, members); }
-
- // Initialize this value as array with initial data, without calling destructor.
- void SetArrayRaw(GenericValue* values, SizeType count, Allocator& allocator) {
- data_.f.flags = kArrayFlag;
- if (count) {
- GenericValue* e = static_cast(allocator.Malloc(count * sizeof(GenericValue)));
- SetElementsPointer(e);
-RAPIDJSON_DIAG_PUSH
-#if defined(__GNUC__) && __GNUC__ >= 8
-RAPIDJSON_DIAG_OFF(class-memaccess) // ignore complains from gcc that no trivial copy constructor exists.
-#endif
- std::memcpy(e, values, count * sizeof(GenericValue));
-RAPIDJSON_DIAG_POP
- }
- else
- SetElementsPointer(0);
- data_.a.size = data_.a.capacity = count;
- }
-
- //! Initialize this value as object with initial data, without calling destructor.
- void SetObjectRaw(Member* members, SizeType count, Allocator& allocator) {
- data_.f.flags = kObjectFlag;
- if (count) {
- Member* m = static_cast(allocator.Malloc(count * sizeof(Member)));
- SetMembersPointer(m);
-RAPIDJSON_DIAG_PUSH
-#if defined(__GNUC__) && __GNUC__ >= 8
-RAPIDJSON_DIAG_OFF(class-memaccess) // ignore complains from gcc that no trivial copy constructor exists.
-#endif
- std::memcpy(m, members, count * sizeof(Member));
-RAPIDJSON_DIAG_POP
- }
- else
- SetMembersPointer(0);
- data_.o.size = data_.o.capacity = count;
- }
-
- //! Initialize this value as constant string, without calling destructor.
- void SetStringRaw(StringRefType s) RAPIDJSON_NOEXCEPT {
- data_.f.flags = kConstStringFlag;
- SetStringPointer(s);
- data_.s.length = s.length;
- }
-
- //! Initialize this value as copy string with initial data, without calling destructor.
- void SetStringRaw(StringRefType s, Allocator& allocator) {
- Ch* str = 0;
- if (ShortString::Usable(s.length)) {
- data_.f.flags = kShortStringFlag;
- data_.ss.SetLength(s.length);
- str = data_.ss.str;
- } else {
- data_.f.flags = kCopyStringFlag;
- data_.s.length = s.length;
- str = static_cast(allocator.Malloc((s.length + 1) * sizeof(Ch)));
- SetStringPointer(str);
- }
- std::memcpy(str, s, s.length * sizeof(Ch));
- str[s.length] = '\0';
- }
-
- //! Assignment without calling destructor
- void RawAssign(GenericValue& rhs) RAPIDJSON_NOEXCEPT {
- data_ = rhs.data_;
- // data_.f.flags = rhs.data_.f.flags;
- rhs.data_.f.flags = kNullFlag;
- }
-
- template
- bool StringEqual(const GenericValue& rhs) const {
- RAPIDJSON_ASSERT(IsString());
- RAPIDJSON_ASSERT(rhs.IsString());
-
- const SizeType len1 = GetStringLength();
- const SizeType len2 = rhs.GetStringLength();
- if(len1 != len2) { return false; }
-
- const Ch* const str1 = GetString();
- const Ch* const str2 = rhs.GetString();
- if(str1 == str2) { return true; } // fast path for constant string
-
- return (std::memcmp(str1, str2, sizeof(Ch) * len1) == 0);
- }
-
- Data data_;
-};
-
-//! GenericValue with UTF8 encoding
-typedef GenericValue > Value;
-
-///////////////////////////////////////////////////////////////////////////////
-// GenericDocument
-
-//! A document for parsing JSON text as DOM.
-/*!
- \note implements Handler concept
- \tparam Encoding Encoding for both parsing and string storage.
- \tparam Allocator Allocator for allocating memory for the DOM
- \tparam StackAllocator Allocator for allocating memory for stack during parsing.
- \warning Although GenericDocument inherits from GenericValue, the API does \b not provide any virtual functions, especially no virtual destructor. To avoid memory leaks, do not \c delete a GenericDocument object via a pointer to a GenericValue.
-*/
-template , typename StackAllocator = CrtAllocator>
-class GenericDocument : public GenericValue {
-public:
- typedef typename Encoding::Ch Ch; //!< Character type derived from Encoding.
- typedef GenericValue ValueType; //!< Value type of the document.
- typedef Allocator AllocatorType; //!< Allocator type from template parameter.
-
- //! Constructor
- /*! Creates an empty document of specified type.
- \param type Mandatory type of object to create.
- \param allocator Optional allocator for allocating memory.
- \param stackCapacity Optional initial capacity of stack in bytes.
- \param stackAllocator Optional allocator for allocating memory for stack.
- */
- explicit GenericDocument(Type type, Allocator* allocator = 0, size_t stackCapacity = kDefaultStackCapacity, StackAllocator* stackAllocator = 0) :
- GenericValue(type), allocator_(allocator), ownAllocator_(0), stack_(stackAllocator, stackCapacity), parseResult_()
- {
- if (!allocator_)
- ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator)();
- }
-
- //! Constructor
- /*! Creates an empty document which type is Null.
- \param allocator Optional allocator for allocating memory.
- \param stackCapacity Optional initial capacity of stack in bytes.
- \param stackAllocator Optional allocator for allocating memory for stack.
- */
- GenericDocument(Allocator* allocator = 0, size_t stackCapacity = kDefaultStackCapacity, StackAllocator* stackAllocator = 0) :
- allocator_(allocator), ownAllocator_(0), stack_(stackAllocator, stackCapacity), parseResult_()
- {
- if (!allocator_)
- ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator)();
- }
-
-#if RAPIDJSON_HAS_CXX11_RVALUE_REFS
- //! Move constructor in C++11
- GenericDocument(GenericDocument&& rhs) RAPIDJSON_NOEXCEPT
- : ValueType(std::forward(rhs)), // explicit cast to avoid prohibited move from Document
- allocator_(rhs.allocator_),
- ownAllocator_(rhs.ownAllocator_),
- stack_(std::move(rhs.stack_)),
- parseResult_(rhs.parseResult_)
- {
- rhs.allocator_ = 0;
- rhs.ownAllocator_ = 0;
- rhs.parseResult_ = ParseResult();
- }
-#endif
-
- ~GenericDocument() {
- Destroy();
- }
-
-#if RAPIDJSON_HAS_CXX11_RVALUE_REFS
- //! Move assignment in C++11
- GenericDocument& operator=(GenericDocument&& rhs) RAPIDJSON_NOEXCEPT
- {
- // The cast to ValueType is necessary here, because otherwise it would
- // attempt to call GenericValue's templated assignment operator.
- ValueType::operator=(std::forward(rhs));
-
- // Calling the destructor here would prematurely call stack_'s destructor
- Destroy();
-
- allocator_ = rhs.allocator_;
- ownAllocator_ = rhs.ownAllocator_;
- stack_ = std::move(rhs.stack_);
- parseResult_ = rhs.parseResult_;
-
- rhs.allocator_ = 0;
- rhs.ownAllocator_ = 0;
- rhs.parseResult_ = ParseResult();
-
- return *this;
- }
-#endif
-
- //! Exchange the contents of this document with those of another.
- /*!
- \param rhs Another document.
- \note Constant complexity.
- \see GenericValue::Swap
- */
- GenericDocument& Swap(GenericDocument& rhs) RAPIDJSON_NOEXCEPT {
- ValueType::Swap(rhs);
- stack_.Swap(rhs.stack_);
- internal::Swap(allocator_, rhs.allocator_);
- internal::Swap(ownAllocator_, rhs.ownAllocator_);
- internal::Swap(parseResult_, rhs.parseResult_);
- return *this;
- }
-
- // Allow Swap with ValueType.
- // Refer to Effective C++ 3rd Edition/Item 33: Avoid hiding inherited names.
- using ValueType::Swap;
-
- //! free-standing swap function helper
- /*!
- Helper function to enable support for common swap implementation pattern based on \c std::swap:
- \code
- void swap(MyClass& a, MyClass& b) {
- using std::swap;
- swap(a.doc, b.doc);
- // ...
- }
- \endcode
- \see Swap()
- */
- friend inline void swap(GenericDocument& a, GenericDocument& b) RAPIDJSON_NOEXCEPT { a.Swap(b); }
-
- //! Populate this document by a generator which produces SAX events.
- /*! \tparam Generator A functor with bool f(Handler) prototype.
- \param g Generator functor which sends SAX events to the parameter.
- \return The document itself for fluent API.
- */
- template
- GenericDocument& Populate(Generator& g) {
- ClearStackOnExit scope(*this);
- if (g(*this)) {
- RAPIDJSON_ASSERT(stack_.GetSize() == sizeof(ValueType)); // Got one and only one root object
- ValueType::operator=(*stack_.template Pop(1));// Move value from stack to document
- }
- return *this;
- }
-
- //!@name Parse from stream
- //!@{
-
- //! Parse JSON text from an input stream (with Encoding conversion)
- /*! \tparam parseFlags Combination of \ref ParseFlag.
- \tparam SourceEncoding Encoding of input stream
- \tparam InputStream Type of input stream, implementing Stream concept
- \param is Input stream to be parsed.
- \return The document itself for fluent API.
- */
- template
- GenericDocument& ParseStream(InputStream& is) {
- GenericReader