├── .gitignore ├── Aircraft.cpp ├── Aircraft.h ├── Algorithm.cpp ├── Algorithm.h ├── Array3.h ├── Atmosphere.cpp ├── Atmosphere.h ├── Component.cpp ├── Component.h ├── Configuration.cpp ├── Configuration.h ├── Console.cpp ├── Console.h ├── DataLogger.cpp ├── DataLogger.h ├── Log.cpp ├── Log.h ├── Math.cpp ├── Math.h ├── Mediator.cpp ├── Mediator.h ├── PSO.cpp ├── PSO.h ├── Problem.cpp ├── Problem.h ├── Reentry.cpp ├── Reentry.h ├── Star.cpp ├── Star.h ├── conf ├── Atmosphere.json ├── CAV_L.json ├── Earth.json ├── PSO.json └── Reentry.json ├── json ├── allocator.h ├── assertions.h ├── autolink.h ├── config.h ├── features.h ├── forwards.h ├── json.h ├── reader.h ├── value.h ├── version.h └── writer.h ├── jsoncpp.lib └── main.cpp /.gitignore: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | !json/ 4 | !conf/ 5 | !*.h 6 | !*.cpp 7 | !*.lib 8 | !*.json 9 | !.gitignore -------------------------------------------------------------------------------- /Aircraft.cpp: -------------------------------------------------------------------------------- 1 | #include "Aircraft.h" 2 | #include "json\json.h" 3 | #include 4 | 5 | Aircraft::Aircraft(std::string filename):Configuration(filename) 6 | { 7 | readConfig(filename); 8 | } 9 | 10 | Aircraft::~Aircraft() 11 | { 12 | } 13 | 14 | bool Aircraft::readConfig(std::string filename) 15 | { 16 | Json::Reader reader; 17 | std::ifstream ifs(filename); 18 | Json::Value root; 19 | reader.parse(ifs, root); 20 | 21 | _mass = root[getKeyByVar(ToString(_mass))].asDouble(); 22 | _s = root[getKeyByVar(ToString(_s))].asDouble(); 23 | _r = root[getKeyByVar(ToString(_r))].asDouble(); 24 | 25 | return true; 26 | } 27 | 28 | bool Aircraft::writeConfig(std::string filename) 29 | { 30 | return false; 31 | } 32 | 33 | double Aircraft::getM() 34 | { 35 | return _mass; 36 | } 37 | 38 | double Aircraft::getS() 39 | { 40 | return _s; 41 | } 42 | 43 | double Aircraft::getR() 44 | { 45 | return _r; 46 | } 47 | -------------------------------------------------------------------------------- /Aircraft.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zpb1992/ReentryTrajectoryGuide/4f4b764896795ec206caabfa12889cd580132921/Aircraft.h -------------------------------------------------------------------------------- /Algorithm.cpp: -------------------------------------------------------------------------------- 1 | #include "Algorithm.h" 2 | 3 | 4 | 5 | Algorithm::Algorithm() 6 | { 7 | } 8 | 9 | 10 | Algorithm::~Algorithm() 11 | { 12 | } 13 | -------------------------------------------------------------------------------- /Algorithm.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "Array3.h" 4 | 5 | class Algorithm 6 | { 7 | public: 8 | Algorithm(); 9 | virtual ~Algorithm(); 10 | 11 | public: 12 | virtual bool calculate() = 0; 13 | }; 14 | 15 | -------------------------------------------------------------------------------- /Array3.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zpb1992/ReentryTrajectoryGuide/4f4b764896795ec206caabfa12889cd580132921/Array3.h -------------------------------------------------------------------------------- /Atmosphere.cpp: -------------------------------------------------------------------------------- 1 | #include "Atmosphere.h" 2 | #include "json/json.h" 3 | #include 4 | #include 5 | #include"Console.h" 6 | 7 | Atmosphere::Atmosphere(std::string filename):Configuration(filename) 8 | { 9 | readConfig(filename); 10 | } 11 | 12 | Atmosphere::~Atmosphere() 13 | { 14 | } 15 | 16 | bool Atmosphere::readConfig(std::string filename) 17 | { 18 | Json::Reader reader; 19 | std::ifstream ifs(filename); 20 | Json::Value root; 21 | reader.parse(ifs, root); 22 | if (ifs) 23 | { 24 | _density = root[getKeyByVar(ToString(_density))].asDouble(); 25 | _densityHeight = root[getKeyByVar(ToString(_densityHeight))].asDouble(); 26 | } 27 | else 28 | { 29 | //Console::instance()->error("atmosphere read config"); 30 | } 31 | 32 | 33 | return true; 34 | } 35 | 36 | bool Atmosphere::writeConfig(std::string filename) 37 | { 38 | return false; 39 | } 40 | 41 | double Atmosphere::getAirDensity(double height) 42 | { 43 | return _density*exp(-height/_densityHeight); 44 | } 45 | 46 | double Atmosphere::getAirDensity() 47 | { 48 | return _density; 49 | } 50 | -------------------------------------------------------------------------------- /Atmosphere.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zpb1992/ReentryTrajectoryGuide/4f4b764896795ec206caabfa12889cd580132921/Atmosphere.h -------------------------------------------------------------------------------- /Component.cpp: -------------------------------------------------------------------------------- 1 | #include "Component.h" 2 | 3 | 4 | 5 | Component::Component() 6 | { 7 | } 8 | 9 | 10 | Component::~Component() 11 | { 12 | } 13 | -------------------------------------------------------------------------------- /Component.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "Array3.h" 4 | class Mediator; 5 | 6 | class Component 7 | { 8 | public: 9 | Component(); 10 | ~Component(); 11 | public: 12 | virtual bool tieMediator(Mediator *mediator) = 0; 13 | virtual bool recvData(Array3 data) = 0; 14 | }; 15 | -------------------------------------------------------------------------------- /Configuration.cpp: -------------------------------------------------------------------------------- 1 | #include "Configuration.h" 2 | #include 3 | #include 4 | 5 | 6 | Configuration::Configuration(std::string filename) 7 | { 8 | _fileName = filename; 9 | } 10 | 11 | Configuration::~Configuration() 12 | { 13 | } 14 | 15 | std::string Configuration::getKeyByVar(std::string varName) 16 | { 17 | assert(varName[0] == '_'); 18 | 19 | varName.erase(0,1); 20 | if (varName[0]>='a'&&varName[0]<='z') 21 | varName[0] -= 'a' - 'A'; 22 | else if (varName[0] >= 'A'&&varName[0] <= 'Z') 23 | ; 24 | return varName; 25 | } 26 | -------------------------------------------------------------------------------- /Configuration.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | #define ToString(var) #var 6 | 7 | 8 | class Configuration 9 | { 10 | public: 11 | Configuration(std::string filename); 12 | ~Configuration(); 13 | 14 | public: 15 | virtual bool readConfig(std::string filename) = 0; 16 | virtual bool writeConfig(std::string filename) = 0; 17 | 18 | protected: 19 | std::string _fileName; 20 | std::string getKeyByVar(std::string varName); 21 | }; 22 | 23 | -------------------------------------------------------------------------------- /Console.cpp: -------------------------------------------------------------------------------- 1 | #include "Console.h" 2 | #include 3 | 4 | Console *Console::_console = nullptr; 5 | 6 | Console::Console() 7 | { 8 | } 9 | 10 | Console::~Console() 11 | { 12 | } 13 | 14 | Console * Console::instance() 15 | { 16 | if (_console == nullptr) 17 | { 18 | _console = new Console(); 19 | } 20 | return _console; 21 | } 22 | 23 | void Console::error(std::string mes) 24 | { 25 | std::cout << "\033[31m" 26 | << mes 27 | << "\033[0m" << std::endl; 28 | exit(1); 29 | } 30 | 31 | Console * Console::warn(std::string mes) 32 | { 33 | std::cout << "\033[33m" 34 | << mes 35 | << "\033[0m" << std::endl; 36 | return this; 37 | } 38 | 39 | Console * Console::inform(std::string mes) 40 | { 41 | std::cout << "\033[32m" 42 | << mes 43 | << "\033[0m" << std::endl; 44 | return this; 45 | } 46 | 47 | void Console::error(int num) 48 | { 49 | std::cout << "\033[31m" 50 | << "count: " << num 51 | << "\033[0m" << std::endl; 52 | exit(1); 53 | 54 | } 55 | 56 | Console * Console::warn(int num) 57 | { 58 | std::cout << "\033[33m" 59 | << "count: " << num 60 | << "\033[0m" << std::endl; 61 | return this; 62 | } 63 | 64 | Console * Console::inform(int num) 65 | { 66 | std::cout << "\033[32m" 67 | << "count: " << num 68 | << "\033[0m" << std::endl; 69 | return this; 70 | } 71 | 72 | Console * Console::count(int start, bool initial) 73 | { 74 | static int num = 0; 75 | if (initial) 76 | num = start; 77 | std::cout << "\033[32m" 78 | << "count: " << num 79 | << "\033[0m" << std::endl; 80 | ++num; 81 | 82 | return this; 83 | } 84 | 85 | -------------------------------------------------------------------------------- /Console.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | 4 | class Console 5 | { 6 | private: 7 | Console(); 8 | public: 9 | ~Console(); 10 | private: 11 | static Console *_console; 12 | public: 13 | static Console *instance(); 14 | 15 | void error(std::string mes); 16 | Console * warn(std::string mes); 17 | Console * inform(std::string mes); 18 | 19 | void error(int num); 20 | Console * warn(int num); 21 | Console * inform(int num); 22 | 23 | Console * count(int start,bool initial = false); 24 | }; 25 | 26 | -------------------------------------------------------------------------------- /DataLogger.cpp: -------------------------------------------------------------------------------- 1 | #include "DataLogger.h" 2 | #include "Log.h" 3 | 4 | 5 | DataLogger::DataLogger() 6 | { 7 | } 8 | 9 | 10 | DataLogger::~DataLogger() 11 | { 12 | } 13 | 14 | bool DataLogger::log(double * data, unsigned num) 15 | { 16 | Log::instance()->write(data, num); 17 | return true; 18 | } 19 | -------------------------------------------------------------------------------- /DataLogger.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | class DataLogger 3 | { 4 | public: 5 | DataLogger(); 6 | ~DataLogger(); 7 | 8 | public: 9 | bool log(double *data, unsigned num); 10 | }; 11 | 12 | -------------------------------------------------------------------------------- /Log.cpp: -------------------------------------------------------------------------------- 1 | #include "Log.h" 2 | #include"Console.h" 3 | 4 | Log *Log::_instance = nullptr; 5 | 6 | Log::Log() 7 | { 8 | file(); 9 | } 10 | 11 | bool Log::file() 12 | { 13 | setDateFile(); 14 | if (_ofs.is_open()) 15 | _ofs.close(); 16 | _ofs.open(_filename, std::ofstream::out | std::ofstream::app); 17 | printTime(); 18 | return true; 19 | } 20 | 21 | bool Log::file(std::string filename) 22 | { 23 | if (_ofs.is_open()) 24 | _ofs.close(); 25 | _ofs.open(_filename, std::ofstream::out | std::ofstream::app); 26 | printTime(); 27 | return true; 28 | } 29 | 30 | Log::~Log() 31 | { 32 | _ofs << std::endl; 33 | close(); 34 | } 35 | 36 | Log * Log::instance() 37 | { 38 | if (_instance == nullptr) 39 | _instance = new Log; 40 | return nullptr; 41 | } 42 | 43 | bool Log::close() 44 | { 45 | if (_ofs) 46 | _ofs.close(); 47 | return true; 48 | } 49 | 50 | bool Log::printTime() 51 | { 52 | std::string t; 53 | time_t time_sec = time(nullptr); 54 | tm time; 55 | localtime_s(&time, &time_sec); 56 | t += "at "; 57 | t += std::to_string(time.tm_hour); 58 | t += ":"; 59 | t += std::to_string(time.tm_min); 60 | t += ":"; 61 | t += std::to_string(time.tm_sec); 62 | _ofs << t << std::endl; 63 | return false; 64 | } 65 | 66 | std::string & Log::setDateFile() 67 | { 68 | time_t tempTime = time(nullptr); 69 | tm localTime; 70 | localtime_s(&localTime, &tempTime); 71 | _filename += std::to_string(localTime.tm_year + 1900); 72 | _filename += "_"; 73 | _filename += std::to_string(localTime.tm_mon + 1); 74 | _filename += "_"; 75 | _filename += std::to_string(localTime.tm_mday); 76 | _filename += ".log"; 77 | 78 | return _filename; 79 | } 80 | -------------------------------------------------------------------------------- /Log.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | class Log 8 | { 9 | private: 10 | Log(); 11 | 12 | public: 13 | bool file(); 14 | bool file(std::string filename); 15 | ~Log(); 16 | 17 | public: 18 | static Log * instance(); 19 | template 20 | bool write(T *data, unsigned num); 21 | bool close(); 22 | 23 | private: 24 | static Log *_instance; 25 | 26 | std::ofstream _ofs; 27 | std::string _filename; 28 | private: 29 | bool printTime(); 30 | std::string &setDateFile(); 31 | }; 32 | 33 | template 34 | inline bool Log::write(T * data, unsigned num) 35 | { 36 | for (unsigned i = 0; i < num; ++i) 37 | { 38 | _ofs << data[i] << " "; 39 | } 40 | _ofs << std::endl; 41 | return true; 42 | } 43 | -------------------------------------------------------------------------------- /Math.cpp: -------------------------------------------------------------------------------- 1 | #include "Math.h" 2 | #include 3 | 4 | double Math::_error= 0.001; 5 | double Math::PI=3.1415926; 6 | double Math::SOUND_VELCITY= 295.188; 7 | 8 | Math::Math() 9 | { 10 | } 11 | 12 | 13 | Math::~Math() 14 | { 15 | } 16 | 17 | double Math::linearInterpolation(double x1, double y1, double x2, double y2, double x) 18 | { 19 | assert(x1<(x + _error) && x2>(x - _error)); 20 | return (y2-y1)*(x-x1)/(x2-x1)+y1; 21 | } 22 | 23 | double Math::getDegree(double radian) 24 | { 25 | return radian/PI*180.0; 26 | } 27 | 28 | double Math::getRadian(double degree) 29 | { 30 | return degree/180.0*PI; 31 | } 32 | 33 | bool Math::keepRange(double &num, double min, double max) 34 | { 35 | if (num < min) 36 | num = min; 37 | else if (num > max) 38 | num = max; 39 | else 40 | return true; 41 | return false; 42 | } 43 | 44 | -------------------------------------------------------------------------------- /Math.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include 4 | 5 | class Math 6 | { 7 | private: 8 | Math(); 9 | public: 10 | ~Math(); 11 | 12 | private: 13 | static double _error; 14 | public: 15 | static double SOUND_VELCITY; 16 | static double PI; 17 | public: 18 | template 19 | static T random(T min, T max); 20 | 21 | template 22 | static unsigned max(T *data, unsigned num); 23 | 24 | static double linearInterpolation(double x1, double y1, double x2, double y2, double x); 25 | 26 | static double getDegree(double radian); 27 | static double getRadian(double degree); 28 | 29 | static bool keepRange(double &num, double min, double max); 30 | }; 31 | 32 | template 33 | inline T Math::random(T min, T max) 34 | { 35 | double decimals = static_cast(rand()) / RAND_MAX; 36 | T result = (max - min)*decimals + min; 37 | return result; 38 | } 39 | 40 | template 41 | inline unsigned Math::max(T * data, unsigned num) 42 | { 43 | unsigned index = 0; 44 | T max = data[index]; 45 | for (unsigned i = 0; i < num; ++i) 46 | { 47 | if (data[index] > max) 48 | { 49 | max = data[index]; 50 | index = i; 51 | } 52 | } 53 | return index; 54 | } 55 | 56 | //long double operator ""_deg(long double degree) 57 | //{ 58 | // 59 | //} -------------------------------------------------------------------------------- /Mediator.cpp: -------------------------------------------------------------------------------- 1 | #include "Mediator.h" 2 | 3 | 4 | Mediator::Mediator(Component * problem, Component * algorithm) 5 | { 6 | _problem = problem; 7 | _algorithm = algorithm; 8 | } 9 | 10 | Mediator::~Mediator() 11 | { 12 | } 13 | 14 | bool Mediator::sendControl(Array3 &control) 15 | { 16 | _problem->recvData(control); 17 | return true; 18 | } 19 | 20 | bool Mediator::sendState(Array3 &state) 21 | { 22 | _algorithm->recvData(state); 23 | return true; 24 | } 25 | 26 | -------------------------------------------------------------------------------- /Mediator.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "Problem.h" 4 | #include "Algorithm.h" 5 | #include "Array3.h" 6 | #include "Component.h" 7 | 8 | class Mediator 9 | { 10 | public: 11 | Mediator(Component *problem, Component *algorithm); 12 | ~Mediator(); 13 | 14 | private: 15 | Component *_problem; 16 | Component *_algorithm; 17 | 18 | public: 19 | bool sendControl(Array3 &control); 20 | bool sendState(Array3 &state); 21 | }; 22 | 23 | -------------------------------------------------------------------------------- /PSO.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zpb1992/ReentryTrajectoryGuide/4f4b764896795ec206caabfa12889cd580132921/PSO.cpp -------------------------------------------------------------------------------- /PSO.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zpb1992/ReentryTrajectoryGuide/4f4b764896795ec206caabfa12889cd580132921/PSO.h -------------------------------------------------------------------------------- /Problem.cpp: -------------------------------------------------------------------------------- 1 | #include "Problem.h" 2 | 3 | 4 | 5 | Problem::Problem() 6 | { 7 | } 8 | 9 | 10 | Problem::~Problem() 11 | { 12 | } 13 | -------------------------------------------------------------------------------- /Problem.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "Array3.h" 4 | 5 | class Problem 6 | { 7 | public: 8 | Problem(); 9 | ~Problem(); 10 | 11 | public: 12 | virtual bool calculateState()=0; 13 | }; 14 | 15 | -------------------------------------------------------------------------------- /Reentry.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zpb1992/ReentryTrajectoryGuide/4f4b764896795ec206caabfa12889cd580132921/Reentry.cpp -------------------------------------------------------------------------------- /Reentry.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zpb1992/ReentryTrajectoryGuide/4f4b764896795ec206caabfa12889cd580132921/Reentry.h -------------------------------------------------------------------------------- /Star.cpp: -------------------------------------------------------------------------------- 1 | #include "Star.h" 2 | #include "json\json.h" 3 | #include 4 | #include"Math.h" 5 | 6 | Star::Star(std::string filename) :Configuration(filename) 7 | { 8 | readConfig(_fileName); 9 | } 10 | 11 | Star::~Star() 12 | { 13 | } 14 | 15 | bool Star::readConfig(std::string filename) 16 | { 17 | Json::Reader reader; 18 | std::ifstream ifs(filename); 19 | Json::Value root; 20 | reader.parse(ifs, root); 21 | 22 | _rotationW = 2.0*Math::PI / (24 * 3600); 23 | _radius = root[getKeyByVar(ToString(_radius))].asDouble(); 24 | _gravityAcc = root[getKeyByVar(ToString(_gravityAcc))].asDouble(); 25 | 26 | return true; 27 | } 28 | 29 | bool Star::writeConfig(std::string filename) 30 | { 31 | return false; 32 | } 33 | 34 | double Star::getGravityAcc(double radius) 35 | { 36 | return _radius*_radius*_gravityAcc / (radius*radius); 37 | } 38 | 39 | double Star::getRotationW() 40 | { 41 | return _rotationW; 42 | } 43 | 44 | double Star::getRadius() 45 | { 46 | return _radius; 47 | } 48 | -------------------------------------------------------------------------------- /Star.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zpb1992/ReentryTrajectoryGuide/4f4b764896795ec206caabfa12889cd580132921/Star.h -------------------------------------------------------------------------------- /conf/Atmosphere.json: -------------------------------------------------------------------------------- 1 | { 2 | "Density": 1.2258, 3 | "DensityHeight": 7254.26188 4 | } -------------------------------------------------------------------------------- /conf/CAV_L.json: -------------------------------------------------------------------------------- 1 | { 2 | "Mass":907.2, 3 | "S":0.4839, 4 | "R":0.1 5 | } -------------------------------------------------------------------------------- /conf/Earth.json: -------------------------------------------------------------------------------- 1 | { 2 | //"RotationW": 2, 3 | "Radius": 6371000, 4 | "GravityAcc": 9.80665 5 | } -------------------------------------------------------------------------------- /conf/PSO.json: -------------------------------------------------------------------------------- 1 | { 2 | "ParticleNum": 50, 3 | "ParticleDim": [ 20, 20, 1 ], 4 | "PositionScope": [ 5 | { 6 | "min": -80, 7 | "max": 80 8 | }, 9 | { 10 | "min ": -20, 11 | "max": 20 12 | }, 13 | { 14 | "min": 1000, 15 | "max": 3000 16 | } 17 | ], 18 | "VelcityScope": [ 19 | { 20 | "min": -50, 21 | "max": 50 22 | }, 23 | { 24 | "min ": -10, 25 | "max": 10 26 | }, 27 | { 28 | "min": -1000, 29 | "max": 1000 30 | } 31 | ], 32 | "Iterations": 200, 33 | "InertiaWeight": 2, 34 | "LearningFactor1": 2, 35 | "LearningFactor2": 2, 36 | 37 | // 归一化的参数中的角度是按弧度给的 38 | "FinalState": [ 6391000, 232, 37, 1000, 0, 0 ], 39 | // 6371000+20000 40 | "FinalStateWeights": [ 0.4438, 0.4438, 0.4438, 0.4438, 0, 0 ], 41 | "FinalStateNormalization":[100,0.01,0.01,10,0.01,0.01], 42 | "PathStateMax": [ 1000000, 500000, 6 ], 43 | "PathStateWeights": [ 0.2488, 0.2488, 0.2488 ], 44 | "PathStateNormalization":[100000,10000,1], 45 | "ControlWeights": [ 0.0762, 0.0762 ], 46 | "ControlNormalization":[100,100], 47 | "BalanceWeights": [ 0.0762, 0.0762 ], 48 | "BalanceNormalization":[100,100] 49 | } -------------------------------------------------------------------------------- /conf/Reentry.json: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zpb1992/ReentryTrajectoryGuide/4f4b764896795ec206caabfa12889cd580132921/conf/Reentry.json -------------------------------------------------------------------------------- /json/allocator.h: -------------------------------------------------------------------------------- 1 | // Copyright 2007-2010 Baptiste Lepilleur 2 | // Distributed under MIT license, or public domain if desired and 3 | // recognized in your jurisdiction. 4 | // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE 5 | 6 | #ifndef CPPTL_JSON_ALLOCATOR_H_INCLUDED 7 | #define CPPTL_JSON_ALLOCATOR_H_INCLUDED 8 | 9 | #include 10 | #include 11 | 12 | namespace Json { 13 | template 14 | class SecureAllocator { 15 | public: 16 | // Type definitions 17 | using value_type = T; 18 | using pointer = T*; 19 | using const_pointer = const T*; 20 | using reference = T&; 21 | using const_reference = const T&; 22 | using size_type = std::size_t; 23 | using difference_type = std::ptrdiff_t; 24 | 25 | /** 26 | * Allocate memory for N items using the standard allocator. 27 | */ 28 | pointer allocate(size_type n) { 29 | // allocate using "global operator new" 30 | return static_cast(::operator new(n * sizeof(T))); 31 | } 32 | 33 | /** 34 | * Release memory which was allocated for N items at pointer P. 35 | * 36 | * The memory block is filled with zeroes before being released. 37 | * The pointer argument is tagged as "volatile" to prevent the 38 | * compiler optimizing out this critical step. 39 | */ 40 | void deallocate(volatile pointer p, size_type n) { 41 | std::memset(p, 0, n * sizeof(T)); 42 | // free using "global operator delete" 43 | ::operator delete(p); 44 | } 45 | 46 | /** 47 | * Construct an item in-place at pointer P. 48 | */ 49 | template 50 | void construct(pointer p, Args&&... args) { 51 | // construct using "placement new" and "perfect forwarding" 52 | ::new (static_cast(p)) T(std::forward(args)...); 53 | } 54 | 55 | size_type max_size() const { 56 | return size_t(-1) / sizeof(T); 57 | } 58 | 59 | pointer address( reference x ) const { 60 | return std::addressof(x); 61 | } 62 | 63 | const_pointer address( const_reference x ) const { 64 | return std::addressof(x); 65 | } 66 | 67 | /** 68 | * Destroy an item in-place at pointer P. 69 | */ 70 | void destroy(pointer p) { 71 | // destroy using "explicit destructor" 72 | p->~T(); 73 | } 74 | 75 | // Boilerplate 76 | SecureAllocator() {} 77 | template SecureAllocator(const SecureAllocator&) {} 78 | template struct rebind { using other = SecureAllocator; }; 79 | }; 80 | 81 | 82 | template 83 | bool operator==(const SecureAllocator&, const SecureAllocator&) { 84 | return true; 85 | } 86 | 87 | template 88 | bool operator!=(const SecureAllocator&, const SecureAllocator&) { 89 | return false; 90 | } 91 | 92 | } //namespace Json 93 | 94 | #endif // CPPTL_JSON_ALLOCATOR_H_INCLUDED 95 | -------------------------------------------------------------------------------- /json/assertions.h: -------------------------------------------------------------------------------- 1 | // Copyright 2007-2010 Baptiste Lepilleur 2 | // Distributed under MIT license, or public domain if desired and 3 | // recognized in your jurisdiction. 4 | // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE 5 | 6 | #ifndef CPPTL_JSON_ASSERTIONS_H_INCLUDED 7 | #define CPPTL_JSON_ASSERTIONS_H_INCLUDED 8 | 9 | #include 10 | #include 11 | 12 | #if !defined(JSON_IS_AMALGAMATION) 13 | #include "config.h" 14 | #endif // if !defined(JSON_IS_AMALGAMATION) 15 | 16 | /** It should not be possible for a maliciously designed file to 17 | * cause an abort() or seg-fault, so these macros are used only 18 | * for pre-condition violations and internal logic errors. 19 | */ 20 | #if JSON_USE_EXCEPTION 21 | 22 | // @todo <= add detail about condition in exception 23 | # define JSON_ASSERT(condition) \ 24 | {if (!(condition)) {Json::throwLogicError( "assert json failed" );}} 25 | 26 | # define JSON_FAIL_MESSAGE(message) \ 27 | { \ 28 | JSONCPP_OSTRINGSTREAM oss; oss << message; \ 29 | Json::throwLogicError(oss.str()); \ 30 | abort(); \ 31 | } 32 | 33 | #else // JSON_USE_EXCEPTION 34 | 35 | # define JSON_ASSERT(condition) assert(condition) 36 | 37 | // The call to assert() will show the failure message in debug builds. In 38 | // release builds we abort, for a core-dump or debugger. 39 | # define JSON_FAIL_MESSAGE(message) \ 40 | { \ 41 | JSONCPP_OSTRINGSTREAM oss; oss << message; \ 42 | assert(false && oss.str().c_str()); \ 43 | abort(); \ 44 | } 45 | 46 | 47 | #endif 48 | 49 | #define JSON_ASSERT_MESSAGE(condition, message) \ 50 | if (!(condition)) { \ 51 | JSON_FAIL_MESSAGE(message); \ 52 | } 53 | 54 | #endif // CPPTL_JSON_ASSERTIONS_H_INCLUDED 55 | -------------------------------------------------------------------------------- /json/autolink.h: -------------------------------------------------------------------------------- 1 | // Copyright 2007-2010 Baptiste Lepilleur 2 | // Distributed under MIT license, or public domain if desired and 3 | // recognized in your jurisdiction. 4 | // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE 5 | 6 | #ifndef JSON_AUTOLINK_H_INCLUDED 7 | #define JSON_AUTOLINK_H_INCLUDED 8 | 9 | #include "config.h" 10 | 11 | #ifdef JSON_IN_CPPTL 12 | #include 13 | #endif 14 | 15 | #if !defined(JSON_NO_AUTOLINK) && !defined(JSON_DLL_BUILD) && \ 16 | !defined(JSON_IN_CPPTL) 17 | #define CPPTL_AUTOLINK_NAME "json" 18 | #undef CPPTL_AUTOLINK_DLL 19 | #ifdef JSON_DLL 20 | #define CPPTL_AUTOLINK_DLL 21 | #endif 22 | #include "autolink.h" 23 | #endif 24 | 25 | #endif // JSON_AUTOLINK_H_INCLUDED 26 | -------------------------------------------------------------------------------- /json/config.h: -------------------------------------------------------------------------------- 1 | // Copyright 2007-2010 Baptiste Lepilleur 2 | // Distributed under MIT license, or public domain if desired and 3 | // recognized in your jurisdiction. 4 | // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE 5 | 6 | #ifndef JSON_CONFIG_H_INCLUDED 7 | #define JSON_CONFIG_H_INCLUDED 8 | #include 9 | #include //typdef String 10 | 11 | /// If defined, indicates that json library is embedded in CppTL library. 12 | //# define JSON_IN_CPPTL 1 13 | 14 | /// If defined, indicates that json may leverage CppTL library 15 | //# define JSON_USE_CPPTL 1 16 | /// If defined, indicates that cpptl vector based map should be used instead of 17 | /// std::map 18 | /// as Value container. 19 | //# define JSON_USE_CPPTL_SMALLMAP 1 20 | 21 | // If non-zero, the library uses exceptions to report bad input instead of C 22 | // assertion macros. The default is to use exceptions. 23 | #ifndef JSON_USE_EXCEPTION 24 | #define JSON_USE_EXCEPTION 1 25 | #endif 26 | 27 | /// If defined, indicates that the source file is amalgated 28 | /// to prevent private header inclusion. 29 | /// Remarks: it is automatically defined in the generated amalgated header. 30 | // #define JSON_IS_AMALGAMATION 31 | 32 | #ifdef JSON_IN_CPPTL 33 | #include 34 | #ifndef JSON_USE_CPPTL 35 | #define JSON_USE_CPPTL 1 36 | #endif 37 | #endif 38 | 39 | #ifdef JSON_IN_CPPTL 40 | #define JSON_API CPPTL_API 41 | #elif defined(JSON_DLL_BUILD) 42 | #if defined(_MSC_VER) || defined(__MINGW32__) 43 | #define JSON_API __declspec(dllexport) 44 | #define JSONCPP_DISABLE_DLL_INTERFACE_WARNING 45 | #endif // if defined(_MSC_VER) 46 | #elif defined(JSON_DLL) 47 | #if defined(_MSC_VER) || defined(__MINGW32__) 48 | #define JSON_API __declspec(dllimport) 49 | #define JSONCPP_DISABLE_DLL_INTERFACE_WARNING 50 | #endif // if defined(_MSC_VER) 51 | #endif // ifdef JSON_IN_CPPTL 52 | #if !defined(JSON_API) 53 | #define JSON_API 54 | #endif 55 | 56 | // If JSON_NO_INT64 is defined, then Json only support C++ "int" type for 57 | // integer 58 | // Storages, and 64 bits integer support is disabled. 59 | // #define JSON_NO_INT64 1 60 | 61 | #if defined(_MSC_VER) // MSVC 62 | # if _MSC_VER <= 1200 // MSVC 6 63 | // Microsoft Visual Studio 6 only support conversion from __int64 to double 64 | // (no conversion from unsigned __int64). 65 | # define JSON_USE_INT64_DOUBLE_CONVERSION 1 66 | // Disable warning 4786 for VS6 caused by STL (identifier was truncated to '255' 67 | // characters in the debug information) 68 | // All projects I've ever seen with VS6 were using this globally (not bothering 69 | // with pragma push/pop). 70 | # pragma warning(disable : 4786) 71 | # endif // MSVC 6 72 | 73 | # if _MSC_VER >= 1500 // MSVC 2008 74 | /// Indicates that the following function is deprecated. 75 | # define JSONCPP_DEPRECATED(message) __declspec(deprecated(message)) 76 | # endif 77 | 78 | #endif // defined(_MSC_VER) 79 | 80 | // In c++11 the override keyword allows you to explicity define that a function 81 | // is intended to override the base-class version. This makes the code more 82 | // managable and fixes a set of common hard-to-find bugs. 83 | #if __cplusplus >= 201103L 84 | # define JSONCPP_OVERRIDE override 85 | #elif defined(_MSC_VER) && _MSC_VER > 1600 86 | # define JSONCPP_OVERRIDE override 87 | #else 88 | # define JSONCPP_OVERRIDE 89 | #endif 90 | 91 | #ifndef JSON_HAS_RVALUE_REFERENCES 92 | 93 | #if defined(_MSC_VER) && _MSC_VER >= 1600 // MSVC >= 2010 94 | #define JSON_HAS_RVALUE_REFERENCES 1 95 | #endif // MSVC >= 2010 96 | 97 | #ifdef __clang__ 98 | #if __has_feature(cxx_rvalue_references) 99 | #define JSON_HAS_RVALUE_REFERENCES 1 100 | #endif // has_feature 101 | 102 | #elif defined __GNUC__ // not clang (gcc comes later since clang emulates gcc) 103 | #if defined(__GXX_EXPERIMENTAL_CXX0X__) || (__cplusplus >= 201103L) 104 | #define JSON_HAS_RVALUE_REFERENCES 1 105 | #endif // GXX_EXPERIMENTAL 106 | 107 | #endif // __clang__ || __GNUC__ 108 | 109 | #endif // not defined JSON_HAS_RVALUE_REFERENCES 110 | 111 | #ifndef JSON_HAS_RVALUE_REFERENCES 112 | #define JSON_HAS_RVALUE_REFERENCES 0 113 | #endif 114 | 115 | #ifdef __clang__ 116 | #elif defined __GNUC__ // not clang (gcc comes later since clang emulates gcc) 117 | # if (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5)) 118 | # define JSONCPP_DEPRECATED(message) __attribute__ ((deprecated(message))) 119 | # elif (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1)) 120 | # define JSONCPP_DEPRECATED(message) __attribute__((__deprecated__)) 121 | # endif // GNUC version 122 | #endif // __clang__ || __GNUC__ 123 | 124 | #if !defined(JSONCPP_DEPRECATED) 125 | #define JSONCPP_DEPRECATED(message) 126 | #endif // if !defined(JSONCPP_DEPRECATED) 127 | 128 | #if __GNUC__ >= 6 129 | # define JSON_USE_INT64_DOUBLE_CONVERSION 1 130 | #endif 131 | 132 | #if !defined(JSON_IS_AMALGAMATION) 133 | 134 | # include "version.h" 135 | 136 | # if JSONCPP_USING_SECURE_MEMORY 137 | # include "allocator.h" //typedef Allocator 138 | # endif 139 | 140 | #endif // if !defined(JSON_IS_AMALGAMATION) 141 | 142 | namespace Json { 143 | typedef int Int; 144 | typedef unsigned int UInt; 145 | #if defined(JSON_NO_INT64) 146 | typedef int LargestInt; 147 | typedef unsigned int LargestUInt; 148 | #undef JSON_HAS_INT64 149 | #else // if defined(JSON_NO_INT64) 150 | // For Microsoft Visual use specific types as long long is not supported 151 | #if defined(_MSC_VER) // Microsoft Visual Studio 152 | typedef __int64 Int64; 153 | typedef unsigned __int64 UInt64; 154 | #else // if defined(_MSC_VER) // Other platforms, use long long 155 | typedef long long int Int64; 156 | typedef unsigned long long int UInt64; 157 | #endif // if defined(_MSC_VER) 158 | typedef Int64 LargestInt; 159 | typedef UInt64 LargestUInt; 160 | #define JSON_HAS_INT64 161 | #endif // if defined(JSON_NO_INT64) 162 | #if JSONCPP_USING_SECURE_MEMORY 163 | #define JSONCPP_STRING std::basic_string, Json::SecureAllocator > 164 | #define JSONCPP_OSTRINGSTREAM std::basic_ostringstream, Json::SecureAllocator > 165 | #define JSONCPP_OSTREAM std::basic_ostream> 166 | #define JSONCPP_ISTRINGSTREAM std::basic_istringstream, Json::SecureAllocator > 167 | #define JSONCPP_ISTREAM std::istream 168 | #else 169 | #define JSONCPP_STRING std::string 170 | #define JSONCPP_OSTRINGSTREAM std::ostringstream 171 | #define JSONCPP_OSTREAM std::ostream 172 | #define JSONCPP_ISTRINGSTREAM std::istringstream 173 | #define JSONCPP_ISTREAM std::istream 174 | #endif // if JSONCPP_USING_SECURE_MEMORY 175 | } // end namespace Json 176 | 177 | #endif // JSON_CONFIG_H_INCLUDED 178 | -------------------------------------------------------------------------------- /json/features.h: -------------------------------------------------------------------------------- 1 | // Copyright 2007-2010 Baptiste Lepilleur 2 | // Distributed under MIT license, or public domain if desired and 3 | // recognized in your jurisdiction. 4 | // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE 5 | 6 | #ifndef CPPTL_JSON_FEATURES_H_INCLUDED 7 | #define CPPTL_JSON_FEATURES_H_INCLUDED 8 | 9 | #if !defined(JSON_IS_AMALGAMATION) 10 | #include "forwards.h" 11 | #endif // if !defined(JSON_IS_AMALGAMATION) 12 | 13 | namespace Json { 14 | 15 | /** \brief Configuration passed to reader and writer. 16 | * This configuration object can be used to force the Reader or Writer 17 | * to behave in a standard conforming way. 18 | */ 19 | class JSON_API Features { 20 | public: 21 | /** \brief A configuration that allows all features and assumes all strings 22 | * are UTF-8. 23 | * - C & C++ comments are allowed 24 | * - Root object can be any JSON value 25 | * - Assumes Value strings are encoded in UTF-8 26 | */ 27 | static Features all(); 28 | 29 | /** \brief A configuration that is strictly compatible with the JSON 30 | * specification. 31 | * - Comments are forbidden. 32 | * - Root object must be either an array or an object value. 33 | * - Assumes Value strings are encoded in UTF-8 34 | */ 35 | static Features strictMode(); 36 | 37 | /** \brief Initialize the configuration like JsonConfig::allFeatures; 38 | */ 39 | Features(); 40 | 41 | /// \c true if comments are allowed. Default: \c true. 42 | bool allowComments_; 43 | 44 | /// \c true if root must be either an array or an object value. Default: \c 45 | /// false. 46 | bool strictRoot_; 47 | 48 | /// \c true if dropped null placeholders are allowed. Default: \c false. 49 | bool allowDroppedNullPlaceholders_; 50 | 51 | /// \c true if numeric object key are allowed. Default: \c false. 52 | bool allowNumericKeys_; 53 | }; 54 | 55 | } // namespace Json 56 | 57 | #endif // CPPTL_JSON_FEATURES_H_INCLUDED 58 | -------------------------------------------------------------------------------- /json/forwards.h: -------------------------------------------------------------------------------- 1 | // Copyright 2007-2010 Baptiste Lepilleur 2 | // Distributed under MIT license, or public domain if desired and 3 | // recognized in your jurisdiction. 4 | // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE 5 | 6 | #ifndef JSON_FORWARDS_H_INCLUDED 7 | #define JSON_FORWARDS_H_INCLUDED 8 | 9 | #if !defined(JSON_IS_AMALGAMATION) 10 | #include "config.h" 11 | #endif // if !defined(JSON_IS_AMALGAMATION) 12 | 13 | namespace Json { 14 | 15 | // writer.h 16 | class FastWriter; 17 | class StyledWriter; 18 | 19 | // reader.h 20 | class Reader; 21 | 22 | // features.h 23 | class Features; 24 | 25 | // value.h 26 | typedef unsigned int ArrayIndex; 27 | class StaticString; 28 | class Path; 29 | class PathArgument; 30 | class Value; 31 | class ValueIteratorBase; 32 | class ValueIterator; 33 | class ValueConstIterator; 34 | 35 | } // namespace Json 36 | 37 | #endif // JSON_FORWARDS_H_INCLUDED 38 | -------------------------------------------------------------------------------- /json/json.h: -------------------------------------------------------------------------------- 1 | // Copyright 2007-2010 Baptiste Lepilleur 2 | // Distributed under MIT license, or public domain if desired and 3 | // recognized in your jurisdiction. 4 | // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE 5 | 6 | #ifndef JSON_JSON_H_INCLUDED 7 | #define JSON_JSON_H_INCLUDED 8 | 9 | #include "autolink.h" 10 | #include "value.h" 11 | #include "reader.h" 12 | #include "writer.h" 13 | #include "features.h" 14 | 15 | #endif // JSON_JSON_H_INCLUDED 16 | -------------------------------------------------------------------------------- /json/reader.h: -------------------------------------------------------------------------------- 1 | // Copyright 2007-2010 Baptiste Lepilleur 2 | // Distributed under MIT license, or public domain if desired and 3 | // recognized in your jurisdiction. 4 | // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE 5 | 6 | #ifndef CPPTL_JSON_READER_H_INCLUDED 7 | #define CPPTL_JSON_READER_H_INCLUDED 8 | 9 | #if !defined(JSON_IS_AMALGAMATION) 10 | #include "features.h" 11 | #include "value.h" 12 | #endif // if !defined(JSON_IS_AMALGAMATION) 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | 19 | // Disable warning C4251: : needs to have dll-interface to 20 | // be used by... 21 | #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) 22 | #pragma warning(push) 23 | #pragma warning(disable : 4251) 24 | #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) 25 | 26 | namespace Json { 27 | 28 | /** \brief Unserialize a JSON document into a 29 | *Value. 30 | * 31 | * \deprecated Use CharReader and CharReaderBuilder. 32 | */ 33 | class JSON_API Reader { 34 | public: 35 | typedef char Char; 36 | typedef const Char* Location; 37 | 38 | /** \brief An error tagged with where in the JSON text it was encountered. 39 | * 40 | * The offsets give the [start, limit) range of bytes within the text. Note 41 | * that this is bytes, not codepoints. 42 | * 43 | */ 44 | struct StructuredError { 45 | ptrdiff_t offset_start; 46 | ptrdiff_t offset_limit; 47 | JSONCPP_STRING message; 48 | }; 49 | 50 | /** \brief Constructs a Reader allowing all features 51 | * for parsing. 52 | */ 53 | Reader(); 54 | 55 | /** \brief Constructs a Reader allowing the specified feature set 56 | * for parsing. 57 | */ 58 | Reader(const Features& features); 59 | 60 | /** \brief Read a Value from a JSON 61 | * document. 62 | * \param document UTF-8 encoded string containing the document to read. 63 | * \param root [out] Contains the root value of the document if it was 64 | * successfully parsed. 65 | * \param collectComments \c true to collect comment and allow writing them 66 | * back during 67 | * serialization, \c false to discard comments. 68 | * This parameter is ignored if 69 | * Features::allowComments_ 70 | * is \c false. 71 | * \return \c true if the document was successfully parsed, \c false if an 72 | * error occurred. 73 | */ 74 | bool 75 | parse(const std::string& document, Value& root, bool collectComments = true); 76 | 77 | /** \brief Read a Value from a JSON 78 | document. 79 | * \param beginDoc Pointer on the beginning of the UTF-8 encoded string of the 80 | document to read. 81 | * \param endDoc Pointer on the end of the UTF-8 encoded string of the 82 | document to read. 83 | * Must be >= beginDoc. 84 | * \param root [out] Contains the root value of the document if it was 85 | * successfully parsed. 86 | * \param collectComments \c true to collect comment and allow writing them 87 | back during 88 | * serialization, \c false to discard comments. 89 | * This parameter is ignored if 90 | Features::allowComments_ 91 | * is \c false. 92 | * \return \c true if the document was successfully parsed, \c false if an 93 | error occurred. 94 | */ 95 | bool parse(const char* beginDoc, 96 | const char* endDoc, 97 | Value& root, 98 | bool collectComments = true); 99 | 100 | /// \brief Parse from input stream. 101 | /// \see Json::operator>>(std::istream&, Json::Value&). 102 | bool parse(JSONCPP_ISTREAM& is, Value& root, bool collectComments = true); 103 | 104 | /** \brief Returns a user friendly string that list errors in the parsed 105 | * document. 106 | * \return Formatted error message with the list of errors with their location 107 | * in 108 | * the parsed document. An empty string is returned if no error 109 | * occurred 110 | * during parsing. 111 | * \deprecated Use getFormattedErrorMessages() instead (typo fix). 112 | */ 113 | JSONCPP_DEPRECATED("Use getFormattedErrorMessages() instead.") 114 | JSONCPP_STRING getFormatedErrorMessages() const; 115 | 116 | /** \brief Returns a user friendly string that list errors in the parsed 117 | * document. 118 | * \return Formatted error message with the list of errors with their location 119 | * in 120 | * the parsed document. An empty string is returned if no error 121 | * occurred 122 | * during parsing. 123 | */ 124 | JSONCPP_STRING getFormattedErrorMessages() const; 125 | 126 | /** \brief Returns a vector of structured erros encounted while parsing. 127 | * \return A (possibly empty) vector of StructuredError objects. Currently 128 | * only one error can be returned, but the caller should tolerate 129 | * multiple 130 | * errors. This can occur if the parser recovers from a non-fatal 131 | * parse error and then encounters additional errors. 132 | */ 133 | std::vector getStructuredErrors() const; 134 | 135 | /** \brief Add a semantic error message. 136 | * \param value JSON Value location associated with the error 137 | * \param message The error message. 138 | * \return \c true if the error was successfully added, \c false if the 139 | * Value offset exceeds the document size. 140 | */ 141 | bool pushError(const Value& value, const JSONCPP_STRING& message); 142 | 143 | /** \brief Add a semantic error message with extra context. 144 | * \param value JSON Value location associated with the error 145 | * \param message The error message. 146 | * \param extra Additional JSON Value location to contextualize the error 147 | * \return \c true if the error was successfully added, \c false if either 148 | * Value offset exceeds the document size. 149 | */ 150 | bool pushError(const Value& value, const JSONCPP_STRING& message, const Value& extra); 151 | 152 | /** \brief Return whether there are any errors. 153 | * \return \c true if there are no errors to report \c false if 154 | * errors have occurred. 155 | */ 156 | bool good() const; 157 | 158 | private: 159 | enum TokenType { 160 | tokenEndOfStream = 0, 161 | tokenObjectBegin, 162 | tokenObjectEnd, 163 | tokenArrayBegin, 164 | tokenArrayEnd, 165 | tokenString, 166 | tokenNumber, 167 | tokenTrue, 168 | tokenFalse, 169 | tokenNull, 170 | tokenArraySeparator, 171 | tokenMemberSeparator, 172 | tokenComment, 173 | tokenError 174 | }; 175 | 176 | class Token { 177 | public: 178 | TokenType type_; 179 | Location start_; 180 | Location end_; 181 | }; 182 | 183 | class ErrorInfo { 184 | public: 185 | Token token_; 186 | JSONCPP_STRING message_; 187 | Location extra_; 188 | }; 189 | 190 | typedef std::deque Errors; 191 | 192 | bool readToken(Token& token); 193 | void skipSpaces(); 194 | bool match(Location pattern, int patternLength); 195 | bool readComment(); 196 | bool readCStyleComment(); 197 | bool readCppStyleComment(); 198 | bool readString(); 199 | void readNumber(); 200 | bool readValue(); 201 | bool readObject(Token& token); 202 | bool readArray(Token& token); 203 | bool decodeNumber(Token& token); 204 | bool decodeNumber(Token& token, Value& decoded); 205 | bool decodeString(Token& token); 206 | bool decodeString(Token& token, JSONCPP_STRING& decoded); 207 | bool decodeDouble(Token& token); 208 | bool decodeDouble(Token& token, Value& decoded); 209 | bool decodeUnicodeCodePoint(Token& token, 210 | Location& current, 211 | Location end, 212 | unsigned int& unicode); 213 | bool decodeUnicodeEscapeSequence(Token& token, 214 | Location& current, 215 | Location end, 216 | unsigned int& unicode); 217 | bool addError(const JSONCPP_STRING& message, Token& token, Location extra = 0); 218 | bool recoverFromError(TokenType skipUntilToken); 219 | bool addErrorAndRecover(const JSONCPP_STRING& message, 220 | Token& token, 221 | TokenType skipUntilToken); 222 | void skipUntilSpace(); 223 | Value& currentValue(); 224 | Char getNextChar(); 225 | void 226 | getLocationLineAndColumn(Location location, int& line, int& column) const; 227 | JSONCPP_STRING getLocationLineAndColumn(Location location) const; 228 | void addComment(Location begin, Location end, CommentPlacement placement); 229 | void skipCommentTokens(Token& token); 230 | 231 | typedef std::stack Nodes; 232 | Nodes nodes_; 233 | Errors errors_; 234 | JSONCPP_STRING document_; 235 | Location begin_; 236 | Location end_; 237 | Location current_; 238 | Location lastValueEnd_; 239 | Value* lastValue_; 240 | JSONCPP_STRING commentsBefore_; 241 | Features features_; 242 | bool collectComments_; 243 | }; // Reader 244 | 245 | /** Interface for reading JSON from a char array. 246 | */ 247 | class JSON_API CharReader { 248 | public: 249 | virtual ~CharReader() {} 250 | /** \brief Read a Value from a JSON 251 | document. 252 | * The document must be a UTF-8 encoded string containing the document to read. 253 | * 254 | * \param beginDoc Pointer on the beginning of the UTF-8 encoded string of the 255 | document to read. 256 | * \param endDoc Pointer on the end of the UTF-8 encoded string of the 257 | document to read. 258 | * Must be >= beginDoc. 259 | * \param root [out] Contains the root value of the document if it was 260 | * successfully parsed. 261 | * \param errs [out] Formatted error messages (if not NULL) 262 | * a user friendly string that lists errors in the parsed 263 | * document. 264 | * \return \c true if the document was successfully parsed, \c false if an 265 | error occurred. 266 | */ 267 | virtual bool parse( 268 | char const* beginDoc, char const* endDoc, 269 | Value* root, JSONCPP_STRING* errs) = 0; 270 | 271 | class JSON_API Factory { 272 | public: 273 | virtual ~Factory() {} 274 | /** \brief Allocate a CharReader via operator new(). 275 | * \throw std::exception if something goes wrong (e.g. invalid settings) 276 | */ 277 | virtual CharReader* newCharReader() const = 0; 278 | }; // Factory 279 | }; // CharReader 280 | 281 | /** \brief Build a CharReader implementation. 282 | 283 | Usage: 284 | \code 285 | using namespace Json; 286 | CharReaderBuilder builder; 287 | builder["collectComments"] = false; 288 | Value value; 289 | JSONCPP_STRING errs; 290 | bool ok = parseFromStream(builder, std::cin, &value, &errs); 291 | \endcode 292 | */ 293 | class JSON_API CharReaderBuilder : public CharReader::Factory { 294 | public: 295 | // Note: We use a Json::Value so that we can add data-members to this class 296 | // without a major version bump. 297 | /** Configuration of this builder. 298 | These are case-sensitive. 299 | Available settings (case-sensitive): 300 | - `"collectComments": false or true` 301 | - true to collect comment and allow writing them 302 | back during serialization, false to discard comments. 303 | This parameter is ignored if allowComments is false. 304 | - `"allowComments": false or true` 305 | - true if comments are allowed. 306 | - `"strictRoot": false or true` 307 | - true if root must be either an array or an object value 308 | - `"allowDroppedNullPlaceholders": false or true` 309 | - true if dropped null placeholders are allowed. (See StreamWriterBuilder.) 310 | - `"allowNumericKeys": false or true` 311 | - true if numeric object keys are allowed. 312 | - `"allowSingleQuotes": false or true` 313 | - true if '' are allowed for strings (both keys and values) 314 | - `"stackLimit": integer` 315 | - Exceeding stackLimit (recursive depth of `readValue()`) will 316 | cause an exception. 317 | - This is a security issue (seg-faults caused by deeply nested JSON), 318 | so the default is low. 319 | - `"failIfExtra": false or true` 320 | - If true, `parse()` returns false when extra non-whitespace trails 321 | the JSON value in the input string. 322 | - `"rejectDupKeys": false or true` 323 | - If true, `parse()` returns false when a key is duplicated within an object. 324 | - `"allowSpecialFloats": false or true` 325 | - If true, special float values (NaNs and infinities) are allowed 326 | and their values are lossfree restorable. 327 | 328 | You can examine 'settings_` yourself 329 | to see the defaults. You can also write and read them just like any 330 | JSON Value. 331 | \sa setDefaults() 332 | */ 333 | Json::Value settings_; 334 | 335 | CharReaderBuilder(); 336 | ~CharReaderBuilder() JSONCPP_OVERRIDE; 337 | 338 | CharReader* newCharReader() const JSONCPP_OVERRIDE; 339 | 340 | /** \return true if 'settings' are legal and consistent; 341 | * otherwise, indicate bad settings via 'invalid'. 342 | */ 343 | bool validate(Json::Value* invalid) const; 344 | 345 | /** A simple way to update a specific setting. 346 | */ 347 | Value& operator[](JSONCPP_STRING key); 348 | 349 | /** Called by ctor, but you can use this to reset settings_. 350 | * \pre 'settings' != NULL (but Json::null is fine) 351 | * \remark Defaults: 352 | * \snippet src/lib_json/json_reader.cpp CharReaderBuilderDefaults 353 | */ 354 | static void setDefaults(Json::Value* settings); 355 | /** Same as old Features::strictMode(). 356 | * \pre 'settings' != NULL (but Json::null is fine) 357 | * \remark Defaults: 358 | * \snippet src/lib_json/json_reader.cpp CharReaderBuilderStrictMode 359 | */ 360 | static void strictMode(Json::Value* settings); 361 | }; 362 | 363 | /** Consume entire stream and use its begin/end. 364 | * Someday we might have a real StreamReader, but for now this 365 | * is convenient. 366 | */ 367 | bool JSON_API parseFromStream( 368 | CharReader::Factory const&, 369 | JSONCPP_ISTREAM&, 370 | Value* root, std::string* errs); 371 | 372 | /** \brief Read from 'sin' into 'root'. 373 | 374 | Always keep comments from the input JSON. 375 | 376 | This can be used to read a file into a particular sub-object. 377 | For example: 378 | \code 379 | Json::Value root; 380 | cin >> root["dir"]["file"]; 381 | cout << root; 382 | \endcode 383 | Result: 384 | \verbatim 385 | { 386 | "dir": { 387 | "file": { 388 | // The input stream JSON would be nested here. 389 | } 390 | } 391 | } 392 | \endverbatim 393 | \throw std::exception on parse error. 394 | \see Json::operator<<() 395 | */ 396 | JSON_API JSONCPP_ISTREAM& operator>>(JSONCPP_ISTREAM&, Value&); 397 | 398 | } // namespace Json 399 | 400 | #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) 401 | #pragma warning(pop) 402 | #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) 403 | 404 | #endif // CPPTL_JSON_READER_H_INCLUDED 405 | -------------------------------------------------------------------------------- /json/value.h: -------------------------------------------------------------------------------- 1 | // Copyright 2007-2010 Baptiste Lepilleur 2 | // Distributed under MIT license, or public domain if desired and 3 | // recognized in your jurisdiction. 4 | // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE 5 | 6 | #ifndef CPPTL_JSON_H_INCLUDED 7 | #define CPPTL_JSON_H_INCLUDED 8 | 9 | #if !defined(JSON_IS_AMALGAMATION) 10 | #include "forwards.h" 11 | #endif // if !defined(JSON_IS_AMALGAMATION) 12 | #include 13 | #include 14 | #include 15 | 16 | #ifndef JSON_USE_CPPTL_SMALLMAP 17 | #include 18 | #else 19 | #include 20 | #endif 21 | #ifdef JSON_USE_CPPTL 22 | #include 23 | #endif 24 | 25 | //Conditional NORETURN attribute on the throw functions would: 26 | // a) suppress false positives from static code analysis 27 | // b) possibly improve optimization opportunities. 28 | #if !defined(JSONCPP_NORETURN) 29 | # if defined(_MSC_VER) 30 | # define JSONCPP_NORETURN __declspec(noreturn) 31 | # elif defined(__GNUC__) 32 | # define JSONCPP_NORETURN __attribute__ ((__noreturn__)) 33 | # else 34 | # define JSONCPP_NORETURN 35 | # endif 36 | #endif 37 | 38 | // Disable warning C4251: : needs to have dll-interface to 39 | // be used by... 40 | #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) 41 | #pragma warning(push) 42 | #pragma warning(disable : 4251) 43 | #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) 44 | 45 | /** \brief JSON (JavaScript Object Notation). 46 | */ 47 | namespace Json { 48 | 49 | /** Base class for all exceptions we throw. 50 | * 51 | * We use nothing but these internally. Of course, STL can throw others. 52 | */ 53 | class JSON_API Exception : public std::exception { 54 | public: 55 | Exception(JSONCPP_STRING const& msg); 56 | ~Exception() throw() JSONCPP_OVERRIDE; 57 | char const* what() const throw() JSONCPP_OVERRIDE; 58 | protected: 59 | JSONCPP_STRING msg_; 60 | }; 61 | 62 | /** Exceptions which the user cannot easily avoid. 63 | * 64 | * E.g. out-of-memory (when we use malloc), stack-overflow, malicious input 65 | * 66 | * \remark derived from Json::Exception 67 | */ 68 | class JSON_API RuntimeError : public Exception { 69 | public: 70 | RuntimeError(JSONCPP_STRING const& msg); 71 | }; 72 | 73 | /** Exceptions thrown by JSON_ASSERT/JSON_FAIL macros. 74 | * 75 | * These are precondition-violations (user bugs) and internal errors (our bugs). 76 | * 77 | * \remark derived from Json::Exception 78 | */ 79 | class JSON_API LogicError : public Exception { 80 | public: 81 | LogicError(JSONCPP_STRING const& msg); 82 | }; 83 | 84 | /// used internally 85 | JSONCPP_NORETURN void throwRuntimeError(JSONCPP_STRING const& msg); 86 | /// used internally 87 | JSONCPP_NORETURN void throwLogicError(JSONCPP_STRING const& msg); 88 | 89 | /** \brief Type of the value held by a Value object. 90 | */ 91 | enum ValueType { 92 | nullValue = 0, ///< 'null' value 93 | intValue, ///< signed integer value 94 | uintValue, ///< unsigned integer value 95 | realValue, ///< double value 96 | stringValue, ///< UTF-8 string value 97 | booleanValue, ///< bool value 98 | arrayValue, ///< array value (ordered list) 99 | objectValue ///< object value (collection of name/value pairs). 100 | }; 101 | 102 | enum CommentPlacement { 103 | commentBefore = 0, ///< a comment placed on the line before a value 104 | commentAfterOnSameLine, ///< a comment just after a value on the same line 105 | commentAfter, ///< a comment on the line after a value (only make sense for 106 | /// root value) 107 | numberOfCommentPlacement 108 | }; 109 | 110 | //# ifdef JSON_USE_CPPTL 111 | // typedef CppTL::AnyEnumerator EnumMemberNames; 112 | // typedef CppTL::AnyEnumerator EnumValues; 113 | //# endif 114 | 115 | /** \brief Lightweight wrapper to tag static string. 116 | * 117 | * Value constructor and objectValue member assignement takes advantage of the 118 | * StaticString and avoid the cost of string duplication when storing the 119 | * string or the member name. 120 | * 121 | * Example of usage: 122 | * \code 123 | * Json::Value aValue( StaticString("some text") ); 124 | * Json::Value object; 125 | * static const StaticString code("code"); 126 | * object[code] = 1234; 127 | * \endcode 128 | */ 129 | class JSON_API StaticString { 130 | public: 131 | explicit StaticString(const char* czstring) : c_str_(czstring) {} 132 | 133 | operator const char*() const { return c_str_; } 134 | 135 | const char* c_str() const { return c_str_; } 136 | 137 | private: 138 | const char* c_str_; 139 | }; 140 | 141 | /** \brief Represents a JSON value. 142 | * 143 | * This class is a discriminated union wrapper that can represents a: 144 | * - signed integer [range: Value::minInt - Value::maxInt] 145 | * - unsigned integer (range: 0 - Value::maxUInt) 146 | * - double 147 | * - UTF-8 string 148 | * - boolean 149 | * - 'null' 150 | * - an ordered list of Value 151 | * - collection of name/value pairs (javascript object) 152 | * 153 | * The type of the held value is represented by a #ValueType and 154 | * can be obtained using type(). 155 | * 156 | * Values of an #objectValue or #arrayValue can be accessed using operator[]() 157 | * methods. 158 | * Non-const methods will automatically create the a #nullValue element 159 | * if it does not exist. 160 | * The sequence of an #arrayValue will be automatically resized and initialized 161 | * with #nullValue. resize() can be used to enlarge or truncate an #arrayValue. 162 | * 163 | * The get() methods can be used to obtain default value in the case the 164 | * required element does not exist. 165 | * 166 | * It is possible to iterate over the list of a #objectValue values using 167 | * the getMemberNames() method. 168 | * 169 | * \note #Value string-length fit in size_t, but keys must be < 2^30. 170 | * (The reason is an implementation detail.) A #CharReader will raise an 171 | * exception if a bound is exceeded to avoid security holes in your app, 172 | * but the Value API does *not* check bounds. That is the responsibility 173 | * of the caller. 174 | */ 175 | class JSON_API Value { 176 | friend class ValueIteratorBase; 177 | public: 178 | typedef std::vector Members; 179 | typedef ValueIterator iterator; 180 | typedef ValueConstIterator const_iterator; 181 | typedef Json::UInt UInt; 182 | typedef Json::Int Int; 183 | #if defined(JSON_HAS_INT64) 184 | typedef Json::UInt64 UInt64; 185 | typedef Json::Int64 Int64; 186 | #endif // defined(JSON_HAS_INT64) 187 | typedef Json::LargestInt LargestInt; 188 | typedef Json::LargestUInt LargestUInt; 189 | typedef Json::ArrayIndex ArrayIndex; 190 | 191 | static const Value& null; ///< We regret this reference to a global instance; prefer the simpler Value(). 192 | static const Value& nullRef; ///< just a kludge for binary-compatibility; same as null 193 | static Value const& nullSingleton(); ///< Prefer this to null or nullRef. 194 | 195 | /// Minimum signed integer value that can be stored in a Json::Value. 196 | static const LargestInt minLargestInt; 197 | /// Maximum signed integer value that can be stored in a Json::Value. 198 | static const LargestInt maxLargestInt; 199 | /// Maximum unsigned integer value that can be stored in a Json::Value. 200 | static const LargestUInt maxLargestUInt; 201 | 202 | /// Minimum signed int value that can be stored in a Json::Value. 203 | static const Int minInt; 204 | /// Maximum signed int value that can be stored in a Json::Value. 205 | static const Int maxInt; 206 | /// Maximum unsigned int value that can be stored in a Json::Value. 207 | static const UInt maxUInt; 208 | 209 | #if defined(JSON_HAS_INT64) 210 | /// Minimum signed 64 bits int value that can be stored in a Json::Value. 211 | static const Int64 minInt64; 212 | /// Maximum signed 64 bits int value that can be stored in a Json::Value. 213 | static const Int64 maxInt64; 214 | /// Maximum unsigned 64 bits int value that can be stored in a Json::Value. 215 | static const UInt64 maxUInt64; 216 | #endif // defined(JSON_HAS_INT64) 217 | 218 | private: 219 | #ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION 220 | class CZString { 221 | public: 222 | enum DuplicationPolicy { 223 | noDuplication = 0, 224 | duplicate, 225 | duplicateOnCopy 226 | }; 227 | CZString(ArrayIndex index); 228 | CZString(char const* str, unsigned length, DuplicationPolicy allocate); 229 | CZString(CZString const& other); 230 | #if JSON_HAS_RVALUE_REFERENCES 231 | CZString(CZString&& other); 232 | #endif 233 | ~CZString(); 234 | CZString& operator=(CZString other); 235 | bool operator<(CZString const& other) const; 236 | bool operator==(CZString const& other) const; 237 | ArrayIndex index() const; 238 | //const char* c_str() const; ///< \deprecated 239 | char const* data() const; 240 | unsigned length() const; 241 | bool isStaticString() const; 242 | 243 | private: 244 | void swap(CZString& other); 245 | 246 | struct StringStorage { 247 | unsigned policy_: 2; 248 | unsigned length_: 30; // 1GB max 249 | }; 250 | 251 | char const* cstr_; // actually, a prefixed string, unless policy is noDup 252 | union { 253 | ArrayIndex index_; 254 | StringStorage storage_; 255 | }; 256 | }; 257 | 258 | public: 259 | #ifndef JSON_USE_CPPTL_SMALLMAP 260 | typedef std::map ObjectValues; 261 | #else 262 | typedef CppTL::SmallMap ObjectValues; 263 | #endif // ifndef JSON_USE_CPPTL_SMALLMAP 264 | #endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION 265 | 266 | public: 267 | /** \brief Create a default Value of the given type. 268 | 269 | This is a very useful constructor. 270 | To create an empty array, pass arrayValue. 271 | To create an empty object, pass objectValue. 272 | Another Value can then be set to this one by assignment. 273 | This is useful since clear() and resize() will not alter types. 274 | 275 | Examples: 276 | \code 277 | Json::Value null_value; // null 278 | Json::Value arr_value(Json::arrayValue); // [] 279 | Json::Value obj_value(Json::objectValue); // {} 280 | \endcode 281 | */ 282 | Value(ValueType type = nullValue); 283 | Value(Int value); 284 | Value(UInt value); 285 | #if defined(JSON_HAS_INT64) 286 | Value(Int64 value); 287 | Value(UInt64 value); 288 | #endif // if defined(JSON_HAS_INT64) 289 | Value(double value); 290 | Value(const char* value); ///< Copy til first 0. (NULL causes to seg-fault.) 291 | Value(const char* begin, const char* end); ///< Copy all, incl zeroes. 292 | /** \brief Constructs a value from a static string. 293 | 294 | * Like other value string constructor but do not duplicate the string for 295 | * internal storage. The given string must remain alive after the call to this 296 | * constructor. 297 | * \note This works only for null-terminated strings. (We cannot change the 298 | * size of this class, so we have nowhere to store the length, 299 | * which might be computed later for various operations.) 300 | * 301 | * Example of usage: 302 | * \code 303 | * static StaticString foo("some text"); 304 | * Json::Value aValue(foo); 305 | * \endcode 306 | */ 307 | Value(const StaticString& value); 308 | Value(const JSONCPP_STRING& value); ///< Copy data() til size(). Embedded zeroes too. 309 | #ifdef JSON_USE_CPPTL 310 | Value(const CppTL::ConstString& value); 311 | #endif 312 | Value(bool value); 313 | /// Deep copy. 314 | Value(const Value& other); 315 | #if JSON_HAS_RVALUE_REFERENCES 316 | /// Move constructor 317 | Value(Value&& other); 318 | #endif 319 | ~Value(); 320 | 321 | /// Deep copy, then swap(other). 322 | /// \note Over-write existing comments. To preserve comments, use #swapPayload(). 323 | Value& operator=(Value other); 324 | /// Swap everything. 325 | void swap(Value& other); 326 | /// Swap values but leave comments and source offsets in place. 327 | void swapPayload(Value& other); 328 | 329 | ValueType type() const; 330 | 331 | /// Compare payload only, not comments etc. 332 | bool operator<(const Value& other) const; 333 | bool operator<=(const Value& other) const; 334 | bool operator>=(const Value& other) const; 335 | bool operator>(const Value& other) const; 336 | bool operator==(const Value& other) const; 337 | bool operator!=(const Value& other) const; 338 | int compare(const Value& other) const; 339 | 340 | const char* asCString() const; ///< Embedded zeroes could cause you trouble! 341 | #if JSONCPP_USING_SECURE_MEMORY 342 | unsigned getCStringLength() const; //Allows you to understand the length of the CString 343 | #endif 344 | JSONCPP_STRING asString() const; ///< Embedded zeroes are possible. 345 | /** Get raw char* of string-value. 346 | * \return false if !string. (Seg-fault if str or end are NULL.) 347 | */ 348 | bool getString( 349 | char const** begin, char const** end) const; 350 | #ifdef JSON_USE_CPPTL 351 | CppTL::ConstString asConstString() const; 352 | #endif 353 | Int asInt() const; 354 | UInt asUInt() const; 355 | #if defined(JSON_HAS_INT64) 356 | Int64 asInt64() const; 357 | UInt64 asUInt64() const; 358 | #endif // if defined(JSON_HAS_INT64) 359 | LargestInt asLargestInt() const; 360 | LargestUInt asLargestUInt() const; 361 | float asFloat() const; 362 | double asDouble() const; 363 | bool asBool() const; 364 | 365 | bool isNull() const; 366 | bool isBool() const; 367 | bool isInt() const; 368 | bool isInt64() const; 369 | bool isUInt() const; 370 | bool isUInt64() const; 371 | bool isIntegral() const; 372 | bool isDouble() const; 373 | bool isNumeric() const; 374 | bool isString() const; 375 | bool isArray() const; 376 | bool isObject() const; 377 | 378 | bool isConvertibleTo(ValueType other) const; 379 | 380 | /// Number of values in array or object 381 | ArrayIndex size() const; 382 | 383 | /// \brief Return true if empty array, empty object, or null; 384 | /// otherwise, false. 385 | bool empty() const; 386 | 387 | /// Return isNull() 388 | bool operator!() const; 389 | 390 | /// Remove all object members and array elements. 391 | /// \pre type() is arrayValue, objectValue, or nullValue 392 | /// \post type() is unchanged 393 | void clear(); 394 | 395 | /// Resize the array to size elements. 396 | /// New elements are initialized to null. 397 | /// May only be called on nullValue or arrayValue. 398 | /// \pre type() is arrayValue or nullValue 399 | /// \post type() is arrayValue 400 | void resize(ArrayIndex size); 401 | 402 | /// Access an array element (zero based index ). 403 | /// If the array contains less than index element, then null value are 404 | /// inserted 405 | /// in the array so that its size is index+1. 406 | /// (You may need to say 'value[0u]' to get your compiler to distinguish 407 | /// this from the operator[] which takes a string.) 408 | Value& operator[](ArrayIndex index); 409 | 410 | /// Access an array element (zero based index ). 411 | /// If the array contains less than index element, then null value are 412 | /// inserted 413 | /// in the array so that its size is index+1. 414 | /// (You may need to say 'value[0u]' to get your compiler to distinguish 415 | /// this from the operator[] which takes a string.) 416 | Value& operator[](int index); 417 | 418 | /// Access an array element (zero based index ) 419 | /// (You may need to say 'value[0u]' to get your compiler to distinguish 420 | /// this from the operator[] which takes a string.) 421 | const Value& operator[](ArrayIndex index) const; 422 | 423 | /// Access an array element (zero based index ) 424 | /// (You may need to say 'value[0u]' to get your compiler to distinguish 425 | /// this from the operator[] which takes a string.) 426 | const Value& operator[](int index) const; 427 | 428 | /// If the array contains at least index+1 elements, returns the element 429 | /// value, 430 | /// otherwise returns defaultValue. 431 | Value get(ArrayIndex index, const Value& defaultValue) const; 432 | /// Return true if index < size(). 433 | bool isValidIndex(ArrayIndex index) const; 434 | /// \brief Append value to array at the end. 435 | /// 436 | /// Equivalent to jsonvalue[jsonvalue.size()] = value; 437 | Value& append(const Value& value); 438 | 439 | /// Access an object value by name, create a null member if it does not exist. 440 | /// \note Because of our implementation, keys are limited to 2^30 -1 chars. 441 | /// Exceeding that will cause an exception. 442 | Value& operator[](const char* key); 443 | /// Access an object value by name, returns null if there is no member with 444 | /// that name. 445 | const Value& operator[](const char* key) const; 446 | /// Access an object value by name, create a null member if it does not exist. 447 | /// \param key may contain embedded nulls. 448 | Value& operator[](const JSONCPP_STRING& key); 449 | /// Access an object value by name, returns null if there is no member with 450 | /// that name. 451 | /// \param key may contain embedded nulls. 452 | const Value& operator[](const JSONCPP_STRING& key) const; 453 | /** \brief Access an object value by name, create a null member if it does not 454 | exist. 455 | 456 | * If the object has no entry for that name, then the member name used to store 457 | * the new entry is not duplicated. 458 | * Example of use: 459 | * \code 460 | * Json::Value object; 461 | * static const StaticString code("code"); 462 | * object[code] = 1234; 463 | * \endcode 464 | */ 465 | Value& operator[](const StaticString& key); 466 | #ifdef JSON_USE_CPPTL 467 | /// Access an object value by name, create a null member if it does not exist. 468 | Value& operator[](const CppTL::ConstString& key); 469 | /// Access an object value by name, returns null if there is no member with 470 | /// that name. 471 | const Value& operator[](const CppTL::ConstString& key) const; 472 | #endif 473 | /// Return the member named key if it exist, defaultValue otherwise. 474 | /// \note deep copy 475 | Value get(const char* key, const Value& defaultValue) const; 476 | /// Return the member named key if it exist, defaultValue otherwise. 477 | /// \note deep copy 478 | /// \note key may contain embedded nulls. 479 | Value get(const char* begin, const char* end, const Value& defaultValue) const; 480 | /// Return the member named key if it exist, defaultValue otherwise. 481 | /// \note deep copy 482 | /// \param key may contain embedded nulls. 483 | Value get(const JSONCPP_STRING& key, const Value& defaultValue) const; 484 | #ifdef JSON_USE_CPPTL 485 | /// Return the member named key if it exist, defaultValue otherwise. 486 | /// \note deep copy 487 | Value get(const CppTL::ConstString& key, const Value& defaultValue) const; 488 | #endif 489 | /// Most general and efficient version of isMember()const, get()const, 490 | /// and operator[]const 491 | /// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30 492 | Value const* find(char const* begin, char const* end) const; 493 | /// Most general and efficient version of object-mutators. 494 | /// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30 495 | /// \return non-zero, but JSON_ASSERT if this is neither object nor nullValue. 496 | Value const* demand(char const* begin, char const* end); 497 | /// \brief Remove and return the named member. 498 | /// 499 | /// Do nothing if it did not exist. 500 | /// \return the removed Value, or null. 501 | /// \pre type() is objectValue or nullValue 502 | /// \post type() is unchanged 503 | /// \deprecated 504 | Value removeMember(const char* key); 505 | /// Same as removeMember(const char*) 506 | /// \param key may contain embedded nulls. 507 | /// \deprecated 508 | Value removeMember(const JSONCPP_STRING& key); 509 | /// Same as removeMember(const char* begin, const char* end, Value* removed), 510 | /// but 'key' is null-terminated. 511 | bool removeMember(const char* key, Value* removed); 512 | /** \brief Remove the named map member. 513 | 514 | Update 'removed' iff removed. 515 | \param key may contain embedded nulls. 516 | \return true iff removed (no exceptions) 517 | */ 518 | bool removeMember(JSONCPP_STRING const& key, Value* removed); 519 | /// Same as removeMember(JSONCPP_STRING const& key, Value* removed) 520 | bool removeMember(const char* begin, const char* end, Value* removed); 521 | /** \brief Remove the indexed array element. 522 | 523 | O(n) expensive operations. 524 | Update 'removed' iff removed. 525 | \return true iff removed (no exceptions) 526 | */ 527 | bool removeIndex(ArrayIndex i, Value* removed); 528 | 529 | /// Return true if the object has a member named key. 530 | /// \note 'key' must be null-terminated. 531 | bool isMember(const char* key) const; 532 | /// Return true if the object has a member named key. 533 | /// \param key may contain embedded nulls. 534 | bool isMember(const JSONCPP_STRING& key) const; 535 | /// Same as isMember(JSONCPP_STRING const& key)const 536 | bool isMember(const char* begin, const char* end) const; 537 | #ifdef JSON_USE_CPPTL 538 | /// Return true if the object has a member named key. 539 | bool isMember(const CppTL::ConstString& key) const; 540 | #endif 541 | 542 | /// \brief Return a list of the member names. 543 | /// 544 | /// If null, return an empty list. 545 | /// \pre type() is objectValue or nullValue 546 | /// \post if type() was nullValue, it remains nullValue 547 | Members getMemberNames() const; 548 | 549 | //# ifdef JSON_USE_CPPTL 550 | // EnumMemberNames enumMemberNames() const; 551 | // EnumValues enumValues() const; 552 | //# endif 553 | 554 | /// \deprecated Always pass len. 555 | JSONCPP_DEPRECATED("Use setComment(JSONCPP_STRING const&) instead.") 556 | void setComment(const char* comment, CommentPlacement placement); 557 | /// Comments must be //... or /* ... */ 558 | void setComment(const char* comment, size_t len, CommentPlacement placement); 559 | /// Comments must be //... or /* ... */ 560 | void setComment(const JSONCPP_STRING& comment, CommentPlacement placement); 561 | bool hasComment(CommentPlacement placement) const; 562 | /// Include delimiters and embedded newlines. 563 | JSONCPP_STRING getComment(CommentPlacement placement) const; 564 | 565 | JSONCPP_STRING toStyledString() const; 566 | 567 | const_iterator begin() const; 568 | const_iterator end() const; 569 | 570 | iterator begin(); 571 | iterator end(); 572 | 573 | // Accessors for the [start, limit) range of bytes within the JSON text from 574 | // which this value was parsed, if any. 575 | void setOffsetStart(ptrdiff_t start); 576 | void setOffsetLimit(ptrdiff_t limit); 577 | ptrdiff_t getOffsetStart() const; 578 | ptrdiff_t getOffsetLimit() const; 579 | 580 | private: 581 | void initBasic(ValueType type, bool allocated = false); 582 | 583 | Value& resolveReference(const char* key); 584 | Value& resolveReference(const char* key, const char* end); 585 | 586 | struct CommentInfo { 587 | CommentInfo(); 588 | ~CommentInfo(); 589 | 590 | void setComment(const char* text, size_t len); 591 | 592 | char* comment_; 593 | }; 594 | 595 | // struct MemberNamesTransform 596 | //{ 597 | // typedef const char *result_type; 598 | // const char *operator()( const CZString &name ) const 599 | // { 600 | // return name.c_str(); 601 | // } 602 | //}; 603 | 604 | union ValueHolder { 605 | LargestInt int_; 606 | LargestUInt uint_; 607 | double real_; 608 | bool bool_; 609 | char* string_; // actually ptr to unsigned, followed by str, unless !allocated_ 610 | ObjectValues* map_; 611 | } value_; 612 | ValueType type_ : 8; 613 | unsigned int allocated_ : 1; // Notes: if declared as bool, bitfield is useless. 614 | // If not allocated_, string_ must be null-terminated. 615 | CommentInfo* comments_; 616 | 617 | // [start, limit) byte offsets in the source JSON text from which this Value 618 | // was extracted. 619 | ptrdiff_t start_; 620 | ptrdiff_t limit_; 621 | }; 622 | 623 | /** \brief Experimental and untested: represents an element of the "path" to 624 | * access a node. 625 | */ 626 | class JSON_API PathArgument { 627 | public: 628 | friend class Path; 629 | 630 | PathArgument(); 631 | PathArgument(ArrayIndex index); 632 | PathArgument(const char* key); 633 | PathArgument(const JSONCPP_STRING& key); 634 | 635 | private: 636 | enum Kind { 637 | kindNone = 0, 638 | kindIndex, 639 | kindKey 640 | }; 641 | JSONCPP_STRING key_; 642 | ArrayIndex index_; 643 | Kind kind_; 644 | }; 645 | 646 | /** \brief Experimental and untested: represents a "path" to access a node. 647 | * 648 | * Syntax: 649 | * - "." => root node 650 | * - ".[n]" => elements at index 'n' of root node (an array value) 651 | * - ".name" => member named 'name' of root node (an object value) 652 | * - ".name1.name2.name3" 653 | * - ".[0][1][2].name1[3]" 654 | * - ".%" => member name is provided as parameter 655 | * - ".[%]" => index is provied as parameter 656 | */ 657 | class JSON_API Path { 658 | public: 659 | Path(const JSONCPP_STRING& path, 660 | const PathArgument& a1 = PathArgument(), 661 | const PathArgument& a2 = PathArgument(), 662 | const PathArgument& a3 = PathArgument(), 663 | const PathArgument& a4 = PathArgument(), 664 | const PathArgument& a5 = PathArgument()); 665 | 666 | const Value& resolve(const Value& root) const; 667 | Value resolve(const Value& root, const Value& defaultValue) const; 668 | /// Creates the "path" to access the specified node and returns a reference on 669 | /// the node. 670 | Value& make(Value& root) const; 671 | 672 | private: 673 | typedef std::vector InArgs; 674 | typedef std::vector Args; 675 | 676 | void makePath(const JSONCPP_STRING& path, const InArgs& in); 677 | void addPathInArg(const JSONCPP_STRING& path, 678 | const InArgs& in, 679 | InArgs::const_iterator& itInArg, 680 | PathArgument::Kind kind); 681 | void invalidPath(const JSONCPP_STRING& path, int location); 682 | 683 | Args args_; 684 | }; 685 | 686 | /** \brief base class for Value iterators. 687 | * 688 | */ 689 | class JSON_API ValueIteratorBase { 690 | public: 691 | typedef std::bidirectional_iterator_tag iterator_category; 692 | typedef unsigned int size_t; 693 | typedef int difference_type; 694 | typedef ValueIteratorBase SelfType; 695 | 696 | bool operator==(const SelfType& other) const { return isEqual(other); } 697 | 698 | bool operator!=(const SelfType& other) const { return !isEqual(other); } 699 | 700 | difference_type operator-(const SelfType& other) const { 701 | return other.computeDistance(*this); 702 | } 703 | 704 | /// Return either the index or the member name of the referenced value as a 705 | /// Value. 706 | Value key() const; 707 | 708 | /// Return the index of the referenced Value, or -1 if it is not an arrayValue. 709 | UInt index() const; 710 | 711 | /// Return the member name of the referenced Value, or "" if it is not an 712 | /// objectValue. 713 | /// \note Avoid `c_str()` on result, as embedded zeroes are possible. 714 | JSONCPP_STRING name() const; 715 | 716 | /// Return the member name of the referenced Value. "" if it is not an 717 | /// objectValue. 718 | /// \deprecated This cannot be used for UTF-8 strings, since there can be embedded nulls. 719 | JSONCPP_DEPRECATED("Use `key = name();` instead.") 720 | char const* memberName() const; 721 | /// Return the member name of the referenced Value, or NULL if it is not an 722 | /// objectValue. 723 | /// \note Better version than memberName(). Allows embedded nulls. 724 | char const* memberName(char const** end) const; 725 | 726 | protected: 727 | Value& deref() const; 728 | 729 | void increment(); 730 | 731 | void decrement(); 732 | 733 | difference_type computeDistance(const SelfType& other) const; 734 | 735 | bool isEqual(const SelfType& other) const; 736 | 737 | void copy(const SelfType& other); 738 | 739 | private: 740 | Value::ObjectValues::iterator current_; 741 | // Indicates that iterator is for a null value. 742 | bool isNull_; 743 | 744 | public: 745 | // For some reason, BORLAND needs these at the end, rather 746 | // than earlier. No idea why. 747 | ValueIteratorBase(); 748 | explicit ValueIteratorBase(const Value::ObjectValues::iterator& current); 749 | }; 750 | 751 | /** \brief const iterator for object and array value. 752 | * 753 | */ 754 | class JSON_API ValueConstIterator : public ValueIteratorBase { 755 | friend class Value; 756 | 757 | public: 758 | typedef const Value value_type; 759 | //typedef unsigned int size_t; 760 | //typedef int difference_type; 761 | typedef const Value& reference; 762 | typedef const Value* pointer; 763 | typedef ValueConstIterator SelfType; 764 | 765 | ValueConstIterator(); 766 | ValueConstIterator(ValueIterator const& other); 767 | 768 | private: 769 | /*! \internal Use by Value to create an iterator. 770 | */ 771 | explicit ValueConstIterator(const Value::ObjectValues::iterator& current); 772 | public: 773 | SelfType& operator=(const ValueIteratorBase& other); 774 | 775 | SelfType operator++(int) { 776 | SelfType temp(*this); 777 | ++*this; 778 | return temp; 779 | } 780 | 781 | SelfType operator--(int) { 782 | SelfType temp(*this); 783 | --*this; 784 | return temp; 785 | } 786 | 787 | SelfType& operator--() { 788 | decrement(); 789 | return *this; 790 | } 791 | 792 | SelfType& operator++() { 793 | increment(); 794 | return *this; 795 | } 796 | 797 | reference operator*() const { return deref(); } 798 | 799 | pointer operator->() const { return &deref(); } 800 | }; 801 | 802 | /** \brief Iterator for object and array value. 803 | */ 804 | class JSON_API ValueIterator : public ValueIteratorBase { 805 | friend class Value; 806 | 807 | public: 808 | typedef Value value_type; 809 | typedef unsigned int size_t; 810 | typedef int difference_type; 811 | typedef Value& reference; 812 | typedef Value* pointer; 813 | typedef ValueIterator SelfType; 814 | 815 | ValueIterator(); 816 | explicit ValueIterator(const ValueConstIterator& other); 817 | ValueIterator(const ValueIterator& other); 818 | 819 | private: 820 | /*! \internal Use by Value to create an iterator. 821 | */ 822 | explicit ValueIterator(const Value::ObjectValues::iterator& current); 823 | public: 824 | SelfType& operator=(const SelfType& other); 825 | 826 | SelfType operator++(int) { 827 | SelfType temp(*this); 828 | ++*this; 829 | return temp; 830 | } 831 | 832 | SelfType operator--(int) { 833 | SelfType temp(*this); 834 | --*this; 835 | return temp; 836 | } 837 | 838 | SelfType& operator--() { 839 | decrement(); 840 | return *this; 841 | } 842 | 843 | SelfType& operator++() { 844 | increment(); 845 | return *this; 846 | } 847 | 848 | reference operator*() const { return deref(); } 849 | 850 | pointer operator->() const { return &deref(); } 851 | }; 852 | 853 | } // namespace Json 854 | 855 | 856 | namespace std { 857 | /// Specialize std::swap() for Json::Value. 858 | template<> 859 | inline void swap(Json::Value& a, Json::Value& b) { a.swap(b); } 860 | } 861 | 862 | 863 | #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) 864 | #pragma warning(pop) 865 | #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) 866 | 867 | #endif // CPPTL_JSON_H_INCLUDED 868 | -------------------------------------------------------------------------------- /json/version.h: -------------------------------------------------------------------------------- 1 | // DO NOT EDIT. This file (and "version") is generated by CMake. 2 | // Run CMake configure step to update it. 3 | #ifndef JSON_VERSION_H_INCLUDED 4 | # define JSON_VERSION_H_INCLUDED 5 | 6 | # define JSONCPP_VERSION_STRING "1.7.4" 7 | # define JSONCPP_VERSION_MAJOR 1 8 | # define JSONCPP_VERSION_MINOR 7 9 | # define JSONCPP_VERSION_PATCH 4 10 | # define JSONCPP_VERSION_QUALIFIER 11 | # define JSONCPP_VERSION_HEXA ((JSONCPP_VERSION_MAJOR << 24) | (JSONCPP_VERSION_MINOR << 16) | (JSONCPP_VERSION_PATCH << 8)) 12 | 13 | #ifdef JSONCPP_USING_SECURE_MEMORY 14 | #undef JSONCPP_USING_SECURE_MEMORY 15 | #endif 16 | #define JSONCPP_USING_SECURE_MEMORY 0 17 | // If non-zero, the library zeroes any memory that it has allocated before 18 | // it frees its memory. 19 | 20 | #endif // JSON_VERSION_H_INCLUDED 21 | -------------------------------------------------------------------------------- /json/writer.h: -------------------------------------------------------------------------------- 1 | // Copyright 2007-2010 Baptiste Lepilleur 2 | // Distributed under MIT license, or public domain if desired and 3 | // recognized in your jurisdiction. 4 | // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE 5 | 6 | #ifndef JSON_WRITER_H_INCLUDED 7 | #define JSON_WRITER_H_INCLUDED 8 | 9 | #if !defined(JSON_IS_AMALGAMATION) 10 | #include "value.h" 11 | #endif // if !defined(JSON_IS_AMALGAMATION) 12 | #include 13 | #include 14 | #include 15 | 16 | // Disable warning C4251: : needs to have dll-interface to 17 | // be used by... 18 | #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) 19 | #pragma warning(push) 20 | #pragma warning(disable : 4251) 21 | #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) 22 | 23 | namespace Json { 24 | 25 | class Value; 26 | 27 | /** 28 | 29 | Usage: 30 | \code 31 | using namespace Json; 32 | void writeToStdout(StreamWriter::Factory const& factory, Value const& value) { 33 | std::unique_ptr const writer( 34 | factory.newStreamWriter()); 35 | writer->write(value, &std::cout); 36 | std::cout << std::endl; // add lf and flush 37 | } 38 | \endcode 39 | */ 40 | class JSON_API StreamWriter { 41 | protected: 42 | JSONCPP_OSTREAM* sout_; // not owned; will not delete 43 | public: 44 | StreamWriter(); 45 | virtual ~StreamWriter(); 46 | /** Write Value into document as configured in sub-class. 47 | Do not take ownership of sout, but maintain a reference during function. 48 | \pre sout != NULL 49 | \return zero on success (For now, we always return zero, so check the stream instead.) 50 | \throw std::exception possibly, depending on configuration 51 | */ 52 | virtual int write(Value const& root, JSONCPP_OSTREAM* sout) = 0; 53 | 54 | /** \brief A simple abstract factory. 55 | */ 56 | class JSON_API Factory { 57 | public: 58 | virtual ~Factory(); 59 | /** \brief Allocate a CharReader via operator new(). 60 | * \throw std::exception if something goes wrong (e.g. invalid settings) 61 | */ 62 | virtual StreamWriter* newStreamWriter() const = 0; 63 | }; // Factory 64 | }; // StreamWriter 65 | 66 | /** \brief Write into stringstream, then return string, for convenience. 67 | * A StreamWriter will be created from the factory, used, and then deleted. 68 | */ 69 | JSONCPP_STRING JSON_API writeString(StreamWriter::Factory const& factory, Value const& root); 70 | 71 | 72 | /** \brief Build a StreamWriter implementation. 73 | 74 | Usage: 75 | \code 76 | using namespace Json; 77 | Value value = ...; 78 | StreamWriterBuilder builder; 79 | builder["commentStyle"] = "None"; 80 | builder["indentation"] = " "; // or whatever you like 81 | std::unique_ptr writer( 82 | builder.newStreamWriter()); 83 | writer->write(value, &std::cout); 84 | std::cout << std::endl; // add lf and flush 85 | \endcode 86 | */ 87 | class JSON_API StreamWriterBuilder : public StreamWriter::Factory { 88 | public: 89 | // Note: We use a Json::Value so that we can add data-members to this class 90 | // without a major version bump. 91 | /** Configuration of this builder. 92 | Available settings (case-sensitive): 93 | - "commentStyle": "None" or "All" 94 | - "indentation": "" 95 | - "enableYAMLCompatibility": false or true 96 | - slightly change the whitespace around colons 97 | - "dropNullPlaceholders": false or true 98 | - Drop the "null" string from the writer's output for nullValues. 99 | Strictly speaking, this is not valid JSON. But when the output is being 100 | fed to a browser's Javascript, it makes for smaller output and the 101 | browser can handle the output just fine. 102 | - "useSpecialFloats": false or true 103 | - If true, outputs non-finite floating point values in the following way: 104 | NaN values as "NaN", positive infinity as "Infinity", and negative infinity 105 | as "-Infinity". 106 | 107 | You can examine 'settings_` yourself 108 | to see the defaults. You can also write and read them just like any 109 | JSON Value. 110 | \sa setDefaults() 111 | */ 112 | Json::Value settings_; 113 | 114 | StreamWriterBuilder(); 115 | ~StreamWriterBuilder() JSONCPP_OVERRIDE; 116 | 117 | /** 118 | * \throw std::exception if something goes wrong (e.g. invalid settings) 119 | */ 120 | StreamWriter* newStreamWriter() const JSONCPP_OVERRIDE; 121 | 122 | /** \return true if 'settings' are legal and consistent; 123 | * otherwise, indicate bad settings via 'invalid'. 124 | */ 125 | bool validate(Json::Value* invalid) const; 126 | /** A simple way to update a specific setting. 127 | */ 128 | Value& operator[](JSONCPP_STRING key); 129 | 130 | /** Called by ctor, but you can use this to reset settings_. 131 | * \pre 'settings' != NULL (but Json::null is fine) 132 | * \remark Defaults: 133 | * \snippet src/lib_json/json_writer.cpp StreamWriterBuilderDefaults 134 | */ 135 | static void setDefaults(Json::Value* settings); 136 | }; 137 | 138 | /** \brief Abstract class for writers. 139 | * \deprecated Use StreamWriter. (And really, this is an implementation detail.) 140 | */ 141 | class JSON_API Writer { 142 | public: 143 | virtual ~Writer(); 144 | 145 | virtual JSONCPP_STRING write(const Value& root) = 0; 146 | }; 147 | 148 | /** \brief Outputs a Value in JSON format 149 | *without formatting (not human friendly). 150 | * 151 | * The JSON document is written in a single line. It is not intended for 'human' 152 | *consumption, 153 | * but may be usefull to support feature such as RPC where bandwith is limited. 154 | * \sa Reader, Value 155 | * \deprecated Use StreamWriterBuilder. 156 | */ 157 | class JSON_API FastWriter : public Writer { 158 | 159 | public: 160 | FastWriter(); 161 | ~FastWriter() JSONCPP_OVERRIDE {} 162 | 163 | void enableYAMLCompatibility(); 164 | 165 | /** \brief Drop the "null" string from the writer's output for nullValues. 166 | * Strictly speaking, this is not valid JSON. But when the output is being 167 | * fed to a browser's Javascript, it makes for smaller output and the 168 | * browser can handle the output just fine. 169 | */ 170 | void dropNullPlaceholders(); 171 | 172 | void omitEndingLineFeed(); 173 | 174 | public: // overridden from Writer 175 | JSONCPP_STRING write(const Value& root) JSONCPP_OVERRIDE; 176 | 177 | private: 178 | void writeValue(const Value& value); 179 | 180 | JSONCPP_STRING document_; 181 | bool yamlCompatiblityEnabled_; 182 | bool dropNullPlaceholders_; 183 | bool omitEndingLineFeed_; 184 | }; 185 | 186 | /** \brief Writes a Value in JSON format in a 187 | *human friendly way. 188 | * 189 | * The rules for line break and indent are as follow: 190 | * - Object value: 191 | * - if empty then print {} without indent and line break 192 | * - if not empty the print '{', line break & indent, print one value per 193 | *line 194 | * and then unindent and line break and print '}'. 195 | * - Array value: 196 | * - if empty then print [] without indent and line break 197 | * - if the array contains no object value, empty array or some other value 198 | *types, 199 | * and all the values fit on one lines, then print the array on a single 200 | *line. 201 | * - otherwise, it the values do not fit on one line, or the array contains 202 | * object or non empty array, then print one value per line. 203 | * 204 | * If the Value have comments then they are outputed according to their 205 | *#CommentPlacement. 206 | * 207 | * \sa Reader, Value, Value::setComment() 208 | * \deprecated Use StreamWriterBuilder. 209 | */ 210 | class JSON_API StyledWriter : public Writer { 211 | public: 212 | StyledWriter(); 213 | ~StyledWriter() JSONCPP_OVERRIDE {} 214 | 215 | public: // overridden from Writer 216 | /** \brief Serialize a Value in JSON format. 217 | * \param root Value to serialize. 218 | * \return String containing the JSON document that represents the root value. 219 | */ 220 | JSONCPP_STRING write(const Value& root) JSONCPP_OVERRIDE; 221 | 222 | private: 223 | void writeValue(const Value& value); 224 | void writeArrayValue(const Value& value); 225 | bool isMultineArray(const Value& value); 226 | void pushValue(const JSONCPP_STRING& value); 227 | void writeIndent(); 228 | void writeWithIndent(const JSONCPP_STRING& value); 229 | void indent(); 230 | void unindent(); 231 | void writeCommentBeforeValue(const Value& root); 232 | void writeCommentAfterValueOnSameLine(const Value& root); 233 | bool hasCommentForValue(const Value& value); 234 | static JSONCPP_STRING normalizeEOL(const JSONCPP_STRING& text); 235 | 236 | typedef std::vector ChildValues; 237 | 238 | ChildValues childValues_; 239 | JSONCPP_STRING document_; 240 | JSONCPP_STRING indentString_; 241 | unsigned int rightMargin_; 242 | unsigned int indentSize_; 243 | bool addChildValues_; 244 | }; 245 | 246 | /** \brief Writes a Value in JSON format in a 247 | human friendly way, 248 | to a stream rather than to a string. 249 | * 250 | * The rules for line break and indent are as follow: 251 | * - Object value: 252 | * - if empty then print {} without indent and line break 253 | * - if not empty the print '{', line break & indent, print one value per 254 | line 255 | * and then unindent and line break and print '}'. 256 | * - Array value: 257 | * - if empty then print [] without indent and line break 258 | * - if the array contains no object value, empty array or some other value 259 | types, 260 | * and all the values fit on one lines, then print the array on a single 261 | line. 262 | * - otherwise, it the values do not fit on one line, or the array contains 263 | * object or non empty array, then print one value per line. 264 | * 265 | * If the Value have comments then they are outputed according to their 266 | #CommentPlacement. 267 | * 268 | * \param indentation Each level will be indented by this amount extra. 269 | * \sa Reader, Value, Value::setComment() 270 | * \deprecated Use StreamWriterBuilder. 271 | */ 272 | class JSON_API StyledStreamWriter { 273 | public: 274 | StyledStreamWriter(JSONCPP_STRING indentation = "\t"); 275 | ~StyledStreamWriter() {} 276 | 277 | public: 278 | /** \brief Serialize a Value in JSON format. 279 | * \param out Stream to write to. (Can be ostringstream, e.g.) 280 | * \param root Value to serialize. 281 | * \note There is no point in deriving from Writer, since write() should not 282 | * return a value. 283 | */ 284 | void write(JSONCPP_OSTREAM& out, const Value& root); 285 | 286 | private: 287 | void writeValue(const Value& value); 288 | void writeArrayValue(const Value& value); 289 | bool isMultineArray(const Value& value); 290 | void pushValue(const JSONCPP_STRING& value); 291 | void writeIndent(); 292 | void writeWithIndent(const JSONCPP_STRING& value); 293 | void indent(); 294 | void unindent(); 295 | void writeCommentBeforeValue(const Value& root); 296 | void writeCommentAfterValueOnSameLine(const Value& root); 297 | bool hasCommentForValue(const Value& value); 298 | static JSONCPP_STRING normalizeEOL(const JSONCPP_STRING& text); 299 | 300 | typedef std::vector ChildValues; 301 | 302 | ChildValues childValues_; 303 | JSONCPP_OSTREAM* document_; 304 | JSONCPP_STRING indentString_; 305 | unsigned int rightMargin_; 306 | JSONCPP_STRING indentation_; 307 | bool addChildValues_ : 1; 308 | bool indented_ : 1; 309 | }; 310 | 311 | #if defined(JSON_HAS_INT64) 312 | JSONCPP_STRING JSON_API valueToString(Int value); 313 | JSONCPP_STRING JSON_API valueToString(UInt value); 314 | #endif // if defined(JSON_HAS_INT64) 315 | JSONCPP_STRING JSON_API valueToString(LargestInt value); 316 | JSONCPP_STRING JSON_API valueToString(LargestUInt value); 317 | JSONCPP_STRING JSON_API valueToString(double value); 318 | JSONCPP_STRING JSON_API valueToString(bool value); 319 | JSONCPP_STRING JSON_API valueToQuotedString(const char* value); 320 | 321 | /// \brief Output using the StyledStreamWriter. 322 | /// \see Json::operator>>() 323 | JSON_API JSONCPP_OSTREAM& operator<<(JSONCPP_OSTREAM&, const Value& root); 324 | 325 | } // namespace Json 326 | 327 | #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) 328 | #pragma warning(pop) 329 | #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) 330 | 331 | #endif // JSON_WRITER_H_INCLUDED 332 | -------------------------------------------------------------------------------- /jsoncpp.lib: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zpb1992/ReentryTrajectoryGuide/4f4b764896795ec206caabfa12889cd580132921/jsoncpp.lib -------------------------------------------------------------------------------- /main.cpp: -------------------------------------------------------------------------------- 1 | #include"Console.h" 2 | #include "PSO.h" 3 | #include "Reentry.h" 4 | #include "Mediator.h" 5 | #include 6 | 7 | #pragma comment(lib,"./Debug/jsoncpp.lib") 8 | 9 | int main() 10 | { 11 | srand(static_cast(time(0))); 12 | 13 | 14 | PSO pso; 15 | Reentry reentry; 16 | Mediator mediator(&reentry, &pso); 17 | 18 | unsigned start = time(0); 19 | 20 | 21 | pso.tieMediator(&mediator); 22 | reentry.tieMediator(&mediator); 23 | 24 | pso.calculate(); 25 | 26 | unsigned end = time(0); 27 | 28 | Console::instance()->inform("run time")->inform(end-start); 29 | 30 | return 0; 31 | } --------------------------------------------------------------------------------