├── .gitignore ├── .gitmodules ├── .travis.yml ├── CMakeLists.txt ├── README.md ├── include ├── client │ └── socket_tcp_connection.h ├── helper.h ├── itransport_layer.h ├── messages │ ├── rosbridge_advertise_msg.h │ ├── rosbridge_advertise_service_msg.h │ ├── rosbridge_call_service_msg.h │ ├── rosbridge_msg.h │ ├── rosbridge_publish_msg.h │ ├── rosbridge_service_response_msg.h │ ├── rosbridge_subscribe_msg.h │ ├── rosbridge_unadvertise_msg.h │ ├── rosbridge_unadvertise_service_msg.h │ └── rosbridge_unsubscribe_msg.h ├── rapidjson │ ├── allocators.h │ ├── document.h │ ├── encodedstream.h │ ├── encodings.h │ ├── error │ │ ├── en.h │ │ └── error.h │ ├── filereadstream.h │ ├── filewritestream.h │ ├── fwd.h │ ├── internal │ │ ├── biginteger.h │ │ ├── diyfp.h │ │ ├── dtoa.h │ │ ├── ieee754.h │ │ ├── itoa.h │ │ ├── meta.h │ │ ├── pow10.h │ │ ├── regex.h │ │ ├── stack.h │ │ ├── strfunc.h │ │ ├── strtod.h │ │ └── swap.h │ ├── istreamwrapper.h │ ├── memorybuffer.h │ ├── memorystream.h │ ├── msinttypes │ │ ├── inttypes.h │ │ └── stdint.h │ ├── ostreamwrapper.h │ ├── pointer.h │ ├── prettywriter.h │ ├── rapidjson.h │ ├── reader.h │ ├── schema.h │ ├── stream.h │ ├── stringbuffer.h │ └── writer.h ├── ros_bridge.h ├── ros_message_factory.h ├── ros_service.h ├── ros_tf_broadcaster.h ├── ros_time.h ├── ros_topic.h ├── spinlock.h └── types.h ├── install_deps.sh └── src ├── client ├── client.cpp └── socket_tcp_connection.cpp ├── ros_bridge.cpp ├── ros_service.cpp ├── ros_tf_broadcaster.cpp ├── ros_time.cpp └── ros_topic.cpp /.gitignore: -------------------------------------------------------------------------------- 1 | # Prerequisites 2 | *.d 3 | 4 | # Compiled Object files 5 | *.slo 6 | *.lo 7 | *.o 8 | *.obj 9 | 10 | # Precompiled Headers 11 | *.gch 12 | *.pch 13 | 14 | # Compiled Dynamic libraries 15 | *.so 16 | *.dylib 17 | *.dll 18 | 19 | # Fortran module files 20 | *.mod 21 | *.smod 22 | 23 | # Compiled Static libraries 24 | *.lai 25 | *.la 26 | *.a 27 | *.lib 28 | 29 | # Executables 30 | *.exe 31 | *.out 32 | *.app 33 | 34 | # VIM 35 | *.swp 36 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "lib/googletest"] 2 | path = lib/googletest 3 | url = https://github.com/google/googletest.git 4 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | language: cpp 3 | dist: bionic 4 | compiler: 5 | - clang 6 | os: 7 | - linux 8 | addons: 9 | apt: 10 | packages: 11 | - pkg-config 12 | - libssl-dev 13 | - libsasl2-dev 14 | 15 | before_script: 16 | - export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:~/deps/libbson/lib/pkgconfig/ 17 | script: 18 | - clang --version 19 | - chmod u+x install_deps.sh 20 | - ./install_deps.sh 21 | - mkdir build 22 | - cd build 23 | - cmake .. 24 | - make 25 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Thanks to https://github.com/dmonopoly/gtest-cmake-example/blob/master/CMakeLists.txt 2 | # for providing a basic setup to use gtest in a cmake project 3 | # Another solution would make use of ExternalProject_Add to downloads and installs 4 | # googletest in the build/ dir: 5 | # http://stackoverflow.com/questions/9689183/cmake-googletest/9695234#9695234 6 | # However, this requires an active internet connection 7 | 8 | 9 | cmake_minimum_required(VERSION 2.8) 10 | set(PROJECT_NAME rosbridge2cpp) 11 | project(${PROJECT_NAME}) 12 | 13 | option(test "Build all tests." OFF) # Makes boolean 'test' available. 14 | 15 | find_package(PkgConfig QUIET) 16 | if(PkgConfig_FOUND) 17 | pkg_search_module(LIBBSON REQUIRED libbson-1.0) 18 | else() 19 | message(STATUS "Didn't fount PkgConfig, please specify the path yourself") 20 | set(LIBBSON_DIR "" CACHE PATH "Install directory of libbson. Should contain /include and /lib") 21 | set(LIBBSON_INCLUDE_DIRS "${LIBBSON_DIR}/include") 22 | set(LIBBSON_LIBRARY_DIRS "${LIBBSON_DIR}/lib") 23 | set(LIBBSON_CFLAGS_OTHER "-I${LIBBSON_INCLUDE_DIRS}/libbson-1.0") 24 | set(LIBBSON_LIBRARIES "bson-static-1.0.lib" CACHE STRING "Lib file. Different between platforms") 25 | endif() 26 | 27 | if(NOT WIN32) 28 | find_package(Threads) 29 | set(LIBS ${LIBS} ${CMAKE_THREAD_LIBS_INIT}) 30 | set(CMAKE_CXX_FLAGS "-g -Wall") 31 | endif() 32 | 33 | set(CXX_STANDARD C++11) 34 | add_definitions(-DRAPIDJSON_HAS_STDSTRING=1) 35 | add_definitions(-DBSON_STATIC=1) 36 | 37 | include_directories(${LIBBSON_INCLUDE_DIRS}) 38 | link_directories(${LIBBSON_LIBRARY_DIRS}) 39 | add_definitions(${LIBBSON_CFLAGS_OTHER}) 40 | set(LIBS ${LIBS} ${LIBBSON_LIBRARIES}) 41 | 42 | if(WIN32 AND NOT PkgConfig_FOUND) 43 | set(LIBS ${LIBS} "ws2_32") # Needed by libbson on windows 44 | endif() 45 | 46 | INCLUDE_DIRECTORIES( include) 47 | ADD_EXECUTABLE( rosbridge2cpp-client 48 | src/client/client.cpp 49 | src/client/socket_tcp_connection.cpp 50 | src/ros_bridge.cpp 51 | src/ros_topic.cpp 52 | src/ros_service.cpp 53 | src/ros_tf_broadcaster.cpp 54 | ) 55 | 56 | ADD_LIBRARY( rosbridge2cpp SHARED 57 | # src/client/socket_tcp_connection.cpp #Not needed for the lib 58 | src/ros_bridge.cpp 59 | src/ros_topic.cpp 60 | src/ros_service.cpp 61 | src/ros_tf_broadcaster.cpp 62 | ) 63 | target_link_libraries(rosbridge2cpp-client ${LIBS}) 64 | target_link_libraries(rosbridge2cpp ${LIBS}) 65 | # 66 | ################################# 67 | ## Testing 68 | ################################# 69 | #if (test) 70 | # # This adds another subdirectory, which has 'project(gtest)'. 71 | # add_subdirectory(lib/googletest/googletest) 72 | # 73 | # enable_testing() 74 | # 75 | # # Include the gtest library. gtest_SOURCE_DIR is available due to 76 | # # 'project(gtest)' above. 77 | # include_directories(${gtest_SOURCE_DIR}/include ${gtest_SOURCE_DIR}) 78 | # 79 | # ############## 80 | # # Unit Tests 81 | # ############## 82 | # add_executable(runUnitTests tests/tests.cpp) 83 | # 84 | # # Standard linking to gtest stuff. 85 | # target_link_libraries(runUnitTests gtest gtest_main rosbridge2cpp) 86 | # 87 | # # Extra linking for the project. 88 | # #target_link_libraries(runUnitTests project1_lib) 89 | # 90 | # # This is so you can do 'make test' to see all your tests run, instead of 91 | # # manually running the executable runUnitTests to see those specific tests. 92 | # #add_test(NAME that-test-I-made COMMAND runUnitTests) 93 | # 94 | # # You can also omit NAME and COMMAND. The second argument could be some other 95 | # # test executable. 96 | # add_test(that-other-test-I-made runUnitTests) 97 | #endif() 98 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # rosbridge2cpp [![Build Status](https://travis-ci.org/Sanic/rosbridge2cpp.svg?branch=master)](https://travis-ci.org/Sanic/rosbridge2cpp) 2 | A C++11 library to interface ROS via rosbridge 3 | 4 | This library can be used to talk to [ROS](http://www.ros.org/) via [rosbridge](http://wiki.ros.org/rosbridge_suite). 5 | It enables you to communicate with ROS even if you don't have the full ROS Stack on your machine available (for example, when you are using Windows). 6 | The network communication of this library is abstracted from a specific network implementation. 7 | This abstraction allows you to use this library in different contexts, for example in Windows Applications or even in Game Engines like [Unreal](https://www.unrealengine.com/). 8 | 9 | Please note that this library is in an early development stage and features are added as needed. 10 | Even though the library supports JSON and BSON, it's strongly recommended to use BSON. 11 | 12 | ## Compiling the library 13 | 14 | Before you can compile the library, you need to install [libbson](https://github.com/mongodb/libbson). In short, this can be accomplished by: 15 | ``` 16 | wget https://github.com/mongodb/libbson/releases/download/1.5.3/libbson-1.5.3.tar.gz 17 | tar xzf libbson-1.5.3.tar.gz 18 | cd libbson-1.5.3 19 | ./configure --prefix=$HOME/deps/libbson && make -j$(grep -c ^processor /proc/cpuinfo) && make install 20 | ``` 21 | Please note that libbson will not be installed system-wide to avoid interference with existing installations that might need libbson in a different version. 22 | To be able to find this library at link-time, we'll add the pkgconfig to our .bashrc to persist the change: 23 | ``` 24 | PKG_CONFIG_PATH=$PKG_CONFIG_PATH:~/deps/libbson/lib/pkgconfig/ >> ~/.bashrc 25 | source ~/.bashrc 26 | ``` 27 | Now you can clone this repo. Please use --recursive if you want to use the unit tests. 28 | After cloning the repo, change into that directory and execute: 29 | ``` 30 | mkdir build 31 | cd build 32 | cmake .. # or 'cmake .. -Dtest=on' if you build the unit tests 33 | make 34 | ``` 35 | 36 | ## Usage 37 | Checkout [src/client/client.cpp](src/client/client.cpp) for an example implementation based on UNIX sockets. 38 | On the server-side, please ensure that you're starting the TCP variant of the rosbridge server. 39 | Websockets are currently not supported. 40 | 41 | In order to use the recommended, full-duplex BSON variant of the library, you need a recent rosbridge version that has been released after March 15 2017. At the time of writing this README, there is no release after that date. So right now, you need to install [rosbridge](https://github.com/RobotWebTools/rosbridge_suite) from the repository. Everything after commit [f0844e2](https://github.com/RobotWebTools/rosbridge_suite/commit/f0844e24d05ded3c4ab803dc235c339e854175e8) should be fine. 42 | When you've rosbridge_suite downloaded and put in your ROS workspace, you can launch rosbridge with BSON-Mode like this: 43 | ``` 44 | roslaunch rosbridge_server rosbridge_tcp.launch bson_only_mode:=True 45 | ``` 46 | 47 | ## Running the unit tests 48 | Please ensure that the you executed cmake with '-Dtest=on' before you continue. 49 | When the library and the unit tests are compiled, execute the following commands on a machine running ROS to setup a minimal testing environment: 50 | ``` 51 | roslaunch rosbridge_server rosbridge_tcp.launch # plus bson_only_mode:=True if you want to use BSON 52 | rostopic pub /test std_msgs/String a5424890996794277159554918 53 | rosrun rospy_tutorials add_two_ints_server 54 | ``` 55 | Write down the IP address of the machine where you executed these commands mentally and change to your 'build/' directory. 56 | Call the Unit Tests like this: 57 | ``` 58 | export rosb2_cpp_ip=THE_IP_ADDRESS_OF_YOUR_ROS_MACHINE; export rosb2_cpp_port=9090; ./runUnitTests 59 | ``` 60 | 61 | -------------------------------------------------------------------------------- /include/client/socket_tcp_connection.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | #include "rapidjson/document.h" 14 | 15 | #include "itransport_layer.h" 16 | #include "types.h" 17 | #include "helper.h" 18 | #include "messages/rosbridge_msg.h" 19 | 20 | using json = rapidjson::Document; 21 | 22 | namespace rosbridge2cpp{ 23 | class SocketTCPConnection : public ITransportLayer{ 24 | public: 25 | SocketTCPConnection () = default; 26 | // SocketTCPConnection (bool bson_only_mode) : bson_only_mode_(bson_only_mode){ 27 | // }; 28 | 29 | ~SocketTCPConnection (){ 30 | std::cout << "Connection Destructor called " << std::endl; 31 | std::cout << "Closing Socket" << std::endl; 32 | if(sock_ >= 0) 33 | close(sock_); 34 | terminate_receiver_thread_ = true; 35 | std::cout << "Waiting for Thread to join" << std::endl; 36 | if(receiver_thread_set_up_){ 37 | std::cout << "Thread is set up : Calling .join() on it" << std::endl; 38 | // std::cout << "Joinable? : " << receiverThread.joinable() << std::endl; 39 | receiver_thread_.join(); // Wait for the receiver thread to finish 40 | std::cout << "join() in Connection Destructor done" << std::endl; 41 | }else{ 42 | std::cout << "receiverThread hasn't been set up. Skipping join() on it" << std::endl; 43 | } 44 | } 45 | 46 | // A callback that just outputs received messages 47 | // void static messageCallback(const json &message){ 48 | // std::string str_repr = Helper::get_string_from_rapidjson(message); 49 | // std::cout << "Message received: " << str_repr << std::endl; 50 | // } 51 | 52 | 53 | bool Init(std::string p_ip_addr, int p_port); 54 | bool SendMessage(std::string data); 55 | bool SendMessage(const uint8_t *data, unsigned int length); 56 | int ReceiverThreadFunction(); 57 | void RegisterIncomingMessageCallback(std::function fun); 58 | void RegisterIncomingMessageCallback(std::function fun); 59 | void RegisterErrorCallback(std::function fun); 60 | void ReportError(TransportError err); 61 | void SetTransportMode(ITransportLayer::TransportMode mode); 62 | 63 | private: 64 | std::string ip_addr_; 65 | int port_; 66 | 67 | int sock_ = socket(AF_INET , SOCK_STREAM , 0); 68 | struct sockaddr_in connect_to_; 69 | std::thread receiver_thread_; 70 | bool terminate_receiver_thread_ = false; 71 | bool receiver_thread_set_up_ = false; 72 | bool callback_function_defined_ = false; 73 | bool bson_only_mode_ = false; 74 | std::function incoming_message_callback_; 75 | std::function incoming_message_callback_bson_; 76 | std::function error_callback_ = nullptr; 77 | }; 78 | } 79 | -------------------------------------------------------------------------------- /include/helper.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "rapidjson/document.h" 4 | #include "rapidjson/writer.h" 5 | #include "rapidjson/stringbuffer.h" 6 | #include 7 | 8 | using json = rapidjson::Document; 9 | namespace rosbridge2cpp { 10 | class Helper { 11 | public: 12 | Helper() = default; 13 | ~Helper() = default; 14 | 15 | std::string static get_string_from_rapidjson(json &d) 16 | { 17 | rapidjson::StringBuffer buffer; 18 | rapidjson::Writer writer(buffer); 19 | d.Accept(writer); 20 | return buffer.GetString(); 21 | } 22 | 23 | std::string static get_string_from_rapidjson(const json &d) 24 | { 25 | rapidjson::StringBuffer buffer; 26 | rapidjson::Writer writer(buffer); 27 | d.Accept(writer); 28 | return buffer.GetString(); 29 | } 30 | 31 | // dot_notation refers to MongoDB dot notation 32 | // returns "" and sets success to true if suitable data can't be found via the dot notation 33 | std::string static get_utf8_by_key(const char *dot_notation, bson_t &b, bool &success) 34 | { 35 | bson_iter_t iter; 36 | bson_iter_t val; 37 | 38 | if (bson_iter_init(&iter, &b) && 39 | bson_iter_find_descendant(&iter, dot_notation, &val) && 40 | BSON_ITER_HOLDS_UTF8(&val)) { 41 | success = true; 42 | return std::string(bson_iter_utf8(&val, NULL)); 43 | } 44 | 45 | success = false; 46 | return ""; 47 | } 48 | 49 | // dot_notation refers to MongoDB dot notation 50 | // returns INT32_MAX and sets success to 'false' if suitable data can't be found via the dot notation 51 | int32_t static get_int32_by_key(const char *dot_notation, bson_t &b, bool &success) 52 | { 53 | bson_iter_t iter; 54 | bson_iter_t val; 55 | 56 | if (bson_iter_init(&iter, &b) && 57 | bson_iter_find_descendant(&iter, dot_notation, &val) && 58 | BSON_ITER_HOLDS_INT32(&val)) { 59 | success = true; 60 | return bson_iter_int32(&val); 61 | } 62 | success = false; 63 | return INT32_MAX; 64 | } 65 | 66 | // dot_notation refers to MongoDB dot notation 67 | // returns -1 and sets success to 'false' if suitable data can't be found via the dot notation 68 | double static get_double_by_key(const char *dot_notation, bson_t &b, bool &success) 69 | { 70 | bson_iter_t iter; 71 | bson_iter_t val; 72 | 73 | // if (bson_iter_init (&iter, &b) && 74 | // bson_iter_find_descendant (&iter, dot_notation, &val) && 75 | // BSON_ITER_HOLDS_DOUBLE (&val)) { 76 | if (bson_iter_init(&iter, &b) && 77 | bson_iter_find_descendant(&iter, dot_notation, &val)) { 78 | if (!BSON_ITER_HOLDS_DOUBLE(&val)) { 79 | std::cout << "Key found, but not double typed" << std::endl; 80 | } 81 | else { 82 | //std::cout << "Key " << dot_notation << " found. success is = " << success << std::endl; 83 | //std::cout << "Key " << dot_notation << " found." << std::endl; 84 | success = true; 85 | //std::cout << " success is now = " << success << std::endl; 86 | return bson_iter_double(&val); 87 | } 88 | } 89 | std::cout << "Couldn't find descendant" << std::endl; 90 | success = false; 91 | return -1.0; 92 | } 93 | 94 | // dot_notation refers to MongoDB dot notation 95 | // returns false and sets success to 'false' if suitable data can't be found via the dot notation 96 | bool static get_bool_by_key(const char *dot_notation, bson_t &b, bool &success) 97 | { 98 | bson_iter_t iter; 99 | bson_iter_t val; 100 | 101 | if (bson_iter_init(&iter, &b) && 102 | bson_iter_find_descendant(&iter, dot_notation, &val) && 103 | BSON_ITER_HOLDS_BOOL(&val)) { 104 | success = true; 105 | return bson_iter_bool(&val); 106 | } 107 | success = false; 108 | return false; 109 | } 110 | 111 | // dot_notation refers to MongoDB dot notation 112 | // returns nullptr and sets success to 'false' if suitable data can't be found via the dot notation 113 | // 114 | // binary_data_length holds the size of the buffer where the returned pointer points to. 115 | static const uint8_t * get_binary_by_key(const char *dot_notation, bson_t &b, uint32_t &binary_data_length, bool &success) 116 | { 117 | bson_iter_t iter; 118 | bson_iter_t val; 119 | 120 | if (bson_iter_init(&iter, &b) && 121 | bson_iter_find_descendant(&iter, dot_notation, &val) && 122 | BSON_ITER_HOLDS_BINARY(&val)) { 123 | bson_subtype_t subtype; 124 | const uint8_t *binary; 125 | 126 | bson_iter_binary(&val, &subtype, &binary_data_length, &binary); 127 | assert(binary); 128 | success = true; 129 | return binary; 130 | } 131 | success = false; 132 | return nullptr; 133 | } 134 | 135 | // dot_notation refers to MongoDB dot notation 136 | // returns nullptr and sets success to 'false' if suitable data can't be found via the dot notation 137 | // 138 | // array_size holds the size in byte of the buffer where the returned pointer points to. 139 | static const uint8_t * get_array_by_key(const char *dot_notation, bson_t &b, uint32_t &array_size, bool &success) 140 | { 141 | bson_iter_t iter; 142 | bson_iter_t val; 143 | 144 | if (bson_iter_init(&iter, &b) && 145 | bson_iter_find_descendant(&iter, dot_notation, &val) && 146 | BSON_ITER_HOLDS_ARRAY(&val)) { 147 | const uint8_t *binary; 148 | 149 | bson_iter_array(&val, &array_size, &binary); 150 | assert(binary); 151 | success = true; 152 | return binary; 153 | } 154 | success = false; 155 | return nullptr; 156 | } 157 | 158 | bool static bson_has_key(bson_t &b, const char *key) 159 | { 160 | return bson_has_field(&b, key); 161 | } 162 | }; 163 | } 164 | -------------------------------------------------------------------------------- /include/itransport_layer.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "types.h" 4 | 5 | /* 6 | * This class provides an interfaces for generic Transportlayers that can be used by the ROSBridge. 7 | * Since this library has been developed for different plattforms, 8 | * we abstract from the actual transport layer, since this varies from plattforms (and frameworks) a lot. 9 | * 10 | * Please see client/socket_tcp_connection.h for an example implementation that uses UNIX Sockets 11 | * to connect to a ROSBridge server 12 | */ 13 | namespace rosbridge2cpp { 14 | class ITransportLayer { 15 | public: 16 | enum TransportMode { JSON, BSON }; 17 | virtual ~ITransportLayer() = default; 18 | 19 | // Initialize the TransportLayer by connecting to the given IP and port 20 | // The implementing class should have an active connection to IP:port 21 | // when the method has been executed completly. 22 | // Returns true if the connection has been successfully. 23 | virtual bool Init(std::string ip_addr, int port) = 0; 24 | 25 | // Send a string over the underlying transport mechanism to the rosbridge server 26 | virtual bool SendMessage(std::string data) = 0; 27 | 28 | // Send a string over the underlying transport mechanism to the rosbridge server 29 | virtual bool SendMessage(const uint8_t *data, unsigned int length) = 0; 30 | 31 | // Register a std::function that will be called whenever a new data packet has been received by this TransportLayer. 32 | virtual void RegisterIncomingMessageCallback(std::function) = 0; 33 | 34 | // Register a std::function that will be called whenever a new data packet has been received by this TransportLayer. 35 | virtual void RegisterIncomingMessageCallback(std::function) = 0; 36 | 37 | // Register a std::function that will be called when errors occur. 38 | virtual void RegisterErrorCallback(std::function) = 0; 39 | 40 | // Report an error to the registered ErrorCallback (see RegisterErrorCallback) 41 | virtual void ReportError(TransportError) = 0; 42 | 43 | // Report an error to the registered ErrorCallback (see RegisterErrorCallback) 44 | virtual void SetTransportMode(TransportMode) = 0; 45 | private: 46 | /* data */ 47 | }; 48 | } 49 | -------------------------------------------------------------------------------- /include/messages/rosbridge_advertise_msg.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | #include "messages/rosbridge_msg.h" 6 | 7 | class ROSBridgeAdvertiseMsg : public ROSBridgeMsg { 8 | public: 9 | ROSBridgeAdvertiseMsg () : ROSBridgeMsg() {} 10 | 11 | ROSBridgeAdvertiseMsg(bool init_opcode) : ROSBridgeMsg() 12 | { 13 | if (init_opcode) 14 | op_ = ROSBridgeMsg::ADVERTISE; 15 | } 16 | 17 | virtual ~ROSBridgeAdvertiseMsg() = default; 18 | 19 | // Advertise messages will never be received from the client 20 | // So we don't need to fill this instance from JSON or other wire-level representations 21 | bool FromJSON(const rapidjson::Document &data) = delete; 22 | bool FromBSON(bson_t &bson) = delete; 23 | 24 | rapidjson::Document ToJSON(rapidjson::Document::AllocatorType& alloc) 25 | { 26 | rapidjson::Document d(rapidjson::kObjectType); 27 | d.AddMember("op", getOpCodeString(), alloc); 28 | 29 | add_if_value_changed(d, alloc, "id", id_); 30 | add_if_value_changed(d, alloc, "topic", topic_); 31 | add_if_value_changed(d, alloc, "type", type_); 32 | add_if_value_changed(d, alloc, "queue_size", queue_size_); 33 | 34 | d.AddMember("latch", latch_, alloc); 35 | 36 | return d; 37 | } 38 | 39 | void ToBSON(bson_t &bson) 40 | { 41 | BSON_APPEND_UTF8(&bson, "op", getOpCodeString().c_str()); 42 | 43 | add_if_value_changed(bson, "id", id_); 44 | add_if_value_changed(bson, "topic", topic_); 45 | add_if_value_changed(bson, "type", type_); 46 | 47 | add_if_value_changed(bson, "queue_size", queue_size_); 48 | 49 | //d.AddMember("latch", latch_, alloc); 50 | BSON_APPEND_BOOL(&bson, "latch", latch_); 51 | } 52 | 53 | std::string topic_; 54 | std::string type_; 55 | //std::string compression_ = "none"; 56 | //int throttle_rate_ = 0; 57 | bool latch_ = false; 58 | int queue_size_ = -1; 59 | private: 60 | /* data */ 61 | }; 62 | -------------------------------------------------------------------------------- /include/messages/rosbridge_advertise_service_msg.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | #include "messages/rosbridge_msg.h" 6 | 7 | class ROSBridgeAdvertiseServiceMsg : public ROSBridgeMsg{ 8 | public: 9 | ROSBridgeAdvertiseServiceMsg() : ROSBridgeMsg() {} 10 | 11 | ROSBridgeAdvertiseServiceMsg(bool init_opcode) : ROSBridgeMsg() { 12 | if (init_opcode) 13 | op_ = ROSBridgeMsg::ADVERTISE_SERVICE; 14 | } 15 | 16 | virtual ~ROSBridgeAdvertiseServiceMsg() = default; 17 | 18 | // Advertise messages will never be received from the client 19 | // So we don't need to fill this instance from JSON or other wire-level representations 20 | bool FromJSON(const rapidjson::Document &data) = delete; 21 | bool FromBSON(bson_t &bson) = delete; 22 | 23 | rapidjson::Document ToJSON(rapidjson::Document::AllocatorType& alloc) 24 | { 25 | rapidjson::Document d(rapidjson::kObjectType); 26 | d.AddMember("op", getOpCodeString(), alloc); 27 | 28 | add_if_value_changed(d, alloc, "id", id_); 29 | add_if_value_changed(d, alloc, "service", service_); 30 | add_if_value_changed(d, alloc, "type", type_); 31 | return d; 32 | } 33 | 34 | void ToBSON(bson_t &bson) 35 | { 36 | BSON_APPEND_UTF8(&bson, "op", getOpCodeString().c_str()); 37 | 38 | add_if_value_changed(bson, "id", id_); 39 | add_if_value_changed(bson, "service", service_); 40 | add_if_value_changed(bson, "type", type_); 41 | } 42 | 43 | 44 | std::string service_; 45 | std::string type_; 46 | private: 47 | /* data */ 48 | }; 49 | -------------------------------------------------------------------------------- /include/messages/rosbridge_call_service_msg.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | #include "messages/rosbridge_msg.h" 6 | 7 | class ROSBridgeCallServiceMsg : public ROSBridgeMsg { 8 | public: 9 | ROSBridgeCallServiceMsg() : ROSBridgeMsg() {} 10 | 11 | ROSBridgeCallServiceMsg(bool init_opcode) : ROSBridgeMsg() 12 | { 13 | if (init_opcode) 14 | op_ = ROSBridgeMsg::CALL_SERVICE; 15 | } 16 | 17 | virtual ~ROSBridgeCallServiceMsg() 18 | { 19 | if (args_bson_ != nullptr) 20 | bson_destroy(args_bson_); 21 | if (full_msg_bson_ != nullptr) 22 | bson_destroy(full_msg_bson_); 23 | } 24 | 25 | // Warning: This conversion moves the 'args' field 26 | // out of the given JSON data into this class 27 | // 'args' will become null afterwards. 28 | // 29 | // This method parses the "service" and "args" fields from 30 | // incoming publish messages into this class 31 | bool FromJSON(rapidjson::Document &data) 32 | { 33 | if (!ROSBridgeMsg::FromJSON(data)) 34 | return false; 35 | 36 | if (!data.HasMember("service")) 37 | { 38 | std::cerr << "[ROSBridgeCallServiceMsg] Received 'call_service' message without 'service' field." << std::endl; 39 | return false; 40 | } 41 | 42 | service_ = data["service"].GetString(); 43 | 44 | if (!data.HasMember("args")) 45 | { 46 | return true; // return true, since args is optional. Other parameters will not be set right now 47 | } 48 | 49 | args_json_ = data["args"]; 50 | 51 | return true; 52 | } 53 | 54 | bool FromBSON(bson_t &bson) { 55 | if (!ROSBridgeMsg::FromBSON(bson)) 56 | return false; 57 | 58 | if (!bson_has_field(&bson, "service")) { 59 | std::cerr << "[ROSBridgeCallServiceMsg] Received 'call_service' message without 'service' field." << std::endl; 60 | return false; 61 | } 62 | 63 | bool key_found = false; 64 | service_ = rosbridge2cpp::Helper::get_utf8_by_key("service", bson, key_found); 65 | assert(key_found); 66 | key_found = false; 67 | 68 | if (!bson_has_field(&bson, "args")) { 69 | std::cerr << "[ROSBridgeCallServiceMsg] Received 'call_service' message without 'args' field." << std::endl; 70 | return false; 71 | } 72 | 73 | full_msg_bson_ = &bson; 74 | 75 | return true; 76 | } 77 | 78 | rapidjson::Document ToJSON(rapidjson::Document::AllocatorType& alloc) 79 | { 80 | rapidjson::Document d(rapidjson::kObjectType); 81 | d.AddMember("op", getOpCodeString(), alloc); 82 | 83 | add_if_value_changed(d, alloc, "id", id_); 84 | add_if_value_changed(d, alloc, "service", service_); 85 | 86 | if (!args_json_.IsNull()) 87 | d.AddMember("args", args_json_, alloc); 88 | return d; 89 | } 90 | 91 | void ToBSON(bson_t &bson) 92 | { 93 | BSON_APPEND_UTF8(&bson, "op", getOpCodeString().c_str()); 94 | add_if_value_changed(bson, "id", id_); 95 | 96 | add_if_value_changed(bson, "service", service_); 97 | if (args_bson_ != nullptr && !BSON_APPEND_DOCUMENT(&bson, "args", args_bson_)) { 98 | std::cerr << "Error while appending 'args' bson to messge BSON" << std::endl; 99 | } 100 | } 101 | 102 | std::string service_; 103 | // The json data in the different wire-level representations 104 | rapidjson::Value args_json_; 105 | bson_t *args_bson_ = nullptr; 106 | 107 | // WARNING: 108 | // In contrast to the other bson variable above, 109 | // this BSON instance will contain the full 110 | // received rosbridge Message 111 | // when FromBSON has been called in bson_only_mode 112 | // 113 | // This is due to the absence of robust pointers to subdocuments 114 | // in bson that are still valid to use when the parent document 115 | // might get modified. 116 | bson_t *full_msg_bson_ = nullptr; 117 | 118 | private: 119 | /* data */ 120 | }; 121 | -------------------------------------------------------------------------------- /include/messages/rosbridge_msg.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "rapidjson/document.h" 4 | #include "rapidjson/writer.h" 5 | #include "rapidjson/stringbuffer.h" 6 | #include 7 | 8 | #include 9 | 10 | #include "helper.h" 11 | 12 | 13 | /* 14 | * The base class for all ROSBridge messages 15 | * 16 | * Incoming Messages will be parsed to this class 17 | */ 18 | 19 | class ROSBridgeMsg { 20 | public: 21 | enum OpCode { 22 | OPCODE_UNDEFINED, // Default value, before parsing 23 | 24 | FRAGMENT, // not implemented currently 25 | PNG, // not implemented currently 26 | SET_LEVEL, // not implemented currently 27 | STATUS, // not implemented currently 28 | AUTH, // not implemented currently 29 | ADVERTISE, 30 | UNADVERTISE, 31 | PUBLISH, 32 | SUBSCRIBE, 33 | UNSUBSCRIBE, 34 | ADVERTISE_SERVICE, 35 | UNADVERTISE_SERVICE, 36 | CALL_SERVICE, 37 | SERVICE_RESPONSE 38 | }; 39 | 40 | std::unordered_map op_code_mapping = { 41 | {"fragment", FRAGMENT}, 42 | {"png", PNG}, 43 | {"set_level", SET_LEVEL}, 44 | {"status", STATUS}, 45 | {"auth", AUTH}, 46 | {"advertise", ADVERTISE}, 47 | {"unadvertise", UNADVERTISE}, 48 | {"publish", PUBLISH}, 49 | {"subscribe", SUBSCRIBE}, 50 | {"unsubscribe", UNSUBSCRIBE}, 51 | {"advertise_service", ADVERTISE_SERVICE}, 52 | {"unadvertise_service", UNADVERTISE_SERVICE}, 53 | {"call_service", CALL_SERVICE}, 54 | {"service_response", SERVICE_RESPONSE} 55 | }; 56 | 57 | // std::unordered_map reverse_op_code_mapping = { 58 | // {OPCODE_UNDEFINED,"opcode_undefined"}, 59 | // {FRAGMENT,"fragment"}, 60 | // {PNG,"png"}, 61 | // {SET_LEVEL,"set_level"}, 62 | // {STATUS, "status"}, 63 | // {AUTH, "auth"}, 64 | // {ADVERTISE, "advertise"}, 65 | // {UNADVERTISE, "unadvertise"}, 66 | // {PUBLISH, "publish"}, 67 | // {SUBSCRIBE, "subscribe"}, 68 | // {UNSUBSCRIBE, "unsubscribe"}, 69 | // {ADVERTISE_SERVICE, "advertise_service"}, 70 | // {UNADVERTISE_SERVICE, "unadvertise_service"}, 71 | // {CALL_SERVICE, "call_service"}, 72 | // {SERVICE_RESPONSE, "service_response"} 73 | // }; 74 | 75 | ROSBridgeMsg() = default; 76 | 77 | // This method can be used to parse incoming ROSBridge messages in order 78 | // to fill the class variables from the wire representation (for example, JSON or BSON) 79 | // 80 | // Returns true if a 'op' field could be found in the given data package 81 | // 82 | // This method will care about the 'op' and 'id' key 83 | // 'op' is mandatory, while 'id' is optional 84 | bool FromJSON(const rapidjson::Document &data) 85 | { 86 | if (!data.HasMember("op")) { 87 | std::cerr << "[ROSBridgeMsg] Received message without 'op' field" << std::endl; 88 | return false; 89 | } 90 | 91 | std::string op_code = data["op"].GetString(); 92 | auto mapping_iterator = op_code_mapping.find(op_code); 93 | if (mapping_iterator == op_code_mapping.end()) { 94 | std::cerr << "[ROSBridgeMsg] Received message with invalid 'op' field: " << op_code << std::endl; 95 | return false; 96 | } 97 | 98 | op_ = mapping_iterator->second; 99 | 100 | if (!data.HasMember("id")) 101 | return true; // return true, because id is only optional 102 | 103 | id_ = data["id"].GetString(); 104 | 105 | return true; 106 | } 107 | 108 | bool FromBSON(bson_t &bson) 109 | { 110 | if (!bson_has_field(&bson, "op")) { 111 | std::cerr << "[ROSBridgeMsg] Received message without 'op' field" << std::endl; 112 | return false; 113 | } 114 | 115 | bool key_found = false; 116 | std::string op_code = rosbridge2cpp::Helper::get_utf8_by_key("op", bson, key_found); 117 | assert(key_found); // should always be true, otherwise this is contradictory to the !bson_has_field check 118 | key_found = false; 119 | 120 | auto mapping_iterator = op_code_mapping.find(op_code); 121 | if (mapping_iterator == op_code_mapping.end()) { 122 | std::cerr << "[ROSBridgeMsg] Received message with invalid 'op' field: " << op_code << std::endl; 123 | return false; 124 | } 125 | 126 | op_ = mapping_iterator->second; 127 | 128 | if (!bson_has_field(&bson, "id")) 129 | return true; // return true, because id is only optional 130 | 131 | id_ = rosbridge2cpp::Helper::get_utf8_by_key("id", bson, key_found); 132 | assert(key_found); 133 | 134 | return true; 135 | } 136 | 137 | std::string getOpCodeString() 138 | { 139 | if (op_ == OPCODE_UNDEFINED) return "opcode_undefined"; 140 | if (op_ == FRAGMENT) return "fragment"; 141 | if (op_ == PNG) return "png"; 142 | if (op_ == SET_LEVEL) return "set_level"; 143 | if (op_ == STATUS) return "status"; 144 | if (op_ == AUTH) return "auth"; 145 | if (op_ == ADVERTISE) return "advertise"; 146 | if (op_ == UNADVERTISE) return "unadvertise"; 147 | if (op_ == PUBLISH) return "publish"; 148 | if (op_ == SUBSCRIBE) return "subscribe"; 149 | if (op_ == UNSUBSCRIBE) return "unsubscribe"; 150 | if (op_ == ADVERTISE_SERVICE) return "advertise_service"; 151 | if (op_ == UNADVERTISE_SERVICE) return "unadvertise_service"; 152 | if (op_ == CALL_SERVICE) return "call_service"; 153 | if (op_ == SERVICE_RESPONSE) return "service_response"; 154 | return ""; 155 | } 156 | 157 | virtual ~ROSBridgeMsg() = default; 158 | 159 | virtual rapidjson::Document ToJSON(rapidjson::Document::AllocatorType& alloc) = 0; 160 | virtual void ToBSON(bson_t& bson) = 0; 161 | 162 | OpCode op_ = OPCODE_UNDEFINED; 163 | std::string id_ = ""; 164 | 165 | protected: 166 | // key must be valid as long as 'd' lives! 167 | void add_if_value_changed(rapidjson::Document &d, rapidjson::Document::AllocatorType& alloc, const char* key, const std::string& value) 168 | { 169 | if (!value.empty()) 170 | d.AddMember(rapidjson::StringRef(key), value, alloc); 171 | } 172 | 173 | // key must be valid as long as 'd' lives! 174 | void add_if_value_changed(rapidjson::Document &d, rapidjson::Document::AllocatorType& alloc, const char* key, int value) 175 | { 176 | if (value != -1) 177 | d.AddMember(rapidjson::StringRef(key), value, alloc); 178 | } 179 | 180 | void add_if_value_changed(bson_t &bson, const char* key, const std::string& value) 181 | { 182 | if (!value.empty()) 183 | BSON_APPEND_UTF8(&bson, key, value.c_str()); 184 | } 185 | 186 | // key must be valid as long as 'd' lives! 187 | void add_if_value_changed(bson_t &bson, const char* key, int value) 188 | { 189 | if (value != -1) 190 | BSON_APPEND_INT32(&bson, key, value); 191 | } 192 | 193 | private: 194 | /* data */ 195 | }; 196 | -------------------------------------------------------------------------------- /include/messages/rosbridge_publish_msg.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | #include "messages/rosbridge_msg.h" 6 | 7 | class ROSBridgePublishMsg : public ROSBridgeMsg { 8 | public: 9 | ROSBridgePublishMsg() : ROSBridgeMsg() {} 10 | 11 | ROSBridgePublishMsg(bool init_opcode) : ROSBridgeMsg() 12 | { 13 | if (init_opcode) 14 | op_ = ROSBridgeMsg::PUBLISH; 15 | } 16 | 17 | virtual ~ROSBridgePublishMsg() 18 | { 19 | if (msg_bson_ != nullptr) 20 | bson_destroy(msg_bson_); 21 | if (full_msg_bson_ != nullptr) 22 | bson_destroy(full_msg_bson_); 23 | } 24 | 25 | // Warning: This conversion moves the 'msg' field 26 | // out of the given JSON data into this class 27 | // 'msg' will become null afterwards. 28 | // 29 | // This method parses the "topic" and "msg" fields from 30 | // incoming publish messages into this class 31 | bool FromJSON(rapidjson::Document &data) { 32 | if (!ROSBridgeMsg::FromJSON(data)) 33 | return false; 34 | 35 | if (!data.HasMember("topic")) { 36 | std::cerr << "[ROSBridgePublishMsg] Received 'publish' message without 'topic' field." << std::endl; // TODO: use generic logging 37 | return false; 38 | } 39 | 40 | topic_ = data["topic"].GetString(); 41 | 42 | if (!data.HasMember("msg")) { 43 | std::cerr << "[ROSBridgePublishMsg] Received 'publish' message without 'msg' field." << std::endl; 44 | return false; 45 | } 46 | 47 | msg_json_ = data["msg"]; 48 | 49 | return true; 50 | } 51 | 52 | bool FromBSON(bson_t &bson) 53 | { 54 | if (!ROSBridgeMsg::FromBSON(bson)) 55 | return false; 56 | 57 | if (!bson_has_field(&bson, "topic")) { 58 | std::cerr << "[ROSBridgePublishMsg] Received 'publish' message without 'topic' field." << std::endl; 59 | return false; 60 | } 61 | 62 | bool key_found = false; 63 | topic_ = rosbridge2cpp::Helper::get_utf8_by_key("topic", bson, key_found); 64 | assert(key_found); 65 | key_found = false; 66 | 67 | if (!bson_has_field(&bson, "msg")) { 68 | std::cerr << "[ROSBridgePublishMsg] Received 'publish' message without 'msg' field." << std::endl; 69 | return false; 70 | } 71 | 72 | full_msg_bson_ = &bson; 73 | 74 | return true; 75 | } 76 | 77 | rapidjson::Document ToJSON(rapidjson::Document::AllocatorType& alloc) 78 | { 79 | rapidjson::Document d(rapidjson::kObjectType); 80 | d.AddMember("op", getOpCodeString(), alloc); 81 | 82 | add_if_value_changed(d, alloc, "id", id_); 83 | add_if_value_changed(d, alloc, "topic", topic_); 84 | add_if_value_changed(d, alloc, "type", type_); 85 | 86 | 87 | d.AddMember("latch", latch_, alloc); 88 | 89 | if (!msg_json_.IsNull()) 90 | d.AddMember("msg", msg_json_, alloc); 91 | 92 | return d; 93 | } 94 | 95 | void ToBSON(bson_t &bson) 96 | { 97 | BSON_APPEND_UTF8(&bson, "op", getOpCodeString().c_str()); 98 | add_if_value_changed(bson, "id", id_); 99 | 100 | add_if_value_changed(bson, "topic", topic_); 101 | add_if_value_changed(bson, "type", type_); 102 | 103 | BSON_APPEND_BOOL(&bson, "latch", latch_); 104 | if (msg_bson_ != nullptr && !BSON_APPEND_DOCUMENT(&bson, "msg", msg_bson_)) { 105 | std::cerr << "Error while appending 'msg' bson to messge BSON" << std::endl; 106 | } 107 | } 108 | 109 | std::string topic_; 110 | std::string type_; 111 | // std::string compression_; 112 | // std::string throttle_rate_; 113 | // std::string queue_length_; 114 | bool latch_ = false; 115 | 116 | // The json data in the different wire-level representations 117 | rapidjson::Value msg_json_; 118 | 119 | bson_t *msg_bson_ = nullptr; 120 | 121 | // WARNING: 122 | // In contrast to the other bson variable above, 123 | // this BSON instance will contain the full 124 | // received rosbridge Message 125 | // when FromBSON has been called in bson_only_mode 126 | // 127 | // This is due to the absence of robust pointers to subdocuments 128 | // in bson that are still valid to use when the parent document 129 | // might get modified. 130 | bson_t *full_msg_bson_ = nullptr; 131 | 132 | private: 133 | /* data */ 134 | }; 135 | -------------------------------------------------------------------------------- /include/messages/rosbridge_service_response_msg.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | #include "messages/rosbridge_msg.h" 6 | 7 | class ROSBridgeServiceResponseMsg : public ROSBridgeMsg { 8 | public: 9 | ROSBridgeServiceResponseMsg() : ROSBridgeMsg() {} 10 | 11 | ROSBridgeServiceResponseMsg(bool init_opcode) : ROSBridgeMsg() 12 | { 13 | if (init_opcode) 14 | op_ = ROSBridgeMsg::SERVICE_RESPONSE; 15 | } 16 | 17 | virtual ~ROSBridgeServiceResponseMsg() 18 | { 19 | if (values_bson_ != nullptr) 20 | bson_destroy(values_bson_); 21 | if (full_msg_bson_ != nullptr) 22 | bson_destroy(full_msg_bson_); 23 | } 24 | 25 | // Warning: This conversion moves the 'values' field 26 | // out of the given JSON data into this class 27 | // 'values' will become null afterwards. 28 | // 29 | // This method parses the "service", "result" and "values" fields from 30 | // incoming publish messages into this class 31 | bool FromJSON(rapidjson::Document &data) 32 | { 33 | if (!ROSBridgeMsg::FromJSON(data)) 34 | return false; 35 | 36 | if (!data.HasMember("service")) { 37 | std::cerr << "[ROSBridgeServiceResponseMsg] Received 'service_response' message without 'service' field." << std::endl; // TODO: use generic logging 38 | return false; 39 | } 40 | 41 | service_ = data["service"].GetString(); 42 | 43 | if (!data.HasMember("result")) { 44 | std::cerr << "[ROSBridgeServiceResponseMsg] Received 'service_response' message without 'result' field." << std::endl; 45 | return false; 46 | } 47 | 48 | result_ = data["result"].GetBool(); 49 | 50 | if (!data.HasMember("values")) { 51 | return true; // return true, since args is optional. Other parameters will not be set right now 52 | } 53 | 54 | values_json_ = data["values"]; 55 | 56 | return true; 57 | } 58 | 59 | bool FromBSON(bson_t &bson) 60 | { 61 | if (!ROSBridgeMsg::FromBSON(bson)) 62 | return false; 63 | 64 | if (!bson_has_field(&bson, "service")) { 65 | std::cerr << "[ROSBridgeServiceResponseMsg] Received 'service_response' message without 'service' field." << std::endl; 66 | return false; 67 | } 68 | 69 | bool key_found = false; 70 | service_ = rosbridge2cpp::Helper::get_utf8_by_key("service", bson, key_found); 71 | assert(key_found); 72 | key_found = false; 73 | 74 | if (!bson_has_field(&bson, "result")) { 75 | std::cerr << "[ROSBridgeServiceResponseMsg] Received 'service_response' message without 'result' field." << std::endl; 76 | return false; 77 | } 78 | 79 | result_ = rosbridge2cpp::Helper::get_bool_by_key("result", bson, key_found); 80 | assert(key_found); 81 | key_found = false; 82 | 83 | if (!bson_has_field(&bson, "values")) { 84 | return true; 85 | } 86 | 87 | full_msg_bson_ = &bson; 88 | 89 | return true; 90 | } 91 | 92 | rapidjson::Document ToJSON(rapidjson::Document::AllocatorType& alloc) 93 | { 94 | rapidjson::Document d(rapidjson::kObjectType); 95 | d.AddMember("op", getOpCodeString(), alloc); 96 | add_if_value_changed(d, alloc, "id", id_); 97 | add_if_value_changed(d, alloc, "service", service_); 98 | 99 | d.AddMember("result", result_, alloc); 100 | 101 | if (!values_json_.IsNull()) 102 | d.AddMember("values", values_json_, alloc); 103 | return d; 104 | } 105 | 106 | void ToBSON(bson_t &bson) 107 | { 108 | BSON_APPEND_UTF8(&bson, "op", getOpCodeString().c_str()); 109 | add_if_value_changed(bson, "id", id_); 110 | 111 | add_if_value_changed(bson, "service", service_); 112 | 113 | BSON_APPEND_BOOL(&bson, "result", result_); 114 | if (values_bson_ != nullptr && !BSON_APPEND_DOCUMENT(&bson, "values", values_bson_)) { 115 | std::cerr << "Error while appending 'values' bson to messge BSON" << std::endl; 116 | } 117 | } 118 | 119 | std::string service_; 120 | bool result_ = false; 121 | // The json data in the different wire-level representations 122 | rapidjson::Value values_json_; 123 | bson_t *values_bson_ = nullptr; 124 | 125 | // WARNING: 126 | // In contrast to the other bson variable above, 127 | // this BSON instance will contain the full 128 | // received rosbridge Message 129 | // when FromBSON has been called in bson_only_mode 130 | // 131 | // This is due to the absence of robust pointers to subdocuments 132 | // in bson that are still valid to use when the parent document 133 | // might get modified. 134 | // 135 | // This ptr will be set, when ToBSON is called and the ServiceResponse carries 'values' 136 | // Otherwise, it stays as a nullptr 137 | bson_t *full_msg_bson_ = nullptr; 138 | 139 | 140 | private: 141 | /* data */ 142 | }; 143 | -------------------------------------------------------------------------------- /include/messages/rosbridge_subscribe_msg.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | #include "messages/rosbridge_msg.h" 6 | 7 | class ROSBridgeSubscribeMsg : public ROSBridgeMsg { 8 | public: 9 | ROSBridgeSubscribeMsg() : ROSBridgeMsg() {} 10 | 11 | ROSBridgeSubscribeMsg(bool init_opcode) : ROSBridgeMsg() 12 | { 13 | if (init_opcode) 14 | op_ = ROSBridgeMsg::SUBSCRIBE; 15 | } 16 | 17 | virtual ~ROSBridgeSubscribeMsg() = default; 18 | 19 | 20 | // Subscribe messages will never be received from the client 21 | // So we don't need to fill this instance from JSON or other wire-level representations 22 | bool FromJSON(const rapidjson::Document &data) = delete; 23 | bool FromBSON(bson_t &bson) = delete; 24 | 25 | rapidjson::Document ToJSON(rapidjson::Document::AllocatorType& alloc) 26 | { 27 | rapidjson::Document d(rapidjson::kObjectType); 28 | d.AddMember("op", getOpCodeString(), alloc); 29 | 30 | add_if_value_changed(d, alloc, "id", id_); 31 | add_if_value_changed(d, alloc, "topic", topic_); 32 | add_if_value_changed(d, alloc, "type", type_); 33 | add_if_value_changed(d, alloc, "queue_length", queue_length_); 34 | add_if_value_changed(d, alloc, "throttle_rate", throttle_rate_); 35 | add_if_value_changed(d, alloc, "compression", compression_); 36 | 37 | return d; 38 | } 39 | 40 | void ToBSON(bson_t &bson) 41 | { 42 | BSON_APPEND_UTF8(&bson, "op", getOpCodeString().c_str()); 43 | add_if_value_changed(bson, "id", id_); 44 | 45 | add_if_value_changed(bson, "topic", topic_); 46 | add_if_value_changed(bson, "type", type_); 47 | add_if_value_changed(bson, "queue_length", queue_length_); 48 | add_if_value_changed(bson, "throttle_rate", throttle_rate_); 49 | add_if_value_changed(bson, "compression", compression_); 50 | } 51 | 52 | std::string topic_; 53 | std::string type_; 54 | int queue_length_ = -1; 55 | int throttle_rate_ = -1; 56 | std::string compression_; 57 | private: 58 | /* data */ 59 | }; 60 | -------------------------------------------------------------------------------- /include/messages/rosbridge_unadvertise_msg.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | #include "messages/rosbridge_msg.h" 6 | 7 | class ROSBridgeUnadvertiseMsg : public ROSBridgeMsg { 8 | public: 9 | ROSBridgeUnadvertiseMsg() : ROSBridgeMsg() {} 10 | 11 | ROSBridgeUnadvertiseMsg(bool init_opcode) : ROSBridgeMsg() 12 | { 13 | if (init_opcode) 14 | op_ = ROSBridgeMsg::UNADVERTISE; 15 | } 16 | 17 | virtual ~ROSBridgeUnadvertiseMsg() = default; 18 | 19 | 20 | // Unadvertise messages will never be received from the client 21 | // So we don't need to fill this instance from JSON or other wire-level representations 22 | bool FromJSON(const rapidjson::Document &data) = delete; 23 | bool FromBSON(bson_t &bson) = delete; 24 | 25 | rapidjson::Document ToJSON(rapidjson::Document::AllocatorType& alloc) 26 | { 27 | rapidjson::Document d(rapidjson::kObjectType); 28 | d.AddMember("op", getOpCodeString(), alloc); 29 | add_if_value_changed(d, alloc, "id", id_); 30 | add_if_value_changed(d, alloc, "topic", topic_); 31 | return d; 32 | } 33 | 34 | void ToBSON(bson_t &bson) 35 | { 36 | BSON_APPEND_UTF8(&bson, "op", getOpCodeString().c_str()); 37 | add_if_value_changed(bson, "id", id_); 38 | 39 | add_if_value_changed(bson, "topic", topic_); 40 | } 41 | 42 | 43 | std::string topic_; 44 | private: 45 | /* data */ 46 | }; 47 | -------------------------------------------------------------------------------- /include/messages/rosbridge_unadvertise_service_msg.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | #include "messages/rosbridge_msg.h" 6 | 7 | class ROSBridgeUnadvertiseServiceMsg : public ROSBridgeMsg { 8 | public: 9 | ROSBridgeUnadvertiseServiceMsg() : ROSBridgeMsg() {} 10 | 11 | ROSBridgeUnadvertiseServiceMsg(bool init_opcode) : ROSBridgeMsg() 12 | { 13 | if (init_opcode) 14 | op_ = ROSBridgeMsg::UNADVERTISE_SERVICE; 15 | } 16 | 17 | virtual ~ROSBridgeUnadvertiseServiceMsg() = default; 18 | 19 | 20 | // Unadvertise messages will never be received from the client 21 | // So we don't need to fill this instance from JSON or other wire-level representations 22 | bool FromJSON(const rapidjson::Document &data) = delete; 23 | bool FromBSON(bson_t &bson) = delete; 24 | 25 | rapidjson::Document ToJSON(rapidjson::Document::AllocatorType& alloc) 26 | { 27 | rapidjson::Document d(rapidjson::kObjectType); 28 | d.AddMember("op", getOpCodeString(), alloc); 29 | add_if_value_changed(d, alloc, "id", id_); 30 | add_if_value_changed(d, alloc, "service", service_); 31 | return d; 32 | } 33 | 34 | void ToBSON(bson_t &bson) 35 | { 36 | BSON_APPEND_UTF8(&bson, "op", getOpCodeString().c_str()); 37 | add_if_value_changed(bson, "id", id_); 38 | 39 | add_if_value_changed(bson, "service", service_); 40 | } 41 | 42 | std::string service_; 43 | private: 44 | /* data */ 45 | }; 46 | -------------------------------------------------------------------------------- /include/messages/rosbridge_unsubscribe_msg.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | #include "messages/rosbridge_msg.h" 6 | 7 | class ROSBridgeUnsubscribeMsg : public ROSBridgeMsg { 8 | public: 9 | ROSBridgeUnsubscribeMsg() : ROSBridgeMsg() {} 10 | 11 | ROSBridgeUnsubscribeMsg(bool init_opcode) : ROSBridgeMsg() 12 | { 13 | if (init_opcode) 14 | op_ = ROSBridgeMsg::UNSUBSCRIBE; 15 | } 16 | 17 | virtual ~ROSBridgeUnsubscribeMsg() = default; 18 | 19 | 20 | // Unsubscribe messages will never be received from the client 21 | // So we don't need to fill this instance from JSON or other wire-level representations 22 | bool FromJSON(const rapidjson::Document &data) = delete; 23 | bool FromBSON(bson_t &bson) = delete; 24 | 25 | rapidjson::Document ToJSON(rapidjson::Document::AllocatorType& alloc) 26 | { 27 | rapidjson::Document d(rapidjson::kObjectType); 28 | d.AddMember("op", getOpCodeString(), alloc); 29 | add_if_value_changed(d, alloc, "id", id_); 30 | add_if_value_changed(d, alloc, "topic", topic_); 31 | return d; 32 | } 33 | 34 | void ToBSON(bson_t &bson) 35 | { 36 | BSON_APPEND_UTF8(&bson, "op", getOpCodeString().c_str()); 37 | add_if_value_changed(bson, "id", id_); 38 | 39 | add_if_value_changed(bson, "topic", topic_); 40 | } 41 | 42 | std::string topic_; 43 | private: 44 | /* data */ 45 | }; 46 | -------------------------------------------------------------------------------- /include/rapidjson/error/en.h: -------------------------------------------------------------------------------- 1 | // Tencent is pleased to support the open source community by making RapidJSON available. 2 | // 3 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. 4 | // 5 | // Licensed under the MIT License (the "License"); you may not use this file except 6 | // in compliance with the License. You may obtain a copy of the License at 7 | // 8 | // http://opensource.org/licenses/MIT 9 | // 10 | // Unless required by applicable law or agreed to in writing, software distributed 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the 13 | // specific language governing permissions and limitations under the License. 14 | 15 | #ifndef RAPIDJSON_ERROR_EN_H_ 16 | #define RAPIDJSON_ERROR_EN_H_ 17 | 18 | #include "error.h" 19 | 20 | #ifdef __clang__ 21 | RAPIDJSON_DIAG_PUSH 22 | RAPIDJSON_DIAG_OFF(switch-enum) 23 | RAPIDJSON_DIAG_OFF(covered-switch-default) 24 | #endif 25 | 26 | RAPIDJSON_NAMESPACE_BEGIN 27 | 28 | //! Maps error code of parsing into error message. 29 | /*! 30 | \ingroup RAPIDJSON_ERRORS 31 | \param parseErrorCode Error code obtained in parsing. 32 | \return the error message. 33 | \note User can make a copy of this function for localization. 34 | Using switch-case is safer for future modification of error codes. 35 | */ 36 | inline const RAPIDJSON_ERROR_CHARTYPE* GetParseError_En(ParseErrorCode parseErrorCode) { 37 | switch (parseErrorCode) { 38 | case kParseErrorNone: return RAPIDJSON_ERROR_STRING("No error."); 39 | 40 | case kParseErrorDocumentEmpty: return RAPIDJSON_ERROR_STRING("The document is empty."); 41 | case kParseErrorDocumentRootNotSingular: return RAPIDJSON_ERROR_STRING("The document root must not be followed by other values."); 42 | 43 | case kParseErrorValueInvalid: return RAPIDJSON_ERROR_STRING("Invalid value."); 44 | 45 | case kParseErrorObjectMissName: return RAPIDJSON_ERROR_STRING("Missing a name for object member."); 46 | case kParseErrorObjectMissColon: return RAPIDJSON_ERROR_STRING("Missing a colon after a name of object member."); 47 | case kParseErrorObjectMissCommaOrCurlyBracket: return RAPIDJSON_ERROR_STRING("Missing a comma or '}' after an object member."); 48 | 49 | case kParseErrorArrayMissCommaOrSquareBracket: return RAPIDJSON_ERROR_STRING("Missing a comma or ']' after an array element."); 50 | 51 | case kParseErrorStringUnicodeEscapeInvalidHex: return RAPIDJSON_ERROR_STRING("Incorrect hex digit after \\u escape in string."); 52 | case kParseErrorStringUnicodeSurrogateInvalid: return RAPIDJSON_ERROR_STRING("The surrogate pair in string is invalid."); 53 | case kParseErrorStringEscapeInvalid: return RAPIDJSON_ERROR_STRING("Invalid escape character in string."); 54 | case kParseErrorStringMissQuotationMark: return RAPIDJSON_ERROR_STRING("Missing a closing quotation mark in string."); 55 | case kParseErrorStringInvalidEncoding: return RAPIDJSON_ERROR_STRING("Invalid encoding in string."); 56 | 57 | case kParseErrorNumberTooBig: return RAPIDJSON_ERROR_STRING("Number too big to be stored in double."); 58 | case kParseErrorNumberMissFraction: return RAPIDJSON_ERROR_STRING("Miss fraction part in number."); 59 | case kParseErrorNumberMissExponent: return RAPIDJSON_ERROR_STRING("Miss exponent in number."); 60 | 61 | case kParseErrorTermination: return RAPIDJSON_ERROR_STRING("Terminate parsing due to Handler error."); 62 | case kParseErrorUnspecificSyntaxError: return RAPIDJSON_ERROR_STRING("Unspecific syntax error."); 63 | 64 | default: return RAPIDJSON_ERROR_STRING("Unknown error."); 65 | } 66 | } 67 | 68 | RAPIDJSON_NAMESPACE_END 69 | 70 | #ifdef __clang__ 71 | RAPIDJSON_DIAG_POP 72 | #endif 73 | 74 | #endif // RAPIDJSON_ERROR_EN_H_ 75 | -------------------------------------------------------------------------------- /include/rapidjson/error/error.h: -------------------------------------------------------------------------------- 1 | // Tencent is pleased to support the open source community by making RapidJSON available. 2 | // 3 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. 4 | // 5 | // Licensed under the MIT License (the "License"); you may not use this file except 6 | // in compliance with the License. You may obtain a copy of the License at 7 | // 8 | // http://opensource.org/licenses/MIT 9 | // 10 | // Unless required by applicable law or agreed to in writing, software distributed 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the 13 | // specific language governing permissions and limitations under the License. 14 | 15 | #ifndef RAPIDJSON_ERROR_ERROR_H_ 16 | #define RAPIDJSON_ERROR_ERROR_H_ 17 | 18 | #include "../rapidjson.h" 19 | 20 | #ifdef __clang__ 21 | RAPIDJSON_DIAG_PUSH 22 | RAPIDJSON_DIAG_OFF(padded) 23 | #endif 24 | 25 | /*! \file error.h */ 26 | 27 | /*! \defgroup RAPIDJSON_ERRORS RapidJSON error handling */ 28 | 29 | /////////////////////////////////////////////////////////////////////////////// 30 | // RAPIDJSON_ERROR_CHARTYPE 31 | 32 | //! Character type of error messages. 33 | /*! \ingroup RAPIDJSON_ERRORS 34 | The default character type is \c char. 35 | On Windows, user can define this macro as \c TCHAR for supporting both 36 | unicode/non-unicode settings. 37 | */ 38 | #ifndef RAPIDJSON_ERROR_CHARTYPE 39 | #define RAPIDJSON_ERROR_CHARTYPE char 40 | #endif 41 | 42 | /////////////////////////////////////////////////////////////////////////////// 43 | // RAPIDJSON_ERROR_STRING 44 | 45 | //! Macro for converting string literial to \ref RAPIDJSON_ERROR_CHARTYPE[]. 46 | /*! \ingroup RAPIDJSON_ERRORS 47 | By default this conversion macro does nothing. 48 | On Windows, user can define this macro as \c _T(x) for supporting both 49 | unicode/non-unicode settings. 50 | */ 51 | #ifndef RAPIDJSON_ERROR_STRING 52 | #define RAPIDJSON_ERROR_STRING(x) x 53 | #endif 54 | 55 | RAPIDJSON_NAMESPACE_BEGIN 56 | 57 | /////////////////////////////////////////////////////////////////////////////// 58 | // ParseErrorCode 59 | 60 | //! Error code of parsing. 61 | /*! \ingroup RAPIDJSON_ERRORS 62 | \see GenericReader::Parse, GenericReader::GetParseErrorCode 63 | */ 64 | enum ParseErrorCode { 65 | kParseErrorNone = 0, //!< No error. 66 | 67 | kParseErrorDocumentEmpty, //!< The document is empty. 68 | kParseErrorDocumentRootNotSingular, //!< The document root must not follow by other values. 69 | 70 | kParseErrorValueInvalid, //!< Invalid value. 71 | 72 | kParseErrorObjectMissName, //!< Missing a name for object member. 73 | kParseErrorObjectMissColon, //!< Missing a colon after a name of object member. 74 | kParseErrorObjectMissCommaOrCurlyBracket, //!< Missing a comma or '}' after an object member. 75 | 76 | kParseErrorArrayMissCommaOrSquareBracket, //!< Missing a comma or ']' after an array element. 77 | 78 | kParseErrorStringUnicodeEscapeInvalidHex, //!< Incorrect hex digit after \\u escape in string. 79 | kParseErrorStringUnicodeSurrogateInvalid, //!< The surrogate pair in string is invalid. 80 | kParseErrorStringEscapeInvalid, //!< Invalid escape character in string. 81 | kParseErrorStringMissQuotationMark, //!< Missing a closing quotation mark in string. 82 | kParseErrorStringInvalidEncoding, //!< Invalid encoding in string. 83 | 84 | kParseErrorNumberTooBig, //!< Number too big to be stored in double. 85 | kParseErrorNumberMissFraction, //!< Miss fraction part in number. 86 | kParseErrorNumberMissExponent, //!< Miss exponent in number. 87 | 88 | kParseErrorTermination, //!< Parsing was terminated. 89 | kParseErrorUnspecificSyntaxError //!< Unspecific syntax error. 90 | }; 91 | 92 | //! Result of parsing (wraps ParseErrorCode) 93 | /*! 94 | \ingroup RAPIDJSON_ERRORS 95 | \code 96 | Document doc; 97 | ParseResult ok = doc.Parse("[42]"); 98 | if (!ok) { 99 | fprintf(stderr, "JSON parse error: %s (%u)", 100 | GetParseError_En(ok.Code()), ok.Offset()); 101 | exit(EXIT_FAILURE); 102 | } 103 | \endcode 104 | \see GenericReader::Parse, GenericDocument::Parse 105 | */ 106 | struct ParseResult { 107 | public: 108 | //! Default constructor, no error. 109 | ParseResult() : code_(kParseErrorNone), offset_(0) {} 110 | //! Constructor to set an error. 111 | ParseResult(ParseErrorCode code, size_t offset) : code_(code), offset_(offset) {} 112 | 113 | //! Get the error code. 114 | ParseErrorCode Code() const { return code_; } 115 | //! Get the error offset, if \ref IsError(), 0 otherwise. 116 | size_t Offset() const { return offset_; } 117 | 118 | //! Conversion to \c bool, returns \c true, iff !\ref IsError(). 119 | operator bool() const { return !IsError(); } 120 | //! Whether the result is an error. 121 | bool IsError() const { return code_ != kParseErrorNone; } 122 | 123 | bool operator==(const ParseResult& that) const { return code_ == that.code_; } 124 | bool operator==(ParseErrorCode code) const { return code_ == code; } 125 | friend bool operator==(ParseErrorCode code, const ParseResult & err) { return code == err.code_; } 126 | 127 | //! Reset error code. 128 | void Clear() { Set(kParseErrorNone); } 129 | //! Update error code and offset. 130 | void Set(ParseErrorCode code, size_t offset = 0) { code_ = code; offset_ = offset; } 131 | 132 | private: 133 | ParseErrorCode code_; 134 | size_t offset_; 135 | }; 136 | 137 | //! Function pointer type of GetParseError(). 138 | /*! \ingroup RAPIDJSON_ERRORS 139 | 140 | This is the prototype for \c GetParseError_X(), where \c X is a locale. 141 | User can dynamically change locale in runtime, e.g.: 142 | \code 143 | GetParseErrorFunc GetParseError = GetParseError_En; // or whatever 144 | const RAPIDJSON_ERROR_CHARTYPE* s = GetParseError(document.GetParseErrorCode()); 145 | \endcode 146 | */ 147 | typedef const RAPIDJSON_ERROR_CHARTYPE* (*GetParseErrorFunc)(ParseErrorCode); 148 | 149 | RAPIDJSON_NAMESPACE_END 150 | 151 | #ifdef __clang__ 152 | RAPIDJSON_DIAG_POP 153 | #endif 154 | 155 | #endif // RAPIDJSON_ERROR_ERROR_H_ 156 | -------------------------------------------------------------------------------- /include/rapidjson/filereadstream.h: -------------------------------------------------------------------------------- 1 | // Tencent is pleased to support the open source community by making RapidJSON available. 2 | // 3 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. 4 | // 5 | // Licensed under the MIT License (the "License"); you may not use this file except 6 | // in compliance with the License. You may obtain a copy of the License at 7 | // 8 | // http://opensource.org/licenses/MIT 9 | // 10 | // Unless required by applicable law or agreed to in writing, software distributed 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the 13 | // specific language governing permissions and limitations under the License. 14 | 15 | #ifndef RAPIDJSON_FILEREADSTREAM_H_ 16 | #define RAPIDJSON_FILEREADSTREAM_H_ 17 | 18 | #include "stream.h" 19 | #include 20 | 21 | #ifdef __clang__ 22 | RAPIDJSON_DIAG_PUSH 23 | RAPIDJSON_DIAG_OFF(padded) 24 | RAPIDJSON_DIAG_OFF(unreachable-code) 25 | RAPIDJSON_DIAG_OFF(missing-noreturn) 26 | #endif 27 | 28 | RAPIDJSON_NAMESPACE_BEGIN 29 | 30 | //! File byte stream for input using fread(). 31 | /*! 32 | \note implements Stream concept 33 | */ 34 | class FileReadStream { 35 | public: 36 | typedef char Ch; //!< Character type (byte). 37 | 38 | //! Constructor. 39 | /*! 40 | \param fp File pointer opened for read. 41 | \param buffer user-supplied buffer. 42 | \param bufferSize size of buffer in bytes. Must >=4 bytes. 43 | */ 44 | FileReadStream(std::FILE* fp, char* buffer, size_t bufferSize) : fp_(fp), buffer_(buffer), bufferSize_(bufferSize), bufferLast_(0), current_(buffer_), readCount_(0), count_(0), eof_(false) { 45 | RAPIDJSON_ASSERT(fp_ != 0); 46 | RAPIDJSON_ASSERT(bufferSize >= 4); 47 | Read(); 48 | } 49 | 50 | Ch Peek() const { return *current_; } 51 | Ch Take() { Ch c = *current_; Read(); return c; } 52 | size_t Tell() const { return count_ + static_cast(current_ - buffer_); } 53 | 54 | // Not implemented 55 | void Put(Ch) { RAPIDJSON_ASSERT(false); } 56 | void Flush() { RAPIDJSON_ASSERT(false); } 57 | Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; } 58 | size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; } 59 | 60 | // For encoding detection only. 61 | const Ch* Peek4() const { 62 | return (current_ + 4 <= bufferLast_) ? current_ : 0; 63 | } 64 | 65 | private: 66 | void Read() { 67 | if (current_ < bufferLast_) 68 | ++current_; 69 | else if (!eof_) { 70 | count_ += readCount_; 71 | readCount_ = fread(buffer_, 1, bufferSize_, fp_); 72 | bufferLast_ = buffer_ + readCount_ - 1; 73 | current_ = buffer_; 74 | 75 | if (readCount_ < bufferSize_) { 76 | buffer_[readCount_] = '\0'; 77 | ++bufferLast_; 78 | eof_ = true; 79 | } 80 | } 81 | } 82 | 83 | std::FILE* fp_; 84 | Ch *buffer_; 85 | size_t bufferSize_; 86 | Ch *bufferLast_; 87 | Ch *current_; 88 | size_t readCount_; 89 | size_t count_; //!< Number of characters read 90 | bool eof_; 91 | }; 92 | 93 | RAPIDJSON_NAMESPACE_END 94 | 95 | #ifdef __clang__ 96 | RAPIDJSON_DIAG_POP 97 | #endif 98 | 99 | #endif // RAPIDJSON_FILESTREAM_H_ 100 | -------------------------------------------------------------------------------- /include/rapidjson/filewritestream.h: -------------------------------------------------------------------------------- 1 | // Tencent is pleased to support the open source community by making RapidJSON available. 2 | // 3 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. 4 | // 5 | // Licensed under the MIT License (the "License"); you may not use this file except 6 | // in compliance with the License. You may obtain a copy of the License at 7 | // 8 | // http://opensource.org/licenses/MIT 9 | // 10 | // Unless required by applicable law or agreed to in writing, software distributed 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the 13 | // specific language governing permissions and limitations under the License. 14 | 15 | #ifndef RAPIDJSON_FILEWRITESTREAM_H_ 16 | #define RAPIDJSON_FILEWRITESTREAM_H_ 17 | 18 | #include "stream.h" 19 | #include 20 | 21 | #ifdef __clang__ 22 | RAPIDJSON_DIAG_PUSH 23 | RAPIDJSON_DIAG_OFF(unreachable-code) 24 | #endif 25 | 26 | RAPIDJSON_NAMESPACE_BEGIN 27 | 28 | //! Wrapper of C file stream for input using fread(). 29 | /*! 30 | \note implements Stream concept 31 | */ 32 | class FileWriteStream { 33 | public: 34 | typedef char Ch; //!< Character type. Only support char. 35 | 36 | FileWriteStream(std::FILE* fp, char* buffer, size_t bufferSize) : fp_(fp), buffer_(buffer), bufferEnd_(buffer + bufferSize), current_(buffer_) { 37 | RAPIDJSON_ASSERT(fp_ != 0); 38 | } 39 | 40 | void Put(char c) { 41 | if (current_ >= bufferEnd_) 42 | Flush(); 43 | 44 | *current_++ = c; 45 | } 46 | 47 | void PutN(char c, size_t n) { 48 | size_t avail = static_cast(bufferEnd_ - current_); 49 | while (n > avail) { 50 | std::memset(current_, c, avail); 51 | current_ += avail; 52 | Flush(); 53 | n -= avail; 54 | avail = static_cast(bufferEnd_ - current_); 55 | } 56 | 57 | if (n > 0) { 58 | std::memset(current_, c, n); 59 | current_ += n; 60 | } 61 | } 62 | 63 | void Flush() { 64 | if (current_ != buffer_) { 65 | size_t result = fwrite(buffer_, 1, static_cast(current_ - buffer_), fp_); 66 | if (result < static_cast(current_ - buffer_)) { 67 | // failure deliberately ignored at this time 68 | // added to avoid warn_unused_result build errors 69 | } 70 | current_ = buffer_; 71 | } 72 | } 73 | 74 | // Not implemented 75 | char Peek() const { RAPIDJSON_ASSERT(false); return 0; } 76 | char Take() { RAPIDJSON_ASSERT(false); return 0; } 77 | size_t Tell() const { RAPIDJSON_ASSERT(false); return 0; } 78 | char* PutBegin() { RAPIDJSON_ASSERT(false); return 0; } 79 | size_t PutEnd(char*) { RAPIDJSON_ASSERT(false); return 0; } 80 | 81 | private: 82 | // Prohibit copy constructor & assignment operator. 83 | FileWriteStream(const FileWriteStream&); 84 | FileWriteStream& operator=(const FileWriteStream&); 85 | 86 | std::FILE* fp_; 87 | char *buffer_; 88 | char *bufferEnd_; 89 | char *current_; 90 | }; 91 | 92 | //! Implement specialized version of PutN() with memset() for better performance. 93 | template<> 94 | inline void PutN(FileWriteStream& stream, char c, size_t n) { 95 | stream.PutN(c, n); 96 | } 97 | 98 | RAPIDJSON_NAMESPACE_END 99 | 100 | #ifdef __clang__ 101 | RAPIDJSON_DIAG_POP 102 | #endif 103 | 104 | #endif // RAPIDJSON_FILESTREAM_H_ 105 | -------------------------------------------------------------------------------- /include/rapidjson/fwd.h: -------------------------------------------------------------------------------- 1 | // Tencent is pleased to support the open source community by making RapidJSON available. 2 | // 3 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. 4 | // 5 | // Licensed under the MIT License (the "License"); you may not use this file except 6 | // in compliance with the License. You may obtain a copy of the License at 7 | // 8 | // http://opensource.org/licenses/MIT 9 | // 10 | // Unless required by applicable law or agreed to in writing, software distributed 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the 13 | // specific language governing permissions and limitations under the License. 14 | 15 | #ifndef RAPIDJSON_FWD_H_ 16 | #define RAPIDJSON_FWD_H_ 17 | 18 | #include "rapidjson.h" 19 | 20 | RAPIDJSON_NAMESPACE_BEGIN 21 | 22 | // encodings.h 23 | 24 | template struct UTF8; 25 | template struct UTF16; 26 | template struct UTF16BE; 27 | template struct UTF16LE; 28 | template struct UTF32; 29 | template struct UTF32BE; 30 | template struct UTF32LE; 31 | template struct ASCII; 32 | template struct AutoUTF; 33 | 34 | template 35 | struct Transcoder; 36 | 37 | // allocators.h 38 | 39 | class CrtAllocator; 40 | 41 | template 42 | class MemoryPoolAllocator; 43 | 44 | // stream.h 45 | 46 | template 47 | struct GenericStringStream; 48 | 49 | typedef GenericStringStream > StringStream; 50 | 51 | template 52 | struct GenericInsituStringStream; 53 | 54 | typedef GenericInsituStringStream > InsituStringStream; 55 | 56 | // stringbuffer.h 57 | 58 | template 59 | class GenericStringBuffer; 60 | 61 | typedef GenericStringBuffer, CrtAllocator> StringBuffer; 62 | 63 | // filereadstream.h 64 | 65 | class FileReadStream; 66 | 67 | // filewritestream.h 68 | 69 | class FileWriteStream; 70 | 71 | // memorybuffer.h 72 | 73 | template 74 | struct GenericMemoryBuffer; 75 | 76 | typedef GenericMemoryBuffer MemoryBuffer; 77 | 78 | // memorystream.h 79 | 80 | struct MemoryStream; 81 | 82 | // reader.h 83 | 84 | template 85 | struct BaseReaderHandler; 86 | 87 | template 88 | class GenericReader; 89 | 90 | typedef GenericReader, UTF8, CrtAllocator> Reader; 91 | 92 | // writer.h 93 | 94 | template 95 | class Writer; 96 | 97 | // prettywriter.h 98 | 99 | template 100 | class PrettyWriter; 101 | 102 | // document.h 103 | 104 | template 105 | struct GenericMember; 106 | 107 | template 108 | class GenericMemberIterator; 109 | 110 | template 111 | struct GenericStringRef; 112 | 113 | template 114 | class GenericValue; 115 | 116 | typedef GenericValue, MemoryPoolAllocator > Value; 117 | 118 | template 119 | class GenericDocument; 120 | 121 | typedef GenericDocument, MemoryPoolAllocator, CrtAllocator> Document; 122 | 123 | // pointer.h 124 | 125 | template 126 | class GenericPointer; 127 | 128 | typedef GenericPointer Pointer; 129 | 130 | // schema.h 131 | 132 | template 133 | class IGenericRemoteSchemaDocumentProvider; 134 | 135 | template 136 | class GenericSchemaDocument; 137 | 138 | typedef GenericSchemaDocument SchemaDocument; 139 | typedef IGenericRemoteSchemaDocumentProvider IRemoteSchemaDocumentProvider; 140 | 141 | template < 142 | typename SchemaDocumentType, 143 | typename OutputHandler, 144 | typename StateAllocator> 145 | class GenericSchemaValidator; 146 | 147 | typedef GenericSchemaValidator, void>, CrtAllocator> SchemaValidator; 148 | 149 | RAPIDJSON_NAMESPACE_END 150 | 151 | #endif // RAPIDJSON_RAPIDJSONFWD_H_ 152 | -------------------------------------------------------------------------------- /include/rapidjson/internal/biginteger.h: -------------------------------------------------------------------------------- 1 | // Tencent is pleased to support the open source community by making RapidJSON available. 2 | // 3 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. 4 | // 5 | // Licensed under the MIT License (the "License"); you may not use this file except 6 | // in compliance with the License. You may obtain a copy of the License at 7 | // 8 | // http://opensource.org/licenses/MIT 9 | // 10 | // Unless required by applicable law or agreed to in writing, software distributed 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the 13 | // specific language governing permissions and limitations under the License. 14 | 15 | #ifndef RAPIDJSON_BIGINTEGER_H_ 16 | #define RAPIDJSON_BIGINTEGER_H_ 17 | 18 | #include "../rapidjson.h" 19 | 20 | #if defined(_MSC_VER) && defined(_M_AMD64) 21 | #include // for _umul128 22 | #pragma intrinsic(_umul128) 23 | #endif 24 | 25 | RAPIDJSON_NAMESPACE_BEGIN 26 | namespace internal { 27 | 28 | class BigInteger { 29 | public: 30 | typedef uint64_t Type; 31 | 32 | BigInteger(const BigInteger& rhs) : count_(rhs.count_) { 33 | std::memcpy(digits_, rhs.digits_, count_ * sizeof(Type)); 34 | } 35 | 36 | explicit BigInteger(uint64_t u) : count_(1) { 37 | digits_[0] = u; 38 | } 39 | 40 | BigInteger(const char* decimals, size_t length) : count_(1) { 41 | RAPIDJSON_ASSERT(length > 0); 42 | digits_[0] = 0; 43 | size_t i = 0; 44 | const size_t kMaxDigitPerIteration = 19; // 2^64 = 18446744073709551616 > 10^19 45 | while (length >= kMaxDigitPerIteration) { 46 | AppendDecimal64(decimals + i, decimals + i + kMaxDigitPerIteration); 47 | length -= kMaxDigitPerIteration; 48 | i += kMaxDigitPerIteration; 49 | } 50 | 51 | if (length > 0) 52 | AppendDecimal64(decimals + i, decimals + i + length); 53 | } 54 | 55 | BigInteger& operator=(const BigInteger &rhs) 56 | { 57 | if (this != &rhs) { 58 | count_ = rhs.count_; 59 | std::memcpy(digits_, rhs.digits_, count_ * sizeof(Type)); 60 | } 61 | return *this; 62 | } 63 | 64 | BigInteger& operator=(uint64_t u) { 65 | digits_[0] = u; 66 | count_ = 1; 67 | return *this; 68 | } 69 | 70 | BigInteger& operator+=(uint64_t u) { 71 | Type backup = digits_[0]; 72 | digits_[0] += u; 73 | for (size_t i = 0; i < count_ - 1; i++) { 74 | if (digits_[i] >= backup) 75 | return *this; // no carry 76 | backup = digits_[i + 1]; 77 | digits_[i + 1] += 1; 78 | } 79 | 80 | // Last carry 81 | if (digits_[count_ - 1] < backup) 82 | PushBack(1); 83 | 84 | return *this; 85 | } 86 | 87 | BigInteger& operator*=(uint64_t u) { 88 | if (u == 0) return *this = 0; 89 | if (u == 1) return *this; 90 | if (*this == 1) return *this = u; 91 | 92 | uint64_t k = 0; 93 | for (size_t i = 0; i < count_; i++) { 94 | uint64_t hi; 95 | digits_[i] = MulAdd64(digits_[i], u, k, &hi); 96 | k = hi; 97 | } 98 | 99 | if (k > 0) 100 | PushBack(k); 101 | 102 | return *this; 103 | } 104 | 105 | BigInteger& operator*=(uint32_t u) { 106 | if (u == 0) return *this = 0; 107 | if (u == 1) return *this; 108 | if (*this == 1) return *this = u; 109 | 110 | uint64_t k = 0; 111 | for (size_t i = 0; i < count_; i++) { 112 | const uint64_t c = digits_[i] >> 32; 113 | const uint64_t d = digits_[i] & 0xFFFFFFFF; 114 | const uint64_t uc = u * c; 115 | const uint64_t ud = u * d; 116 | const uint64_t p0 = ud + k; 117 | const uint64_t p1 = uc + (p0 >> 32); 118 | digits_[i] = (p0 & 0xFFFFFFFF) | (p1 << 32); 119 | k = p1 >> 32; 120 | } 121 | 122 | if (k > 0) 123 | PushBack(k); 124 | 125 | return *this; 126 | } 127 | 128 | BigInteger& operator<<=(size_t shift) { 129 | if (IsZero() || shift == 0) return *this; 130 | 131 | size_t offset = shift / kTypeBit; 132 | size_t interShift = shift % kTypeBit; 133 | RAPIDJSON_ASSERT(count_ + offset <= kCapacity); 134 | 135 | if (interShift == 0) { 136 | std::memmove(&digits_[count_ - 1 + offset], &digits_[count_ - 1], count_ * sizeof(Type)); 137 | count_ += offset; 138 | } 139 | else { 140 | digits_[count_] = 0; 141 | for (size_t i = count_; i > 0; i--) 142 | digits_[i + offset] = (digits_[i] << interShift) | (digits_[i - 1] >> (kTypeBit - interShift)); 143 | digits_[offset] = digits_[0] << interShift; 144 | count_ += offset; 145 | if (digits_[count_]) 146 | count_++; 147 | } 148 | 149 | std::memset(digits_, 0, offset * sizeof(Type)); 150 | 151 | return *this; 152 | } 153 | 154 | bool operator==(const BigInteger& rhs) const { 155 | return count_ == rhs.count_ && std::memcmp(digits_, rhs.digits_, count_ * sizeof(Type)) == 0; 156 | } 157 | 158 | bool operator==(const Type rhs) const { 159 | return count_ == 1 && digits_[0] == rhs; 160 | } 161 | 162 | BigInteger& MultiplyPow5(unsigned exp) { 163 | static const uint32_t kPow5[12] = { 164 | 5, 165 | 5 * 5, 166 | 5 * 5 * 5, 167 | 5 * 5 * 5 * 5, 168 | 5 * 5 * 5 * 5 * 5, 169 | 5 * 5 * 5 * 5 * 5 * 5, 170 | 5 * 5 * 5 * 5 * 5 * 5 * 5, 171 | 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5, 172 | 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5, 173 | 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5, 174 | 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5, 175 | 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 176 | }; 177 | if (exp == 0) return *this; 178 | for (; exp >= 27; exp -= 27) *this *= RAPIDJSON_UINT64_C2(0X6765C793, 0XFA10079D); // 5^27 179 | for (; exp >= 13; exp -= 13) *this *= static_cast(1220703125u); // 5^13 180 | if (exp > 0) *this *= kPow5[exp - 1]; 181 | return *this; 182 | } 183 | 184 | // Compute absolute difference of this and rhs. 185 | // Assume this != rhs 186 | bool Difference(const BigInteger& rhs, BigInteger* out) const { 187 | int cmp = Compare(rhs); 188 | RAPIDJSON_ASSERT(cmp != 0); 189 | const BigInteger *a, *b; // Makes a > b 190 | bool ret; 191 | if (cmp < 0) { a = &rhs; b = this; ret = true; } 192 | else { a = this; b = &rhs; ret = false; } 193 | 194 | Type borrow = 0; 195 | for (size_t i = 0; i < a->count_; i++) { 196 | Type d = a->digits_[i] - borrow; 197 | if (i < b->count_) 198 | d -= b->digits_[i]; 199 | borrow = (d > a->digits_[i]) ? 1 : 0; 200 | out->digits_[i] = d; 201 | if (d != 0) 202 | out->count_ = i + 1; 203 | } 204 | 205 | return ret; 206 | } 207 | 208 | int Compare(const BigInteger& rhs) const { 209 | if (count_ != rhs.count_) 210 | return count_ < rhs.count_ ? -1 : 1; 211 | 212 | for (size_t i = count_; i-- > 0;) 213 | if (digits_[i] != rhs.digits_[i]) 214 | return digits_[i] < rhs.digits_[i] ? -1 : 1; 215 | 216 | return 0; 217 | } 218 | 219 | size_t GetCount() const { return count_; } 220 | Type GetDigit(size_t index) const { RAPIDJSON_ASSERT(index < count_); return digits_[index]; } 221 | bool IsZero() const { return count_ == 1 && digits_[0] == 0; } 222 | 223 | private: 224 | void AppendDecimal64(const char* begin, const char* end) { 225 | uint64_t u = ParseUint64(begin, end); 226 | if (IsZero()) 227 | *this = u; 228 | else { 229 | unsigned exp = static_cast(end - begin); 230 | (MultiplyPow5(exp) <<= exp) += u; // *this = *this * 10^exp + u 231 | } 232 | } 233 | 234 | void PushBack(Type digit) { 235 | RAPIDJSON_ASSERT(count_ < kCapacity); 236 | digits_[count_++] = digit; 237 | } 238 | 239 | static uint64_t ParseUint64(const char* begin, const char* end) { 240 | uint64_t r = 0; 241 | for (const char* p = begin; p != end; ++p) { 242 | RAPIDJSON_ASSERT(*p >= '0' && *p <= '9'); 243 | r = r * 10u + static_cast(*p - '0'); 244 | } 245 | return r; 246 | } 247 | 248 | // Assume a * b + k < 2^128 249 | static uint64_t MulAdd64(uint64_t a, uint64_t b, uint64_t k, uint64_t* outHigh) { 250 | #if defined(_MSC_VER) && defined(_M_AMD64) 251 | uint64_t low = _umul128(a, b, outHigh) + k; 252 | if (low < k) 253 | (*outHigh)++; 254 | return low; 255 | #elif (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) && defined(__x86_64__) 256 | __extension__ typedef unsigned __int128 uint128; 257 | uint128 p = static_cast(a) * static_cast(b); 258 | p += k; 259 | *outHigh = static_cast(p >> 64); 260 | return static_cast(p); 261 | #else 262 | const uint64_t a0 = a & 0xFFFFFFFF, a1 = a >> 32, b0 = b & 0xFFFFFFFF, b1 = b >> 32; 263 | uint64_t x0 = a0 * b0, x1 = a0 * b1, x2 = a1 * b0, x3 = a1 * b1; 264 | x1 += (x0 >> 32); // can't give carry 265 | x1 += x2; 266 | if (x1 < x2) 267 | x3 += (static_cast(1) << 32); 268 | uint64_t lo = (x1 << 32) + (x0 & 0xFFFFFFFF); 269 | uint64_t hi = x3 + (x1 >> 32); 270 | 271 | lo += k; 272 | if (lo < k) 273 | hi++; 274 | *outHigh = hi; 275 | return lo; 276 | #endif 277 | } 278 | 279 | static const size_t kBitCount = 3328; // 64bit * 54 > 10^1000 280 | static const size_t kCapacity = kBitCount / sizeof(Type); 281 | static const size_t kTypeBit = sizeof(Type) * 8; 282 | 283 | Type digits_[kCapacity]; 284 | size_t count_; 285 | }; 286 | 287 | } // namespace internal 288 | RAPIDJSON_NAMESPACE_END 289 | 290 | #endif // RAPIDJSON_BIGINTEGER_H_ 291 | -------------------------------------------------------------------------------- /include/rapidjson/internal/dtoa.h: -------------------------------------------------------------------------------- 1 | // Tencent is pleased to support the open source community by making RapidJSON available. 2 | // 3 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. 4 | // 5 | // Licensed under the MIT License (the "License"); you may not use this file except 6 | // in compliance with the License. You may obtain a copy of the License at 7 | // 8 | // http://opensource.org/licenses/MIT 9 | // 10 | // Unless required by applicable law or agreed to in writing, software distributed 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the 13 | // specific language governing permissions and limitations under the License. 14 | 15 | // This is a C++ header-only implementation of Grisu2 algorithm from the publication: 16 | // Loitsch, Florian. "Printing floating-point numbers quickly and accurately with 17 | // integers." ACM Sigplan Notices 45.6 (2010): 233-243. 18 | 19 | #ifndef RAPIDJSON_DTOA_ 20 | #define RAPIDJSON_DTOA_ 21 | 22 | #include "itoa.h" // GetDigitsLut() 23 | #include "diyfp.h" 24 | #include "ieee754.h" 25 | 26 | RAPIDJSON_NAMESPACE_BEGIN 27 | namespace internal { 28 | 29 | #ifdef __GNUC__ 30 | RAPIDJSON_DIAG_PUSH 31 | RAPIDJSON_DIAG_OFF(effc++) 32 | RAPIDJSON_DIAG_OFF(array-bounds) // some gcc versions generate wrong warnings https://gcc.gnu.org/bugzilla/show_bug.cgi?id=59124 33 | #endif 34 | 35 | inline void GrisuRound(char* buffer, int len, uint64_t delta, uint64_t rest, uint64_t ten_kappa, uint64_t wp_w) { 36 | while (rest < wp_w && delta - rest >= ten_kappa && 37 | (rest + ten_kappa < wp_w || /// closer 38 | wp_w - rest > rest + ten_kappa - wp_w)) { 39 | buffer[len - 1]--; 40 | rest += ten_kappa; 41 | } 42 | } 43 | 44 | inline unsigned CountDecimalDigit32(uint32_t n) { 45 | // Simple pure C++ implementation was faster than __builtin_clz version in this situation. 46 | if (n < 10) return 1; 47 | if (n < 100) return 2; 48 | if (n < 1000) return 3; 49 | if (n < 10000) return 4; 50 | if (n < 100000) return 5; 51 | if (n < 1000000) return 6; 52 | if (n < 10000000) return 7; 53 | if (n < 100000000) return 8; 54 | // Will not reach 10 digits in DigitGen() 55 | //if (n < 1000000000) return 9; 56 | //return 10; 57 | return 9; 58 | } 59 | 60 | inline void DigitGen(const DiyFp& W, const DiyFp& Mp, uint64_t delta, char* buffer, int* len, int* K) { 61 | static const uint32_t kPow10[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 }; 62 | const DiyFp one(uint64_t(1) << -Mp.e, Mp.e); 63 | const DiyFp wp_w = Mp - W; 64 | uint32_t p1 = static_cast(Mp.f >> -one.e); 65 | uint64_t p2 = Mp.f & (one.f - 1); 66 | unsigned kappa = CountDecimalDigit32(p1); // kappa in [0, 9] 67 | *len = 0; 68 | 69 | while (kappa > 0) { 70 | uint32_t d = 0; 71 | switch (kappa) { 72 | case 9: d = p1 / 100000000; p1 %= 100000000; break; 73 | case 8: d = p1 / 10000000; p1 %= 10000000; break; 74 | case 7: d = p1 / 1000000; p1 %= 1000000; break; 75 | case 6: d = p1 / 100000; p1 %= 100000; break; 76 | case 5: d = p1 / 10000; p1 %= 10000; break; 77 | case 4: d = p1 / 1000; p1 %= 1000; break; 78 | case 3: d = p1 / 100; p1 %= 100; break; 79 | case 2: d = p1 / 10; p1 %= 10; break; 80 | case 1: d = p1; p1 = 0; break; 81 | default:; 82 | } 83 | if (d || *len) 84 | buffer[(*len)++] = static_cast('0' + static_cast(d)); 85 | kappa--; 86 | uint64_t tmp = (static_cast(p1) << -one.e) + p2; 87 | if (tmp <= delta) { 88 | *K += kappa; 89 | GrisuRound(buffer, *len, delta, tmp, static_cast(kPow10[kappa]) << -one.e, wp_w.f); 90 | return; 91 | } 92 | } 93 | 94 | // kappa = 0 95 | for (;;) { 96 | p2 *= 10; 97 | delta *= 10; 98 | char d = static_cast(p2 >> -one.e); 99 | if (d || *len) 100 | buffer[(*len)++] = static_cast('0' + d); 101 | p2 &= one.f - 1; 102 | kappa--; 103 | if (p2 < delta) { 104 | *K += kappa; 105 | int index = -static_cast(kappa); 106 | GrisuRound(buffer, *len, delta, p2, one.f, wp_w.f * (index < 9 ? kPow10[-static_cast(kappa)] : 0)); 107 | return; 108 | } 109 | } 110 | } 111 | 112 | inline void Grisu2(double value, char* buffer, int* length, int* K) { 113 | const DiyFp v(value); 114 | DiyFp w_m, w_p; 115 | v.NormalizedBoundaries(&w_m, &w_p); 116 | 117 | const DiyFp c_mk = GetCachedPower(w_p.e, K); 118 | const DiyFp W = v.Normalize() * c_mk; 119 | DiyFp Wp = w_p * c_mk; 120 | DiyFp Wm = w_m * c_mk; 121 | Wm.f++; 122 | Wp.f--; 123 | DigitGen(W, Wp, Wp.f - Wm.f, buffer, length, K); 124 | } 125 | 126 | inline char* WriteExponent(int K, char* buffer) { 127 | if (K < 0) { 128 | *buffer++ = '-'; 129 | K = -K; 130 | } 131 | 132 | if (K >= 100) { 133 | *buffer++ = static_cast('0' + static_cast(K / 100)); 134 | K %= 100; 135 | const char* d = GetDigitsLut() + K * 2; 136 | *buffer++ = d[0]; 137 | *buffer++ = d[1]; 138 | } 139 | else if (K >= 10) { 140 | const char* d = GetDigitsLut() + K * 2; 141 | *buffer++ = d[0]; 142 | *buffer++ = d[1]; 143 | } 144 | else 145 | *buffer++ = static_cast('0' + static_cast(K)); 146 | 147 | return buffer; 148 | } 149 | 150 | inline char* Prettify(char* buffer, int length, int k, int maxDecimalPlaces) { 151 | const int kk = length + k; // 10^(kk-1) <= v < 10^kk 152 | 153 | if (0 <= k && kk <= 21) { 154 | // 1234e7 -> 12340000000 155 | for (int i = length; i < kk; i++) 156 | buffer[i] = '0'; 157 | buffer[kk] = '.'; 158 | buffer[kk + 1] = '0'; 159 | return &buffer[kk + 2]; 160 | } 161 | else if (0 < kk && kk <= 21) { 162 | // 1234e-2 -> 12.34 163 | std::memmove(&buffer[kk + 1], &buffer[kk], static_cast(length - kk)); 164 | buffer[kk] = '.'; 165 | if (0 > k + maxDecimalPlaces) { 166 | // When maxDecimalPlaces = 2, 1.2345 -> 1.23, 1.102 -> 1.1 167 | // Remove extra trailing zeros (at least one) after truncation. 168 | for (int i = kk + maxDecimalPlaces; i > kk + 1; i--) 169 | if (buffer[i] != '0') 170 | return &buffer[i + 1]; 171 | return &buffer[kk + 2]; // Reserve one zero 172 | } 173 | else 174 | return &buffer[length + 1]; 175 | } 176 | else if (-6 < kk && kk <= 0) { 177 | // 1234e-6 -> 0.001234 178 | const int offset = 2 - kk; 179 | std::memmove(&buffer[offset], &buffer[0], static_cast(length)); 180 | buffer[0] = '0'; 181 | buffer[1] = '.'; 182 | for (int i = 2; i < offset; i++) 183 | buffer[i] = '0'; 184 | if (length - kk > maxDecimalPlaces) { 185 | // When maxDecimalPlaces = 2, 0.123 -> 0.12, 0.102 -> 0.1 186 | // Remove extra trailing zeros (at least one) after truncation. 187 | for (int i = maxDecimalPlaces + 1; i > 2; i--) 188 | if (buffer[i] != '0') 189 | return &buffer[i + 1]; 190 | return &buffer[3]; // Reserve one zero 191 | } 192 | else 193 | return &buffer[length + offset]; 194 | } 195 | else if (kk < -maxDecimalPlaces) { 196 | // Truncate to zero 197 | buffer[0] = '0'; 198 | buffer[1] = '.'; 199 | buffer[2] = '0'; 200 | return &buffer[3]; 201 | } 202 | else if (length == 1) { 203 | // 1e30 204 | buffer[1] = 'e'; 205 | return WriteExponent(kk - 1, &buffer[2]); 206 | } 207 | else { 208 | // 1234e30 -> 1.234e33 209 | std::memmove(&buffer[2], &buffer[1], static_cast(length - 1)); 210 | buffer[1] = '.'; 211 | buffer[length + 1] = 'e'; 212 | return WriteExponent(kk - 1, &buffer[0 + length + 2]); 213 | } 214 | } 215 | 216 | inline char* dtoa(double value, char* buffer, int maxDecimalPlaces = 324) { 217 | RAPIDJSON_ASSERT(maxDecimalPlaces >= 1); 218 | Double d(value); 219 | if (d.IsZero()) { 220 | if (d.Sign()) 221 | *buffer++ = '-'; // -0.0, Issue #289 222 | buffer[0] = '0'; 223 | buffer[1] = '.'; 224 | buffer[2] = '0'; 225 | return &buffer[3]; 226 | } 227 | else { 228 | if (value < 0) { 229 | *buffer++ = '-'; 230 | value = -value; 231 | } 232 | int length, K; 233 | Grisu2(value, buffer, &length, &K); 234 | return Prettify(buffer, length, K, maxDecimalPlaces); 235 | } 236 | } 237 | 238 | #ifdef __GNUC__ 239 | RAPIDJSON_DIAG_POP 240 | #endif 241 | 242 | } // namespace internal 243 | RAPIDJSON_NAMESPACE_END 244 | 245 | #endif // RAPIDJSON_DTOA_ 246 | -------------------------------------------------------------------------------- /include/rapidjson/internal/ieee754.h: -------------------------------------------------------------------------------- 1 | // Tencent is pleased to support the open source community by making RapidJSON available. 2 | // 3 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. 4 | // 5 | // Licensed under the MIT License (the "License"); you may not use this file except 6 | // in compliance with the License. You may obtain a copy of the License at 7 | // 8 | // http://opensource.org/licenses/MIT 9 | // 10 | // Unless required by applicable law or agreed to in writing, software distributed 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the 13 | // specific language governing permissions and limitations under the License. 14 | 15 | #ifndef RAPIDJSON_IEEE754_ 16 | #define RAPIDJSON_IEEE754_ 17 | 18 | #include "../rapidjson.h" 19 | 20 | RAPIDJSON_NAMESPACE_BEGIN 21 | namespace internal { 22 | 23 | class Double { 24 | public: 25 | Double() {} 26 | Double(double d) : d_(d) {} 27 | Double(uint64_t u) : u_(u) {} 28 | 29 | double Value() const { return d_; } 30 | uint64_t Uint64Value() const { return u_; } 31 | 32 | double NextPositiveDouble() const { 33 | RAPIDJSON_ASSERT(!Sign()); 34 | return Double(u_ + 1).Value(); 35 | } 36 | 37 | bool Sign() const { return (u_ & kSignMask) != 0; } 38 | uint64_t Significand() const { return u_ & kSignificandMask; } 39 | int Exponent() const { return static_cast(((u_ & kExponentMask) >> kSignificandSize) - kExponentBias); } 40 | 41 | bool IsNan() const { return (u_ & kExponentMask) == kExponentMask && Significand() != 0; } 42 | bool IsInf() const { return (u_ & kExponentMask) == kExponentMask && Significand() == 0; } 43 | bool IsNanOrInf() const { return (u_ & kExponentMask) == kExponentMask; } 44 | bool IsNormal() const { return (u_ & kExponentMask) != 0 || Significand() == 0; } 45 | bool IsZero() const { return (u_ & (kExponentMask | kSignificandMask)) == 0; } 46 | 47 | uint64_t IntegerSignificand() const { return IsNormal() ? Significand() | kHiddenBit : Significand(); } 48 | int IntegerExponent() const { return (IsNormal() ? Exponent() : kDenormalExponent) - kSignificandSize; } 49 | uint64_t ToBias() const { return (u_ & kSignMask) ? ~u_ + 1 : u_ | kSignMask; } 50 | 51 | static unsigned EffectiveSignificandSize(int order) { 52 | if (order >= -1021) 53 | return 53; 54 | else if (order <= -1074) 55 | return 0; 56 | else 57 | return static_cast(order) + 1074; 58 | } 59 | 60 | private: 61 | static const int kSignificandSize = 52; 62 | static const int kExponentBias = 0x3FF; 63 | static const int kDenormalExponent = 1 - kExponentBias; 64 | static const uint64_t kSignMask = RAPIDJSON_UINT64_C2(0x80000000, 0x00000000); 65 | static const uint64_t kExponentMask = RAPIDJSON_UINT64_C2(0x7FF00000, 0x00000000); 66 | static const uint64_t kSignificandMask = RAPIDJSON_UINT64_C2(0x000FFFFF, 0xFFFFFFFF); 67 | static const uint64_t kHiddenBit = RAPIDJSON_UINT64_C2(0x00100000, 0x00000000); 68 | 69 | union { 70 | double d_; 71 | uint64_t u_; 72 | }; 73 | }; 74 | 75 | } // namespace internal 76 | RAPIDJSON_NAMESPACE_END 77 | 78 | #endif // RAPIDJSON_IEEE754_ 79 | -------------------------------------------------------------------------------- /include/rapidjson/internal/meta.h: -------------------------------------------------------------------------------- 1 | // Tencent is pleased to support the open source community by making RapidJSON available. 2 | // 3 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. 4 | // 5 | // Licensed under the MIT License (the "License"); you may not use this file except 6 | // in compliance with the License. You may obtain a copy of the License at 7 | // 8 | // http://opensource.org/licenses/MIT 9 | // 10 | // Unless required by applicable law or agreed to in writing, software distributed 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the 13 | // specific language governing permissions and limitations under the License. 14 | 15 | #ifndef RAPIDJSON_INTERNAL_META_H_ 16 | #define RAPIDJSON_INTERNAL_META_H_ 17 | 18 | #include "../rapidjson.h" 19 | 20 | #ifdef __GNUC__ 21 | RAPIDJSON_DIAG_PUSH 22 | RAPIDJSON_DIAG_OFF(effc++) 23 | #endif 24 | #if defined(_MSC_VER) 25 | RAPIDJSON_DIAG_PUSH 26 | RAPIDJSON_DIAG_OFF(6334) 27 | #endif 28 | 29 | #if RAPIDJSON_HAS_CXX11_TYPETRAITS 30 | #include 31 | #endif 32 | 33 | //@cond RAPIDJSON_INTERNAL 34 | RAPIDJSON_NAMESPACE_BEGIN 35 | namespace internal { 36 | 37 | // Helper to wrap/convert arbitrary types to void, useful for arbitrary type matching 38 | template struct Void { typedef void Type; }; 39 | 40 | /////////////////////////////////////////////////////////////////////////////// 41 | // BoolType, TrueType, FalseType 42 | // 43 | template struct BoolType { 44 | static const bool Value = Cond; 45 | typedef BoolType Type; 46 | }; 47 | typedef BoolType TrueType; 48 | typedef BoolType FalseType; 49 | 50 | 51 | /////////////////////////////////////////////////////////////////////////////// 52 | // SelectIf, BoolExpr, NotExpr, AndExpr, OrExpr 53 | // 54 | 55 | template struct SelectIfImpl { template struct Apply { typedef T1 Type; }; }; 56 | template <> struct SelectIfImpl { template struct Apply { typedef T2 Type; }; }; 57 | template struct SelectIfCond : SelectIfImpl::template Apply {}; 58 | template struct SelectIf : SelectIfCond {}; 59 | 60 | template struct AndExprCond : FalseType {}; 61 | template <> struct AndExprCond : TrueType {}; 62 | template struct OrExprCond : TrueType {}; 63 | template <> struct OrExprCond : FalseType {}; 64 | 65 | template struct BoolExpr : SelectIf::Type {}; 66 | template struct NotExpr : SelectIf::Type {}; 67 | template struct AndExpr : AndExprCond::Type {}; 68 | template struct OrExpr : OrExprCond::Type {}; 69 | 70 | 71 | /////////////////////////////////////////////////////////////////////////////// 72 | // AddConst, MaybeAddConst, RemoveConst 73 | template struct AddConst { typedef const T Type; }; 74 | template struct MaybeAddConst : SelectIfCond {}; 75 | template struct RemoveConst { typedef T Type; }; 76 | template struct RemoveConst { typedef T Type; }; 77 | 78 | 79 | /////////////////////////////////////////////////////////////////////////////// 80 | // IsSame, IsConst, IsMoreConst, IsPointer 81 | // 82 | template struct IsSame : FalseType {}; 83 | template struct IsSame : TrueType {}; 84 | 85 | template struct IsConst : FalseType {}; 86 | template struct IsConst : TrueType {}; 87 | 88 | template 89 | struct IsMoreConst 90 | : AndExpr::Type, typename RemoveConst::Type>, 91 | BoolType::Value >= IsConst::Value> >::Type {}; 92 | 93 | template struct IsPointer : FalseType {}; 94 | template struct IsPointer : TrueType {}; 95 | 96 | /////////////////////////////////////////////////////////////////////////////// 97 | // IsBaseOf 98 | // 99 | #if RAPIDJSON_HAS_CXX11_TYPETRAITS 100 | 101 | template struct IsBaseOf 102 | : BoolType< ::std::is_base_of::value> {}; 103 | 104 | #else // simplified version adopted from Boost 105 | 106 | template struct IsBaseOfImpl { 107 | RAPIDJSON_STATIC_ASSERT(sizeof(B) != 0); 108 | RAPIDJSON_STATIC_ASSERT(sizeof(D) != 0); 109 | 110 | typedef char (&Yes)[1]; 111 | typedef char (&No) [2]; 112 | 113 | template 114 | static Yes Check(const D*, T); 115 | static No Check(const B*, int); 116 | 117 | struct Host { 118 | operator const B*() const; 119 | operator const D*(); 120 | }; 121 | 122 | enum { Value = (sizeof(Check(Host(), 0)) == sizeof(Yes)) }; 123 | }; 124 | 125 | template struct IsBaseOf 126 | : OrExpr, BoolExpr > >::Type {}; 127 | 128 | #endif // RAPIDJSON_HAS_CXX11_TYPETRAITS 129 | 130 | 131 | ////////////////////////////////////////////////////////////////////////// 132 | // EnableIf / DisableIf 133 | // 134 | template struct EnableIfCond { typedef T Type; }; 135 | template struct EnableIfCond { /* empty */ }; 136 | 137 | template struct DisableIfCond { typedef T Type; }; 138 | template struct DisableIfCond { /* empty */ }; 139 | 140 | template 141 | struct EnableIf : EnableIfCond {}; 142 | 143 | template 144 | struct DisableIf : DisableIfCond {}; 145 | 146 | // SFINAE helpers 147 | struct SfinaeTag {}; 148 | template struct RemoveSfinaeTag; 149 | template struct RemoveSfinaeTag { typedef T Type; }; 150 | 151 | #define RAPIDJSON_REMOVEFPTR_(type) \ 152 | typename ::RAPIDJSON_NAMESPACE::internal::RemoveSfinaeTag \ 153 | < ::RAPIDJSON_NAMESPACE::internal::SfinaeTag&(*) type>::Type 154 | 155 | #define RAPIDJSON_ENABLEIF(cond) \ 156 | typename ::RAPIDJSON_NAMESPACE::internal::EnableIf \ 157 | ::Type * = NULL 158 | 159 | #define RAPIDJSON_DISABLEIF(cond) \ 160 | typename ::RAPIDJSON_NAMESPACE::internal::DisableIf \ 161 | ::Type * = NULL 162 | 163 | #define RAPIDJSON_ENABLEIF_RETURN(cond,returntype) \ 164 | typename ::RAPIDJSON_NAMESPACE::internal::EnableIf \ 165 | ::Type 167 | 168 | #define RAPIDJSON_DISABLEIF_RETURN(cond,returntype) \ 169 | typename ::RAPIDJSON_NAMESPACE::internal::DisableIf \ 170 | ::Type 172 | 173 | } // namespace internal 174 | RAPIDJSON_NAMESPACE_END 175 | //@endcond 176 | 177 | #if defined(__GNUC__) || defined(_MSC_VER) 178 | RAPIDJSON_DIAG_POP 179 | #endif 180 | 181 | #endif // RAPIDJSON_INTERNAL_META_H_ 182 | -------------------------------------------------------------------------------- /include/rapidjson/internal/pow10.h: -------------------------------------------------------------------------------- 1 | // Tencent is pleased to support the open source community by making RapidJSON available. 2 | // 3 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. 4 | // 5 | // Licensed under the MIT License (the "License"); you may not use this file except 6 | // in compliance with the License. You may obtain a copy of the License at 7 | // 8 | // http://opensource.org/licenses/MIT 9 | // 10 | // Unless required by applicable law or agreed to in writing, software distributed 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the 13 | // specific language governing permissions and limitations under the License. 14 | 15 | #ifndef RAPIDJSON_POW10_ 16 | #define RAPIDJSON_POW10_ 17 | 18 | #include "../rapidjson.h" 19 | 20 | RAPIDJSON_NAMESPACE_BEGIN 21 | namespace internal { 22 | 23 | //! Computes integer powers of 10 in double (10.0^n). 24 | /*! This function uses lookup table for fast and accurate results. 25 | \param n non-negative exponent. Must <= 308. 26 | \return 10.0^n 27 | */ 28 | inline double Pow10(int n) { 29 | static const double e[] = { // 1e-0...1e308: 309 * 8 bytes = 2472 bytes 30 | 1e+0, 31 | 1e+1, 1e+2, 1e+3, 1e+4, 1e+5, 1e+6, 1e+7, 1e+8, 1e+9, 1e+10, 1e+11, 1e+12, 1e+13, 1e+14, 1e+15, 1e+16, 1e+17, 1e+18, 1e+19, 1e+20, 32 | 1e+21, 1e+22, 1e+23, 1e+24, 1e+25, 1e+26, 1e+27, 1e+28, 1e+29, 1e+30, 1e+31, 1e+32, 1e+33, 1e+34, 1e+35, 1e+36, 1e+37, 1e+38, 1e+39, 1e+40, 33 | 1e+41, 1e+42, 1e+43, 1e+44, 1e+45, 1e+46, 1e+47, 1e+48, 1e+49, 1e+50, 1e+51, 1e+52, 1e+53, 1e+54, 1e+55, 1e+56, 1e+57, 1e+58, 1e+59, 1e+60, 34 | 1e+61, 1e+62, 1e+63, 1e+64, 1e+65, 1e+66, 1e+67, 1e+68, 1e+69, 1e+70, 1e+71, 1e+72, 1e+73, 1e+74, 1e+75, 1e+76, 1e+77, 1e+78, 1e+79, 1e+80, 35 | 1e+81, 1e+82, 1e+83, 1e+84, 1e+85, 1e+86, 1e+87, 1e+88, 1e+89, 1e+90, 1e+91, 1e+92, 1e+93, 1e+94, 1e+95, 1e+96, 1e+97, 1e+98, 1e+99, 1e+100, 36 | 1e+101,1e+102,1e+103,1e+104,1e+105,1e+106,1e+107,1e+108,1e+109,1e+110,1e+111,1e+112,1e+113,1e+114,1e+115,1e+116,1e+117,1e+118,1e+119,1e+120, 37 | 1e+121,1e+122,1e+123,1e+124,1e+125,1e+126,1e+127,1e+128,1e+129,1e+130,1e+131,1e+132,1e+133,1e+134,1e+135,1e+136,1e+137,1e+138,1e+139,1e+140, 38 | 1e+141,1e+142,1e+143,1e+144,1e+145,1e+146,1e+147,1e+148,1e+149,1e+150,1e+151,1e+152,1e+153,1e+154,1e+155,1e+156,1e+157,1e+158,1e+159,1e+160, 39 | 1e+161,1e+162,1e+163,1e+164,1e+165,1e+166,1e+167,1e+168,1e+169,1e+170,1e+171,1e+172,1e+173,1e+174,1e+175,1e+176,1e+177,1e+178,1e+179,1e+180, 40 | 1e+181,1e+182,1e+183,1e+184,1e+185,1e+186,1e+187,1e+188,1e+189,1e+190,1e+191,1e+192,1e+193,1e+194,1e+195,1e+196,1e+197,1e+198,1e+199,1e+200, 41 | 1e+201,1e+202,1e+203,1e+204,1e+205,1e+206,1e+207,1e+208,1e+209,1e+210,1e+211,1e+212,1e+213,1e+214,1e+215,1e+216,1e+217,1e+218,1e+219,1e+220, 42 | 1e+221,1e+222,1e+223,1e+224,1e+225,1e+226,1e+227,1e+228,1e+229,1e+230,1e+231,1e+232,1e+233,1e+234,1e+235,1e+236,1e+237,1e+238,1e+239,1e+240, 43 | 1e+241,1e+242,1e+243,1e+244,1e+245,1e+246,1e+247,1e+248,1e+249,1e+250,1e+251,1e+252,1e+253,1e+254,1e+255,1e+256,1e+257,1e+258,1e+259,1e+260, 44 | 1e+261,1e+262,1e+263,1e+264,1e+265,1e+266,1e+267,1e+268,1e+269,1e+270,1e+271,1e+272,1e+273,1e+274,1e+275,1e+276,1e+277,1e+278,1e+279,1e+280, 45 | 1e+281,1e+282,1e+283,1e+284,1e+285,1e+286,1e+287,1e+288,1e+289,1e+290,1e+291,1e+292,1e+293,1e+294,1e+295,1e+296,1e+297,1e+298,1e+299,1e+300, 46 | 1e+301,1e+302,1e+303,1e+304,1e+305,1e+306,1e+307,1e+308 47 | }; 48 | RAPIDJSON_ASSERT(n >= 0 && n <= 308); 49 | return e[n]; 50 | } 51 | 52 | } // namespace internal 53 | RAPIDJSON_NAMESPACE_END 54 | 55 | #endif // RAPIDJSON_POW10_ 56 | -------------------------------------------------------------------------------- /include/rapidjson/internal/stack.h: -------------------------------------------------------------------------------- 1 | // Tencent is pleased to support the open source community by making RapidJSON available. 2 | // 3 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. 4 | // 5 | // Licensed under the MIT License (the "License"); you may not use this file except 6 | // in compliance with the License. You may obtain a copy of the License at 7 | // 8 | // http://opensource.org/licenses/MIT 9 | // 10 | // Unless required by applicable law or agreed to in writing, software distributed 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the 13 | // specific language governing permissions and limitations under the License. 14 | 15 | #ifndef RAPIDJSON_INTERNAL_STACK_H_ 16 | #define RAPIDJSON_INTERNAL_STACK_H_ 17 | 18 | #include "../allocators.h" 19 | #include "swap.h" 20 | 21 | #if defined(__clang__) 22 | RAPIDJSON_DIAG_PUSH 23 | RAPIDJSON_DIAG_OFF(c++98-compat) 24 | #endif 25 | 26 | RAPIDJSON_NAMESPACE_BEGIN 27 | namespace internal { 28 | 29 | /////////////////////////////////////////////////////////////////////////////// 30 | // Stack 31 | 32 | //! A type-unsafe stack for storing different types of data. 33 | /*! \tparam Allocator Allocator for allocating stack memory. 34 | */ 35 | template 36 | class Stack { 37 | public: 38 | // Optimization note: Do not allocate memory for stack_ in constructor. 39 | // Do it lazily when first Push() -> Expand() -> Resize(). 40 | Stack(Allocator* allocator, size_t stackCapacity) : allocator_(allocator), ownAllocator_(0), stack_(0), stackTop_(0), stackEnd_(0), initialCapacity_(stackCapacity) { 41 | } 42 | 43 | #if RAPIDJSON_HAS_CXX11_RVALUE_REFS 44 | Stack(Stack&& rhs) 45 | : allocator_(rhs.allocator_), 46 | ownAllocator_(rhs.ownAllocator_), 47 | stack_(rhs.stack_), 48 | stackTop_(rhs.stackTop_), 49 | stackEnd_(rhs.stackEnd_), 50 | initialCapacity_(rhs.initialCapacity_) 51 | { 52 | rhs.allocator_ = 0; 53 | rhs.ownAllocator_ = 0; 54 | rhs.stack_ = 0; 55 | rhs.stackTop_ = 0; 56 | rhs.stackEnd_ = 0; 57 | rhs.initialCapacity_ = 0; 58 | } 59 | #endif 60 | 61 | ~Stack() { 62 | Destroy(); 63 | } 64 | 65 | #if RAPIDJSON_HAS_CXX11_RVALUE_REFS 66 | Stack& operator=(Stack&& rhs) { 67 | if (&rhs != this) 68 | { 69 | Destroy(); 70 | 71 | allocator_ = rhs.allocator_; 72 | ownAllocator_ = rhs.ownAllocator_; 73 | stack_ = rhs.stack_; 74 | stackTop_ = rhs.stackTop_; 75 | stackEnd_ = rhs.stackEnd_; 76 | initialCapacity_ = rhs.initialCapacity_; 77 | 78 | rhs.allocator_ = 0; 79 | rhs.ownAllocator_ = 0; 80 | rhs.stack_ = 0; 81 | rhs.stackTop_ = 0; 82 | rhs.stackEnd_ = 0; 83 | rhs.initialCapacity_ = 0; 84 | } 85 | return *this; 86 | } 87 | #endif 88 | 89 | void Swap(Stack& rhs) RAPIDJSON_NOEXCEPT { 90 | internal::Swap(allocator_, rhs.allocator_); 91 | internal::Swap(ownAllocator_, rhs.ownAllocator_); 92 | internal::Swap(stack_, rhs.stack_); 93 | internal::Swap(stackTop_, rhs.stackTop_); 94 | internal::Swap(stackEnd_, rhs.stackEnd_); 95 | internal::Swap(initialCapacity_, rhs.initialCapacity_); 96 | } 97 | 98 | void Clear() { stackTop_ = stack_; } 99 | 100 | void ShrinkToFit() { 101 | if (Empty()) { 102 | // If the stack is empty, completely deallocate the memory. 103 | Allocator::Free(stack_); 104 | stack_ = 0; 105 | stackTop_ = 0; 106 | stackEnd_ = 0; 107 | } 108 | else 109 | Resize(GetSize()); 110 | } 111 | 112 | // Optimization note: try to minimize the size of this function for force inline. 113 | // Expansion is run very infrequently, so it is moved to another (probably non-inline) function. 114 | template 115 | RAPIDJSON_FORCEINLINE void Reserve(size_t count = 1) { 116 | // Expand the stack if needed 117 | if (RAPIDJSON_UNLIKELY(stackTop_ + sizeof(T) * count > stackEnd_)) 118 | Expand(count); 119 | } 120 | 121 | template 122 | RAPIDJSON_FORCEINLINE T* Push(size_t count = 1) { 123 | Reserve(count); 124 | return PushUnsafe(count); 125 | } 126 | 127 | template 128 | RAPIDJSON_FORCEINLINE T* PushUnsafe(size_t count = 1) { 129 | RAPIDJSON_ASSERT(stackTop_); 130 | RAPIDJSON_ASSERT(stackTop_ + sizeof(T) * count <= stackEnd_); 131 | T* ret = reinterpret_cast(stackTop_); 132 | stackTop_ += sizeof(T) * count; 133 | return ret; 134 | } 135 | 136 | template 137 | T* Pop(size_t count) { 138 | RAPIDJSON_ASSERT(GetSize() >= count * sizeof(T)); 139 | stackTop_ -= count * sizeof(T); 140 | return reinterpret_cast(stackTop_); 141 | } 142 | 143 | template 144 | T* Top() { 145 | RAPIDJSON_ASSERT(GetSize() >= sizeof(T)); 146 | return reinterpret_cast(stackTop_ - sizeof(T)); 147 | } 148 | 149 | template 150 | const T* Top() const { 151 | RAPIDJSON_ASSERT(GetSize() >= sizeof(T)); 152 | return reinterpret_cast(stackTop_ - sizeof(T)); 153 | } 154 | 155 | template 156 | T* End() { return reinterpret_cast(stackTop_); } 157 | 158 | template 159 | const T* End() const { return reinterpret_cast(stackTop_); } 160 | 161 | template 162 | T* Bottom() { return reinterpret_cast(stack_); } 163 | 164 | template 165 | const T* Bottom() const { return reinterpret_cast(stack_); } 166 | 167 | bool HasAllocator() const { 168 | return allocator_ != 0; 169 | } 170 | 171 | Allocator& GetAllocator() { 172 | RAPIDJSON_ASSERT(allocator_); 173 | return *allocator_; 174 | } 175 | 176 | bool Empty() const { return stackTop_ == stack_; } 177 | size_t GetSize() const { return static_cast(stackTop_ - stack_); } 178 | size_t GetCapacity() const { return static_cast(stackEnd_ - stack_); } 179 | 180 | private: 181 | template 182 | void Expand(size_t count) { 183 | // Only expand the capacity if the current stack exists. Otherwise just create a stack with initial capacity. 184 | size_t newCapacity; 185 | if (stack_ == 0) { 186 | if (!allocator_) 187 | ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator)(); 188 | newCapacity = initialCapacity_; 189 | } else { 190 | newCapacity = GetCapacity(); 191 | newCapacity += (newCapacity + 1) / 2; 192 | } 193 | size_t newSize = GetSize() + sizeof(T) * count; 194 | if (newCapacity < newSize) 195 | newCapacity = newSize; 196 | 197 | Resize(newCapacity); 198 | } 199 | 200 | void Resize(size_t newCapacity) { 201 | const size_t size = GetSize(); // Backup the current size 202 | stack_ = static_cast(allocator_->Realloc(stack_, GetCapacity(), newCapacity)); 203 | stackTop_ = stack_ + size; 204 | stackEnd_ = stack_ + newCapacity; 205 | } 206 | 207 | void Destroy() { 208 | Allocator::Free(stack_); 209 | RAPIDJSON_DELETE(ownAllocator_); // Only delete if it is owned by the stack 210 | } 211 | 212 | // Prohibit copy constructor & assignment operator. 213 | Stack(const Stack&); 214 | Stack& operator=(const Stack&); 215 | 216 | Allocator* allocator_; 217 | Allocator* ownAllocator_; 218 | char *stack_; 219 | char *stackTop_; 220 | char *stackEnd_; 221 | size_t initialCapacity_; 222 | }; 223 | 224 | } // namespace internal 225 | RAPIDJSON_NAMESPACE_END 226 | 227 | #if defined(__clang__) 228 | RAPIDJSON_DIAG_POP 229 | #endif 230 | 231 | #endif // RAPIDJSON_STACK_H_ 232 | -------------------------------------------------------------------------------- /include/rapidjson/internal/strfunc.h: -------------------------------------------------------------------------------- 1 | // Tencent is pleased to support the open source community by making RapidJSON available. 2 | // 3 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. 4 | // 5 | // Licensed under the MIT License (the "License"); you may not use this file except 6 | // in compliance with the License. You may obtain a copy of the License at 7 | // 8 | // http://opensource.org/licenses/MIT 9 | // 10 | // Unless required by applicable law or agreed to in writing, software distributed 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the 13 | // specific language governing permissions and limitations under the License. 14 | 15 | #ifndef RAPIDJSON_INTERNAL_STRFUNC_H_ 16 | #define RAPIDJSON_INTERNAL_STRFUNC_H_ 17 | 18 | #include "../stream.h" 19 | 20 | RAPIDJSON_NAMESPACE_BEGIN 21 | namespace internal { 22 | 23 | //! Custom strlen() which works on different character types. 24 | /*! \tparam Ch Character type (e.g. char, wchar_t, short) 25 | \param s Null-terminated input string. 26 | \return Number of characters in the string. 27 | \note This has the same semantics as strlen(), the return value is not number of Unicode codepoints. 28 | */ 29 | template 30 | inline SizeType StrLen(const Ch* s) { 31 | RAPIDJSON_ASSERT(s != 0); 32 | const Ch* p = s; 33 | while (*p) ++p; 34 | return SizeType(p - s); 35 | } 36 | 37 | //! Returns number of code points in a encoded string. 38 | template 39 | bool CountStringCodePoint(const typename Encoding::Ch* s, SizeType length, SizeType* outCount) { 40 | RAPIDJSON_ASSERT(s != 0); 41 | RAPIDJSON_ASSERT(outCount != 0); 42 | GenericStringStream is(s); 43 | const typename Encoding::Ch* end = s + length; 44 | SizeType count = 0; 45 | while (is.src_ < end) { 46 | unsigned codepoint; 47 | if (!Encoding::Decode(is, &codepoint)) 48 | return false; 49 | count++; 50 | } 51 | *outCount = count; 52 | return true; 53 | } 54 | 55 | } // namespace internal 56 | RAPIDJSON_NAMESPACE_END 57 | 58 | #endif // RAPIDJSON_INTERNAL_STRFUNC_H_ 59 | -------------------------------------------------------------------------------- /include/rapidjson/internal/strtod.h: -------------------------------------------------------------------------------- 1 | // Tencent is pleased to support the open source community by making RapidJSON available. 2 | // 3 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. 4 | // 5 | // Licensed under the MIT License (the "License"); you may not use this file except 6 | // in compliance with the License. You may obtain a copy of the License at 7 | // 8 | // http://opensource.org/licenses/MIT 9 | // 10 | // Unless required by applicable law or agreed to in writing, software distributed 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the 13 | // specific language governing permissions and limitations under the License. 14 | 15 | #ifndef RAPIDJSON_STRTOD_ 16 | #define RAPIDJSON_STRTOD_ 17 | 18 | #include "ieee754.h" 19 | #include "biginteger.h" 20 | #include "diyfp.h" 21 | #include "pow10.h" 22 | 23 | RAPIDJSON_NAMESPACE_BEGIN 24 | namespace internal { 25 | 26 | inline double FastPath(double significand, int exp) { 27 | if (exp < -308) 28 | return 0.0; 29 | else if (exp >= 0) 30 | return significand * internal::Pow10(exp); 31 | else 32 | return significand / internal::Pow10(-exp); 33 | } 34 | 35 | inline double StrtodNormalPrecision(double d, int p) { 36 | if (p < -308) { 37 | // Prevent expSum < -308, making Pow10(p) = 0 38 | d = FastPath(d, -308); 39 | d = FastPath(d, p + 308); 40 | } 41 | else 42 | d = FastPath(d, p); 43 | return d; 44 | } 45 | 46 | template 47 | inline T Min3(T a, T b, T c) { 48 | T m = a; 49 | if (m > b) m = b; 50 | if (m > c) m = c; 51 | return m; 52 | } 53 | 54 | inline int CheckWithinHalfULP(double b, const BigInteger& d, int dExp) { 55 | const Double db(b); 56 | const uint64_t bInt = db.IntegerSignificand(); 57 | const int bExp = db.IntegerExponent(); 58 | const int hExp = bExp - 1; 59 | 60 | int dS_Exp2 = 0, dS_Exp5 = 0, bS_Exp2 = 0, bS_Exp5 = 0, hS_Exp2 = 0, hS_Exp5 = 0; 61 | 62 | // Adjust for decimal exponent 63 | if (dExp >= 0) { 64 | dS_Exp2 += dExp; 65 | dS_Exp5 += dExp; 66 | } 67 | else { 68 | bS_Exp2 -= dExp; 69 | bS_Exp5 -= dExp; 70 | hS_Exp2 -= dExp; 71 | hS_Exp5 -= dExp; 72 | } 73 | 74 | // Adjust for binary exponent 75 | if (bExp >= 0) 76 | bS_Exp2 += bExp; 77 | else { 78 | dS_Exp2 -= bExp; 79 | hS_Exp2 -= bExp; 80 | } 81 | 82 | // Adjust for half ulp exponent 83 | if (hExp >= 0) 84 | hS_Exp2 += hExp; 85 | else { 86 | dS_Exp2 -= hExp; 87 | bS_Exp2 -= hExp; 88 | } 89 | 90 | // Remove common power of two factor from all three scaled values 91 | int common_Exp2 = Min3(dS_Exp2, bS_Exp2, hS_Exp2); 92 | dS_Exp2 -= common_Exp2; 93 | bS_Exp2 -= common_Exp2; 94 | hS_Exp2 -= common_Exp2; 95 | 96 | BigInteger dS = d; 97 | dS.MultiplyPow5(static_cast(dS_Exp5)) <<= static_cast(dS_Exp2); 98 | 99 | BigInteger bS(bInt); 100 | bS.MultiplyPow5(static_cast(bS_Exp5)) <<= static_cast(bS_Exp2); 101 | 102 | BigInteger hS(1); 103 | hS.MultiplyPow5(static_cast(hS_Exp5)) <<= static_cast(hS_Exp2); 104 | 105 | BigInteger delta(0); 106 | dS.Difference(bS, &delta); 107 | 108 | return delta.Compare(hS); 109 | } 110 | 111 | inline bool StrtodFast(double d, int p, double* result) { 112 | // Use fast path for string-to-double conversion if possible 113 | // see http://www.exploringbinary.com/fast-path-decimal-to-floating-point-conversion/ 114 | if (p > 22 && p < 22 + 16) { 115 | // Fast Path Cases In Disguise 116 | d *= internal::Pow10(p - 22); 117 | p = 22; 118 | } 119 | 120 | if (p >= -22 && p <= 22 && d <= 9007199254740991.0) { // 2^53 - 1 121 | *result = FastPath(d, p); 122 | return true; 123 | } 124 | else 125 | return false; 126 | } 127 | 128 | // Compute an approximation and see if it is within 1/2 ULP 129 | inline bool StrtodDiyFp(const char* decimals, size_t length, size_t decimalPosition, int exp, double* result) { 130 | uint64_t significand = 0; 131 | size_t i = 0; // 2^64 - 1 = 18446744073709551615, 1844674407370955161 = 0x1999999999999999 132 | for (; i < length; i++) { 133 | if (significand > RAPIDJSON_UINT64_C2(0x19999999, 0x99999999) || 134 | (significand == RAPIDJSON_UINT64_C2(0x19999999, 0x99999999) && decimals[i] > '5')) 135 | break; 136 | significand = significand * 10u + static_cast(decimals[i] - '0'); 137 | } 138 | 139 | if (i < length && decimals[i] >= '5') // Rounding 140 | significand++; 141 | 142 | size_t remaining = length - i; 143 | const unsigned kUlpShift = 3; 144 | const unsigned kUlp = 1 << kUlpShift; 145 | int64_t error = (remaining == 0) ? 0 : kUlp / 2; 146 | 147 | DiyFp v(significand, 0); 148 | v = v.Normalize(); 149 | error <<= -v.e; 150 | 151 | const int dExp = static_cast(decimalPosition) - static_cast(i) + exp; 152 | 153 | int actualExp; 154 | DiyFp cachedPower = GetCachedPower10(dExp, &actualExp); 155 | if (actualExp != dExp) { 156 | static const DiyFp kPow10[] = { 157 | DiyFp(RAPIDJSON_UINT64_C2(0xa0000000, 00000000), -60), // 10^1 158 | DiyFp(RAPIDJSON_UINT64_C2(0xc8000000, 00000000), -57), // 10^2 159 | DiyFp(RAPIDJSON_UINT64_C2(0xfa000000, 00000000), -54), // 10^3 160 | DiyFp(RAPIDJSON_UINT64_C2(0x9c400000, 00000000), -50), // 10^4 161 | DiyFp(RAPIDJSON_UINT64_C2(0xc3500000, 00000000), -47), // 10^5 162 | DiyFp(RAPIDJSON_UINT64_C2(0xf4240000, 00000000), -44), // 10^6 163 | DiyFp(RAPIDJSON_UINT64_C2(0x98968000, 00000000), -40) // 10^7 164 | }; 165 | int adjustment = dExp - actualExp - 1; 166 | RAPIDJSON_ASSERT(adjustment >= 0 && adjustment < 7); 167 | v = v * kPow10[adjustment]; 168 | if (length + static_cast(adjustment)> 19u) // has more digits than decimal digits in 64-bit 169 | error += kUlp / 2; 170 | } 171 | 172 | v = v * cachedPower; 173 | 174 | error += kUlp + (error == 0 ? 0 : 1); 175 | 176 | const int oldExp = v.e; 177 | v = v.Normalize(); 178 | error <<= oldExp - v.e; 179 | 180 | const unsigned effectiveSignificandSize = Double::EffectiveSignificandSize(64 + v.e); 181 | unsigned precisionSize = 64 - effectiveSignificandSize; 182 | if (precisionSize + kUlpShift >= 64) { 183 | unsigned scaleExp = (precisionSize + kUlpShift) - 63; 184 | v.f >>= scaleExp; 185 | v.e += scaleExp; 186 | error = (error >> scaleExp) + 1 + static_cast(kUlp); 187 | precisionSize -= scaleExp; 188 | } 189 | 190 | DiyFp rounded(v.f >> precisionSize, v.e + static_cast(precisionSize)); 191 | const uint64_t precisionBits = (v.f & ((uint64_t(1) << precisionSize) - 1)) * kUlp; 192 | const uint64_t halfWay = (uint64_t(1) << (precisionSize - 1)) * kUlp; 193 | if (precisionBits >= halfWay + static_cast(error)) { 194 | rounded.f++; 195 | if (rounded.f & (DiyFp::kDpHiddenBit << 1)) { // rounding overflows mantissa (issue #340) 196 | rounded.f >>= 1; 197 | rounded.e++; 198 | } 199 | } 200 | 201 | *result = rounded.ToDouble(); 202 | 203 | return halfWay - static_cast(error) >= precisionBits || precisionBits >= halfWay + static_cast(error); 204 | } 205 | 206 | inline double StrtodBigInteger(double approx, const char* decimals, size_t length, size_t decimalPosition, int exp) { 207 | const BigInteger dInt(decimals, length); 208 | const int dExp = static_cast(decimalPosition) - static_cast(length) + exp; 209 | Double a(approx); 210 | int cmp = CheckWithinHalfULP(a.Value(), dInt, dExp); 211 | if (cmp < 0) 212 | return a.Value(); // within half ULP 213 | else if (cmp == 0) { 214 | // Round towards even 215 | if (a.Significand() & 1) 216 | return a.NextPositiveDouble(); 217 | else 218 | return a.Value(); 219 | } 220 | else // adjustment 221 | return a.NextPositiveDouble(); 222 | } 223 | 224 | inline double StrtodFullPrecision(double d, int p, const char* decimals, size_t length, size_t decimalPosition, int exp) { 225 | RAPIDJSON_ASSERT(d >= 0.0); 226 | RAPIDJSON_ASSERT(length >= 1); 227 | 228 | double result; 229 | if (StrtodFast(d, p, &result)) 230 | return result; 231 | 232 | // Trim leading zeros 233 | while (*decimals == '0' && length > 1) { 234 | length--; 235 | decimals++; 236 | decimalPosition--; 237 | } 238 | 239 | // Trim trailing zeros 240 | while (decimals[length - 1] == '0' && length > 1) { 241 | length--; 242 | decimalPosition--; 243 | exp++; 244 | } 245 | 246 | // Trim right-most digits 247 | const int kMaxDecimalDigit = 780; 248 | if (static_cast(length) > kMaxDecimalDigit) { 249 | int delta = (static_cast(length) - kMaxDecimalDigit); 250 | exp += delta; 251 | decimalPosition -= static_cast(delta); 252 | length = kMaxDecimalDigit; 253 | } 254 | 255 | // If too small, underflow to zero 256 | if (int(length) + exp < -324) 257 | return 0.0; 258 | 259 | if (StrtodDiyFp(decimals, length, decimalPosition, exp, &result)) 260 | return result; 261 | 262 | // Use approximation from StrtodDiyFp and make adjustment with BigInteger comparison 263 | return StrtodBigInteger(result, decimals, length, decimalPosition, exp); 264 | } 265 | 266 | } // namespace internal 267 | RAPIDJSON_NAMESPACE_END 268 | 269 | #endif // RAPIDJSON_STRTOD_ 270 | -------------------------------------------------------------------------------- /include/rapidjson/internal/swap.h: -------------------------------------------------------------------------------- 1 | // Tencent is pleased to support the open source community by making RapidJSON available. 2 | // 3 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. 4 | // 5 | // Licensed under the MIT License (the "License"); you may not use this file except 6 | // in compliance with the License. You may obtain a copy of the License at 7 | // 8 | // http://opensource.org/licenses/MIT 9 | // 10 | // Unless required by applicable law or agreed to in writing, software distributed 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the 13 | // specific language governing permissions and limitations under the License. 14 | 15 | #ifndef RAPIDJSON_INTERNAL_SWAP_H_ 16 | #define RAPIDJSON_INTERNAL_SWAP_H_ 17 | 18 | #include "../rapidjson.h" 19 | 20 | #if defined(__clang__) 21 | RAPIDJSON_DIAG_PUSH 22 | RAPIDJSON_DIAG_OFF(c++98-compat) 23 | #endif 24 | 25 | RAPIDJSON_NAMESPACE_BEGIN 26 | namespace internal { 27 | 28 | //! Custom swap() to avoid dependency on C++ header 29 | /*! \tparam T Type of the arguments to swap, should be instantiated with primitive C++ types only. 30 | \note This has the same semantics as std::swap(). 31 | */ 32 | template 33 | inline void Swap(T& a, T& b) RAPIDJSON_NOEXCEPT { 34 | T tmp = a; 35 | a = b; 36 | b = tmp; 37 | } 38 | 39 | } // namespace internal 40 | RAPIDJSON_NAMESPACE_END 41 | 42 | #if defined(__clang__) 43 | RAPIDJSON_DIAG_POP 44 | #endif 45 | 46 | #endif // RAPIDJSON_INTERNAL_SWAP_H_ 47 | -------------------------------------------------------------------------------- /include/rapidjson/istreamwrapper.h: -------------------------------------------------------------------------------- 1 | // Tencent is pleased to support the open source community by making RapidJSON available. 2 | // 3 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. 4 | // 5 | // Licensed under the MIT License (the "License"); you may not use this file except 6 | // in compliance with the License. You may obtain a copy of the License at 7 | // 8 | // http://opensource.org/licenses/MIT 9 | // 10 | // Unless required by applicable law or agreed to in writing, software distributed 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the 13 | // specific language governing permissions and limitations under the License. 14 | 15 | #ifndef RAPIDJSON_ISTREAMWRAPPER_H_ 16 | #define RAPIDJSON_ISTREAMWRAPPER_H_ 17 | 18 | #include "stream.h" 19 | #include 20 | 21 | #ifdef __clang__ 22 | RAPIDJSON_DIAG_PUSH 23 | RAPIDJSON_DIAG_OFF(padded) 24 | #endif 25 | 26 | #ifdef _MSC_VER 27 | RAPIDJSON_DIAG_PUSH 28 | RAPIDJSON_DIAG_OFF(4351) // new behavior: elements of array 'array' will be default initialized 29 | #endif 30 | 31 | RAPIDJSON_NAMESPACE_BEGIN 32 | 33 | //! Wrapper of \c std::basic_istream into RapidJSON's Stream concept. 34 | /*! 35 | The classes can be wrapped including but not limited to: 36 | 37 | - \c std::istringstream 38 | - \c std::stringstream 39 | - \c std::wistringstream 40 | - \c std::wstringstream 41 | - \c std::ifstream 42 | - \c std::fstream 43 | - \c std::wifstream 44 | - \c std::wfstream 45 | 46 | \tparam StreamType Class derived from \c std::basic_istream. 47 | */ 48 | 49 | template 50 | class BasicIStreamWrapper { 51 | public: 52 | typedef typename StreamType::char_type Ch; 53 | BasicIStreamWrapper(StreamType& stream) : stream_(stream), count_(), peekBuffer_() {} 54 | 55 | Ch Peek() const { 56 | typename StreamType::int_type c = stream_.peek(); 57 | return RAPIDJSON_LIKELY(c != StreamType::traits_type::eof()) ? static_cast(c) : '\0'; 58 | } 59 | 60 | Ch Take() { 61 | typename StreamType::int_type c = stream_.get(); 62 | if (RAPIDJSON_LIKELY(c != StreamType::traits_type::eof())) { 63 | count_++; 64 | return static_cast(c); 65 | } 66 | else 67 | return '\0'; 68 | } 69 | 70 | // tellg() may return -1 when failed. So we count by ourself. 71 | size_t Tell() const { return count_; } 72 | 73 | Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; } 74 | void Put(Ch) { RAPIDJSON_ASSERT(false); } 75 | void Flush() { RAPIDJSON_ASSERT(false); } 76 | size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; } 77 | 78 | // For encoding detection only. 79 | const Ch* Peek4() const { 80 | RAPIDJSON_ASSERT(sizeof(Ch) == 1); // Only usable for byte stream. 81 | int i; 82 | bool hasError = false; 83 | for (i = 0; i < 4; ++i) { 84 | typename StreamType::int_type c = stream_.get(); 85 | if (c == StreamType::traits_type::eof()) { 86 | hasError = true; 87 | stream_.clear(); 88 | break; 89 | } 90 | peekBuffer_[i] = static_cast(c); 91 | } 92 | for (--i; i >= 0; --i) 93 | stream_.putback(peekBuffer_[i]); 94 | return !hasError ? peekBuffer_ : 0; 95 | } 96 | 97 | private: 98 | BasicIStreamWrapper(const BasicIStreamWrapper&); 99 | BasicIStreamWrapper& operator=(const BasicIStreamWrapper&); 100 | 101 | StreamType& stream_; 102 | size_t count_; //!< Number of characters read. Note: 103 | mutable Ch peekBuffer_[4]; 104 | }; 105 | 106 | typedef BasicIStreamWrapper IStreamWrapper; 107 | typedef BasicIStreamWrapper WIStreamWrapper; 108 | 109 | #if defined(__clang__) || defined(_MSC_VER) 110 | RAPIDJSON_DIAG_POP 111 | #endif 112 | 113 | RAPIDJSON_NAMESPACE_END 114 | 115 | #endif // RAPIDJSON_ISTREAMWRAPPER_H_ 116 | -------------------------------------------------------------------------------- /include/rapidjson/memorybuffer.h: -------------------------------------------------------------------------------- 1 | // Tencent is pleased to support the open source community by making RapidJSON available. 2 | // 3 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. 4 | // 5 | // Licensed under the MIT License (the "License"); you may not use this file except 6 | // in compliance with the License. You may obtain a copy of the License at 7 | // 8 | // http://opensource.org/licenses/MIT 9 | // 10 | // Unless required by applicable law or agreed to in writing, software distributed 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the 13 | // specific language governing permissions and limitations under the License. 14 | 15 | #ifndef RAPIDJSON_MEMORYBUFFER_H_ 16 | #define RAPIDJSON_MEMORYBUFFER_H_ 17 | 18 | #include "stream.h" 19 | #include "internal/stack.h" 20 | 21 | RAPIDJSON_NAMESPACE_BEGIN 22 | 23 | //! Represents an in-memory output byte stream. 24 | /*! 25 | This class is mainly for being wrapped by EncodedOutputStream or AutoUTFOutputStream. 26 | 27 | It is similar to FileWriteBuffer but the destination is an in-memory buffer instead of a file. 28 | 29 | Differences between MemoryBuffer and StringBuffer: 30 | 1. StringBuffer has Encoding but MemoryBuffer is only a byte buffer. 31 | 2. StringBuffer::GetString() returns a null-terminated string. MemoryBuffer::GetBuffer() returns a buffer without terminator. 32 | 33 | \tparam Allocator type for allocating memory buffer. 34 | \note implements Stream concept 35 | */ 36 | template 37 | struct GenericMemoryBuffer { 38 | typedef char Ch; // byte 39 | 40 | GenericMemoryBuffer(Allocator* allocator = 0, size_t capacity = kDefaultCapacity) : stack_(allocator, capacity) {} 41 | 42 | void Put(Ch c) { *stack_.template Push() = c; } 43 | void Flush() {} 44 | 45 | void Clear() { stack_.Clear(); } 46 | void ShrinkToFit() { stack_.ShrinkToFit(); } 47 | Ch* Push(size_t count) { return stack_.template Push(count); } 48 | void Pop(size_t count) { stack_.template Pop(count); } 49 | 50 | const Ch* GetBuffer() const { 51 | return stack_.template Bottom(); 52 | } 53 | 54 | size_t GetSize() const { return stack_.GetSize(); } 55 | 56 | static const size_t kDefaultCapacity = 256; 57 | mutable internal::Stack stack_; 58 | }; 59 | 60 | typedef GenericMemoryBuffer<> MemoryBuffer; 61 | 62 | //! Implement specialized version of PutN() with memset() for better performance. 63 | template<> 64 | inline void PutN(MemoryBuffer& memoryBuffer, char c, size_t n) { 65 | std::memset(memoryBuffer.stack_.Push(n), c, n * sizeof(c)); 66 | } 67 | 68 | RAPIDJSON_NAMESPACE_END 69 | 70 | #endif // RAPIDJSON_MEMORYBUFFER_H_ 71 | -------------------------------------------------------------------------------- /include/rapidjson/memorystream.h: -------------------------------------------------------------------------------- 1 | // Tencent is pleased to support the open source community by making RapidJSON available. 2 | // 3 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. 4 | // 5 | // Licensed under the MIT License (the "License"); you may not use this file except 6 | // in compliance with the License. You may obtain a copy of the License at 7 | // 8 | // http://opensource.org/licenses/MIT 9 | // 10 | // Unless required by applicable law or agreed to in writing, software distributed 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the 13 | // specific language governing permissions and limitations under the License. 14 | 15 | #ifndef RAPIDJSON_MEMORYSTREAM_H_ 16 | #define RAPIDJSON_MEMORYSTREAM_H_ 17 | 18 | #include "stream.h" 19 | 20 | #ifdef __clang__ 21 | RAPIDJSON_DIAG_PUSH 22 | RAPIDJSON_DIAG_OFF(unreachable-code) 23 | RAPIDJSON_DIAG_OFF(missing-noreturn) 24 | #endif 25 | 26 | RAPIDJSON_NAMESPACE_BEGIN 27 | 28 | //! Represents an in-memory input byte stream. 29 | /*! 30 | This class is mainly for being wrapped by EncodedInputStream or AutoUTFInputStream. 31 | 32 | It is similar to FileReadBuffer but the source is an in-memory buffer instead of a file. 33 | 34 | Differences between MemoryStream and StringStream: 35 | 1. StringStream has encoding but MemoryStream is a byte stream. 36 | 2. MemoryStream needs size of the source buffer and the buffer don't need to be null terminated. StringStream assume null-terminated string as source. 37 | 3. MemoryStream supports Peek4() for encoding detection. StringStream is specified with an encoding so it should not have Peek4(). 38 | \note implements Stream concept 39 | */ 40 | struct MemoryStream { 41 | typedef char Ch; // byte 42 | 43 | MemoryStream(const Ch *src, size_t size) : src_(src), begin_(src), end_(src + size), size_(size) {} 44 | 45 | Ch Peek() const { return RAPIDJSON_UNLIKELY(src_ == end_) ? '\0' : *src_; } 46 | Ch Take() { return RAPIDJSON_UNLIKELY(src_ == end_) ? '\0' : *src_++; } 47 | size_t Tell() const { return static_cast(src_ - begin_); } 48 | 49 | Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; } 50 | void Put(Ch) { RAPIDJSON_ASSERT(false); } 51 | void Flush() { RAPIDJSON_ASSERT(false); } 52 | size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; } 53 | 54 | // For encoding detection only. 55 | const Ch* Peek4() const { 56 | return Tell() + 4 <= size_ ? src_ : 0; 57 | } 58 | 59 | const Ch* src_; //!< Current read position. 60 | const Ch* begin_; //!< Original head of the string. 61 | const Ch* end_; //!< End of stream. 62 | size_t size_; //!< Size of the stream. 63 | }; 64 | 65 | RAPIDJSON_NAMESPACE_END 66 | 67 | #ifdef __clang__ 68 | RAPIDJSON_DIAG_POP 69 | #endif 70 | 71 | #endif // RAPIDJSON_MEMORYBUFFER_H_ 72 | -------------------------------------------------------------------------------- /include/rapidjson/msinttypes/inttypes.h: -------------------------------------------------------------------------------- 1 | // ISO C9x compliant inttypes.h for Microsoft Visual Studio 2 | // Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124 3 | // 4 | // Copyright (c) 2006-2013 Alexander Chemeris 5 | // 6 | // Redistribution and use in source and binary forms, with or without 7 | // modification, are permitted provided that the following conditions are met: 8 | // 9 | // 1. Redistributions of source code must retain the above copyright notice, 10 | // this list of conditions and the following disclaimer. 11 | // 12 | // 2. Redistributions in binary form must reproduce the above copyright 13 | // notice, this list of conditions and the following disclaimer in the 14 | // documentation and/or other materials provided with the distribution. 15 | // 16 | // 3. Neither the name of the product nor the names of its contributors may 17 | // be used to endorse or promote products derived from this software 18 | // without specific prior written permission. 19 | // 20 | // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED 21 | // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 22 | // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO 23 | // EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 24 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 25 | // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; 26 | // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 27 | // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR 28 | // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF 29 | // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 30 | // 31 | /////////////////////////////////////////////////////////////////////////////// 32 | 33 | // The above software in this distribution may have been modified by 34 | // THL A29 Limited ("Tencent Modifications"). 35 | // All Tencent Modifications are Copyright (C) 2015 THL A29 Limited. 36 | 37 | #ifndef _MSC_VER // [ 38 | #error "Use this header only with Microsoft Visual C++ compilers!" 39 | #endif // _MSC_VER ] 40 | 41 | #ifndef _MSC_INTTYPES_H_ // [ 42 | #define _MSC_INTTYPES_H_ 43 | 44 | #if _MSC_VER > 1000 45 | #pragma once 46 | #endif 47 | 48 | #include "stdint.h" 49 | 50 | // miloyip: VC supports inttypes.h since VC2013 51 | #if _MSC_VER >= 1800 52 | #include 53 | #else 54 | 55 | // 7.8 Format conversion of integer types 56 | 57 | typedef struct { 58 | intmax_t quot; 59 | intmax_t rem; 60 | } imaxdiv_t; 61 | 62 | // 7.8.1 Macros for format specifiers 63 | 64 | #if !defined(__cplusplus) || defined(__STDC_FORMAT_MACROS) // [ See footnote 185 at page 198 65 | 66 | // The fprintf macros for signed integers are: 67 | #define PRId8 "d" 68 | #define PRIi8 "i" 69 | #define PRIdLEAST8 "d" 70 | #define PRIiLEAST8 "i" 71 | #define PRIdFAST8 "d" 72 | #define PRIiFAST8 "i" 73 | 74 | #define PRId16 "hd" 75 | #define PRIi16 "hi" 76 | #define PRIdLEAST16 "hd" 77 | #define PRIiLEAST16 "hi" 78 | #define PRIdFAST16 "hd" 79 | #define PRIiFAST16 "hi" 80 | 81 | #define PRId32 "I32d" 82 | #define PRIi32 "I32i" 83 | #define PRIdLEAST32 "I32d" 84 | #define PRIiLEAST32 "I32i" 85 | #define PRIdFAST32 "I32d" 86 | #define PRIiFAST32 "I32i" 87 | 88 | #define PRId64 "I64d" 89 | #define PRIi64 "I64i" 90 | #define PRIdLEAST64 "I64d" 91 | #define PRIiLEAST64 "I64i" 92 | #define PRIdFAST64 "I64d" 93 | #define PRIiFAST64 "I64i" 94 | 95 | #define PRIdMAX "I64d" 96 | #define PRIiMAX "I64i" 97 | 98 | #define PRIdPTR "Id" 99 | #define PRIiPTR "Ii" 100 | 101 | // The fprintf macros for unsigned integers are: 102 | #define PRIo8 "o" 103 | #define PRIu8 "u" 104 | #define PRIx8 "x" 105 | #define PRIX8 "X" 106 | #define PRIoLEAST8 "o" 107 | #define PRIuLEAST8 "u" 108 | #define PRIxLEAST8 "x" 109 | #define PRIXLEAST8 "X" 110 | #define PRIoFAST8 "o" 111 | #define PRIuFAST8 "u" 112 | #define PRIxFAST8 "x" 113 | #define PRIXFAST8 "X" 114 | 115 | #define PRIo16 "ho" 116 | #define PRIu16 "hu" 117 | #define PRIx16 "hx" 118 | #define PRIX16 "hX" 119 | #define PRIoLEAST16 "ho" 120 | #define PRIuLEAST16 "hu" 121 | #define PRIxLEAST16 "hx" 122 | #define PRIXLEAST16 "hX" 123 | #define PRIoFAST16 "ho" 124 | #define PRIuFAST16 "hu" 125 | #define PRIxFAST16 "hx" 126 | #define PRIXFAST16 "hX" 127 | 128 | #define PRIo32 "I32o" 129 | #define PRIu32 "I32u" 130 | #define PRIx32 "I32x" 131 | #define PRIX32 "I32X" 132 | #define PRIoLEAST32 "I32o" 133 | #define PRIuLEAST32 "I32u" 134 | #define PRIxLEAST32 "I32x" 135 | #define PRIXLEAST32 "I32X" 136 | #define PRIoFAST32 "I32o" 137 | #define PRIuFAST32 "I32u" 138 | #define PRIxFAST32 "I32x" 139 | #define PRIXFAST32 "I32X" 140 | 141 | #define PRIo64 "I64o" 142 | #define PRIu64 "I64u" 143 | #define PRIx64 "I64x" 144 | #define PRIX64 "I64X" 145 | #define PRIoLEAST64 "I64o" 146 | #define PRIuLEAST64 "I64u" 147 | #define PRIxLEAST64 "I64x" 148 | #define PRIXLEAST64 "I64X" 149 | #define PRIoFAST64 "I64o" 150 | #define PRIuFAST64 "I64u" 151 | #define PRIxFAST64 "I64x" 152 | #define PRIXFAST64 "I64X" 153 | 154 | #define PRIoMAX "I64o" 155 | #define PRIuMAX "I64u" 156 | #define PRIxMAX "I64x" 157 | #define PRIXMAX "I64X" 158 | 159 | #define PRIoPTR "Io" 160 | #define PRIuPTR "Iu" 161 | #define PRIxPTR "Ix" 162 | #define PRIXPTR "IX" 163 | 164 | // The fscanf macros for signed integers are: 165 | #define SCNd8 "d" 166 | #define SCNi8 "i" 167 | #define SCNdLEAST8 "d" 168 | #define SCNiLEAST8 "i" 169 | #define SCNdFAST8 "d" 170 | #define SCNiFAST8 "i" 171 | 172 | #define SCNd16 "hd" 173 | #define SCNi16 "hi" 174 | #define SCNdLEAST16 "hd" 175 | #define SCNiLEAST16 "hi" 176 | #define SCNdFAST16 "hd" 177 | #define SCNiFAST16 "hi" 178 | 179 | #define SCNd32 "ld" 180 | #define SCNi32 "li" 181 | #define SCNdLEAST32 "ld" 182 | #define SCNiLEAST32 "li" 183 | #define SCNdFAST32 "ld" 184 | #define SCNiFAST32 "li" 185 | 186 | #define SCNd64 "I64d" 187 | #define SCNi64 "I64i" 188 | #define SCNdLEAST64 "I64d" 189 | #define SCNiLEAST64 "I64i" 190 | #define SCNdFAST64 "I64d" 191 | #define SCNiFAST64 "I64i" 192 | 193 | #define SCNdMAX "I64d" 194 | #define SCNiMAX "I64i" 195 | 196 | #ifdef _WIN64 // [ 197 | # define SCNdPTR "I64d" 198 | # define SCNiPTR "I64i" 199 | #else // _WIN64 ][ 200 | # define SCNdPTR "ld" 201 | # define SCNiPTR "li" 202 | #endif // _WIN64 ] 203 | 204 | // The fscanf macros for unsigned integers are: 205 | #define SCNo8 "o" 206 | #define SCNu8 "u" 207 | #define SCNx8 "x" 208 | #define SCNX8 "X" 209 | #define SCNoLEAST8 "o" 210 | #define SCNuLEAST8 "u" 211 | #define SCNxLEAST8 "x" 212 | #define SCNXLEAST8 "X" 213 | #define SCNoFAST8 "o" 214 | #define SCNuFAST8 "u" 215 | #define SCNxFAST8 "x" 216 | #define SCNXFAST8 "X" 217 | 218 | #define SCNo16 "ho" 219 | #define SCNu16 "hu" 220 | #define SCNx16 "hx" 221 | #define SCNX16 "hX" 222 | #define SCNoLEAST16 "ho" 223 | #define SCNuLEAST16 "hu" 224 | #define SCNxLEAST16 "hx" 225 | #define SCNXLEAST16 "hX" 226 | #define SCNoFAST16 "ho" 227 | #define SCNuFAST16 "hu" 228 | #define SCNxFAST16 "hx" 229 | #define SCNXFAST16 "hX" 230 | 231 | #define SCNo32 "lo" 232 | #define SCNu32 "lu" 233 | #define SCNx32 "lx" 234 | #define SCNX32 "lX" 235 | #define SCNoLEAST32 "lo" 236 | #define SCNuLEAST32 "lu" 237 | #define SCNxLEAST32 "lx" 238 | #define SCNXLEAST32 "lX" 239 | #define SCNoFAST32 "lo" 240 | #define SCNuFAST32 "lu" 241 | #define SCNxFAST32 "lx" 242 | #define SCNXFAST32 "lX" 243 | 244 | #define SCNo64 "I64o" 245 | #define SCNu64 "I64u" 246 | #define SCNx64 "I64x" 247 | #define SCNX64 "I64X" 248 | #define SCNoLEAST64 "I64o" 249 | #define SCNuLEAST64 "I64u" 250 | #define SCNxLEAST64 "I64x" 251 | #define SCNXLEAST64 "I64X" 252 | #define SCNoFAST64 "I64o" 253 | #define SCNuFAST64 "I64u" 254 | #define SCNxFAST64 "I64x" 255 | #define SCNXFAST64 "I64X" 256 | 257 | #define SCNoMAX "I64o" 258 | #define SCNuMAX "I64u" 259 | #define SCNxMAX "I64x" 260 | #define SCNXMAX "I64X" 261 | 262 | #ifdef _WIN64 // [ 263 | # define SCNoPTR "I64o" 264 | # define SCNuPTR "I64u" 265 | # define SCNxPTR "I64x" 266 | # define SCNXPTR "I64X" 267 | #else // _WIN64 ][ 268 | # define SCNoPTR "lo" 269 | # define SCNuPTR "lu" 270 | # define SCNxPTR "lx" 271 | # define SCNXPTR "lX" 272 | #endif // _WIN64 ] 273 | 274 | #endif // __STDC_FORMAT_MACROS ] 275 | 276 | // 7.8.2 Functions for greatest-width integer types 277 | 278 | // 7.8.2.1 The imaxabs function 279 | #define imaxabs _abs64 280 | 281 | // 7.8.2.2 The imaxdiv function 282 | 283 | // This is modified version of div() function from Microsoft's div.c found 284 | // in %MSVC.NET%\crt\src\div.c 285 | #ifdef STATIC_IMAXDIV // [ 286 | static 287 | #else // STATIC_IMAXDIV ][ 288 | _inline 289 | #endif // STATIC_IMAXDIV ] 290 | imaxdiv_t __cdecl imaxdiv(intmax_t numer, intmax_t denom) 291 | { 292 | imaxdiv_t result; 293 | 294 | result.quot = numer / denom; 295 | result.rem = numer % denom; 296 | 297 | if (numer < 0 && result.rem > 0) { 298 | // did division wrong; must fix up 299 | ++result.quot; 300 | result.rem -= denom; 301 | } 302 | 303 | return result; 304 | } 305 | 306 | // 7.8.2.3 The strtoimax and strtoumax functions 307 | #define strtoimax _strtoi64 308 | #define strtoumax _strtoui64 309 | 310 | // 7.8.2.4 The wcstoimax and wcstoumax functions 311 | #define wcstoimax _wcstoi64 312 | #define wcstoumax _wcstoui64 313 | 314 | #endif // _MSC_VER >= 1800 315 | 316 | #endif // _MSC_INTTYPES_H_ ] 317 | -------------------------------------------------------------------------------- /include/rapidjson/msinttypes/stdint.h: -------------------------------------------------------------------------------- 1 | // ISO C9x compliant stdint.h for Microsoft Visual Studio 2 | // Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124 3 | // 4 | // Copyright (c) 2006-2013 Alexander Chemeris 5 | // 6 | // Redistribution and use in source and binary forms, with or without 7 | // modification, are permitted provided that the following conditions are met: 8 | // 9 | // 1. Redistributions of source code must retain the above copyright notice, 10 | // this list of conditions and the following disclaimer. 11 | // 12 | // 2. Redistributions in binary form must reproduce the above copyright 13 | // notice, this list of conditions and the following disclaimer in the 14 | // documentation and/or other materials provided with the distribution. 15 | // 16 | // 3. Neither the name of the product nor the names of its contributors may 17 | // be used to endorse or promote products derived from this software 18 | // without specific prior written permission. 19 | // 20 | // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED 21 | // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 22 | // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO 23 | // EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 24 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 25 | // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; 26 | // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 27 | // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR 28 | // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF 29 | // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 30 | // 31 | /////////////////////////////////////////////////////////////////////////////// 32 | 33 | // The above software in this distribution may have been modified by 34 | // THL A29 Limited ("Tencent Modifications"). 35 | // All Tencent Modifications are Copyright (C) 2015 THL A29 Limited. 36 | 37 | #ifndef _MSC_VER // [ 38 | #error "Use this header only with Microsoft Visual C++ compilers!" 39 | #endif // _MSC_VER ] 40 | 41 | #ifndef _MSC_STDINT_H_ // [ 42 | #define _MSC_STDINT_H_ 43 | 44 | #if _MSC_VER > 1000 45 | #pragma once 46 | #endif 47 | 48 | // miloyip: Originally Visual Studio 2010 uses its own stdint.h. However it generates warning with INT64_C(), so change to use this file for vs2010. 49 | #if _MSC_VER >= 1600 // [ 50 | #include 51 | 52 | #if !defined(__cplusplus) || defined(__STDC_CONSTANT_MACROS) // [ See footnote 224 at page 260 53 | 54 | #undef INT8_C 55 | #undef INT16_C 56 | #undef INT32_C 57 | #undef INT64_C 58 | #undef UINT8_C 59 | #undef UINT16_C 60 | #undef UINT32_C 61 | #undef UINT64_C 62 | 63 | // 7.18.4.1 Macros for minimum-width integer constants 64 | 65 | #define INT8_C(val) val##i8 66 | #define INT16_C(val) val##i16 67 | #define INT32_C(val) val##i32 68 | #define INT64_C(val) val##i64 69 | 70 | #define UINT8_C(val) val##ui8 71 | #define UINT16_C(val) val##ui16 72 | #define UINT32_C(val) val##ui32 73 | #define UINT64_C(val) val##ui64 74 | 75 | // 7.18.4.2 Macros for greatest-width integer constants 76 | // These #ifndef's are needed to prevent collisions with . 77 | // Check out Issue 9 for the details. 78 | #ifndef INTMAX_C // [ 79 | # define INTMAX_C INT64_C 80 | #endif // INTMAX_C ] 81 | #ifndef UINTMAX_C // [ 82 | # define UINTMAX_C UINT64_C 83 | #endif // UINTMAX_C ] 84 | 85 | #endif // __STDC_CONSTANT_MACROS ] 86 | 87 | #else // ] _MSC_VER >= 1700 [ 88 | 89 | #include 90 | 91 | // For Visual Studio 6 in C++ mode and for many Visual Studio versions when 92 | // compiling for ARM we have to wrap include with 'extern "C++" {}' 93 | // or compiler would give many errors like this: 94 | // error C2733: second C linkage of overloaded function 'wmemchr' not allowed 95 | #if defined(__cplusplus) && !defined(_M_ARM) 96 | extern "C" { 97 | #endif 98 | # include 99 | #if defined(__cplusplus) && !defined(_M_ARM) 100 | } 101 | #endif 102 | 103 | // Define _W64 macros to mark types changing their size, like intptr_t. 104 | #ifndef _W64 105 | # if !defined(__midl) && (defined(_X86_) || defined(_M_IX86)) && _MSC_VER >= 1300 106 | # define _W64 __w64 107 | # else 108 | # define _W64 109 | # endif 110 | #endif 111 | 112 | 113 | // 7.18.1 Integer types 114 | 115 | // 7.18.1.1 Exact-width integer types 116 | 117 | // Visual Studio 6 and Embedded Visual C++ 4 doesn't 118 | // realize that, e.g. char has the same size as __int8 119 | // so we give up on __intX for them. 120 | #if (_MSC_VER < 1300) 121 | typedef signed char int8_t; 122 | typedef signed short int16_t; 123 | typedef signed int int32_t; 124 | typedef unsigned char uint8_t; 125 | typedef unsigned short uint16_t; 126 | typedef unsigned int uint32_t; 127 | #else 128 | typedef signed __int8 int8_t; 129 | typedef signed __int16 int16_t; 130 | typedef signed __int32 int32_t; 131 | typedef unsigned __int8 uint8_t; 132 | typedef unsigned __int16 uint16_t; 133 | typedef unsigned __int32 uint32_t; 134 | #endif 135 | typedef signed __int64 int64_t; 136 | typedef unsigned __int64 uint64_t; 137 | 138 | 139 | // 7.18.1.2 Minimum-width integer types 140 | typedef int8_t int_least8_t; 141 | typedef int16_t int_least16_t; 142 | typedef int32_t int_least32_t; 143 | typedef int64_t int_least64_t; 144 | typedef uint8_t uint_least8_t; 145 | typedef uint16_t uint_least16_t; 146 | typedef uint32_t uint_least32_t; 147 | typedef uint64_t uint_least64_t; 148 | 149 | // 7.18.1.3 Fastest minimum-width integer types 150 | typedef int8_t int_fast8_t; 151 | typedef int16_t int_fast16_t; 152 | typedef int32_t int_fast32_t; 153 | typedef int64_t int_fast64_t; 154 | typedef uint8_t uint_fast8_t; 155 | typedef uint16_t uint_fast16_t; 156 | typedef uint32_t uint_fast32_t; 157 | typedef uint64_t uint_fast64_t; 158 | 159 | // 7.18.1.4 Integer types capable of holding object pointers 160 | #ifdef _WIN64 // [ 161 | typedef signed __int64 intptr_t; 162 | typedef unsigned __int64 uintptr_t; 163 | #else // _WIN64 ][ 164 | typedef _W64 signed int intptr_t; 165 | typedef _W64 unsigned int uintptr_t; 166 | #endif // _WIN64 ] 167 | 168 | // 7.18.1.5 Greatest-width integer types 169 | typedef int64_t intmax_t; 170 | typedef uint64_t uintmax_t; 171 | 172 | 173 | // 7.18.2 Limits of specified-width integer types 174 | 175 | #if !defined(__cplusplus) || defined(__STDC_LIMIT_MACROS) // [ See footnote 220 at page 257 and footnote 221 at page 259 176 | 177 | // 7.18.2.1 Limits of exact-width integer types 178 | #define INT8_MIN ((int8_t)_I8_MIN) 179 | #define INT8_MAX _I8_MAX 180 | #define INT16_MIN ((int16_t)_I16_MIN) 181 | #define INT16_MAX _I16_MAX 182 | #define INT32_MIN ((int32_t)_I32_MIN) 183 | #define INT32_MAX _I32_MAX 184 | #define INT64_MIN ((int64_t)_I64_MIN) 185 | #define INT64_MAX _I64_MAX 186 | #define UINT8_MAX _UI8_MAX 187 | #define UINT16_MAX _UI16_MAX 188 | #define UINT32_MAX _UI32_MAX 189 | #define UINT64_MAX _UI64_MAX 190 | 191 | // 7.18.2.2 Limits of minimum-width integer types 192 | #define INT_LEAST8_MIN INT8_MIN 193 | #define INT_LEAST8_MAX INT8_MAX 194 | #define INT_LEAST16_MIN INT16_MIN 195 | #define INT_LEAST16_MAX INT16_MAX 196 | #define INT_LEAST32_MIN INT32_MIN 197 | #define INT_LEAST32_MAX INT32_MAX 198 | #define INT_LEAST64_MIN INT64_MIN 199 | #define INT_LEAST64_MAX INT64_MAX 200 | #define UINT_LEAST8_MAX UINT8_MAX 201 | #define UINT_LEAST16_MAX UINT16_MAX 202 | #define UINT_LEAST32_MAX UINT32_MAX 203 | #define UINT_LEAST64_MAX UINT64_MAX 204 | 205 | // 7.18.2.3 Limits of fastest minimum-width integer types 206 | #define INT_FAST8_MIN INT8_MIN 207 | #define INT_FAST8_MAX INT8_MAX 208 | #define INT_FAST16_MIN INT16_MIN 209 | #define INT_FAST16_MAX INT16_MAX 210 | #define INT_FAST32_MIN INT32_MIN 211 | #define INT_FAST32_MAX INT32_MAX 212 | #define INT_FAST64_MIN INT64_MIN 213 | #define INT_FAST64_MAX INT64_MAX 214 | #define UINT_FAST8_MAX UINT8_MAX 215 | #define UINT_FAST16_MAX UINT16_MAX 216 | #define UINT_FAST32_MAX UINT32_MAX 217 | #define UINT_FAST64_MAX UINT64_MAX 218 | 219 | // 7.18.2.4 Limits of integer types capable of holding object pointers 220 | #ifdef _WIN64 // [ 221 | # define INTPTR_MIN INT64_MIN 222 | # define INTPTR_MAX INT64_MAX 223 | # define UINTPTR_MAX UINT64_MAX 224 | #else // _WIN64 ][ 225 | # define INTPTR_MIN INT32_MIN 226 | # define INTPTR_MAX INT32_MAX 227 | # define UINTPTR_MAX UINT32_MAX 228 | #endif // _WIN64 ] 229 | 230 | // 7.18.2.5 Limits of greatest-width integer types 231 | #define INTMAX_MIN INT64_MIN 232 | #define INTMAX_MAX INT64_MAX 233 | #define UINTMAX_MAX UINT64_MAX 234 | 235 | // 7.18.3 Limits of other integer types 236 | 237 | #ifdef _WIN64 // [ 238 | # define PTRDIFF_MIN _I64_MIN 239 | # define PTRDIFF_MAX _I64_MAX 240 | #else // _WIN64 ][ 241 | # define PTRDIFF_MIN _I32_MIN 242 | # define PTRDIFF_MAX _I32_MAX 243 | #endif // _WIN64 ] 244 | 245 | #define SIG_ATOMIC_MIN INT_MIN 246 | #define SIG_ATOMIC_MAX INT_MAX 247 | 248 | #ifndef SIZE_MAX // [ 249 | # ifdef _WIN64 // [ 250 | # define SIZE_MAX _UI64_MAX 251 | # else // _WIN64 ][ 252 | # define SIZE_MAX _UI32_MAX 253 | # endif // _WIN64 ] 254 | #endif // SIZE_MAX ] 255 | 256 | // WCHAR_MIN and WCHAR_MAX are also defined in 257 | #ifndef WCHAR_MIN // [ 258 | # define WCHAR_MIN 0 259 | #endif // WCHAR_MIN ] 260 | #ifndef WCHAR_MAX // [ 261 | # define WCHAR_MAX _UI16_MAX 262 | #endif // WCHAR_MAX ] 263 | 264 | #define WINT_MIN 0 265 | #define WINT_MAX _UI16_MAX 266 | 267 | #endif // __STDC_LIMIT_MACROS ] 268 | 269 | 270 | // 7.18.4 Limits of other integer types 271 | 272 | #if !defined(__cplusplus) || defined(__STDC_CONSTANT_MACROS) // [ See footnote 224 at page 260 273 | 274 | // 7.18.4.1 Macros for minimum-width integer constants 275 | 276 | #define INT8_C(val) val##i8 277 | #define INT16_C(val) val##i16 278 | #define INT32_C(val) val##i32 279 | #define INT64_C(val) val##i64 280 | 281 | #define UINT8_C(val) val##ui8 282 | #define UINT16_C(val) val##ui16 283 | #define UINT32_C(val) val##ui32 284 | #define UINT64_C(val) val##ui64 285 | 286 | // 7.18.4.2 Macros for greatest-width integer constants 287 | // These #ifndef's are needed to prevent collisions with . 288 | // Check out Issue 9 for the details. 289 | #ifndef INTMAX_C // [ 290 | # define INTMAX_C INT64_C 291 | #endif // INTMAX_C ] 292 | #ifndef UINTMAX_C // [ 293 | # define UINTMAX_C UINT64_C 294 | #endif // UINTMAX_C ] 295 | 296 | #endif // __STDC_CONSTANT_MACROS ] 297 | 298 | #endif // _MSC_VER >= 1600 ] 299 | 300 | #endif // _MSC_STDINT_H_ ] 301 | -------------------------------------------------------------------------------- /include/rapidjson/ostreamwrapper.h: -------------------------------------------------------------------------------- 1 | // Tencent is pleased to support the open source community by making RapidJSON available. 2 | // 3 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. 4 | // 5 | // Licensed under the MIT License (the "License"); you may not use this file except 6 | // in compliance with the License. You may obtain a copy of the License at 7 | // 8 | // http://opensource.org/licenses/MIT 9 | // 10 | // Unless required by applicable law or agreed to in writing, software distributed 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the 13 | // specific language governing permissions and limitations under the License. 14 | 15 | #ifndef RAPIDJSON_OSTREAMWRAPPER_H_ 16 | #define RAPIDJSON_OSTREAMWRAPPER_H_ 17 | 18 | #include "stream.h" 19 | #include 20 | 21 | #ifdef __clang__ 22 | RAPIDJSON_DIAG_PUSH 23 | RAPIDJSON_DIAG_OFF(padded) 24 | #endif 25 | 26 | RAPIDJSON_NAMESPACE_BEGIN 27 | 28 | //! Wrapper of \c std::basic_ostream into RapidJSON's Stream concept. 29 | /*! 30 | The classes can be wrapped including but not limited to: 31 | 32 | - \c std::ostringstream 33 | - \c std::stringstream 34 | - \c std::wpstringstream 35 | - \c std::wstringstream 36 | - \c std::ifstream 37 | - \c std::fstream 38 | - \c std::wofstream 39 | - \c std::wfstream 40 | 41 | \tparam StreamType Class derived from \c std::basic_ostream. 42 | */ 43 | 44 | template 45 | class BasicOStreamWrapper { 46 | public: 47 | typedef typename StreamType::char_type Ch; 48 | BasicOStreamWrapper(StreamType& stream) : stream_(stream) {} 49 | 50 | void Put(Ch c) { 51 | stream_.put(c); 52 | } 53 | 54 | void Flush() { 55 | stream_.flush(); 56 | } 57 | 58 | // Not implemented 59 | char Peek() const { RAPIDJSON_ASSERT(false); return 0; } 60 | char Take() { RAPIDJSON_ASSERT(false); return 0; } 61 | size_t Tell() const { RAPIDJSON_ASSERT(false); return 0; } 62 | char* PutBegin() { RAPIDJSON_ASSERT(false); return 0; } 63 | size_t PutEnd(char*) { RAPIDJSON_ASSERT(false); return 0; } 64 | 65 | private: 66 | BasicOStreamWrapper(const BasicOStreamWrapper&); 67 | BasicOStreamWrapper& operator=(const BasicOStreamWrapper&); 68 | 69 | StreamType& stream_; 70 | }; 71 | 72 | typedef BasicOStreamWrapper OStreamWrapper; 73 | typedef BasicOStreamWrapper WOStreamWrapper; 74 | 75 | #ifdef __clang__ 76 | RAPIDJSON_DIAG_POP 77 | #endif 78 | 79 | RAPIDJSON_NAMESPACE_END 80 | 81 | #endif // RAPIDJSON_OSTREAMWRAPPER_H_ 82 | -------------------------------------------------------------------------------- /include/rapidjson/prettywriter.h: -------------------------------------------------------------------------------- 1 | // Tencent is pleased to support the open source community by making RapidJSON available. 2 | // 3 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. 4 | // 5 | // Licensed under the MIT License (the "License"); you may not use this file except 6 | // in compliance with the License. You may obtain a copy of the License at 7 | // 8 | // http://opensource.org/licenses/MIT 9 | // 10 | // Unless required by applicable law or agreed to in writing, software distributed 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the 13 | // specific language governing permissions and limitations under the License. 14 | 15 | #ifndef RAPIDJSON_PRETTYWRITER_H_ 16 | #define RAPIDJSON_PRETTYWRITER_H_ 17 | 18 | #include "writer.h" 19 | 20 | #ifdef __GNUC__ 21 | RAPIDJSON_DIAG_PUSH 22 | RAPIDJSON_DIAG_OFF(effc++) 23 | #endif 24 | 25 | #if defined(__clang__) 26 | RAPIDJSON_DIAG_PUSH 27 | RAPIDJSON_DIAG_OFF(c++98-compat) 28 | #endif 29 | 30 | RAPIDJSON_NAMESPACE_BEGIN 31 | 32 | //! Combination of PrettyWriter format flags. 33 | /*! \see PrettyWriter::SetFormatOptions 34 | */ 35 | enum PrettyFormatOptions { 36 | kFormatDefault = 0, //!< Default pretty formatting. 37 | kFormatSingleLineArray = 1 //!< Format arrays on a single line. 38 | }; 39 | 40 | //! Writer with indentation and spacing. 41 | /*! 42 | \tparam OutputStream Type of ouptut os. 43 | \tparam SourceEncoding Encoding of source string. 44 | \tparam TargetEncoding Encoding of output stream. 45 | \tparam StackAllocator Type of allocator for allocating memory of stack. 46 | */ 47 | template, typename TargetEncoding = UTF8<>, typename StackAllocator = CrtAllocator, unsigned writeFlags = kWriteDefaultFlags> 48 | class PrettyWriter : public Writer { 49 | public: 50 | typedef Writer Base; 51 | typedef typename Base::Ch Ch; 52 | 53 | //! Constructor 54 | /*! \param os Output stream. 55 | \param allocator User supplied allocator. If it is null, it will create a private one. 56 | \param levelDepth Initial capacity of stack. 57 | */ 58 | explicit PrettyWriter(OutputStream& os, StackAllocator* allocator = 0, size_t levelDepth = Base::kDefaultLevelDepth) : 59 | Base(os, allocator, levelDepth), indentChar_(' '), indentCharCount_(4), formatOptions_(kFormatDefault) {} 60 | 61 | 62 | explicit PrettyWriter(StackAllocator* allocator = 0, size_t levelDepth = Base::kDefaultLevelDepth) : 63 | Base(allocator, levelDepth), indentChar_(' '), indentCharCount_(4) {} 64 | 65 | #if RAPIDJSON_HAS_CXX11_RVALUE_REFS 66 | PrettyWriter(PrettyWriter&& rhs) : 67 | Base(std::forward(rhs)), indentChar_(rhs.indentChar_), indentCharCount_(rhs.indentCharCount_), formatOptions_(rhs.formatOptions_) {} 68 | #endif 69 | 70 | //! Set custom indentation. 71 | /*! \param indentChar Character for indentation. Must be whitespace character (' ', '\\t', '\\n', '\\r'). 72 | \param indentCharCount Number of indent characters for each indentation level. 73 | \note The default indentation is 4 spaces. 74 | */ 75 | PrettyWriter& SetIndent(Ch indentChar, unsigned indentCharCount) { 76 | RAPIDJSON_ASSERT(indentChar == ' ' || indentChar == '\t' || indentChar == '\n' || indentChar == '\r'); 77 | indentChar_ = indentChar; 78 | indentCharCount_ = indentCharCount; 79 | return *this; 80 | } 81 | 82 | //! Set pretty writer formatting options. 83 | /*! \param options Formatting options. 84 | */ 85 | PrettyWriter& SetFormatOptions(PrettyFormatOptions options) { 86 | formatOptions_ = options; 87 | return *this; 88 | } 89 | 90 | /*! @name Implementation of Handler 91 | \see Handler 92 | */ 93 | //@{ 94 | 95 | bool Null() { PrettyPrefix(kNullType); return Base::WriteNull(); } 96 | bool Bool(bool b) { PrettyPrefix(b ? kTrueType : kFalseType); return Base::WriteBool(b); } 97 | bool Int(int i) { PrettyPrefix(kNumberType); return Base::WriteInt(i); } 98 | bool Uint(unsigned u) { PrettyPrefix(kNumberType); return Base::WriteUint(u); } 99 | bool Int64(int64_t i64) { PrettyPrefix(kNumberType); return Base::WriteInt64(i64); } 100 | bool Uint64(uint64_t u64) { PrettyPrefix(kNumberType); return Base::WriteUint64(u64); } 101 | bool Double(double d) { PrettyPrefix(kNumberType); return Base::WriteDouble(d); } 102 | 103 | bool RawNumber(const Ch* str, SizeType length, bool copy = false) { 104 | RAPIDJSON_ASSERT(str != 0); 105 | (void)copy; 106 | PrettyPrefix(kNumberType); 107 | return Base::WriteString(str, length); 108 | } 109 | 110 | bool String(const Ch* str, SizeType length, bool copy = false) { 111 | RAPIDJSON_ASSERT(str != 0); 112 | (void)copy; 113 | PrettyPrefix(kStringType); 114 | return Base::WriteString(str, length); 115 | } 116 | 117 | #if RAPIDJSON_HAS_STDSTRING 118 | bool String(const std::basic_string& str) { 119 | return String(str.data(), SizeType(str.size())); 120 | } 121 | #endif 122 | 123 | bool StartObject() { 124 | PrettyPrefix(kObjectType); 125 | new (Base::level_stack_.template Push()) typename Base::Level(false); 126 | return Base::WriteStartObject(); 127 | } 128 | 129 | bool Key(const Ch* str, SizeType length, bool copy = false) { return String(str, length, copy); } 130 | 131 | #if RAPIDJSON_HAS_STDSTRING 132 | bool Key(const std::basic_string& str) { 133 | return Key(str.data(), SizeType(str.size())); 134 | } 135 | #endif 136 | 137 | bool EndObject(SizeType memberCount = 0) { 138 | (void)memberCount; 139 | RAPIDJSON_ASSERT(Base::level_stack_.GetSize() >= sizeof(typename Base::Level)); 140 | RAPIDJSON_ASSERT(!Base::level_stack_.template Top()->inArray); 141 | bool empty = Base::level_stack_.template Pop(1)->valueCount == 0; 142 | 143 | if (!empty) { 144 | Base::os_->Put('\n'); 145 | WriteIndent(); 146 | } 147 | bool ret = Base::WriteEndObject(); 148 | (void)ret; 149 | RAPIDJSON_ASSERT(ret == true); 150 | if (Base::level_stack_.Empty()) // end of json text 151 | Base::os_->Flush(); 152 | return true; 153 | } 154 | 155 | bool StartArray() { 156 | PrettyPrefix(kArrayType); 157 | new (Base::level_stack_.template Push()) typename Base::Level(true); 158 | return Base::WriteStartArray(); 159 | } 160 | 161 | bool EndArray(SizeType memberCount = 0) { 162 | (void)memberCount; 163 | RAPIDJSON_ASSERT(Base::level_stack_.GetSize() >= sizeof(typename Base::Level)); 164 | RAPIDJSON_ASSERT(Base::level_stack_.template Top()->inArray); 165 | bool empty = Base::level_stack_.template Pop(1)->valueCount == 0; 166 | 167 | if (!empty && !(formatOptions_ & kFormatSingleLineArray)) { 168 | Base::os_->Put('\n'); 169 | WriteIndent(); 170 | } 171 | bool ret = Base::WriteEndArray(); 172 | (void)ret; 173 | RAPIDJSON_ASSERT(ret == true); 174 | if (Base::level_stack_.Empty()) // end of json text 175 | Base::os_->Flush(); 176 | return true; 177 | } 178 | 179 | //@} 180 | 181 | /*! @name Convenience extensions */ 182 | //@{ 183 | 184 | //! Simpler but slower overload. 185 | bool String(const Ch* str) { return String(str, internal::StrLen(str)); } 186 | bool Key(const Ch* str) { return Key(str, internal::StrLen(str)); } 187 | 188 | //@} 189 | 190 | //! Write a raw JSON value. 191 | /*! 192 | For user to write a stringified JSON as a value. 193 | 194 | \param json A well-formed JSON value. It should not contain null character within [0, length - 1] range. 195 | \param length Length of the json. 196 | \param type Type of the root of json. 197 | \note When using PrettyWriter::RawValue(), the result json may not be indented correctly. 198 | */ 199 | bool RawValue(const Ch* json, size_t length, Type type) { 200 | RAPIDJSON_ASSERT(json != 0); 201 | PrettyPrefix(type); 202 | return Base::WriteRawValue(json, length); 203 | } 204 | 205 | protected: 206 | void PrettyPrefix(Type type) { 207 | (void)type; 208 | if (Base::level_stack_.GetSize() != 0) { // this value is not at root 209 | typename Base::Level* level = Base::level_stack_.template Top(); 210 | 211 | if (level->inArray) { 212 | if (level->valueCount > 0) { 213 | Base::os_->Put(','); // add comma if it is not the first element in array 214 | if (formatOptions_ & kFormatSingleLineArray) 215 | Base::os_->Put(' '); 216 | } 217 | 218 | if (!(formatOptions_ & kFormatSingleLineArray)) { 219 | Base::os_->Put('\n'); 220 | WriteIndent(); 221 | } 222 | } 223 | else { // in object 224 | if (level->valueCount > 0) { 225 | if (level->valueCount % 2 == 0) { 226 | Base::os_->Put(','); 227 | Base::os_->Put('\n'); 228 | } 229 | else { 230 | Base::os_->Put(':'); 231 | Base::os_->Put(' '); 232 | } 233 | } 234 | else 235 | Base::os_->Put('\n'); 236 | 237 | if (level->valueCount % 2 == 0) 238 | WriteIndent(); 239 | } 240 | if (!level->inArray && level->valueCount % 2 == 0) 241 | RAPIDJSON_ASSERT(type == kStringType); // if it's in object, then even number should be a name 242 | level->valueCount++; 243 | } 244 | else { 245 | RAPIDJSON_ASSERT(!Base::hasRoot_); // Should only has one and only one root. 246 | Base::hasRoot_ = true; 247 | } 248 | } 249 | 250 | void WriteIndent() { 251 | size_t count = (Base::level_stack_.GetSize() / sizeof(typename Base::Level)) * indentCharCount_; 252 | PutN(*Base::os_, static_cast(indentChar_), count); 253 | } 254 | 255 | Ch indentChar_; 256 | unsigned indentCharCount_; 257 | PrettyFormatOptions formatOptions_; 258 | 259 | private: 260 | // Prohibit copy constructor & assignment operator. 261 | PrettyWriter(const PrettyWriter&); 262 | PrettyWriter& operator=(const PrettyWriter&); 263 | }; 264 | 265 | RAPIDJSON_NAMESPACE_END 266 | 267 | #if defined(__clang__) 268 | RAPIDJSON_DIAG_POP 269 | #endif 270 | 271 | #ifdef __GNUC__ 272 | RAPIDJSON_DIAG_POP 273 | #endif 274 | 275 | #endif // RAPIDJSON_RAPIDJSON_H_ 276 | -------------------------------------------------------------------------------- /include/rapidjson/stream.h: -------------------------------------------------------------------------------- 1 | // Tencent is pleased to support the open source community by making RapidJSON available. 2 | // 3 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. 4 | // 5 | // Licensed under the MIT License (the "License"); you may not use this file except 6 | // in compliance with the License. You may obtain a copy of the License at 7 | // 8 | // http://opensource.org/licenses/MIT 9 | // 10 | // Unless required by applicable law or agreed to in writing, software distributed 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the 13 | // specific language governing permissions and limitations under the License. 14 | 15 | #include "rapidjson.h" 16 | 17 | #ifndef RAPIDJSON_STREAM_H_ 18 | #define RAPIDJSON_STREAM_H_ 19 | 20 | #include "encodings.h" 21 | 22 | RAPIDJSON_NAMESPACE_BEGIN 23 | 24 | /////////////////////////////////////////////////////////////////////////////// 25 | // Stream 26 | 27 | /*! \class rapidjson::Stream 28 | \brief Concept for reading and writing characters. 29 | 30 | For read-only stream, no need to implement PutBegin(), Put(), Flush() and PutEnd(). 31 | 32 | For write-only stream, only need to implement Put() and Flush(). 33 | 34 | \code 35 | concept Stream { 36 | typename Ch; //!< Character type of the stream. 37 | 38 | //! Read the current character from stream without moving the read cursor. 39 | Ch Peek() const; 40 | 41 | //! Read the current character from stream and moving the read cursor to next character. 42 | Ch Take(); 43 | 44 | //! Get the current read cursor. 45 | //! \return Number of characters read from start. 46 | size_t Tell(); 47 | 48 | //! Begin writing operation at the current read pointer. 49 | //! \return The begin writer pointer. 50 | Ch* PutBegin(); 51 | 52 | //! Write a character. 53 | void Put(Ch c); 54 | 55 | //! Flush the buffer. 56 | void Flush(); 57 | 58 | //! End the writing operation. 59 | //! \param begin The begin write pointer returned by PutBegin(). 60 | //! \return Number of characters written. 61 | size_t PutEnd(Ch* begin); 62 | } 63 | \endcode 64 | */ 65 | 66 | //! Provides additional information for stream. 67 | /*! 68 | By using traits pattern, this type provides a default configuration for stream. 69 | For custom stream, this type can be specialized for other configuration. 70 | See TEST(Reader, CustomStringStream) in readertest.cpp for example. 71 | */ 72 | template 73 | struct StreamTraits { 74 | //! Whether to make local copy of stream for optimization during parsing. 75 | /*! 76 | By default, for safety, streams do not use local copy optimization. 77 | Stream that can be copied fast should specialize this, like StreamTraits. 78 | */ 79 | enum { copyOptimization = 0 }; 80 | }; 81 | 82 | //! Reserve n characters for writing to a stream. 83 | template 84 | inline void PutReserve(Stream& stream, size_t count) { 85 | (void)stream; 86 | (void)count; 87 | } 88 | 89 | //! Write character to a stream, presuming buffer is reserved. 90 | template 91 | inline void PutUnsafe(Stream& stream, typename Stream::Ch c) { 92 | stream.Put(c); 93 | } 94 | 95 | //! Put N copies of a character to a stream. 96 | template 97 | inline void PutN(Stream& stream, Ch c, size_t n) { 98 | PutReserve(stream, n); 99 | for (size_t i = 0; i < n; i++) 100 | PutUnsafe(stream, c); 101 | } 102 | 103 | /////////////////////////////////////////////////////////////////////////////// 104 | // StringStream 105 | 106 | //! Read-only string stream. 107 | /*! \note implements Stream concept 108 | */ 109 | template 110 | struct GenericStringStream { 111 | typedef typename Encoding::Ch Ch; 112 | 113 | GenericStringStream(const Ch *src) : src_(src), head_(src) {} 114 | 115 | Ch Peek() const { return *src_; } 116 | Ch Take() { return *src_++; } 117 | size_t Tell() const { return static_cast(src_ - head_); } 118 | 119 | Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; } 120 | void Put(Ch) { RAPIDJSON_ASSERT(false); } 121 | void Flush() { RAPIDJSON_ASSERT(false); } 122 | size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; } 123 | 124 | const Ch* src_; //!< Current read position. 125 | const Ch* head_; //!< Original head of the string. 126 | }; 127 | 128 | template 129 | struct StreamTraits > { 130 | enum { copyOptimization = 1 }; 131 | }; 132 | 133 | //! String stream with UTF8 encoding. 134 | typedef GenericStringStream > StringStream; 135 | 136 | /////////////////////////////////////////////////////////////////////////////// 137 | // InsituStringStream 138 | 139 | //! A read-write string stream. 140 | /*! This string stream is particularly designed for in-situ parsing. 141 | \note implements Stream concept 142 | */ 143 | template 144 | struct GenericInsituStringStream { 145 | typedef typename Encoding::Ch Ch; 146 | 147 | GenericInsituStringStream(Ch *src) : src_(src), dst_(0), head_(src) {} 148 | 149 | // Read 150 | Ch Peek() { return *src_; } 151 | Ch Take() { return *src_++; } 152 | size_t Tell() { return static_cast(src_ - head_); } 153 | 154 | // Write 155 | void Put(Ch c) { RAPIDJSON_ASSERT(dst_ != 0); *dst_++ = c; } 156 | 157 | Ch* PutBegin() { return dst_ = src_; } 158 | size_t PutEnd(Ch* begin) { return static_cast(dst_ - begin); } 159 | void Flush() {} 160 | 161 | Ch* Push(size_t count) { Ch* begin = dst_; dst_ += count; return begin; } 162 | void Pop(size_t count) { dst_ -= count; } 163 | 164 | Ch* src_; 165 | Ch* dst_; 166 | Ch* head_; 167 | }; 168 | 169 | template 170 | struct StreamTraits > { 171 | enum { copyOptimization = 1 }; 172 | }; 173 | 174 | //! Insitu string stream with UTF8 encoding. 175 | typedef GenericInsituStringStream > InsituStringStream; 176 | 177 | RAPIDJSON_NAMESPACE_END 178 | 179 | #endif // RAPIDJSON_STREAM_H_ 180 | -------------------------------------------------------------------------------- /include/rapidjson/stringbuffer.h: -------------------------------------------------------------------------------- 1 | // Tencent is pleased to support the open source community by making RapidJSON available. 2 | // 3 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. 4 | // 5 | // Licensed under the MIT License (the "License"); you may not use this file except 6 | // in compliance with the License. You may obtain a copy of the License at 7 | // 8 | // http://opensource.org/licenses/MIT 9 | // 10 | // Unless required by applicable law or agreed to in writing, software distributed 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the 13 | // specific language governing permissions and limitations under the License. 14 | 15 | #ifndef RAPIDJSON_STRINGBUFFER_H_ 16 | #define RAPIDJSON_STRINGBUFFER_H_ 17 | 18 | #include "stream.h" 19 | #include "internal/stack.h" 20 | 21 | #if RAPIDJSON_HAS_CXX11_RVALUE_REFS 22 | #include // std::move 23 | #endif 24 | 25 | #include "internal/stack.h" 26 | 27 | #if defined(__clang__) 28 | RAPIDJSON_DIAG_PUSH 29 | RAPIDJSON_DIAG_OFF(c++98-compat) 30 | #endif 31 | 32 | RAPIDJSON_NAMESPACE_BEGIN 33 | 34 | //! Represents an in-memory output stream. 35 | /*! 36 | \tparam Encoding Encoding of the stream. 37 | \tparam Allocator type for allocating memory buffer. 38 | \note implements Stream concept 39 | */ 40 | template 41 | class GenericStringBuffer { 42 | public: 43 | typedef typename Encoding::Ch Ch; 44 | 45 | GenericStringBuffer(Allocator* allocator = 0, size_t capacity = kDefaultCapacity) : stack_(allocator, capacity) {} 46 | 47 | #if RAPIDJSON_HAS_CXX11_RVALUE_REFS 48 | GenericStringBuffer(GenericStringBuffer&& rhs) : stack_(std::move(rhs.stack_)) {} 49 | GenericStringBuffer& operator=(GenericStringBuffer&& rhs) { 50 | if (&rhs != this) 51 | stack_ = std::move(rhs.stack_); 52 | return *this; 53 | } 54 | #endif 55 | 56 | void Put(Ch c) { *stack_.template Push() = c; } 57 | void PutUnsafe(Ch c) { *stack_.template PushUnsafe() = c; } 58 | void Flush() {} 59 | 60 | void Clear() { stack_.Clear(); } 61 | void ShrinkToFit() { 62 | // Push and pop a null terminator. This is safe. 63 | *stack_.template Push() = '\0'; 64 | stack_.ShrinkToFit(); 65 | stack_.template Pop(1); 66 | } 67 | 68 | void Reserve(size_t count) { stack_.template Reserve(count); } 69 | Ch* Push(size_t count) { return stack_.template Push(count); } 70 | Ch* PushUnsafe(size_t count) { return stack_.template PushUnsafe(count); } 71 | void Pop(size_t count) { stack_.template Pop(count); } 72 | 73 | const Ch* GetString() const { 74 | // Push and pop a null terminator. This is safe. 75 | *stack_.template Push() = '\0'; 76 | stack_.template Pop(1); 77 | 78 | return stack_.template Bottom(); 79 | } 80 | 81 | //! Get the size of string in bytes in the string buffer. 82 | size_t GetSize() const { return stack_.GetSize(); } 83 | 84 | //! Get the length of string in Ch in the string buffer. 85 | size_t GetLength() const { return stack_.GetSize() / sizeof(Ch); } 86 | 87 | static const size_t kDefaultCapacity = 256; 88 | mutable internal::Stack stack_; 89 | 90 | private: 91 | // Prohibit copy constructor & assignment operator. 92 | GenericStringBuffer(const GenericStringBuffer&); 93 | GenericStringBuffer& operator=(const GenericStringBuffer&); 94 | }; 95 | 96 | //! String buffer with UTF8 encoding 97 | typedef GenericStringBuffer > StringBuffer; 98 | 99 | template 100 | inline void PutReserve(GenericStringBuffer& stream, size_t count) { 101 | stream.Reserve(count); 102 | } 103 | 104 | template 105 | inline void PutUnsafe(GenericStringBuffer& stream, typename Encoding::Ch c) { 106 | stream.PutUnsafe(c); 107 | } 108 | 109 | //! Implement specialized version of PutN() with memset() for better performance. 110 | template<> 111 | inline void PutN(GenericStringBuffer >& stream, char c, size_t n) { 112 | std::memset(stream.stack_.Push(n), c, n * sizeof(c)); 113 | } 114 | 115 | RAPIDJSON_NAMESPACE_END 116 | 117 | #if defined(__clang__) 118 | RAPIDJSON_DIAG_POP 119 | #endif 120 | 121 | #endif // RAPIDJSON_STRINGBUFFER_H_ 122 | -------------------------------------------------------------------------------- /include/ros_bridge.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | #include 13 | #include "types.h" 14 | #include "helper.h" 15 | #include "spinlock.h" 16 | 17 | #include "itransport_layer.h" 18 | 19 | #include "rapidjson/document.h" 20 | #include "rapidjson/writer.h" 21 | #include "rapidjson/stringbuffer.h" 22 | 23 | #include "messages/rosbridge_advertise_msg.h" 24 | #include "messages/rosbridge_advertise_service_msg.h" 25 | #include "messages/rosbridge_call_service_msg.h" 26 | #include "messages/rosbridge_msg.h" 27 | #include "messages/rosbridge_publish_msg.h" 28 | #include "messages/rosbridge_service_response_msg.h" 29 | #include "messages/rosbridge_subscribe_msg.h" 30 | #include "messages/rosbridge_unadvertise_msg.h" 31 | #include "messages/rosbridge_unadvertise_service_msg.h" 32 | #include "messages/rosbridge_unsubscribe_msg.h" 33 | 34 | using json = rapidjson::Document; 35 | 36 | namespace rosbridge2cpp { 37 | 38 | /** 39 | * The main rosbridge2cpp class that connects to the rosbridge server. 40 | * The library is inspired by [roslibjs](http://wiki.ros.org/roslibjs), 41 | * which is a feature-rich client-side implementation of the rosbridge protocol in java script. 42 | */ 43 | class ROSBridge { 44 | 45 | public: 46 | ROSBridge(ITransportLayer &transport) : transport_layer_(transport) {} 47 | 48 | ROSBridge(ITransportLayer &transport, bool bson_only_mode) : transport_layer_(transport), bson_only_mode_(bson_only_mode) {} 49 | 50 | ~ROSBridge(); 51 | 52 | // Init the underlying transport layer and everything thats required 53 | // to initialized in this class. 54 | bool Init(std::string ip_addr, int port); 55 | 56 | bool IsHealthy() const; 57 | 58 | // Send arbitrary string-data over the given TransportLayer 59 | bool SendMessage(std::string data); 60 | 61 | // Send json data over the transport layer, 62 | // by serializing it and using 63 | // ROSBridge::send_message(std::string data) 64 | bool SendMessage(json &data); 65 | 66 | bool SendMessage(ROSBridgeMsg &msg); 67 | 68 | bool QueueMessage(const std::string& topic_name, size_t queue_size, ROSBridgePublishMsg& msg); 69 | 70 | 71 | // Registration function for topic callbacks. 72 | // This method should ONLY be called by ROSTopic instances. 73 | // It will pass the received data to the registered std::function. 74 | // 75 | // Please note: 76 | // _If you register more than one callback for the 77 | // same topic, the old one get's overwritten_ 78 | void RegisterTopicCallback(std::string topic_name, ROSCallbackHandle& callback_handle); 79 | 80 | // This method should ONLY be called by ROSTopic instances. 81 | // If you call this on your own, the housekeeping in ROSTopic 82 | // might fail which leads to missing unsubscribe messages etc. 83 | // 84 | // @return true, if the passed callback has been found and removed. false otherwise. 85 | bool UnregisterTopicCallback(std::string topic_name, const ROSCallbackHandle& callback_handle); 86 | 87 | // Register the callback for a service call. 88 | // This callback will be executed when we receive the response for a particular Service Request 89 | void RegisterServiceCallback(std::string service_call_id, FunVrROSServiceResponseMsg fun); 90 | 91 | // Register the callback that shall be executed, 92 | // whenever we receive a request for a service that 93 | // this ROSBridge has advertised via a ROSService. 94 | void RegisterServiceRequestCallback(std::string service_name, FunVrROSCallServiceMsgrROSServiceResponseMsgrAllocator fun); 95 | void RegisterServiceRequestCallback(std::string service_name, FunVrROSCallServiceMsgrROSServiceResponseMsg fun); 96 | 97 | // An ID Counter that will be used to generate increasing 98 | // IDs for service/topic etc. messages 99 | long id_counter = 0; 100 | 101 | // Returns true if the bson only mode is activated 102 | bool bson_only_mode() { 103 | return bson_only_mode_; 104 | } 105 | 106 | // Enable the BSON only mode. 107 | // All communications with the rosbridge server 108 | // will be in BSON, instead of JSON 109 | void enable_bson_mode() { bson_only_mode_ = true; } 110 | 111 | private: 112 | // Callback function for the used ITransportLayer. 113 | // It receives the received json that was contained 114 | // in the incoming ROSBridge packet 115 | // 116 | // @pre This method assumes a valid json variable 117 | void IncomingMessageCallback(json &data); 118 | 119 | void IncomingMessageCallback(bson_t &bson); 120 | 121 | // Handler Method for reply packet 122 | void HandleIncomingPublishMessage(ROSBridgePublishMsg &data); 123 | 124 | // Handler Method for reply packet 125 | void HandleIncomingServiceResponseMessage(ROSBridgeServiceResponseMsg &data); 126 | 127 | // Handler Method for reply packet 128 | void HandleIncomingServiceRequestMessage(ROSBridgeCallServiceMsg &data); 129 | 130 | int RunPublisherQueueThread(); 131 | 132 | ITransportLayer &transport_layer_; 133 | std::unordered_map>> registered_topic_callbacks_; 134 | std::unordered_map registered_service_callbacks_; 135 | std::unordered_map registered_service_request_callbacks_; 136 | std::unordered_map registered_service_request_callbacks_bson_; 137 | bool bson_only_mode_ = false; 138 | 139 | spinlock transport_layer_access_mutex_; 140 | 141 | spinlock change_topics_mutex_; 142 | 143 | std::thread publisher_queue_thread_; 144 | spinlock change_publisher_queues_mutex_; 145 | std::unordered_map publisher_topics_; // points to index in publisher_queues_ 146 | std::vector> publisher_queues_; // data to publish on the queue thread 147 | size_t current_publisher_queue_ = 0; 148 | bool run_publisher_queue_thread_ = true; 149 | std::chrono::system_clock::time_point LastDataSendTime; // watchdog for send thread. Socket sometimes blocks infinitely. 150 | }; 151 | } 152 | -------------------------------------------------------------------------------- /include/ros_message_factory.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "rapidjson/document.h" 4 | 5 | using json = rapidjson::Document; 6 | 7 | /* 8 | * This class creates json variables 9 | * that contain the structure of 10 | * popular ROS Messages. 11 | */ 12 | namespace rosbridge2cpp { 13 | class ROSMessageFactory { 14 | public: 15 | ROSMessageFactory() = default; 16 | ~ROSMessageFactory() = default; 17 | 18 | static json std_msgs_header(json::AllocatorType& allocator) 19 | { 20 | json header(rapidjson::kObjectType); 21 | header.AddMember("seq", (uint32_t)0, allocator); 22 | rapidjson::Value stamp(rapidjson::kObjectType); 23 | stamp.AddMember("secs", (uint64_t)0, allocator); 24 | stamp.AddMember("nsecs", (uint64_t)0, allocator); 25 | header.AddMember("stamp", stamp, allocator); 26 | header.AddMember("frame_id", std::string(""), allocator); 27 | 28 | return header; 29 | } 30 | 31 | 32 | static json geometry_msgs_vector3(json::AllocatorType& allocator) 33 | { 34 | json msg(rapidjson::kObjectType); 35 | msg.AddMember("x", (double)0, allocator); 36 | msg.AddMember("y", (double)0, allocator); 37 | msg.AddMember("z", (double)0, allocator); 38 | 39 | return msg; 40 | } 41 | 42 | static json geometry_msgs_quaternion(json::AllocatorType& allocator) 43 | { 44 | json msg(rapidjson::kObjectType); 45 | msg.AddMember("x", (double)0, allocator); 46 | msg.AddMember("y", (double)0, allocator); 47 | msg.AddMember("z", (double)0, allocator); 48 | msg.AddMember("w", (double)1, allocator); 49 | 50 | return msg; 51 | } 52 | 53 | static json geometry_msgs_transform(json::AllocatorType& allocator) 54 | { 55 | json msg(rapidjson::kObjectType); 56 | msg.AddMember("translation", geometry_msgs_vector3(allocator), allocator); 57 | msg.AddMember("rotation", geometry_msgs_quaternion(allocator), allocator); 58 | 59 | return msg; 60 | } 61 | 62 | static json geometry_msgs_transformstamped(json::AllocatorType& allocator) 63 | { 64 | json msg(rapidjson::kObjectType); 65 | msg.AddMember("header", std_msgs_header(allocator), allocator); 66 | msg.AddMember("child_frame_id", std::string(""), allocator); 67 | msg.AddMember("transform", geometry_msgs_transform(allocator), allocator); 68 | 69 | return msg; 70 | } 71 | 72 | static json sensor_msgs_image(json::AllocatorType& allocator) 73 | { 74 | json msg(rapidjson::kObjectType); 75 | msg.AddMember("header", std_msgs_header(allocator), allocator); 76 | msg.AddMember("height", (uint32_t)0, allocator); 77 | msg.AddMember("width", (uint32_t)0, allocator); 78 | msg.AddMember("encoding", std::string(""), allocator); 79 | msg.AddMember("is_bigendian", (uint32_t)0, allocator); 80 | msg.AddMember("step", (uint32_t)0, allocator); 81 | msg.AddMember("data", std::string(""), allocator); // uint8[] will be represented as a base64 string in rosbridge 82 | //msg.AddMember("child_frame_id", std::string(""), allocator); 83 | //msg.AddMember("transform", geometry_msgs_transform(allocator), allocator); 84 | 85 | return msg; 86 | } 87 | }; 88 | } 89 | -------------------------------------------------------------------------------- /include/ros_service.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | #include "rapidjson/document.h" 6 | 7 | #include "ros_bridge.h" 8 | #include "types.h" 9 | #include "messages/rosbridge_advertise_service_msg.h" 10 | #include "messages/rosbridge_call_service_msg.h" 11 | #include "messages/rosbridge_unadvertise_service_msg.h" 12 | 13 | using json = rapidjson::Document; 14 | 15 | namespace rosbridge2cpp { 16 | class ROSService { 17 | public: 18 | // TODO: Implement setter of other options 19 | ROSService(ROSBridge &ros, std::string service_name, std::string service_type) : 20 | ros_(ros), service_name_(service_name), service_type_(service_type) { 21 | } 22 | 23 | // Advertise a service and define the request handling callback 24 | // The given callback will handle all service requests. 25 | // 26 | // The callback will get the CallService packet from the server and 27 | // a reference to a ServiceResponse packet, that can be filled as desired. 28 | // 29 | // This method will only be used when using rapidjson, since we need to use 30 | // the allocator of rapidjson to avoid copy operations. 31 | bool Advertise(FunVrROSCallServiceMsgrROSServiceResponseMsgrAllocator callback); 32 | bool Advertise(FunVrROSCallServiceMsgrROSServiceResponseMsg callback); 33 | 34 | // Unadvertise an advertised service 35 | // Will do nothing if no service has been advertised before in this instance 36 | bool Unadvertise(); 37 | 38 | // TODO failedCallback parameter 39 | // Call a ROS-Service 40 | // The given callback variable will be called when the service reply 41 | // has been received by ROSBridge. It will passed the received data to the callback. 42 | // The whole content of the "request" parameter will be send as the "args" 43 | // argument of the Service Request 44 | bool CallService(rapidjson::Value &request, FunVrROSServiceResponseMsg callback); 45 | bool CallService(bson_t *request, FunVrROSServiceResponseMsg callback); 46 | 47 | std::string GenerateServiceCallID(); 48 | 49 | std::string ServiceName() { 50 | return service_name_; 51 | } 52 | 53 | private: 54 | ROSBridge &ros_; 55 | std::string service_name_; 56 | std::string service_type_; 57 | bool is_advertised_ = false; 58 | }; 59 | } 60 | -------------------------------------------------------------------------------- /include/ros_tf_broadcaster.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "rapidjson/document.h" 4 | #include 5 | 6 | #include "ros_bridge.h" 7 | #include "ros_topic.h" 8 | #include "helper.h" 9 | 10 | using json = rapidjson::Document; 11 | 12 | namespace rosbridge2cpp { 13 | class ROSTFBroadcaster { 14 | public: 15 | ROSTFBroadcaster(ROSBridge &ros) : ros_(ros) {}; 16 | 17 | // Send a single transform to /tf in JSON mode 18 | void SendTransform(json &geometry_msgs_transformstamped_msg); 19 | // Send Transform in BSON mode 20 | void SendTransform(bson_t &bson); 21 | 22 | // Accepts an json document (where .IsArray() is true) that contains 23 | // an array of geometry_msgs_transformstamped messages. 24 | // Only to be used in json mode 25 | void SendTransforms(json &geometry_msgs_transformstamped_array_msg); 26 | 27 | ~ROSTFBroadcaster() = default; 28 | 29 | private: 30 | ROSBridge &ros_; 31 | ROSTopic tf_topic_{ ros_,"/tf","tf/tfMessage" }; 32 | }; 33 | } 34 | -------------------------------------------------------------------------------- /include/ros_time.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | 4 | namespace rosbridge2cpp { 5 | /** 6 | * A class that contains the same time format like the original ROSTime. 7 | * 8 | * sec_ contains the seconds sind 1.1.1970. 9 | * nsec_ contains the rest nanoseconds from sec_ up to the given time 10 | */ 11 | class ROSTime { 12 | public: 13 | ROSTime() = default; 14 | ROSTime(unsigned long sec, unsigned long nsec) : sec_(sec), nsec_(nsec) {} 15 | 16 | static ROSTime now(); 17 | 18 | unsigned long sec_; 19 | unsigned long nsec_; 20 | 21 | static bool use_sim_time; 22 | static ROSTime sim_time; 23 | 24 | static const std::chrono::high_resolution_clock::duration HRCEpocOffset; 25 | }; 26 | } 27 | -------------------------------------------------------------------------------- /include/ros_topic.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | #include "rapidjson/document.h" 6 | 7 | #include "ros_bridge.h" 8 | #include "types.h" 9 | #include "helper.h" 10 | #include "messages/rosbridge_advertise_msg.h" 11 | #include "messages/rosbridge_publish_msg.h" 12 | #include "messages/rosbridge_subscribe_msg.h" 13 | #include "messages/rosbridge_unsubscribe_msg.h" 14 | #include "messages/rosbridge_unadvertise_msg.h" 15 | 16 | using json = rapidjson::Document; 17 | 18 | namespace rosbridge2cpp{ 19 | 20 | class ROSTopic { 21 | public: 22 | ROSTopic(ROSBridge &ros, std::string topic_name, std::string message_type, int queue_size = 10) 23 | : ros_(ros) 24 | , topic_name_(topic_name) 25 | , message_type_(message_type) 26 | , queue_size_(queue_size) 27 | { 28 | } 29 | 30 | // Subscribes to a ROS Topic and registers a callback function 31 | // for incoming messages 32 | // Multiple callback functions for the same topic within the same instance 33 | // can be registered. 34 | // Please note, that these callbacks shouldn't be anonymous entities such as lambdas, 35 | // to allow to them to unregister them with unsubscribe() 36 | // 37 | // For every incoming message, the callback function will receive the "msg" 38 | // field of the incoming ROSBridge packet for the given topic 39 | // 40 | // *WARNING* When using rapidjson transmission, be aware of moving operations 41 | // in the topic callbacks. 42 | // Things like: 43 | // std::string x = message.msg_json_["data"]; 44 | // in the callbacks will move the data from the 45 | // the json result to the local variable 46 | // When this happens, other callbacks that receive the same message 47 | // will read 'Null' on msg_json_ 48 | ROSCallbackHandle Subscribe(FunVrROSPublishMsg callback); 49 | 50 | // Unsubscribe from a given topic 51 | // If multiple callbacks for this topic have been registered, 52 | // the given callback will be unregistered in the ROSBridge WITHOUT 53 | // sending 'unsubscribe' to the rosbridge server. 54 | // If you're passing the last registered callback to this function, 55 | // it will be unregistered in the ROSBridge instance 56 | // AND 'unsubscribe' will be send to the server 57 | bool Unsubscribe(const ROSCallbackHandle& callback_handle); 58 | 59 | // Advertise as a publisher for this topic 60 | bool Advertise(); 61 | 62 | // Unadvertise as a publisher for this topic 63 | bool Unadvertise(); 64 | 65 | // Publish a message over this topic. 66 | // If advertise() has not been called before, this will be done in this method beforehand. 67 | // Please make sure that the message matches the type of the topic, 68 | // since this will NOT be valided before sending it to the rosbridge. 69 | // 70 | // @deprecated, use void Publish(rapidjson::Value &message); 71 | // void Publish(json &message); 72 | 73 | // Publish a message over this topic. 74 | // If advertise() has not been called before, this will be done in this method beforehand. 75 | // Please make sure that the message matches the type of the topic, 76 | // since this will NOT be valided before sending it to the rosbridge. 77 | bool Publish(rapidjson::Value &message); 78 | bool Publish(bson_t *message); 79 | 80 | std::string GeneratePublishID(); 81 | 82 | std::string TopicName() { 83 | return topic_name_; 84 | } 85 | 86 | private: 87 | ROSBridge &ros_; 88 | std::string topic_name_; 89 | std::string message_type_; 90 | 91 | // Optional parameters and it's defaults 92 | bool is_advertised_ = false; 93 | std::string compression_ = "none"; 94 | int throttle_rate_ = 0; 95 | bool latch_ = false; 96 | 97 | // number of messages queued for remote publisher/subscriber within rosbridge AND local publisher queue (local subscriber queue is not supported at the moment) 98 | int queue_size_ = 10; 99 | 100 | // Householding variables 101 | std::string advertise_id_ = ""; 102 | std::string subscribe_id_ = ""; 103 | 104 | // Count how many callbacks are currently registered in the ROSBridge instance 105 | int subscription_counter_ = 0; 106 | }; 107 | } 108 | -------------------------------------------------------------------------------- /include/spinlock.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | 6 | namespace rosbridge2cpp { 7 | 8 | class spinlock 9 | { 10 | private: 11 | std::atomic_flag lock_; 12 | 13 | public: 14 | spinlock() 15 | { 16 | lock_.clear(std::memory_order_release); 17 | } 18 | 19 | bool try_lock() 20 | { 21 | return !lock_.test_and_set(std::memory_order_acquire); 22 | } 23 | 24 | void lock(const bool sleep = false) 25 | { 26 | while (!try_lock()) 27 | { 28 | if (sleep) 29 | { 30 | std::this_thread::yield(); 31 | } 32 | } 33 | } 34 | 35 | void unlock() 36 | { 37 | lock_.clear(std::memory_order_release); 38 | } 39 | 40 | public: 41 | 42 | template 43 | class scoped_lock 44 | { 45 | private: 46 | spinlock& spinlock_; 47 | scoped_lock(scoped_lock const &); 48 | scoped_lock & operator=(scoped_lock const &); 49 | 50 | public: 51 | explicit scoped_lock(spinlock& sp) : spinlock_(sp) 52 | { 53 | sp.lock(WaitForLongTask); 54 | } 55 | 56 | ~scoped_lock() 57 | { 58 | spinlock_.unlock(); 59 | } 60 | }; 61 | 62 | // assume the other task may take longer, so use sleep/yield 63 | typedef scoped_lock scoped_lock_wait_for_long_task; 64 | // assume the other task finishes soon, so spin wait 65 | typedef scoped_lock scoped_lock_wait_for_short_task; 66 | }; 67 | 68 | } // namespace rosbridge2cpp 69 | -------------------------------------------------------------------------------- /include/types.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | 4 | #include "rapidjson/document.h" 5 | 6 | #include "messages/rosbridge_msg.h" 7 | #include "messages/rosbridge_call_service_msg.h" 8 | #include "messages/rosbridge_publish_msg.h" 9 | #include "messages/rosbridge_service_response_msg.h" 10 | 11 | namespace rosbridge2cpp { 12 | using json = rapidjson::Document; 13 | typedef std::function FunVcrJSON; 14 | // typedef std::function FunVrROSMSG; 15 | typedef std::function FunVrROSPublishMsg; 16 | typedef std::function FunVrROSServiceResponseMsg; 17 | typedef std::function FunVrROSCallServiceMsgrROSServiceResponseMsgrAllocator; 18 | typedef std::function FunVrROSCallServiceMsgrROSServiceResponseMsg; 19 | // typedef std::function FunJSONcrJSON; 20 | 21 | enum class TransportError { R2C_SOCKET_ERROR, R2C_CONNECTION_CLOSED }; 22 | extern unsigned long ROSCallbackHandle_id_counter; 23 | 24 | template 25 | class ROSCallbackHandle { 26 | public: 27 | ROSCallbackHandle() 28 | : id_(0) 29 | , function_() {} 30 | 31 | ROSCallbackHandle(FunctionType& function) 32 | : id_(ROSCallbackHandle_id_counter) 33 | , function_(function) 34 | { 35 | if (function_ != nullptr) { 36 | ROSCallbackHandle_id_counter++; 37 | } else { 38 | id_ = 0; 39 | } 40 | } 41 | 42 | ROSCallbackHandle(const ROSCallbackHandle& other) 43 | : id_(other.id_) 44 | , function_(other.function_) {} 45 | 46 | bool IsValid() const 47 | { 48 | return (function_ != nullptr) && (id_ > 0); 49 | } 50 | 51 | bool operator == (const ROSCallbackHandle& other) const 52 | { 53 | return other.id_ == id_; 54 | } 55 | 56 | bool operator<(const ROSCallbackHandle& other) const 57 | { 58 | return other.id_ < id_; 59 | } 60 | 61 | FunctionType& GetFunction() 62 | { 63 | return function_; 64 | } 65 | 66 | private: 67 | unsigned long id_; 68 | FunctionType function_; 69 | }; 70 | } 71 | -------------------------------------------------------------------------------- /install_deps.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | wget https://github.com/mongodb/libbson/releases/download/1.5.3/libbson-1.5.3.tar.gz 3 | tar xzf libbson-1.5.3.tar.gz 4 | pushd libbson-1.5.3; 5 | ./configure --prefix=$HOME/deps/libbson && make -j$(grep -c ^processor /proc/cpuinfo) && make install; 6 | popd; 7 | -------------------------------------------------------------------------------- /src/client/client.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * This is an example file to get a feeling for the usage of this library. 3 | * You may also check our unit tests in tests/tests.cpp to see more functions in action. 4 | * 5 | * Please note that this example file uses the socket_tcp_connection class to talk 6 | * to the rosbridge server. socket_tcp_connection relies on traditional unix sockets and may 7 | * not work on your individual system. 8 | */ 9 | #include 10 | #include 11 | 12 | #include "types.h" 13 | #include "ros_bridge.h" 14 | #include "ros_topic.h" 15 | #include "ros_service.h" 16 | #include "client/socket_tcp_connection.h" 17 | 18 | using namespace rosbridge2cpp; 19 | 20 | void connection_error_handler(TransportError err) { 21 | if(err == TransportError ::R2C_CONNECTION_CLOSED) 22 | std::cout << "Connection closed - You should reinit ROSBridge" << std::endl; 23 | if(err == TransportError ::R2C_SOCKET_ERROR) 24 | std::cout << "Error on ROSBridge Socket - You should reinit ROSBridge" << std::endl; 25 | } 26 | 27 | 28 | int main() 29 | { 30 | SocketTCPConnection t; 31 | t.RegisterErrorCallback(connection_error_handler); 32 | 33 | 34 | ROSBridge ros(t); 35 | ros.enable_bson_mode(); 36 | if( !ros.Init("127.0.0.1", 9090)) 37 | { 38 | std::cerr << "Failed to connect to ROSBridge" << std::endl; 39 | return 0; 40 | } 41 | 42 | ROSTopic test_topic(ros, "/test_rosbridge2cpp", "std_msgs/String"); 43 | 44 | std::this_thread::sleep_for(std::chrono::milliseconds(50)); 45 | 46 | bson_t *message = BCON_NEW( 47 | "data", "Publish from Test Client" 48 | ); 49 | test_topic.Publish(message); 50 | 51 | while(true){ 52 | std::this_thread::sleep_for(std::chrono::milliseconds(50)); 53 | } 54 | 55 | } 56 | -------------------------------------------------------------------------------- /src/client/socket_tcp_connection.cpp: -------------------------------------------------------------------------------- 1 | #include "client/socket_tcp_connection.h" 2 | 3 | namespace rosbridge2cpp{ 4 | bool SocketTCPConnection::Init(std::string p_ip_addr, int p_port){ 5 | ip_addr_ = p_ip_addr; 6 | port_ = p_port; 7 | 8 | if (sock_ == -1) 9 | { 10 | perror("[TCPConnection] Could not create socket"); 11 | } 12 | 13 | std::cout << "[TCPConnection] Socket created\n"; 14 | // Set up IP address 15 | connect_to_.sin_addr.s_addr = inet_addr( ip_addr_.c_str() ); 16 | 17 | connect_to_.sin_family = AF_INET; 18 | connect_to_.sin_port = htons( port_ ); 19 | 20 | if (connect(sock_ , (struct sockaddr *)&connect_to_ , sizeof(connect_to_)) < 0) 21 | { 22 | perror("[TCPConnection] connect failed. Error"); 23 | return false; 24 | } 25 | 26 | std::cout << "[TCPConnection] Connected\n"; 27 | 28 | // Setting up the receiver thread 29 | std::cout << "[TCPConnection] Setting up receiver thread..." << std::endl; 30 | receiver_thread_ = std::move(std::thread([=]() {ReceiverThreadFunction(); return 1; })); 31 | receiver_thread_set_up_ = true; 32 | 33 | return true; 34 | } 35 | bool SocketTCPConnection::SendMessage(std::string data){ 36 | if( send(sock_ , data.c_str() , strlen( data.c_str() ) , 0) < 0) 37 | { 38 | perror("[TCPConnection] Send failed : "); 39 | return false; 40 | } 41 | std::cout<<"[TCPConnection] Data send: " << data << "\n"; 42 | return true; 43 | } 44 | 45 | bool SocketTCPConnection::SendMessage(const uint8_t *data, unsigned int length){ 46 | if( send(sock_ , data , length , 0) < 0) 47 | { 48 | perror("[TCPConnection] Send failed : "); 49 | return false; 50 | } 51 | std::cout<<"[TCPConnection] Data send ("< recv_buffer(new unsigned char[buf_size]); 67 | 68 | // Register message callback 69 | // std::function message_cb = messageCallback; 70 | 71 | // TODO handle joined messages while reading the buffer 72 | while(!terminate_receiver_thread_){ 73 | std::cout << "." << std::endl; 74 | int count = recv(sock_, recv_buffer.get(), buf_size, 0); 75 | std::cout << "[TCPConnection] Received bytes: " << count << std::endl; 76 | if(count == 0){ 77 | if(!terminate_receiver_thread_) 78 | ReportError(TransportError ::R2C_CONNECTION_CLOSED); 79 | return 1; // connection closed 80 | } 81 | if(count < 0){ 82 | if(!terminate_receiver_thread_) 83 | ReportError(TransportError ::R2C_SOCKET_ERROR); 84 | return 2; // error while receiving from socket 85 | } 86 | 87 | recv_buffer.get()[count] = 0; // null-terminate to handle it like a c-string 88 | if(bson_only_mode_){ 89 | for (int i = 0; i < count; i++) { 90 | std::cout << "0x" << std::setw(2) << std::setfill('0') << std::hex << (int)( recv_buffer[i] ); 91 | } 92 | std::cout << "[TCPConnection] Received Data end" << std::endl; 93 | std::cout << std::endl; 94 | }else{ 95 | // Print the human-readable data 96 | printf("%.*s", count, recv_buffer.get()); 97 | } 98 | 99 | // TODO catch parse error properly 100 | json j; 101 | bson_t b; 102 | 103 | if(bson_only_mode_){ 104 | // std::cerr << "bson receive not implemented right now" << std::endl; 105 | if(!bson_init_static (&b, recv_buffer.get(), count)){ 106 | std::cout << "[TCPConnection] Error on BSON parse - Ignoring message" << std::endl; 107 | continue; 108 | } 109 | if(incoming_message_callback_bson_){ 110 | incoming_message_callback_bson_(b); 111 | } 112 | 113 | continue; 114 | /* 115 | if(!bson_init_static (&b, recv_buffer.get(), count)){ 116 | std::cout << "Error on BSON parse - Ignoring message" << std::endl; 117 | continue; 118 | } 119 | if(incoming_message_callback_bson_){ 120 | incoming_message_callback_bson_(b); 121 | } 122 | std::string str = bson_as_json (&b, NULL); 123 | // if (!bson_init_from_json(&bson, str_repr.c_str(), -1, &error)) { 124 | // printf("bson_init_from_json() failed: %s\n", error.message); 125 | // bson_destroy(&bson); 126 | // return false; 127 | // } 128 | // const uint8_t *bson_data = bson_get_data (&bson); 129 | // uint32_t bson_size = bson.len; 130 | // bool retval = transport_layer_.SendMessage(bson_data,bson_size); 131 | // bson_destroy(&b); 132 | j.Parse(str); 133 | */ 134 | }else{ 135 | j.Parse((char *)recv_buffer.get()); 136 | 137 | // TODO Use a thread for the message callback? 138 | if(incoming_message_callback_){ 139 | incoming_message_callback_(j); 140 | } 141 | } 142 | 143 | 144 | 145 | if(bson_only_mode_) 146 | bson_destroy(&b); 147 | std::cout.flush(); 148 | } 149 | return 0; // Everything went OK - terminateReceiverThread is now true 150 | } 151 | 152 | void SocketTCPConnection::RegisterIncomingMessageCallback(std::function fun){ 153 | // TODO unify with report_error 154 | incoming_message_callback_ = fun; 155 | callback_function_defined_ = true; 156 | } 157 | 158 | void SocketTCPConnection::RegisterIncomingMessageCallback(std::function fun){ 159 | // TODO unify with report_error 160 | incoming_message_callback_bson_ = fun; 161 | callback_function_defined_ = true; 162 | } 163 | 164 | void SocketTCPConnection::RegisterErrorCallback(std::function fun){ 165 | error_callback_ = fun; 166 | } 167 | void SocketTCPConnection::ReportError(TransportError err){ 168 | if(error_callback_ == nullptr) 169 | return; 170 | 171 | error_callback_(err); 172 | } 173 | 174 | void SocketTCPConnection::SetTransportMode(ITransportLayer::TransportMode mode){ 175 | switch(mode){ 176 | case ITransportLayer::JSON: 177 | bson_only_mode_ = false; 178 | break; 179 | case ITransportLayer::BSON: 180 | bson_only_mode_ = true; 181 | break; 182 | default: 183 | std::cerr << "Given TransportMode Not implemented " << std::endl; 184 | } 185 | } 186 | } 187 | -------------------------------------------------------------------------------- /src/ros_service.cpp: -------------------------------------------------------------------------------- 1 | #include "ros_service.h" 2 | 3 | namespace rosbridge2cpp{ 4 | 5 | std::string ROSService::GenerateServiceCallID() { 6 | std::string service_call_id = ""; 7 | service_call_id.append("call_service:"); 8 | service_call_id.append(service_name_); 9 | service_call_id.append(":"); 10 | service_call_id.append(std::to_string(++ros_.id_counter)); 11 | return service_call_id; 12 | } 13 | 14 | bool ROSService::CallService(rapidjson::Value &request, FunVrROSServiceResponseMsg callback) { 15 | if (is_advertised_) // You can't use an advertised ROSService instance to call services. 16 | return false; // Use a separate instance 17 | 18 | std::string service_call_id = GenerateServiceCallID(); 19 | 20 | // Register the callback with the given call id in the ROSBridge 21 | ros_.RegisterServiceCallback(service_call_id, callback); 22 | 23 | ROSBridgeCallServiceMsg cmd(true); 24 | cmd.id_ = service_call_id; 25 | cmd.service_ = service_name_; 26 | cmd.args_json_ = request; 27 | 28 | return ros_.SendMessage(cmd); 29 | } 30 | 31 | bool ROSService::CallService(bson_t *request, FunVrROSServiceResponseMsg callback) { 32 | if (is_advertised_) // You can't use an advertised ROSService instance to call services. 33 | return false; // Use a separate instance 34 | 35 | assert(request); 36 | 37 | std::string service_call_id = GenerateServiceCallID(); 38 | 39 | // Register the callback with the given call id in the ROSBridge 40 | ros_.RegisterServiceCallback(service_call_id, callback); 41 | 42 | ROSBridgeCallServiceMsg cmd(true); 43 | cmd.id_ = service_call_id; 44 | cmd.service_ = service_name_; 45 | cmd.args_bson_ = request; 46 | 47 | return ros_.SendMessage(cmd); 48 | } 49 | 50 | bool ROSService::Advertise(FunVrROSCallServiceMsgrROSServiceResponseMsgrAllocator callback) { 51 | if (is_advertised_) 52 | return true; 53 | 54 | // Register on ROSBridge 55 | ros_.RegisterServiceRequestCallback(service_name_, callback); 56 | 57 | ROSBridgeAdvertiseServiceMsg cmd(true); 58 | cmd.service_ = service_name_; 59 | cmd.type_ = service_type_; 60 | 61 | is_advertised_ = ros_.SendMessage(cmd); 62 | return is_advertised_; 63 | } 64 | 65 | bool ROSService::Advertise(FunVrROSCallServiceMsgrROSServiceResponseMsg callback) { 66 | if (is_advertised_) 67 | return true; 68 | 69 | // Register on ROSBridge 70 | ros_.RegisterServiceRequestCallback(service_name_, callback); 71 | 72 | ROSBridgeAdvertiseServiceMsg cmd(true); 73 | cmd.service_ = service_name_; 74 | cmd.type_ = service_type_; 75 | 76 | is_advertised_ = ros_.SendMessage(cmd); 77 | return is_advertised_; 78 | } 79 | 80 | 81 | // Unadvertise an advertised service 82 | bool ROSService::Unadvertise() { 83 | if (!is_advertised_) 84 | return true; 85 | 86 | ROSBridgeUnadvertiseServiceMsg cmd(true); 87 | cmd.service_ = service_name_; 88 | 89 | is_advertised_ = !ros_.SendMessage(cmd); 90 | return !is_advertised_; 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /src/ros_tf_broadcaster.cpp: -------------------------------------------------------------------------------- 1 | #include "ros_tf_broadcaster.h" 2 | 3 | namespace rosbridge2cpp { 4 | void ROSTFBroadcaster::SendTransform(json &geometry_msgs_transformstamped_msg) 5 | { 6 | assert(geometry_msgs_transformstamped_msg.IsObject()); 7 | 8 | rapidjson::Document transform_array; 9 | transform_array.SetArray(); 10 | transform_array.PushBack(geometry_msgs_transformstamped_msg, transform_array.GetAllocator()); 11 | 12 | SendTransforms(transform_array); 13 | } 14 | 15 | void ROSTFBroadcaster::SendTransforms(json &geometry_msgs_transformstamped_array_msg) 16 | { 17 | assert(geometry_msgs_transformstamped_array_msg.IsArray()); 18 | 19 | rapidjson::Document tf_message; 20 | tf_message.SetObject(); 21 | 22 | tf_message.AddMember("transforms", geometry_msgs_transformstamped_array_msg, tf_message.GetAllocator()); 23 | 24 | tf_topic_.Publish(tf_message); 25 | } 26 | 27 | void ROSTFBroadcaster::SendTransform(bson_t &bson) 28 | { 29 | tf_topic_.Publish(&bson); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/ros_time.cpp: -------------------------------------------------------------------------------- 1 | #include "ros_time.h" 2 | 3 | namespace rosbridge2cpp { 4 | 5 | bool ROSTime::use_sim_time = false; 6 | ROSTime ROSTime::sim_time(0, 0); 7 | 8 | static std::chrono::high_resolution_clock::duration ComputeHRC1970EpocDelta() 9 | { 10 | const std::chrono::high_resolution_clock::time_point hr_time_since_epoch = std::chrono::high_resolution_clock::now(); 11 | const std::chrono::system_clock::time_point time_since_epoch = std::chrono::system_clock::now(); 12 | return time_since_epoch.time_since_epoch() - hr_time_since_epoch.time_since_epoch(); 13 | } 14 | 15 | const std::chrono::high_resolution_clock::duration ROSTime::HRCEpocOffset = ComputeHRC1970EpocDelta(); 16 | 17 | ROSTime ROSTime::now() { 18 | if (use_sim_time) { 19 | return sim_time; 20 | } 21 | 22 | const std::chrono::high_resolution_clock::duration time_since_epoch = HRCEpocOffset + std::chrono::high_resolution_clock::now().time_since_epoch(); 23 | unsigned long seconds_since_epoch = std::chrono::duration_cast(time_since_epoch).count(); 24 | unsigned long long nanoseconds_since_epoch = std::chrono::duration_cast(time_since_epoch).count(); 25 | unsigned long nanosecond_difference = nanoseconds_since_epoch - (seconds_since_epoch * 1000000000ul); 26 | return ROSTime(seconds_since_epoch, nanosecond_difference); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/ros_topic.cpp: -------------------------------------------------------------------------------- 1 | #include "ros_topic.h" 2 | 3 | namespace rosbridge2cpp { 4 | 5 | ROSCallbackHandle ROSTopic::Subscribe(FunVrROSPublishMsg callback) 6 | { 7 | ++subscription_counter_; 8 | 9 | // Only send subscribe when this ROSTopic hasn't sent this command before 10 | if (subscribe_id_ == "") { 11 | subscribe_id_.append("subscribe:"); 12 | subscribe_id_.append(topic_name_); 13 | subscribe_id_.append(":"); 14 | subscribe_id_.append(std::to_string(++ros_.id_counter)); 15 | 16 | ROSBridgeSubscribeMsg cmd(true); 17 | cmd.id_ = subscribe_id_; 18 | cmd.topic_ = topic_name_; 19 | cmd.type_ = message_type_; 20 | cmd.compression_ = compression_; 21 | cmd.throttle_rate_ = throttle_rate_; 22 | cmd.queue_length_ = queue_size_; 23 | 24 | if (!ros_.SendMessage(cmd)) 25 | { 26 | subscribe_id_ = ""; 27 | } 28 | } 29 | 30 | if (subscribe_id_ != "") 31 | { 32 | // Register callback in ROSBridge 33 | ROSCallbackHandle handle(callback); 34 | ros_.RegisterTopicCallback(topic_name_, handle); // Register callback in ROSBridge 35 | return handle; 36 | } 37 | 38 | subscribe_id_ = ""; 39 | return ROSCallbackHandle(); 40 | } 41 | 42 | bool ROSTopic::Unsubscribe(const ROSCallbackHandle& callback_handle) 43 | { 44 | // We've no active subscription 45 | if (subscribe_id_ == "") 46 | return false; 47 | 48 | if (!ros_.UnregisterTopicCallback(topic_name_, callback_handle)) { // Unregister callback in ROSBridge 49 | // failed to unregister callback - maybe the method is different from already registered callbacks 50 | std::cerr << "[ROSTopic] Passed unknown callback to ROSTopic::unsubscribe. This callback is not registered in the ROSBridge instance. Aborting..." << std::endl; 51 | return false; 52 | } 53 | 54 | --subscription_counter_; 55 | 56 | if (subscription_counter_ > 0) 57 | return true; 58 | 59 | std::cout << "[ROSTopic] No callbacks registered anymore - unsubscribe from topic" << std::endl; 60 | // Handle unsubscription when no callback is registered anymore 61 | //rapidjson::Document cmd; 62 | //cmd.SetObject(); 63 | 64 | ROSBridgeUnsubscribeMsg cmd(true); 65 | cmd.id_ = subscribe_id_; 66 | cmd.topic_ = topic_name_; 67 | 68 | if (ros_.SendMessage(cmd)) { 69 | subscribe_id_ = ""; 70 | subscription_counter_ = 0; // shouldn't be necessary ... 71 | return true; 72 | } 73 | return false; 74 | } 75 | 76 | bool ROSTopic::Advertise() 77 | { 78 | if (is_advertised_) 79 | return true; 80 | 81 | advertise_id_ = ""; 82 | advertise_id_.append("advertise:"); 83 | advertise_id_.append(topic_name_); 84 | advertise_id_.append(":"); 85 | advertise_id_.append(std::to_string(++ros_.id_counter)); 86 | 87 | ROSBridgeAdvertiseMsg cmd(true); 88 | cmd.id_ = advertise_id_; 89 | cmd.topic_ = topic_name_; 90 | cmd.type_ = message_type_; 91 | cmd.latch_ = latch_; 92 | cmd.queue_size_ = queue_size_; 93 | 94 | if (ros_.SendMessage(cmd)) { 95 | is_advertised_ = true; 96 | } 97 | return is_advertised_; 98 | } 99 | 100 | bool ROSTopic::Unadvertise() 101 | { 102 | if (!is_advertised_) 103 | return true; 104 | 105 | ROSBridgeUnadvertiseMsg cmd(true); 106 | cmd.id_ = advertise_id_; 107 | cmd.topic_ = topic_name_; 108 | 109 | if (ros_.SendMessage(cmd)) { 110 | is_advertised_ = false; 111 | } 112 | return !is_advertised_; 113 | } 114 | 115 | // void ROSTopic::Publish(json &message){ 116 | // if(!is_advertised_) 117 | // Advertise(); 118 | 119 | // std::string publish_id; 120 | // publish_id.append("publish:"); 121 | // publish_id.append(topic_name_); 122 | // publish_id.append(":"); 123 | // publish_id.append(std::to_string(++ros_.id_counter)); 124 | 125 | // rapidjson::Document cmd; 126 | // cmd.SetObject(); 127 | // cmd.AddMember("op","publish", cmd.GetAllocator()); 128 | // cmd.AddMember("id", publish_id, cmd.GetAllocator()); 129 | // cmd.AddMember("topic", topic_name_, cmd.GetAllocator()); 130 | // cmd.AddMember("msg", message, cmd.GetAllocator()); 131 | // cmd.AddMember("latch", latch_, cmd.GetAllocator()); 132 | 133 | // std::cout << "[ROSTopic] Publishing data " << Helper::get_string_from_rapidjson(cmd); 134 | 135 | // ros_.SendMessage(cmd); 136 | // } 137 | 138 | bool ROSTopic::Publish(rapidjson::Value &message) 139 | { 140 | if (!is_advertised_) { 141 | if (!Advertise()) { 142 | return false; 143 | } 144 | } 145 | 146 | std::string publish_id = GeneratePublishID(); 147 | 148 | ROSBridgePublishMsg cmd(true); 149 | cmd.id_ = publish_id; 150 | cmd.topic_ = topic_name_; 151 | cmd.msg_json_ = message; 152 | cmd.latch_ = latch_; 153 | 154 | //Queue is not implemented for JSON 155 | return ros_.SendMessage(cmd); 156 | } 157 | 158 | bool ROSTopic::Publish(bson_t *message) 159 | { 160 | if (!is_advertised_) { 161 | if (!Advertise()) { 162 | return false; 163 | } 164 | } 165 | 166 | assert(message); 167 | 168 | std::string publish_id = GeneratePublishID(); 169 | 170 | ROSBridgePublishMsg cmd(true); 171 | cmd.id_ = publish_id; 172 | cmd.topic_ = topic_name_; 173 | cmd.msg_bson_ = message; 174 | cmd.latch_ = latch_; 175 | 176 | return ros_.QueueMessage(topic_name_, queue_size_, cmd); 177 | } 178 | 179 | std::string ROSTopic::GeneratePublishID() 180 | { 181 | std::string publish_id; 182 | publish_id.append("publish:"); 183 | publish_id.append(topic_name_); 184 | publish_id.append(":"); 185 | publish_id.append(std::to_string(++ros_.id_counter)); 186 | return publish_id; 187 | } 188 | } 189 | --------------------------------------------------------------------------------