diff --git a/README.md b/README.md index 50ea863..0bed3e5 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,16 @@ livox_ros_driver is a new ROS package, specially used to connect LiDAR products produced by Livox. The driver can be run under ubuntu 14.04/16.04/18.04 operating system with ROS environment (indigo, kinetic, melodic) installed. Tested hardware platforms that can run livox_ros_driver include: Intel x86 cpu platforms, and some ARM64 hardware platforms (such as nvida TX2 / Xavier, etc.). +## 0. Version and Release History + +### 0.1 Current Version + +[v2.6.0](https://github.com/Livox-SDK/livox_ros_driver/releases) + +### 0.2 Release History + +[Release History](https://github.com/Livox-SDK/livox_ros_driver/releases) + ## 1. Install dependencies Before running livox_ros_driver, ROS and Livox-SDK must be installed. @@ -171,14 +181,12 @@ In the "ws_livox/src/livox_ros_driver/launch" path, there are two json files, li     The parameter attributes in the above json file are described in the following table :
LiDAR configuration parameter
- | Parameter | Type | Description | Default | | :------------------------- | ------- | ------------------------------------------------------------ | --------------- | | broadcast_code | String | LiDAR broadcast code, 15 characters, consisting of a 14-character length serial number plus a character-length additional code | 0TFDG3B006H2Z11 | | enable_connect | Boolean | Whether to connect to this LiDAR
true -- Connect this LiDAR
false --Do not connect this LiDAR | false | -| enable_fan | Boolean | Whether to automatically control the fan of this LiDAR
true -- Automatically control the fan of this LiDAR
false -- Does not automatically control the fan of this LiDAR | true | | return_mode | Int | return mode
0 -- First single return mode
1 -- Strongest single return mode
2 -- Dual return mode | 0 | -| coordinate | Int | Coordinate
0 -- Cartesian
1 -- Spherical | 0 | +| coordinate | Int | Coordinate
0 -- Cartesian
1 -- Spherical | 0 | | imu_rate | Int | Push frequency of IMU sensor data
0 -- stop push
1 -- 200 Hz
Others -- undefined, it will cause unpredictable behavior
Currently only Horizon supports this, MID serials do not support it | 0 | | extrinsic_parameter_source | Int | Whether to enable extrinsic parameter automatic compensation
0 -- Disable automatic compensation of LiDAR external reference
1 -- Automatic compensation of LiDAR external reference | 0 | @@ -198,7 +206,6 @@ In the "ws_livox/src/livox_ros_driver/launch" path, there are two json files, li "lidar_config": [ { "broadcast_code": "0TFDG3B006H2Z11", - "enable_fan": true, "return_mode": 0, "imu_rate": 1 } @@ -209,7 +216,6 @@ In the "ws_livox/src/livox_ros_driver/launch" path, there are two json files, li     The main difference between the content of Hub json configuration file and the content of the LiDAR json configuration file is that the Hub configuration item "hub_config" is added, and the related configuration content of the Hub is shown in the following table :
HUB configuration parameter
- | Parameter | Type | Description | Default | | -------------- | ------- | ------------------------------------------------------------ | --------------- | | broadcast_code | String | HUB broadcast code, 15 characters, consisting of a 14-character length serial number plus a character-length additional code | 13UUG1R00400170 | @@ -251,7 +257,6 @@ $GPRMC,190430,A,4812.3038,S,07330.7690,W,3.7,3.8,090210,13.7,E,D*26 livox_ros_driver only supports the timestamp synchronization function when connected to LiDAR. The timestamp related configuration item timesync_config is in the livox_lidar_config.json file. The detailed configuration content is shown in the table below :
Timestamp synchronization function configuration instructions
- | Parameter | Type | Description | Default | | ---------------- | -------- | ------------------------------------------------------------ | -------------- | | enable_timesync | Boolean | Whether to enable the timestamp synchronization
true -- Enable timestamp synchronization
false -- Disable timestamp synchronization | false | diff --git a/README_CN.md b/README_CN.md index 9ece378..2099668 100644 --- a/README_CN.md +++ b/README_CN.md @@ -3,6 +3,16 @@ 览沃ROS驱动程序是一个全新的 ROS 包,专门用于连接览沃生产的 LiDAR 产品。该驱动程序可以在安装了 ROS 环境( indigo,kinetic,melodic )的 ubuntu14.04/16.04/18.04 操作系统下运行。经测试可以运行览沃 ROS 驱动程序的硬件平台包括:intel x86 主流 cpu 平台,部分 ARM64 硬件平台(如,nvida TX2/Xavier 等)。 +## 0. 版本和发布记录 + +### 0.1 当前版本 + +v2.6.0 + +### 0.2 发布记录 + +[发布记录](https://github.com/Livox-SDK/livox_ros_driver/releases) + ## 1. 安装依赖 运行览沃 ROS 驱动程序之前,必须安装 ROS 和 Livox-SDK。 @@ -165,7 +175,6 @@ uint8 line # laser number in lidar { "broadcast_code": "0TFDG3B006H2Z11", "enable_connect": true, - "enable_fan": true, "return_mode": 0, "coordinate": 0, "imu_rate": 1, @@ -178,12 +187,10 @@ uint8 line # laser number in lidar     上面 json 文件中各参数属性说明如下表:
LiDAR 配置参数说明
- | 属性 | 类型 | 描述 | 默认值 | | :------------------------- | ------ | ------------------------------------------------------------ | --------------- | | broadcast_code | 字符串 | LiDAR 广播码,15位字符,由14位字符长度序列号加一个字符长度附加码组成 | 0TFDG3B006H2Z11 | | enable_connect | 布尔值 | 是否连接此 LiDAR
true -- 连接此 LiDAR
false -- 禁止连接此 LiDAR | false | -| enable_fan | 布尔值 | 是否自动控制此 LiDAR 风扇
true -- 自动控制 LiDAR 风扇
false -- 禁止自动控制此 LiDAR 风扇 | true | | return_mode | 整型 | 回波模式
0 -- 第一个回波模式
1 -- 最强回波模式
2 -- 双回波模式 | 0 | | coordinate | 整型 | 原始点云数据的坐标轴类型
0 -- 直角坐标系
1 -- 球坐标系 | 0 | | imu_rate | 整型 | IMU 传感器数据的推送频率
0 -- 关闭 IMU 传感器数据推送
1 -- 以 200Hz 频率推送 IMU 传感器数据
其他值 -- 未定义,会导致不可预测的行为发生
目前只有 Horizon/Tele 支持此选项,MID 序列不支持 | 0 | @@ -206,7 +213,6 @@ uint8 line # laser number in lidar "lidar_config": [ { "broadcast_code": "0TFDG3B006H2Z11", - "enable_fan": true, "return_mode": 0, "imu_rate": 1 } @@ -217,7 +223,6 @@ uint8 line # laser number in lidar     中心板 json 配置文件内容与 LiDAR 配置文件的主要区别在于,增加了中心板配置项 hub_config ,中心板相关的具体配置内容见下表:
HUB 配置参数说明
- | 属性 | 类型 | 描述 | 默认值 | | -------------- | ------ | ------------------------------------------------------------ | --------------- | | broadcast_code | 字符串 | HUB 广播码,15位字符,由14位字符长度的序列号加一个字符长度的附加码组成 | 13UUG1R00400170 | @@ -261,7 +266,6 @@ uint8 line # laser number in lidar 览沃 ROS 驱动程序只有在与 LiDAR 连接的时候才支持时间戳同步功能,时间戳相关的配置项 timesync_config 位于 livox_lidar_config.json 文件中,详细的配置内容见下表:
时间戳同步功能配置说明
- | 属性 | 类型 | 描述 | 默认值 | | ---------------- | ------ | ------------------------------------------------------------ | -------------- | | enable_timesync | 布尔值 | 是否使能时间戳同步功能
true -- 使能时间戳同步功能
false -- 禁止时间戳同步功能 | false | diff --git a/livox_ros_driver/common/FastCRC/FastCRC.h b/livox_ros_driver/common/FastCRC/FastCRC.h index 8b6b3d5..43486fa 100644 --- a/livox_ros_driver/common/FastCRC/FastCRC.h +++ b/livox_ros_driver/common/FastCRC/FastCRC.h @@ -49,32 +49,32 @@ // ================= 16-BIT CRC =================== class FastCRC16 { -public: + public: FastCRC16(uint16_t seed); // change function name from mcrf4xx_upd to mcrf4xx - uint16_t - mcrf4xx_calc(const uint8_t *data, - const uint16_t datalen); // Equivalent to _crc_ccitt_update() in - // crc16.h from avr_libc + uint16_t mcrf4xx_calc( + const uint8_t *data, + const uint16_t datalen); // Equivalent to _crc_ccitt_update() in + // crc16.h from avr_libc -private: + private: uint16_t seed_; }; // ================= 32-BIT CRC =================== class FastCRC32 { -public: + public: FastCRC32(uint32_t seed); // change function name from crc32_upd to crc32 uint32_t crc32_calc( const uint8_t *data, - uint16_t len); // Call for subsequent calculations with previous seed + uint16_t len); // Call for subsequent calculations with previous seed -private: + private: uint32_t seed_; }; -#endif // FASTCRC_FASTCRC_H_ +#endif // FASTCRC_FASTCRC_H_ diff --git a/livox_ros_driver/common/FastCRC/FastCRCsw.cpp b/livox_ros_driver/common/FastCRC/FastCRCsw.cpp index 1ba1e7a..a4baa21 100644 --- a/livox_ros_driver/common/FastCRC/FastCRCsw.cpp +++ b/livox_ros_driver/common/FastCRC/FastCRCsw.cpp @@ -55,7 +55,6 @@ FastCRC16::FastCRC16(uint16_t seed) { seed_ = seed; } */ uint16_t FastCRC16::mcrf4xx_calc(const uint8_t *data, uint16_t len) { - uint16_t crc = seed_; while (((uintptr_t)data & 3) && len) { @@ -90,11 +89,11 @@ FastCRC32::FastCRC32(uint32_t seed) { seed_ = seed; } crc = (table[(crc & 0xff) + 0x300]) ^ (table[((crc >> 8) & 0xff) + 0x200]) ^ \ (table[((crc >> 16) & 0xff) + 0x100]) ^ (table[(crc >> 24) & 0xff]); -#define crcsm_n4d(crc, data, table) \ - crc ^= data; \ - crc = (crc >> 8) ^ (table[crc & 0xff]); \ - crc = (crc >> 8) ^ (table[crc & 0xff]); \ - crc = (crc >> 8) ^ (table[crc & 0xff]); \ +#define crcsm_n4d(crc, data, table) \ + crc ^= data; \ + crc = (crc >> 8) ^ (table[crc & 0xff]); \ + crc = (crc >> 8) ^ (table[crc & 0xff]); \ + crc = (crc >> 8) ^ (table[crc & 0xff]); \ crc = (crc >> 8) ^ (table[crc & 0xff]); /** CRC32 @@ -110,7 +109,6 @@ FastCRC32::FastCRC32(uint32_t seed) { seed_ = seed; } #endif uint32_t FastCRC32::crc32_calc(const uint8_t *data, uint16_t len) { - uint32_t crc = seed_ ^ 0xffffffff; while (((uintptr_t)data & 3) && len) { diff --git a/livox_ros_driver/common/comm/comm_device.h b/livox_ros_driver/common/comm/comm_device.h index 35e5386..3d614c1 100644 --- a/livox_ros_driver/common/comm/comm_device.h +++ b/livox_ros_driver/common/comm/comm_device.h @@ -67,5 +67,5 @@ typedef struct { } config; } CommDevConfig; -} // namespace livox_ros -#endif // COMM_COMM_DEVICE_H_ +} // namespace livox_ros +#endif // COMM_COMM_DEVICE_H_ diff --git a/livox_ros_driver/common/comm/comm_protocol.cpp b/livox_ros_driver/common/comm/comm_protocol.cpp index e2534fe..c63fc80 100644 --- a/livox_ros_driver/common/comm/comm_protocol.cpp +++ b/livox_ros_driver/common/comm/comm_protocol.cpp @@ -23,9 +23,9 @@ // #include "comm_protocol.h" -#include #include #include +#include namespace livox_ros { @@ -116,23 +116,23 @@ int32_t CommProtocol::ParseCommStream(CommPacket *o_pack) { while ((GetValidDataSize() > protocol_->GetPreambleLen()) && (GetValidDataSize() > offset_to_read_index_)) { switch (fsm_parse_step_) { - case kSearchPacketPreamble: { - FsmSearchPacketPreamble(); - break; - } - case kFindPacketLength: { - FsmFindPacketLength(); - break; - } - case kGetPacketData: { - ret = FsmGetPacketData(o_pack); - break; - } - default: { FsmParserStateTransfer(kSearchPacketPreamble); } + case kSearchPacketPreamble: { + FsmSearchPacketPreamble(); + break; + } + case kFindPacketLength: { + FsmFindPacketLength(); + break; + } + case kGetPacketData: { + ret = FsmGetPacketData(o_pack); + break; + } + default: { FsmParserStateTransfer(kSearchPacketPreamble); } } /* Must exit when in the below case */ - if ((ret == kParseSuccess) || (ret == kParseNeedMoreData)) break; + if ((ret == kParseSuccess) || (ret == kParseNeedMoreData)) break; } return ret; @@ -221,4 +221,4 @@ int32_t CommProtocol::FsmGetPacketData(CommPacket *o_pack) { return ret; } -} // namespace livox_ros +} // namespace livox_ros diff --git a/livox_ros_driver/common/comm/comm_protocol.h b/livox_ros_driver/common/comm/comm_protocol.h index c31bf10..bc77cb4 100644 --- a/livox_ros_driver/common/comm/comm_protocol.h +++ b/livox_ros_driver/common/comm/comm_protocol.h @@ -25,10 +25,10 @@ #ifndef COMM_COMM_PROTOCOL_H_ #define COMM_COMM_PROTOCOL_H_ +#include #include "gps_protocol.h" #include "protocol.h" #include "sdk_protocol.h" -#include namespace livox_ros { const uint32_t kCacheSize = 8192; @@ -50,7 +50,7 @@ typedef struct { } CommCache; class CommProtocol { -public: + public: CommProtocol(ProtocolConfig &config); ~CommProtocol(); @@ -67,7 +67,7 @@ class CommProtocol { void ResetParser(); -private: + private: uint32_t GetCacheTailSize(); uint32_t GetValidDataSize(); void UpdateCache(void); @@ -101,5 +101,5 @@ class CommProtocol { } }; -} // namespace livox_ros -#endif // COMM_COMM_PROTOCOL_H_ +} // namespace livox_ros +#endif // COMM_COMM_PROTOCOL_H_ diff --git a/livox_ros_driver/common/comm/gps_protocol.cpp b/livox_ros_driver/common/comm/gps_protocol.cpp index 301f01f..a60da6e 100644 --- a/livox_ros_driver/common/comm/gps_protocol.cpp +++ b/livox_ros_driver/common/comm/gps_protocol.cpp @@ -49,7 +49,7 @@ int32_t GpsProtocol::ParsePacket(const uint8_t *i_buf, uint32_t i_len, // GpsPacket *gps_packet = (GpsPacket *)i_buf; if (i_len < GetPacketWrapperLen()) { - return -1; // packet length error + return -1; // packet length error } memset((void *)o_packet, 0, sizeof(CommPacket)); o_packet->protocol = kGps; @@ -114,14 +114,12 @@ uint8_t GpsProtocol::CalcGpsPacketChecksum(const uint8_t *buf, uint8_t AscciiToHex(const uint8_t *TwoChar) { uint8_t h = toupper(TwoChar[0]) - 0x30; - if (h > 9) - h -= 7; + if (h > 9) h -= 7; uint8_t l = toupper(TwoChar[1]) - 0x30; - if (l > 9) - l -= 7; + if (l > 9) l -= 7; return h * 16 + l; } -} // namespace livox_ros +} // namespace livox_ros diff --git a/livox_ros_driver/common/comm/gps_protocol.h b/livox_ros_driver/common/comm/gps_protocol.h index e4ecdf2..804ac7f 100644 --- a/livox_ros_driver/common/comm/gps_protocol.h +++ b/livox_ros_driver/common/comm/gps_protocol.h @@ -25,8 +25,8 @@ #ifndef LIVOX_GPS_PROTOCOL_H_ #define LIVOX_GPS_PROTOCOL_H_ -#include "protocol.h" #include +#include "protocol.h" namespace livox_ros { @@ -47,7 +47,7 @@ typedef struct { uint8_t AscciiToHex(const uint8_t *TwoChar); class GpsProtocol : public Protocol { -public: + public: GpsProtocol(); ~GpsProtocol() = default; @@ -69,11 +69,11 @@ class GpsProtocol : public Protocol { int32_t CheckPacket(const uint8_t *buf) override; -private: + private: uint32_t found_length_; uint8_t CalcGpsPacketChecksum(const uint8_t *buf, uint32_t length); }; -} // namespace livox_ros -#endif // LIVOX_GPS_PROTOCOL_H_ +} // namespace livox_ros +#endif // LIVOX_GPS_PROTOCOL_H_ diff --git a/livox_ros_driver/common/comm/protocol.h b/livox_ros_driver/common/comm/protocol.h index a86df81..5d50281 100644 --- a/livox_ros_driver/common/comm/protocol.h +++ b/livox_ros_driver/common/comm/protocol.h @@ -60,9 +60,6 @@ typedef struct CommPacket { uint8_t *data; uint16_t data_len; uint32_t padding; - // RequestPackCb *ack_request_cb; - // uint32_t retry_times; - // uint32_t timeout; } CommPacket; /** SDK Protocol info config */ @@ -72,9 +69,7 @@ typedef struct { } SdkProtocolConfig; /** NAME-0183 Protocol info config for gps */ -typedef struct { - void *data; -} GpsProtocolConfig; +typedef struct { void *data; } GpsProtocolConfig; typedef struct { uint8_t type; @@ -85,7 +80,7 @@ typedef struct { } ProtocolConfig; class Protocol { -public: + public: virtual ~Protocol() = default; virtual int32_t ParsePacket(const uint8_t *i_buf, uint32_t i_len, @@ -107,5 +102,5 @@ class Protocol { virtual int32_t CheckPacket(const uint8_t *buf) = 0; }; -} // namespace livox_ros -#endif // COMM_PROTOCOL_H_ +} // namespace livox_ros +#endif // COMM_PROTOCOL_H_ diff --git a/livox_ros_driver/common/comm/sdk_protocol.cpp b/livox_ros_driver/common/comm/sdk_protocol.cpp index c507142..4356326 100644 --- a/livox_ros_driver/common/comm/sdk_protocol.cpp +++ b/livox_ros_driver/common/comm/sdk_protocol.cpp @@ -29,8 +29,8 @@ namespace livox_ros { const uint8_t kSdkProtocolSof = 0xAA; -const uint32_t kSdkPacketCrcSize = 4; // crc32 -const uint32_t kSdkPacketPreambleCrcSize = 2; // crc16 +const uint32_t kSdkPacketCrcSize = 4; // crc32 +const uint32_t kSdkPacketPreambleCrcSize = 2; // crc16 SdkProtocol::SdkProtocol(uint16_t seed16, uint32_t seed32) : crc16_(seed16), crc32_(seed32) {} @@ -77,7 +77,7 @@ int32_t SdkProtocol::ParsePacket(const uint8_t *i_buf, uint32_t i_len, SdkPacket *sdk_packet = (SdkPacket *)i_buf; if (i_len < GetPacketWrapperLen()) { - return -1; // packet lenth error + return -1; // packet lenth error } memset((void *)o_packet, 0, sizeof(CommPacket)); @@ -131,4 +131,4 @@ int32_t SdkProtocol::CheckPacket(const uint8_t *buf) { return -1; } } -} // namespace livox_ros +} // namespace livox_ros diff --git a/livox_ros_driver/common/comm/sdk_protocol.h b/livox_ros_driver/common/comm/sdk_protocol.h index e587b89..5808e07 100644 --- a/livox_ros_driver/common/comm/sdk_protocol.h +++ b/livox_ros_driver/common/comm/sdk_protocol.h @@ -25,9 +25,9 @@ #ifndef LIVOX_SDK_PROTOCOL_H_ #define LIVOX_SDK_PROTOCOL_H_ +#include #include "FastCRC/FastCRC.h" #include "protocol.h" -#include namespace livox_ros { typedef enum { kSdkVerNone, kSdkVer0, kSdkVer1 } SdkVersion; @@ -58,7 +58,7 @@ typedef struct { #pragma pack() class SdkProtocol : public Protocol { -public: + public: SdkProtocol(uint16_t seed16, uint32_t seed32); ~SdkProtocol() = default; @@ -78,9 +78,9 @@ class SdkProtocol : public Protocol { int32_t CheckPacket(const uint8_t *buf) override; -private: + private: FastCRC16 crc16_; FastCRC32 crc32_; }; -} // namespace livox_ros -#endif // LIVOX_SDK_PROTOCOL_H_ +} // namespace livox_ros +#endif // LIVOX_SDK_PROTOCOL_H_ diff --git a/livox_ros_driver/common/rapidjson/allocators.h b/livox_ros_driver/common/rapidjson/allocators.h index 53f7018..03010d5 100644 --- a/livox_ros_driver/common/rapidjson/allocators.h +++ b/livox_ros_driver/common/rapidjson/allocators.h @@ -78,13 +78,13 @@ allocator may not book-keep this, explicitly pass to it can save memory.) \note implements Allocator concept */ class CrtAllocator { -public: + public: static const bool kNeedFree = true; void *Malloc(size_t size) { - if (size) // behavior of malloc(0) is implementation defined. + if (size) // behavior of malloc(0) is implementation defined. return std::malloc(size); else - return NULL; // standardize to returning NULL. + return NULL; // standardize to returning NULL. } void *Realloc(void *originalPtr, size_t originalSize, size_t newSize) { (void)originalSize; @@ -118,11 +118,12 @@ class CrtAllocator { \tparam BaseAllocator the allocator type for allocating memory chunks. Default is CrtAllocator. \note implements Allocator concept */ -template class MemoryPoolAllocator { -public: +template +class MemoryPoolAllocator { + public: static const bool kNeedFree = - false; //!< Tell users that no need to call Free() with this allocator. - //!< (concept Allocator) + false; //!< Tell users that no need to call Free() with this allocator. + //!< (concept Allocator) //! Constructor with chunkSize. /*! \param chunkSize The size of memory chunk. The default is @@ -131,8 +132,11 @@ template class MemoryPoolAllocator { */ MemoryPoolAllocator(size_t chunkSize = kDefaultChunkCapacity, BaseAllocator *baseAllocator = 0) - : chunkHead_(0), chunk_capacity_(chunkSize), userBuffer_(0), - baseAllocator_(baseAllocator), ownBaseAllocator_(0) {} + : chunkHead_(0), + chunk_capacity_(chunkSize), + userBuffer_(0), + baseAllocator_(baseAllocator), + ownBaseAllocator_(0) {} //! Constructor with user-supplied buffer. /*! The user buffer will be used firstly. When it is full, memory pool @@ -149,8 +153,11 @@ template class MemoryPoolAllocator { MemoryPoolAllocator(void *buffer, size_t size, size_t chunkSize = kDefaultChunkCapacity, BaseAllocator *baseAllocator = 0) - : chunkHead_(0), chunk_capacity_(chunkSize), userBuffer_(buffer), - baseAllocator_(baseAllocator), ownBaseAllocator_(0) { + : chunkHead_(0), + chunk_capacity_(chunkSize), + userBuffer_(buffer), + baseAllocator_(baseAllocator), + ownBaseAllocator_(0) { RAPIDJSON_ASSERT(buffer != 0); RAPIDJSON_ASSERT(size > sizeof(ChunkHeader)); chunkHead_ = reinterpret_cast(buffer); @@ -175,7 +182,7 @@ template class MemoryPoolAllocator { chunkHead_ = next; } if (chunkHead_ && chunkHead_ == userBuffer_) - chunkHead_->size = 0; // Clear user buffer + chunkHead_->size = 0; // Clear user buffer } //! Computes the total capacity of allocated memory chunks. @@ -193,15 +200,13 @@ template class MemoryPoolAllocator { */ size_t Size() const { size_t size = 0; - for (ChunkHeader *c = chunkHead_; c != 0; c = c->next) - size += c->size; + for (ChunkHeader *c = chunkHead_; c != 0; c = c->next) size += c->size; return size; } //! Allocates a memory block. (concept Allocator) void *Malloc(size_t size) { - if (!size) - return NULL; + if (!size) return NULL; size = RAPIDJSON_ALIGN(size); if (chunkHead_ == 0 || chunkHead_->size + size > chunkHead_->capacity) @@ -216,24 +221,22 @@ template class MemoryPoolAllocator { //! Resizes a memory block (concept Allocator) void *Realloc(void *originalPtr, size_t originalSize, size_t newSize) { - if (originalPtr == 0) - return Malloc(newSize); + if (originalPtr == 0) return Malloc(newSize); - if (newSize == 0) - return NULL; + if (newSize == 0) return NULL; originalSize = RAPIDJSON_ALIGN(originalSize); newSize = RAPIDJSON_ALIGN(newSize); // Do not shrink if new size is smaller than original - if (originalSize >= newSize) - return originalPtr; + if (originalSize >= newSize) return originalPtr; // Simply expand it if it is the last allocation and there is sufficient // space - if (originalPtr == reinterpret_cast(chunkHead_) + - RAPIDJSON_ALIGN(sizeof(ChunkHeader)) + - chunkHead_->size - originalSize) { + if (originalPtr == + reinterpret_cast(chunkHead_) + + RAPIDJSON_ALIGN(sizeof(ChunkHeader)) + chunkHead_->size - + originalSize) { size_t increment = static_cast(newSize - originalSize); if (chunkHead_->size + increment <= chunkHead_->capacity) { chunkHead_->size += increment; @@ -243,17 +246,16 @@ template class MemoryPoolAllocator { // Realloc process: allocate and copy memory, do not free original buffer. if (void *newBuffer = Malloc(newSize)) { - if (originalSize) - std::memcpy(newBuffer, originalPtr, originalSize); + if (originalSize) std::memcpy(newBuffer, originalPtr, originalSize); return newBuffer; } else return NULL; } //! Frees a memory block (concept Allocator) - static void Free(void *ptr) { (void)ptr; } // Do nothing + static void Free(void *ptr) { (void)ptr; } // Do nothing -private: + private: //! Copy constructor is not permitted. MemoryPoolAllocator(const MemoryPoolAllocator &rhs) /* = delete */; //! Copy assignment operator is not permitted. @@ -279,28 +281,28 @@ template class MemoryPoolAllocator { } static const int kDefaultChunkCapacity = - RAPIDJSON_ALLOCATOR_DEFAULT_CHUNK_CAPACITY; //!< Default chunk capacity. + RAPIDJSON_ALLOCATOR_DEFAULT_CHUNK_CAPACITY; //!< Default chunk capacity. //! Chunk header for perpending to each chunk. /*! Chunks are stored as a singly linked list. */ struct ChunkHeader { - size_t capacity; //!< Capacity of the chunk in bytes (excluding the header - //!< itself). - size_t size; //!< Current size of allocated memory in bytes. - ChunkHeader *next; //!< Next chunk in the linked list. + size_t capacity; //!< Capacity of the chunk in bytes (excluding the header + //!< itself). + size_t size; //!< Current size of allocated memory in bytes. + ChunkHeader *next; //!< Next chunk in the linked list. }; - ChunkHeader *chunkHead_; //!< Head of the chunk linked-list. Only the head - //!< chunk serves allocation. - size_t chunk_capacity_; //!< The minimum capacity of chunk when they are - //!< allocated. - void *userBuffer_; //!< User supplied buffer. + ChunkHeader *chunkHead_; //!< Head of the chunk linked-list. Only the head + //!< chunk serves allocation. + size_t chunk_capacity_; //!< The minimum capacity of chunk when they are + //!< allocated. + void *userBuffer_; //!< User supplied buffer. BaseAllocator - *baseAllocator_; //!< base allocator for allocating memory chunks. - BaseAllocator *ownBaseAllocator_; //!< base allocator created by this object. + *baseAllocator_; //!< base allocator for allocating memory chunks. + BaseAllocator *ownBaseAllocator_; //!< base allocator created by this object. }; RAPIDJSON_NAMESPACE_END -#endif // RAPIDJSON_ENCODINGS_H_ +#endif // RAPIDJSON_ENCODINGS_H_ diff --git a/livox_ros_driver/common/rapidjson/cursorstreamwrapper.h b/livox_ros_driver/common/rapidjson/cursorstreamwrapper.h index cb8ea9c..045ddb8 100644 --- a/livox_ros_driver/common/rapidjson/cursorstreamwrapper.h +++ b/livox_ros_driver/common/rapidjson/cursorstreamwrapper.h @@ -28,8 +28,8 @@ RAPIDJSON_DIAG_OFF(effc++) #if defined(_MSC_VER) && _MSC_VER <= 1800 RAPIDJSON_DIAG_PUSH -RAPIDJSON_DIAG_OFF(4702) // unreachable code -RAPIDJSON_DIAG_OFF(4512) // assignment operator could not be generated +RAPIDJSON_DIAG_OFF(4702) // unreachable code +RAPIDJSON_DIAG_OFF(4512) // assignment operator could not be generated #endif RAPIDJSON_NAMESPACE_BEGIN @@ -40,7 +40,7 @@ RAPIDJSON_NAMESPACE_BEGIN */ template > class CursorStreamWrapper : public GenericStreamWrapper { -public: + public: typedef typename Encoding::Ch Ch; CursorStreamWrapper(InputStream &is) @@ -63,9 +63,9 @@ class CursorStreamWrapper : public GenericStreamWrapper { //! Get the error column number, if error exists. size_t GetColumn() const { return col_; } -private: - size_t line_; //!< Current Line - size_t col_; //!< Current Column + private: + size_t line_; //!< Current Line + size_t col_; //!< Current Column }; #if defined(_MSC_VER) && _MSC_VER <= 1800 @@ -78,4 +78,4 @@ RAPIDJSON_DIAG_POP RAPIDJSON_NAMESPACE_END -#endif // RAPIDJSON_CURSORSTREAMWRAPPER_H_ +#endif // RAPIDJSON_CURSORSTREAMWRAPPER_H_ diff --git a/livox_ros_driver/common/rapidjson/document.h b/livox_ros_driver/common/rapidjson/document.h index d7c3840..27addb7 100644 --- a/livox_ros_driver/common/rapidjson/document.h +++ b/livox_ros_driver/common/rapidjson/document.h @@ -21,13 +21,13 @@ /*! \file document.h */ +#include +#include // placement new #include "encodedstream.h" #include "internal/meta.h" #include "internal/strfunc.h" #include "memorystream.h" #include "reader.h" -#include -#include // placement new RAPIDJSON_DIAG_PUSH #ifdef __clang__ @@ -35,27 +35,28 @@ RAPIDJSON_DIAG_OFF(padded) RAPIDJSON_DIAG_OFF(switch - enum) RAPIDJSON_DIAG_OFF(c++ 98 - compat) #elif defined(_MSC_VER) -RAPIDJSON_DIAG_OFF(4127) // conditional expression is constant +RAPIDJSON_DIAG_OFF(4127) // conditional expression is constant RAPIDJSON_DIAG_OFF( - 4244) // conversion from kXxxFlags to 'uint16_t', possible loss of data + 4244) // conversion from kXxxFlags to 'uint16_t', possible loss of data #endif #ifdef __GNUC__ RAPIDJSON_DIAG_OFF(effc++) -#endif // __GNUC__ +#endif // __GNUC__ #ifndef RAPIDJSON_NOMEMBERITERATORCLASS -#include // std::random_access_iterator_tag +#include // std::random_access_iterator_tag #endif #if RAPIDJSON_HAS_CXX11_RVALUE_REFS -#include // std::move +#include // std::move #endif RAPIDJSON_NAMESPACE_BEGIN // Forward declaration. -template class GenericValue; +template +class GenericValue; template class GenericDocument; @@ -67,10 +68,12 @@ class GenericDocument; that so it moved as a namespace scope struct. https://code.google.com/p/rapidjson/issues/detail?id=64 */ -template class GenericMember { -public: - GenericValue name; //!< name of member (must be a string) - GenericValue value; //!< value of member. +template +class GenericMember { + public: + GenericValue + name; //!< name of member (must be a string) + GenericValue value; //!< value of member. #if RAPIDJSON_HAS_CXX11_RVALUE_REFS //! Move constructor in C++11 @@ -103,7 +106,7 @@ template class GenericMember { a.value.Swap(b.value); } -private: + private: //! Copy constructor is not permitted. GenericMember(const GenericMember &rhs); }; @@ -137,14 +140,14 @@ template class GenericMember { */ template class GenericMemberIterator { - friend class GenericValue; - template friend class GenericMemberIterator; + template + friend class GenericMemberIterator; typedef GenericMember PlainType; typedef typename internal::MaybeAddConst::Type ValueType; -public: + public: //! Iterator type itself typedef GenericMemberIterator Iterator; //! Constant iterator type @@ -256,14 +259,14 @@ class GenericMemberIterator { return ptr_ - that.ptr_; } -private: + private: //! Internal constructor from plain pointer explicit GenericMemberIterator(Pointer p) : ptr_(p) {} - Pointer ptr_; //!< raw pointer + Pointer ptr_; //!< raw pointer }; -#else // RAPIDJSON_NOMEMBERITERATORCLASS +#else // RAPIDJSON_NOMEMBERITERATORCLASS // class-based member iterator implementation disabled, use plain pointers @@ -283,7 +286,7 @@ class GenericMemberIterator { typedef const GenericMember *Iterator; }; -#endif // RAPIDJSON_NOMEMBERITERATORCLASS +#endif // RAPIDJSON_NOMEMBERITERATORCLASS /////////////////////////////////////////////////////////////////////////////// // GenericStringRef @@ -315,72 +318,73 @@ class GenericMemberIterator { \see StringRef, GenericValue::SetString */ -template struct GenericStringRef { - typedef CharType Ch; //!< character type of the string - - //! Create string reference from \c const character array -#ifndef __clang__ // -Wdocumentation - /*! - This constructor implicitly creates a constant string reference from - a \c const character array. It has better performance than - \ref StringRef(const CharType*) by inferring the string \ref length - from the array length, and also supports strings containing null - characters. - - \tparam N length of the string, automatically inferred - - \param str Constant character array, lifetime assumed to be longer - than the use of the string in e.g. a GenericValue - - \post \ref s == str - - \note Constant complexity. - \note There is a hidden, private overload to disallow references to - non-const character arrays to be created via this constructor. - By this, e.g. function-scope arrays used to be filled via - \c snprintf are excluded from consideration. - In such cases, the referenced string should be \b copied to the - GenericValue instead. - */ +template +struct GenericStringRef { + typedef CharType Ch; //!< character type of the string + +//! Create string reference from \c const character array +#ifndef __clang__ // -Wdocumentation + /*! + This constructor implicitly creates a constant string reference from + a \c const character array. It has better performance than + \ref StringRef(const CharType*) by inferring the string \ref length + from the array length, and also supports strings containing null + characters. + + \tparam N length of the string, automatically inferred + + \param str Constant character array, lifetime assumed to be longer + than the use of the string in e.g. a GenericValue + + \post \ref s == str + + \note Constant complexity. + \note There is a hidden, private overload to disallow references to + non-const character arrays to be created via this constructor. + By this, e.g. function-scope arrays used to be filled via + \c snprintf are excluded from consideration. + In such cases, the referenced string should be \b copied to the + GenericValue instead. + */ #endif template GenericStringRef(const CharType (&str)[N]) RAPIDJSON_NOEXCEPT : s(str), length(N - 1) {} - //! Explicitly create string reference from \c const character pointer -#ifndef __clang__ // -Wdocumentation - /*! - This constructor can be used to \b explicitly create a reference to - a constant string pointer. - - \see StringRef(const CharType*) - - \param str Constant character pointer, lifetime assumed to be longer - than the use of the string in e.g. a GenericValue - - \post \ref s == str - - \note There is a hidden, private overload to disallow references to - non-const character arrays to be created via this constructor. - By this, e.g. function-scope arrays used to be filled via - \c snprintf are excluded from consideration. - In such cases, the referenced string should be \b copied to the - GenericValue instead. - */ +//! Explicitly create string reference from \c const character pointer +#ifndef __clang__ // -Wdocumentation + /*! + This constructor can be used to \b explicitly create a reference to + a constant string pointer. + + \see StringRef(const CharType*) + + \param str Constant character pointer, lifetime assumed to be longer + than the use of the string in e.g. a GenericValue + + \post \ref s == str + + \note There is a hidden, private overload to disallow references to + non-const character arrays to be created via this constructor. + By this, e.g. function-scope arrays used to be filled via + \c snprintf are excluded from consideration. + In such cases, the referenced string should be \b copied to the + GenericValue instead. + */ #endif explicit GenericStringRef(const CharType *str) : s(str), length(NotNullStrLen(str)) {} - //! Create constant string reference from pointer and length -#ifndef __clang__ // -Wdocumentation - /*! \param str constant string, lifetime assumed to be longer than the use of - the string in e.g. a GenericValue \param len length of the string, - excluding the trailing NULL terminator +//! Create constant string reference from pointer and length +#ifndef __clang__ // -Wdocumentation +/*! \param str constant string, lifetime assumed to be longer than the use of + the string in e.g. a GenericValue \param len length of the string, + excluding the trailing NULL terminator - \post \ref s == str && \ref length == len - \note Constant complexity. - */ + \post \ref s == str && \ref length == len + \note Constant complexity. + */ #endif GenericStringRef(const CharType *str, SizeType len) : s(RAPIDJSON_LIKELY(str) ? str : emptyString), length(len) { @@ -393,11 +397,11 @@ template struct GenericStringRef { //! implicit conversion to plain CharType pointer operator const Ch *() const { return s; } - const Ch *const s; //!< plain CharType pointer - const SizeType - length; //!< length of the string (excluding the trailing NULL terminator) + const Ch *const s; //!< plain CharType pointer + const SizeType length; //!< length of the string (excluding the trailing NULL + //!terminator) -private: + private: SizeType NotNullStrLen(const CharType *str) { RAPIDJSON_ASSERT(str != 0); return internal::StrLen(str); @@ -407,7 +411,8 @@ template struct GenericStringRef { static const Ch emptyString[]; //! Disallow construction from non-const array - template GenericStringRef(CharType (&str)[N]) /* = delete */; + template + GenericStringRef(CharType (&str)[N]) /* = delete */; //! Copy assignment operator not permitted - immutable type GenericStringRef &operator=(const GenericStringRef &rhs) /* = delete */; }; @@ -470,8 +475,8 @@ inline GenericStringRef StringRef(const CharType *str, preprocessor symbol \ref RAPIDJSON_HAS_STDSTRING. */ template -inline GenericStringRef -StringRef(const std::basic_string &str) { +inline GenericStringRef StringRef( + const std::basic_string &str) { return GenericStringRef(str.data(), SizeType(str.size())); } #endif @@ -493,18 +498,21 @@ struct IsGenericValueImpl::Type, // helper to match arbitrary GenericValue instantiations, including derived // classes -template struct IsGenericValue : IsGenericValueImpl::Type {}; +template +struct IsGenericValue : IsGenericValueImpl::Type {}; -} // namespace internal +} // namespace internal /////////////////////////////////////////////////////////////////////////////// // TypeHelper namespace internal { -template struct TypeHelper {}; +template +struct TypeHelper {}; -template struct TypeHelper { +template +struct TypeHelper { static bool Is(const ValueType &v) { return v.IsBool(); } static bool Get(const ValueType &v) { return v.GetBool(); } static ValueType &Set(ValueType &v, bool data) { return v.SetBool(data); } @@ -514,7 +522,8 @@ template struct TypeHelper { } }; -template struct TypeHelper { +template +struct TypeHelper { static bool Is(const ValueType &v) { return v.IsInt(); } static int Get(const ValueType &v) { return v.GetInt(); } static ValueType &Set(ValueType &v, int data) { return v.SetInt(data); } @@ -524,7 +533,8 @@ template struct TypeHelper { } }; -template struct TypeHelper { +template +struct TypeHelper { static bool Is(const ValueType &v) { return v.IsUint(); } static unsigned Get(const ValueType &v) { return v.GetUint(); } static ValueType &Set(ValueType &v, unsigned data) { return v.SetUint(data); } @@ -536,7 +546,8 @@ template struct TypeHelper { #ifdef _MSC_VER RAPIDJSON_STATIC_ASSERT(sizeof(long) == sizeof(int)); -template struct TypeHelper { +template +struct TypeHelper { static bool Is(const ValueType &v) { return v.IsInt(); } static long Get(const ValueType &v) { return v.GetInt(); } static ValueType &Set(ValueType &v, long data) { return v.SetInt(data); } @@ -547,7 +558,8 @@ template struct TypeHelper { }; RAPIDJSON_STATIC_ASSERT(sizeof(unsigned long) == sizeof(unsigned)); -template struct TypeHelper { +template +struct TypeHelper { static bool Is(const ValueType &v) { return v.IsUint(); } static unsigned long Get(const ValueType &v) { return v.GetUint(); } static ValueType &Set(ValueType &v, unsigned long data) { @@ -560,7 +572,8 @@ template struct TypeHelper { }; #endif -template struct TypeHelper { +template +struct TypeHelper { static bool Is(const ValueType &v) { return v.IsInt64(); } static int64_t Get(const ValueType &v) { return v.GetInt64(); } static ValueType &Set(ValueType &v, int64_t data) { return v.SetInt64(data); } @@ -570,7 +583,8 @@ template struct TypeHelper { } }; -template struct TypeHelper { +template +struct TypeHelper { static bool Is(const ValueType &v) { return v.IsUint64(); } static uint64_t Get(const ValueType &v) { return v.GetUint64(); } static ValueType &Set(ValueType &v, uint64_t data) { @@ -582,7 +596,8 @@ template struct TypeHelper { } }; -template struct TypeHelper { +template +struct TypeHelper { static bool Is(const ValueType &v) { return v.IsDouble(); } static double Get(const ValueType &v) { return v.GetDouble(); } static ValueType &Set(ValueType &v, double data) { return v.SetDouble(data); } @@ -592,7 +607,8 @@ template struct TypeHelper { } }; -template struct TypeHelper { +template +struct TypeHelper { static bool Is(const ValueType &v) { return v.IsFloat(); } static float Get(const ValueType &v) { return v.GetFloat(); } static ValueType &Set(ValueType &v, float data) { return v.SetFloat(data); } @@ -669,11 +685,13 @@ struct TypeHelper { static ObjectType Get(const ValueType &v) { return v.GetObject(); } }; -} // namespace internal +} // namespace internal // Forward declarations -template class GenericArray; -template class GenericObject; +template +class GenericArray; +template +class GenericObject; /////////////////////////////////////////////////////////////////////////////// // GenericValue @@ -691,25 +709,25 @@ template class GenericObject; */ template > class GenericValue { -public: + public: //! Name-value pair in an object. typedef GenericMember Member; typedef Encoding EncodingType; //!< Encoding type from template parameter. typedef Allocator AllocatorType; //!< Allocator type from template parameter. - typedef typename Encoding::Ch Ch; //!< Character type derived from Encoding. + typedef typename Encoding::Ch Ch; //!< Character type derived from Encoding. typedef GenericStringRef - StringRefType; //!< Reference to a constant string + StringRefType; //!< Reference to a constant string typedef typename GenericMemberIterator::Iterator - MemberIterator; //!< Member iterator for iterating in object. + MemberIterator; //!< Member iterator for iterating in object. typedef typename GenericMemberIterator::Iterator - ConstMemberIterator; //!< Constant member iterator for iterating in - //!< object. + ConstMemberIterator; //!< Constant member iterator for iterating in + //!< object. typedef GenericValue - *ValueIterator; //!< Value iterator for iterating in array. + *ValueIterator; //!< Value iterator for iterating in array. typedef const GenericValue - *ConstValueIterator; //!< Constant value iterator for iterating in array. + *ConstValueIterator; //!< Constant value iterator for iterating in array. typedef GenericValue - ValueType; //!< Value type of itself. + ValueType; //!< Value type of itself. typedef GenericArray Array; typedef GenericArray ConstArray; typedef GenericObject Object; @@ -724,11 +742,11 @@ class GenericValue { #if RAPIDJSON_HAS_CXX11_RVALUE_REFS //! Move constructor in C++11 GenericValue(GenericValue &&rhs) RAPIDJSON_NOEXCEPT : data_(rhs.data_) { - rhs.data_.f.flags = kNullFlag; // give up contents + rhs.data_.f.flags = kNullFlag; // give up contents } #endif -private: + private: //! Copy constructor is not permitted. GenericValue(const GenericValue &rhs); @@ -739,11 +757,11 @@ class GenericValue { //! Move assignment from a GenericDocument is not permitted. template - GenericValue & - operator=(GenericDocument &&rhs); + GenericValue &operator=( + GenericDocument &&rhs); #endif -public: + public: //! Constructor with JSON value type. /*! This creates a Value of specified type with default content. \param type Type of the value. @@ -757,8 +775,7 @@ class GenericValue { data_.f.flags = defaultFlags[type]; // Use ShortString to store empty string. - if (type == kStringType) - data_.ss.SetLength(0); + if (type == kStringType) data_.ss.SetLength(0); } //! Explicit copy constructor (with allocator) @@ -774,59 +791,60 @@ class GenericValue { GenericValue(const GenericValue &rhs, Allocator &allocator, bool copyConstStrings = false) { switch (rhs.GetType()) { - case kObjectType: { - SizeType count = rhs.data_.o.size; - Member *lm = - reinterpret_cast(allocator.Malloc(count * sizeof(Member))); - const typename GenericValue::Member *rm = - rhs.GetMembersPointer(); - for (SizeType i = 0; i < count; i++) { - new (&lm[i].name) GenericValue(rm[i].name, allocator, copyConstStrings); - new (&lm[i].value) - GenericValue(rm[i].value, allocator, copyConstStrings); - } - data_.f.flags = kObjectFlag; - data_.o.size = data_.o.capacity = count; - SetMembersPointer(lm); - } break; - case kArrayType: { - SizeType count = rhs.data_.a.size; - GenericValue *le = reinterpret_cast( - allocator.Malloc(count * sizeof(GenericValue))); - const GenericValue *re = - rhs.GetElementsPointer(); - for (SizeType i = 0; i < count; i++) - new (&le[i]) GenericValue(re[i], allocator, copyConstStrings); - data_.f.flags = kArrayFlag; - data_.a.size = data_.a.capacity = count; - SetElementsPointer(le); - } break; - case kStringType: - if (rhs.data_.f.flags == kConstStringFlag && !copyConstStrings) { + case kObjectType: { + SizeType count = rhs.data_.o.size; + Member *lm = reinterpret_cast( + allocator.Malloc(count * sizeof(Member))); + const typename GenericValue::Member *rm = + rhs.GetMembersPointer(); + for (SizeType i = 0; i < count; i++) { + new (&lm[i].name) + GenericValue(rm[i].name, allocator, copyConstStrings); + new (&lm[i].value) + GenericValue(rm[i].value, allocator, copyConstStrings); + } + data_.f.flags = kObjectFlag; + data_.o.size = data_.o.capacity = count; + SetMembersPointer(lm); + } break; + case kArrayType: { + SizeType count = rhs.data_.a.size; + GenericValue *le = reinterpret_cast( + allocator.Malloc(count * sizeof(GenericValue))); + const GenericValue *re = + rhs.GetElementsPointer(); + for (SizeType i = 0; i < count; i++) + new (&le[i]) GenericValue(re[i], allocator, copyConstStrings); + data_.f.flags = kArrayFlag; + data_.a.size = data_.a.capacity = count; + SetElementsPointer(le); + } break; + case kStringType: + if (rhs.data_.f.flags == kConstStringFlag && !copyConstStrings) { + data_.f.flags = rhs.data_.f.flags; + data_ = *reinterpret_cast(&rhs.data_); + } else + SetStringRaw(StringRef(rhs.GetString(), rhs.GetStringLength()), + allocator); + break; + default: data_.f.flags = rhs.data_.f.flags; data_ = *reinterpret_cast(&rhs.data_); - } else - SetStringRaw(StringRef(rhs.GetString(), rhs.GetStringLength()), - allocator); - break; - default: - data_.f.flags = rhs.data_.f.flags; - data_ = *reinterpret_cast(&rhs.data_); - break; + break; } } - //! Constructor for boolean value. - /*! \param b Boolean value - \note This constructor is limited to \em real boolean values and rejects - implicitly converted types like arbitrary pointers. Use an explicit - cast to \c bool, if you want to construct a boolean JSON value in such - cases. - */ -#ifndef RAPIDJSON_DOXYGEN_RUNNING // hide SFINAE from Doxygen +//! Constructor for boolean value. +/*! \param b Boolean value + \note This constructor is limited to \em real boolean values and rejects + implicitly converted types like arbitrary pointers. Use an explicit + cast to \c bool, if you want to construct a boolean JSON value in such + cases. + */ +#ifndef RAPIDJSON_DOXYGEN_RUNNING // hide SFINAE from Doxygen template explicit GenericValue(T b, RAPIDJSON_ENABLEIF((internal::IsSame))) - RAPIDJSON_NOEXCEPT // See #472 + RAPIDJSON_NOEXCEPT // See #472 #else explicit GenericValue(bool b) RAPIDJSON_NOEXCEPT #endif @@ -951,27 +969,27 @@ class GenericValue { /*! Need to destruct elements of array, members of object, or copy-string. */ ~GenericValue() { - if (Allocator::kNeedFree) { // Shortcut by Allocator's trait + if (Allocator::kNeedFree) { // Shortcut by Allocator's trait switch (data_.f.flags) { - case kArrayFlag: { - GenericValue *e = GetElementsPointer(); - for (GenericValue *v = e; v != e + data_.a.size; ++v) - v->~GenericValue(); - Allocator::Free(e); - } break; - - case kObjectFlag: - for (MemberIterator m = MemberBegin(); m != MemberEnd(); ++m) - m->~Member(); - Allocator::Free(GetMembersPointer()); - break; - - case kCopyStringFlag: - Allocator::Free(const_cast(GetStringPointer())); - break; - - default: - break; // Do nothing for other types. + case kArrayFlag: { + GenericValue *e = GetElementsPointer(); + for (GenericValue *v = e; v != e + data_.a.size; ++v) + v->~GenericValue(); + Allocator::Free(e); + } break; + + case kObjectFlag: + for (MemberIterator m = MemberBegin(); m != MemberEnd(); ++m) + m->~Member(); + Allocator::Free(GetMembersPointer()); + break; + + case kCopyStringFlag: + Allocator::Free(const_cast(GetStringPointer())); + break; + + default: + break; // Do nothing for other types. } } } @@ -1091,44 +1109,40 @@ class GenericValue { template bool operator==(const GenericValue &rhs) const { typedef GenericValue RhsType; - if (GetType() != rhs.GetType()) - return false; + if (GetType() != rhs.GetType()) return false; switch (GetType()) { - case kObjectType: // Warning: O(n^2) inner-loop - if (data_.o.size != rhs.data_.o.size) - return false; - for (ConstMemberIterator lhsMemberItr = MemberBegin(); - lhsMemberItr != MemberEnd(); ++lhsMemberItr) { - typename RhsType::ConstMemberIterator rhsMemberItr = - rhs.FindMember(lhsMemberItr->name); - if (rhsMemberItr == rhs.MemberEnd() || - lhsMemberItr->value != rhsMemberItr->value) - return false; - } - return true; - - case kArrayType: - if (data_.a.size != rhs.data_.a.size) - return false; - for (SizeType i = 0; i < data_.a.size; i++) - if ((*this)[i] != rhs[i]) - return false; - return true; - - case kStringType: - return StringEqual(rhs); + case kObjectType: // Warning: O(n^2) inner-loop + if (data_.o.size != rhs.data_.o.size) return false; + for (ConstMemberIterator lhsMemberItr = MemberBegin(); + lhsMemberItr != MemberEnd(); ++lhsMemberItr) { + typename RhsType::ConstMemberIterator rhsMemberItr = + rhs.FindMember(lhsMemberItr->name); + if (rhsMemberItr == rhs.MemberEnd() || + lhsMemberItr->value != rhsMemberItr->value) + return false; + } + return true; + + case kArrayType: + if (data_.a.size != rhs.data_.a.size) return false; + for (SizeType i = 0; i < data_.a.size; i++) + if ((*this)[i] != rhs[i]) return false; + return true; + + case kStringType: + return StringEqual(rhs); + + case kNumberType: + if (IsDouble() || rhs.IsDouble()) { + double a = GetDouble(); // May convert from integer to double. + double b = rhs.GetDouble(); // Ditto + return a >= b && a <= b; // Prevent -Wfloat-equal + } else + return data_.n.u64 == rhs.data_.n.u64; - case kNumberType: - if (IsDouble() || rhs.IsDouble()) { - double a = GetDouble(); // May convert from integer to double. - double b = rhs.GetDouble(); // Ditto - return a >= b && a <= b; // Prevent -Wfloat-equal - } else - return data_.n.u64 == rhs.data_.n.u64; - - default: - return true; + default: + return true; } } @@ -1218,8 +1232,7 @@ class GenericValue { // Checks whether a number can be losslessly converted to a double. bool IsLosslessDouble() const { - if (!IsNumber()) - return false; + if (!IsNumber()) return false; if (IsUint64()) { uint64_t u = GetUint64(); volatile double d = static_cast(u); @@ -1236,26 +1249,24 @@ class GenericValue { (d < static_cast((std::numeric_limits::max)())) && (i == static_cast(d)); } - return true; // double, int, uint are always lossless + return true; // double, int, uint are always lossless } // Checks whether a number is a float (possible lossy). bool IsFloat() const { - if ((data_.f.flags & kDoubleFlag) == 0) - return false; + if ((data_.f.flags & kDoubleFlag) == 0) return false; double d = GetDouble(); return d >= -3.4028234e38 && d <= 3.4028234e38; } // Checks whether a number can be losslessly converted to a float. bool IsLosslessFloat() const { - if (!IsNumber()) - return false; + if (!IsNumber()) return false; double a = GetDouble(); if (a < static_cast(-(std::numeric_limits::max)()) || a > static_cast((std::numeric_limits::max)())) return false; double b = static_cast(static_cast(a)); - return a >= b && a <= b; // Prevent -Wfloat-equal + return a >= b && a <= b; // Prevent -Wfloat-equal } //@} @@ -1355,13 +1366,13 @@ class GenericValue { \note Linear time complexity. */ template - GenericValue & - operator[](const GenericValue &name) { + GenericValue &operator[]( + const GenericValue &name) { MemberIterator member = FindMember(name); if (member != MemberEnd()) return member->value; else { - RAPIDJSON_ASSERT(false); // see above note + RAPIDJSON_ASSERT(false); // see above note // This will generate -Wexit-time-destructors in clang // static GenericValue NullValue; @@ -1373,8 +1384,8 @@ class GenericValue { } } template - const GenericValue & - operator[](const GenericValue &name) const { + const GenericValue &operator[]( + const GenericValue &name) const { return const_cast(*this)[name]; } @@ -1505,19 +1516,18 @@ class GenericValue { \note Linear time complexity. */ template - MemberIterator - FindMember(const GenericValue &name) { + MemberIterator FindMember( + const GenericValue &name) { RAPIDJSON_ASSERT(IsObject()); RAPIDJSON_ASSERT(name.IsString()); MemberIterator member = MemberBegin(); for (; member != MemberEnd(); ++member) - if (name.StringEqual(member->name)) - break; + if (name.StringEqual(member->name)) break; return member; } template - ConstMemberIterator - FindMember(const GenericValue &name) const { + ConstMemberIterator FindMember( + const GenericValue &name) const { return const_cast(*this).FindMember(name); } @@ -1642,7 +1652,7 @@ class GenericValue { GenericValue n(name); return AddMember(n, value, allocator); } -#endif // RAPIDJSON_HAS_CXX11_RVALUE_REFS +#endif // RAPIDJSON_HAS_CXX11_RVALUE_REFS //! Add a member (name-value pair) to the object. /*! \param name A constant string reference as name of member. @@ -1707,8 +1717,7 @@ class GenericValue { */ void RemoveAllMembers() { RAPIDJSON_ASSERT(IsObject()); - for (MemberIterator m = MemberBegin(); m != MemberEnd(); ++m) - m->~Member(); + for (MemberIterator m = MemberBegin(); m != MemberEnd(); ++m) m->~Member(); data_.o.size = 0; } @@ -1757,9 +1766,9 @@ class GenericValue { MemberIterator last(GetMembersPointer() + (data_.o.size - 1)); if (data_.o.size > 1 && m != last) - *m = *last; // Move the last one to this place + *m = *last; // Move the last one to this place else - m->~Member(); // Only one left, just destroy + m->~Member(); // Only one left, just destroy --data_.o.size; return m; } @@ -1796,8 +1805,7 @@ class GenericValue { RAPIDJSON_ASSERT(last <= MemberEnd()); MemberIterator pos = MemberBegin() + (first - MemberBegin()); - for (MemberIterator itr = pos; itr != last; ++itr) - itr->~Member(); + for (MemberIterator itr = pos; itr != last; ++itr) itr->~Member(); std::memmove(static_cast(&*pos), &*last, static_cast(MemberEnd() - last) * sizeof(Member)); data_.o.size -= static_cast(last - first); @@ -1877,8 +1885,7 @@ class GenericValue { void Clear() { RAPIDJSON_ASSERT(IsArray()); GenericValue *e = GetElementsPointer(); - for (GenericValue *v = e; v != e + data_.a.size; ++v) - v->~GenericValue(); + for (GenericValue *v = e; v != e + data_.a.size; ++v) v->~GenericValue(); data_.a.size = 0; } @@ -1961,7 +1968,7 @@ class GenericValue { GenericValue &PushBack(GenericValue &&value, Allocator &allocator) { return PushBack(value, allocator); } -#endif // RAPIDJSON_HAS_CXX11_RVALUE_REFS +#endif // RAPIDJSON_HAS_CXX11_RVALUE_REFS //! Append a constant string reference at the end of the array. /*! \param value Constant string reference to be appended. @@ -2040,8 +2047,7 @@ class GenericValue { RAPIDJSON_ASSERT(first <= last); RAPIDJSON_ASSERT(last <= End()); ValueIterator pos = Begin() + (first - Begin()); - for (ValueIterator itr = pos; itr != last; ++itr) - itr->~GenericValue(); + for (ValueIterator itr = pos; itr != last; ++itr) itr->~GenericValue(); std::memmove(static_cast(pos), last, static_cast(End() - last) * sizeof(GenericValue)); data_.a.size -= static_cast(last - first); @@ -2086,17 +2092,16 @@ class GenericValue { double GetDouble() const { RAPIDJSON_ASSERT(IsNumber()); if ((data_.f.flags & kDoubleFlag) != 0) - return data_.n.d; // exact type, no conversion. - if ((data_.f.flags & kIntFlag) != 0) - return data_.n.i.i; // int -> double + return data_.n.d; // exact type, no conversion. + if ((data_.f.flags & kIntFlag) != 0) return data_.n.i.i; // int -> double if ((data_.f.flags & kUintFlag) != 0) - return data_.n.u.u; // unsigned -> double + return data_.n.u.u; // unsigned -> double if ((data_.f.flags & kInt64Flag) != 0) return static_cast( - data_.n.i64); // int64_t -> double (may lose precision) + data_.n.i64); // int64_t -> double (may lose precision) RAPIDJSON_ASSERT((data_.f.flags & kUint64Flag) != 0); return static_cast( - data_.n.u64); // uint64_t -> double (may lose precision) + data_.n.u64); // uint64_t -> double (may lose precision) } //! Get the value as float type. @@ -2243,19 +2248,23 @@ class GenericValue { \tparam T Either \c bool, \c int, \c unsigned, \c int64_t, \c uint64_t, \c double, \c float, \c const \c char*, \c std::basic_string */ - template bool Is() const { + template + bool Is() const { return internal::TypeHelper::Is(*this); } - template T Get() const { + template + T Get() const { return internal::TypeHelper::Get(*this); } - template T Get() { + template + T Get() { return internal::TypeHelper::Get(*this); } - template ValueType &Set(const T &data) { + template + ValueType &Set(const T &data) { return internal::TypeHelper::Set(*this, data); } @@ -2273,60 +2282,59 @@ class GenericValue { GenericDocument, which is also a Handler. \tparam Handler type of handler. \param handler An object implementing concept Handler. */ - template bool Accept(Handler &handler) const { + template + bool Accept(Handler &handler) const { switch (GetType()) { - case kNullType: - return handler.Null(); - case kFalseType: - return handler.Bool(false); - case kTrueType: - return handler.Bool(true); - - case kObjectType: - if (RAPIDJSON_UNLIKELY(!handler.StartObject())) - return false; - for (ConstMemberIterator m = MemberBegin(); m != MemberEnd(); ++m) { - RAPIDJSON_ASSERT(m->name.IsString()); // User may change the type of - // name by MemberIterator. - if (RAPIDJSON_UNLIKELY( - !handler.Key(m->name.GetString(), m->name.GetStringLength(), - (m->name.data_.f.flags & kCopyFlag) != 0))) - return false; - if (RAPIDJSON_UNLIKELY(!m->value.Accept(handler))) - return false; - } - return handler.EndObject(data_.o.size); - - case kArrayType: - if (RAPIDJSON_UNLIKELY(!handler.StartArray())) - return false; - for (const GenericValue *v = Begin(); v != End(); ++v) - if (RAPIDJSON_UNLIKELY(!v->Accept(handler))) - return false; - return handler.EndArray(data_.a.size); - - case kStringType: - return handler.String(GetString(), GetStringLength(), - (data_.f.flags & kCopyFlag) != 0); - - default: - RAPIDJSON_ASSERT(GetType() == kNumberType); - if (IsDouble()) - return handler.Double(data_.n.d); - else if (IsInt()) - return handler.Int(data_.n.i.i); - else if (IsUint()) - return handler.Uint(data_.n.u.u); - else if (IsInt64()) - return handler.Int64(data_.n.i64); - else - return handler.Uint64(data_.n.u64); + case kNullType: + return handler.Null(); + case kFalseType: + return handler.Bool(false); + case kTrueType: + return handler.Bool(true); + + case kObjectType: + if (RAPIDJSON_UNLIKELY(!handler.StartObject())) return false; + for (ConstMemberIterator m = MemberBegin(); m != MemberEnd(); ++m) { + RAPIDJSON_ASSERT(m->name.IsString()); // User may change the type of + // name by MemberIterator. + if (RAPIDJSON_UNLIKELY( + !handler.Key(m->name.GetString(), m->name.GetStringLength(), + (m->name.data_.f.flags & kCopyFlag) != 0))) + return false; + if (RAPIDJSON_UNLIKELY(!m->value.Accept(handler))) return false; + } + return handler.EndObject(data_.o.size); + + case kArrayType: + if (RAPIDJSON_UNLIKELY(!handler.StartArray())) return false; + for (const GenericValue *v = Begin(); v != End(); ++v) + if (RAPIDJSON_UNLIKELY(!v->Accept(handler))) return false; + return handler.EndArray(data_.a.size); + + case kStringType: + return handler.String(GetString(), GetStringLength(), + (data_.f.flags & kCopyFlag) != 0); + + default: + RAPIDJSON_ASSERT(GetType() == kNumberType); + if (IsDouble()) + return handler.Double(data_.n.d); + else if (IsInt()) + return handler.Int(data_.n.i.i); + else if (IsUint()) + return handler.Uint(data_.n.u.u); + else if (IsInt64()) + return handler.Int64(data_.n.i64); + else + return handler.Uint64(data_.n.u64); } } -private: - template friend class GenericValue; - template friend class GenericDocument; + private: + template + friend class GenericValue; + template + friend class GenericDocument; enum { kBoolFlag = 0x0008, @@ -2367,21 +2375,21 @@ class GenericValue { struct Flag { #if RAPIDJSON_48BITPOINTER_OPTIMIZATION char payload[sizeof(SizeType) * 2 + - 6]; // 2 x SizeType + lower 48-bit pointer + 6]; // 2 x SizeType + lower 48-bit pointer #elif RAPIDJSON_64BIT - char payload[sizeof(SizeType) * 2 + sizeof(void *) + 6]; // 6 padding bytes + char payload[sizeof(SizeType) * 2 + sizeof(void *) + 6]; // 6 padding bytes #else - char payload[sizeof(SizeType) * 2 + sizeof(void *) + - 2]; // 2 padding bytes + char payload[sizeof(SizeType) * 2 + sizeof(void *) + + 2]; // 2 padding bytes #endif uint16_t flags; }; struct String { SizeType length; - SizeType hashcode; //!< reserved + SizeType hashcode; //!< reserved const Ch *str; - }; // 12 bytes in 32-bit mode, 16 bytes in 64-bit mode + }; // 12 bytes in 32-bit mode, 16 bytes in 64-bit mode // implementation detail: ShortString can represent zero-terminated strings up // to MaxSize chars (excluding the terminating zero) and store a value to @@ -2408,8 +2416,8 @@ class GenericValue { inline SizeType GetLength() const { return static_cast(MaxSize - str[LenPos]); } - }; // at most as many bytes as "String" above => 12 bytes in 32-bit mode, 16 - // bytes in 64-bit mode + }; // at most as many bytes as "String" above => 12 bytes in 32-bit mode, 16 + // bytes in 64-bit mode // By using proper binary layout, retrieval of different integer types do not // need conversions. @@ -2436,19 +2444,19 @@ class GenericValue { int64_t i64; uint64_t u64; double d; - }; // 8 bytes + }; // 8 bytes struct ObjectData { SizeType size; SizeType capacity; Member *members; - }; // 12 bytes in 32-bit mode, 16 bytes in 64-bit mode + }; // 12 bytes in 32-bit mode, 16 bytes in 64-bit mode struct ArrayData { SizeType size; SizeType capacity; GenericValue *elements; - }; // 12 bytes in 32-bit mode, 16 bytes in 64-bit mode + }; // 12 bytes in 32-bit mode, 16 bytes in 64-bit mode union Data { String s; @@ -2457,8 +2465,8 @@ class GenericValue { ObjectData o; ArrayData a; Flag f; - }; // 16 bytes in 32-bit mode, 24 bytes in 64-bit mode, 16 bytes in 64-bit - // with RAPIDJSON_48BITPOINTER_OPTIMIZATION + }; // 16 bytes in 32-bit mode, 24 bytes in 64-bit mode, 16 bytes in 64-bit + // with RAPIDJSON_48BITPOINTER_OPTIMIZATION RAPIDJSON_FORCEINLINE const Ch *GetStringPointer() const { return RAPIDJSON_GETPOINTER(Ch, data_.s.str); @@ -2469,8 +2477,8 @@ class GenericValue { RAPIDJSON_FORCEINLINE GenericValue *GetElementsPointer() const { return RAPIDJSON_GETPOINTER(GenericValue, data_.a.elements); } - RAPIDJSON_FORCEINLINE GenericValue * - SetElementsPointer(GenericValue *elements) { + RAPIDJSON_FORCEINLINE GenericValue *SetElementsPointer( + GenericValue *elements) { return RAPIDJSON_SETPOINTER(GenericValue, data_.a.elements, elements); } RAPIDJSON_FORCEINLINE Member *GetMembersPointer() const { @@ -2555,7 +2563,7 @@ class GenericValue { const Ch *const str2 = rhs.GetString(); if (str1 == str2) { return true; - } // fast path for constant string + } // fast path for constant string return (std::memcmp(str1, str2, sizeof(Ch) * len1) == 0); } @@ -2583,11 +2591,11 @@ typedef GenericValue> Value; template , typename StackAllocator = CrtAllocator> class GenericDocument : public GenericValue { -public: - typedef typename Encoding::Ch Ch; //!< Character type derived from Encoding. + public: + typedef typename Encoding::Ch Ch; //!< Character type derived from Encoding. typedef GenericValue - ValueType; //!< Value type of the document. - typedef Allocator AllocatorType; //!< Allocator type from template parameter. + ValueType; //!< Value type of the document. + typedef Allocator AllocatorType; //!< Allocator type from template parameter. //! Constructor /*! Creates an empty document of specified type. @@ -2600,11 +2608,12 @@ class GenericDocument : public GenericValue { explicit GenericDocument(Type type, Allocator *allocator = 0, size_t stackCapacity = kDefaultStackCapacity, StackAllocator *stackAllocator = 0) - : GenericValue(type), allocator_(allocator), - ownAllocator_(0), stack_(stackAllocator, stackCapacity), + : GenericValue(type), + allocator_(allocator), + ownAllocator_(0), + stack_(stackAllocator, stackCapacity), parseResult_() { - if (!allocator_) - ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator)(); + if (!allocator_) ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator)(); } //! Constructor @@ -2617,17 +2626,18 @@ class GenericDocument : public GenericValue { GenericDocument(Allocator *allocator = 0, size_t stackCapacity = kDefaultStackCapacity, StackAllocator *stackAllocator = 0) - : allocator_(allocator), ownAllocator_(0), - stack_(stackAllocator, stackCapacity), parseResult_() { - if (!allocator_) - ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator)(); + : allocator_(allocator), + ownAllocator_(0), + stack_(stackAllocator, stackCapacity), + parseResult_() { + if (!allocator_) ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator)(); } #if RAPIDJSON_HAS_CXX11_RVALUE_REFS //! Move constructor in C++11 GenericDocument(GenericDocument &&rhs) RAPIDJSON_NOEXCEPT : ValueType(std::forward( - rhs)), // explicit cast to avoid prohibited move from Document + rhs)), // explicit cast to avoid prohibited move from Document allocator_(rhs.allocator_), ownAllocator_(rhs.ownAllocator_), stack_(std::move(rhs.stack_)), @@ -2702,13 +2712,14 @@ class GenericDocument : public GenericValue { \param g Generator functor which sends SAX events to the parameter. \return The document itself for fluent API. */ - template GenericDocument &Populate(Generator &g) { + template + GenericDocument &Populate(Generator &g) { ClearStackOnExit scope(*this); if (g(*this)) { RAPIDJSON_ASSERT(stack_.GetSize() == - sizeof(ValueType)); // Got one and only one root object + sizeof(ValueType)); // Got one and only one root object ValueType::operator=(*stack_.template Pop( - 1)); // Move value from stack to document + 1)); // Move value from stack to document } return *this; } @@ -2731,9 +2742,9 @@ class GenericDocument : public GenericValue { parseResult_ = reader.template Parse(is, *this); if (parseResult_) { RAPIDJSON_ASSERT(stack_.GetSize() == - sizeof(ValueType)); // Got one and only one root object + sizeof(ValueType)); // Got one and only one root object ValueType::operator=(*stack_.template Pop( - 1)); // Move value from stack to document + 1)); // Move value from stack to document } return *this; } @@ -2768,7 +2779,8 @@ class GenericDocument : public GenericValue { \param str Mutable zero-terminated string to be parsed. \return The document itself for fluent API. */ - template GenericDocument &ParseInsitu(Ch *str) { + template + GenericDocument &ParseInsitu(Ch *str) { GenericInsituStringStream s(str); return ParseStream(s); } @@ -2802,7 +2814,8 @@ class GenericDocument : public GenericValue { kParseInsituFlag). \param str Read-only zero-terminated string to be parsed. */ - template GenericDocument &Parse(const Ch *str) { + template + GenericDocument &Parse(const Ch *str) { return Parse(str); } @@ -2835,8 +2848,8 @@ class GenericDocument : public GenericValue { #if RAPIDJSON_HAS_STDSTRING template - GenericDocument & - Parse(const std::basic_string &str) { + GenericDocument &Parse( + const std::basic_string &str) { // c_str() is constant complexity according to standard. Should be faster // than Parse(const char*, size_t) return Parse(str.c_str()); @@ -2850,7 +2863,7 @@ class GenericDocument : public GenericValue { GenericDocument &Parse(const std::basic_string &str) { return Parse(str); } -#endif // RAPIDJSON_HAS_STDSTRING +#endif // RAPIDJSON_HAS_STDSTRING //!@} @@ -2866,17 +2879,17 @@ class GenericDocument : public GenericValue { //! Get the position of last parsing error in input, 0 otherwise. size_t GetErrorOffset() const { return parseResult_.Offset(); } - //! Implicit conversion to get the last parse result -#ifndef __clang // -Wdocumentation - /*! \return \ref ParseResult of the last parse operation - - \code - Document doc; - ParseResult ok = doc.Parse(json); - if (!ok) - printf( "JSON parse error: %s (%u)\n", GetParseError_En(ok.Code()), - ok.Offset()); \endcode - */ +//! Implicit conversion to get the last parse result +#ifndef __clang // -Wdocumentation +/*! \return \ref ParseResult of the last parse operation + + \code + Document doc; + ParseResult ok = doc.Parse(json); + if (!ok) + printf( "JSON parse error: %s (%u)\n", GetParseError_En(ok.Code()), + ok.Offset()); \endcode + */ #endif operator ParseResult() const { return parseResult_; } //!@} @@ -2890,13 +2903,13 @@ class GenericDocument : public GenericValue { //! Get the capacity of stack in bytes. size_t GetStackCapacity() const { return stack_.GetCapacity(); } -private: + private: // clear stack on any exit from ParseStream, e.g. due to exception struct ClearStackOnExit { explicit ClearStackOnExit(GenericDocument &d) : d_(d) {} ~ClearStackOnExit() { d_.ClearStack(); } - private: + private: ClearStackOnExit(const ClearStackOnExit &); ClearStackOnExit &operator=(const ClearStackOnExit &); GenericDocument &d_; @@ -2905,9 +2918,10 @@ class GenericDocument : public GenericValue { // callers of the following private Handler functions // template friend class GenericReader; // for // parsing - template friend class GenericValue; // for deep copying + template + friend class GenericValue; // for deep copying -public: + public: // Implementation of Handler bool Null() { new (stack_.template Push()) ValueType(); @@ -2985,7 +2999,7 @@ class GenericDocument : public GenericValue { return true; } -private: + private: //! Prohibit copying GenericDocument(const GenericDocument &); //! Prohibit assignment @@ -2994,8 +3008,8 @@ class GenericDocument : public GenericValue { void ClearStack() { if (Allocator::kNeedFree) while (stack_.GetSize() > - 0) // Here assumes all elements in stack array are GenericValue - // (Member is actually 2 GenericValue objects) + 0) // Here assumes all elements in stack array are GenericValue + // (Member is actually 2 GenericValue objects) (stack_.template Pop(1))->~ValueType(); else stack_.Clear(); @@ -3020,18 +3034,20 @@ typedef GenericDocument> Document; In addition to all APIs for array type, it provides range-based for loop if \c RAPIDJSON_HAS_CXX11_RANGE_FOR=1. */ -template class GenericArray { -public: +template +class GenericArray { + public: typedef GenericArray ConstArray; typedef GenericArray Array; typedef ValueT PlainType; typedef typename internal::MaybeAddConst::Type ValueType; - typedef ValueType *ValueIterator; // This may be const or non-const iterator + typedef ValueType *ValueIterator; // This may be const or non-const iterator typedef const ValueT *ConstValueIterator; typedef typename ValueType::AllocatorType AllocatorType; typedef typename ValueType::StringRefType StringRefType; - template friend class GenericValue; + template + friend class GenericValue; GenericArray(const GenericArray &rhs) : value_(rhs.value_) {} GenericArray &operator=(const GenericArray &rhs) { @@ -3060,7 +3076,7 @@ template class GenericArray { value_.PushBack(value, allocator); return *this; } -#endif // RAPIDJSON_HAS_CXX11_RVALUE_REFS +#endif // RAPIDJSON_HAS_CXX11_RVALUE_REFS GenericArray PushBack(StringRefType value, AllocatorType &allocator) const { value_.PushBack(value, allocator); return *this; @@ -3089,7 +3105,7 @@ template class GenericArray { ValueIterator end() const { return value_.End(); } #endif -private: + private: GenericArray(); GenericArray(ValueType &value) : value_(value) {} ValueType &value_; @@ -3101,15 +3117,16 @@ template class GenericArray { In addition to all APIs for array type, it provides range-based for loop if \c RAPIDJSON_HAS_CXX11_RANGE_FOR=1. */ -template class GenericObject { -public: +template +class GenericObject { + public: typedef GenericObject ConstObject; typedef GenericObject Object; typedef ValueT PlainType; typedef typename internal::MaybeAddConst::Type ValueType; typedef GenericMemberIterator - MemberIterator; // This may be const or non-const iterator + MemberIterator; // This may be const or non-const iterator typedef GenericMemberIterator ConstMemberIterator; @@ -3118,7 +3135,8 @@ template class GenericObject { typedef typename ValueType::EncodingType EncodingType; typedef typename ValueType::Ch Ch; - template friend class GenericValue; + template + friend class GenericValue; GenericObject(const GenericObject &rhs) : value_(rhs.value_) {} GenericObject &operator=(const GenericObject &rhs) { @@ -3130,12 +3148,13 @@ template class GenericObject { SizeType MemberCount() const { return value_.MemberCount(); } SizeType MemberCapacity() const { return value_.MemberCapacity(); } bool ObjectEmpty() const { return value_.ObjectEmpty(); } - template ValueType &operator[](T *name) const { + template + ValueType &operator[](T *name) const { return value_[name]; } template - ValueType & - operator[](const GenericValue &name) const { + ValueType &operator[]( + const GenericValue &name) const { return value_[name]; } #if RAPIDJSON_HAS_STDSTRING @@ -3157,16 +3176,16 @@ template class GenericObject { } #endif template - bool - HasMember(const GenericValue &name) const { + bool HasMember( + const GenericValue &name) const { return value_.HasMember(name); } MemberIterator FindMember(const Ch *name) const { return value_.FindMember(name); } template - MemberIterator - FindMember(const GenericValue &name) const { + MemberIterator FindMember( + const GenericValue &name) const { return value_.FindMember(name); } #if RAPIDJSON_HAS_STDSTRING @@ -3220,7 +3239,7 @@ template class GenericObject { value_.AddMember(name, value, allocator); return *this; } -#endif // RAPIDJSON_HAS_CXX11_RVALUE_REFS +#endif // RAPIDJSON_HAS_CXX11_RVALUE_REFS GenericObject AddMember(StringRefType name, ValueType &value, AllocatorType &allocator) const { value_.AddMember(name, value, allocator); @@ -3247,8 +3266,8 @@ template class GenericObject { } #endif template - bool - RemoveMember(const GenericValue &name) const { + bool RemoveMember( + const GenericValue &name) const { return value_.RemoveMember(name); } MemberIterator RemoveMember(MemberIterator m) const { @@ -3268,8 +3287,8 @@ template class GenericObject { } #endif template - bool - EraseMember(const GenericValue &name) const { + bool EraseMember( + const GenericValue &name) const { return value_.EraseMember(name); } @@ -3278,7 +3297,7 @@ template class GenericObject { MemberIterator end() const { return value_.MemberEnd(); } #endif -private: + private: GenericObject(); GenericObject(ValueType &value) : value_(value) {} ValueType &value_; @@ -3287,4 +3306,4 @@ template class GenericObject { RAPIDJSON_NAMESPACE_END RAPIDJSON_DIAG_POP -#endif // RAPIDJSON_DOCUMENT_H_ +#endif // RAPIDJSON_DOCUMENT_H_ diff --git a/livox_ros_driver/common/rapidjson/encodedstream.h b/livox_ros_driver/common/rapidjson/encodedstream.h index 606e8bd..74ef4ca 100644 --- a/livox_ros_driver/common/rapidjson/encodedstream.h +++ b/livox_ros_driver/common/rapidjson/encodedstream.h @@ -44,7 +44,7 @@ template class EncodedInputStream { RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1); -public: + public: typedef typename Encoding::Ch Ch; EncodedInputStream(InputByteStream &is) : is_(is) { @@ -71,7 +71,7 @@ class EncodedInputStream { return 0; } -private: + private: EncodedInputStream(const EncodedInputStream &); EncodedInputStream &operator=(const EncodedInputStream &); @@ -80,17 +80,15 @@ class EncodedInputStream { }; //! Specialized for UTF8 MemoryStream. -template <> class EncodedInputStream, MemoryStream> { -public: +template <> +class EncodedInputStream, MemoryStream> { + public: typedef UTF8<>::Ch Ch; EncodedInputStream(MemoryStream &is) : is_(is) { - if (static_cast(is_.Peek()) == 0xEFu) - is_.Take(); - if (static_cast(is_.Peek()) == 0xBBu) - is_.Take(); - if (static_cast(is_.Peek()) == 0xBFu) - is_.Take(); + if (static_cast(is_.Peek()) == 0xEFu) is_.Take(); + if (static_cast(is_.Peek()) == 0xBBu) is_.Take(); + if (static_cast(is_.Peek()) == 0xBFu) is_.Take(); } Ch Peek() const { return is_.Peek(); } Ch Take() { return is_.Take(); } @@ -104,7 +102,7 @@ template <> class EncodedInputStream, MemoryStream> { MemoryStream &is_; -private: + private: EncodedInputStream(const EncodedInputStream &); EncodedInputStream &operator=(const EncodedInputStream &); }; @@ -119,12 +117,11 @@ template class EncodedOutputStream { RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1); -public: + public: typedef typename Encoding::Ch Ch; EncodedOutputStream(OutputByteStream &os, bool putBOM = true) : os_(os) { - if (putBOM) - Encoding::PutBOM(os_); + if (putBOM) Encoding::PutBOM(os_); } void Put(Ch c) { Encoding::Put(os_, c); } @@ -152,14 +149,14 @@ class EncodedOutputStream { return 0; } -private: + private: EncodedOutputStream(const EncodedOutputStream &); EncodedOutputStream &operator=(const EncodedOutputStream &); OutputByteStream &os_; }; -#define RAPIDJSON_ENCODINGS_FUNC(x) \ +#define RAPIDJSON_ENCODINGS_FUNC(x) \ UTF8::x, UTF16LE::x, UTF16BE::x, UTF32LE::x, UTF32BE::x //! Input stream wrapper with dynamically bound encoding and automatic encoding @@ -172,7 +169,7 @@ template class AutoUTFInputStream { RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1); -public: + public: typedef CharType Ch; //! Constructor. @@ -212,7 +209,7 @@ class AutoUTFInputStream { return 0; } -private: + private: AutoUTFInputStream(const AutoUTFInputStream &); AutoUTFInputStream &operator=(const AutoUTFInputStream &); @@ -227,8 +224,7 @@ class AutoUTFInputStream { const unsigned char *c = reinterpret_cast(is_->Peek4()); - if (!c) - return; + if (!c) return; unsigned bom = static_cast(c[0] | (c[1] << 8) | (c[2] << 16) | (c[3] << 24)); @@ -280,23 +276,23 @@ class AutoUTFInputStream { int pattern = (c[0] ? 1 : 0) | (c[1] ? 2 : 0) | (c[2] ? 4 : 0) | (c[3] ? 8 : 0); switch (pattern) { - case 0x08: - type_ = kUTF32BE; - break; - case 0x0A: - type_ = kUTF16BE; - break; - case 0x01: - type_ = kUTF32LE; - break; - case 0x05: - type_ = kUTF16LE; - break; - case 0x0F: - type_ = kUTF8; - break; - default: - break; // Use type defined by user. + case 0x08: + type_ = kUTF32BE; + break; + case 0x0A: + type_ = kUTF16BE; + break; + case 0x01: + type_ = kUTF32LE; + break; + case 0x05: + type_ = kUTF16LE; + break; + case 0x0F: + type_ = kUTF8; + break; + default: + break; // Use type defined by user. } } @@ -326,7 +322,7 @@ template class AutoUTFOutputStream { RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1); -public: + public: typedef CharType Ch; //! Constructor. @@ -349,8 +345,7 @@ class AutoUTFOutputStream { static const PutFunc f[] = {RAPIDJSON_ENCODINGS_FUNC(Put)}; putFunc_ = f[type_]; - if (putBOM) - PutBOM(); + if (putBOM) PutBOM(); } UTFType GetType() const { return type_; } @@ -380,7 +375,7 @@ class AutoUTFOutputStream { return 0; } -private: + private: AutoUTFOutputStream(const AutoUTFOutputStream &); AutoUTFOutputStream &operator=(const AutoUTFOutputStream &); @@ -409,4 +404,4 @@ RAPIDJSON_DIAG_POP RAPIDJSON_DIAG_POP #endif -#endif // RAPIDJSON_FILESTREAM_H_ +#endif // RAPIDJSON_FILESTREAM_H_ diff --git a/livox_ros_driver/common/rapidjson/encodings.h b/livox_ros_driver/common/rapidjson/encodings.h index 15e2619..34521cc 100644 --- a/livox_ros_driver/common/rapidjson/encodings.h +++ b/livox_ros_driver/common/rapidjson/encodings.h @@ -24,8 +24,8 @@ #if defined(_MSC_VER) && !defined(__clang__) RAPIDJSON_DIAG_PUSH RAPIDJSON_DIAG_OFF( - 4244) // conversion from 'type1' to 'type2', possible loss of data -RAPIDJSON_DIAG_OFF(4702) // unreachable code + 4244) // conversion from 'type1' to 'type2', possible loss of data +RAPIDJSON_DIAG_OFF(4702) // unreachable code #elif defined(__GNUC__) RAPIDJSON_DIAG_PUSH RAPIDJSON_DIAG_OFF(effc++) @@ -98,7 +98,8 @@ actually decode it. template \tparam CharType Code unit for storing 8-bit UTF-8 data. Default is char. \note implements Encoding concept */ -template struct UTF8 { +template +struct UTF8 { typedef CharType Ch; enum { supportUnicode = 1 }; @@ -145,13 +146,13 @@ template struct UTF8 { template static bool Decode(InputStream &is, unsigned *codepoint) { -#define RAPIDJSON_COPY() \ - c = is.Take(); \ +#define RAPIDJSON_COPY() \ + c = is.Take(); \ *codepoint = (*codepoint << 6) | (static_cast(c) & 0x3Fu) -#define RAPIDJSON_TRANS(mask) \ +#define RAPIDJSON_TRANS(mask) \ result &= ((GetRange(static_cast(c)) & mask) != 0) -#define RAPIDJSON_TAIL() \ - RAPIDJSON_COPY(); \ +#define RAPIDJSON_TAIL() \ + RAPIDJSON_COPY(); \ RAPIDJSON_TRANS(0x70) typename InputStream::Ch c = is.Take(); if (!(c & 0x80)) { @@ -167,42 +168,42 @@ template struct UTF8 { } bool result = true; switch (type) { - case 2: - RAPIDJSON_TAIL(); - return result; - case 3: - RAPIDJSON_TAIL(); - RAPIDJSON_TAIL(); - return result; - case 4: - RAPIDJSON_COPY(); - RAPIDJSON_TRANS(0x50); - RAPIDJSON_TAIL(); - return result; - case 5: - RAPIDJSON_COPY(); - RAPIDJSON_TRANS(0x10); - RAPIDJSON_TAIL(); - RAPIDJSON_TAIL(); - return result; - case 6: - RAPIDJSON_TAIL(); - RAPIDJSON_TAIL(); - RAPIDJSON_TAIL(); - return result; - case 10: - RAPIDJSON_COPY(); - RAPIDJSON_TRANS(0x20); - RAPIDJSON_TAIL(); - return result; - case 11: - RAPIDJSON_COPY(); - RAPIDJSON_TRANS(0x60); - RAPIDJSON_TAIL(); - RAPIDJSON_TAIL(); - return result; - default: - return false; + case 2: + RAPIDJSON_TAIL(); + return result; + case 3: + RAPIDJSON_TAIL(); + RAPIDJSON_TAIL(); + return result; + case 4: + RAPIDJSON_COPY(); + RAPIDJSON_TRANS(0x50); + RAPIDJSON_TAIL(); + return result; + case 5: + RAPIDJSON_COPY(); + RAPIDJSON_TRANS(0x10); + RAPIDJSON_TAIL(); + RAPIDJSON_TAIL(); + return result; + case 6: + RAPIDJSON_TAIL(); + RAPIDJSON_TAIL(); + RAPIDJSON_TAIL(); + return result; + case 10: + RAPIDJSON_COPY(); + RAPIDJSON_TRANS(0x20); + RAPIDJSON_TAIL(); + return result; + case 11: + RAPIDJSON_COPY(); + RAPIDJSON_TRANS(0x60); + RAPIDJSON_TAIL(); + RAPIDJSON_TAIL(); + return result; + default: + return false; } #undef RAPIDJSON_COPY #undef RAPIDJSON_TRANS @@ -212,54 +213,53 @@ template struct UTF8 { template static bool Validate(InputStream &is, OutputStream &os) { #define RAPIDJSON_COPY() os.Put(c = is.Take()) -#define RAPIDJSON_TRANS(mask) \ +#define RAPIDJSON_TRANS(mask) \ result &= ((GetRange(static_cast(c)) & mask) != 0) -#define RAPIDJSON_TAIL() \ - RAPIDJSON_COPY(); \ +#define RAPIDJSON_TAIL() \ + RAPIDJSON_COPY(); \ RAPIDJSON_TRANS(0x70) Ch c; RAPIDJSON_COPY(); - if (!(c & 0x80)) - return true; + if (!(c & 0x80)) return true; bool result = true; switch (GetRange(static_cast(c))) { - case 2: - RAPIDJSON_TAIL(); - return result; - case 3: - RAPIDJSON_TAIL(); - RAPIDJSON_TAIL(); - return result; - case 4: - RAPIDJSON_COPY(); - RAPIDJSON_TRANS(0x50); - RAPIDJSON_TAIL(); - return result; - case 5: - RAPIDJSON_COPY(); - RAPIDJSON_TRANS(0x10); - RAPIDJSON_TAIL(); - RAPIDJSON_TAIL(); - return result; - case 6: - RAPIDJSON_TAIL(); - RAPIDJSON_TAIL(); - RAPIDJSON_TAIL(); - return result; - case 10: - RAPIDJSON_COPY(); - RAPIDJSON_TRANS(0x20); - RAPIDJSON_TAIL(); - return result; - case 11: - RAPIDJSON_COPY(); - RAPIDJSON_TRANS(0x60); - RAPIDJSON_TAIL(); - RAPIDJSON_TAIL(); - return result; - default: - return false; + case 2: + RAPIDJSON_TAIL(); + return result; + case 3: + RAPIDJSON_TAIL(); + RAPIDJSON_TAIL(); + return result; + case 4: + RAPIDJSON_COPY(); + RAPIDJSON_TRANS(0x50); + RAPIDJSON_TAIL(); + return result; + case 5: + RAPIDJSON_COPY(); + RAPIDJSON_TRANS(0x10); + RAPIDJSON_TAIL(); + RAPIDJSON_TAIL(); + return result; + case 6: + RAPIDJSON_TAIL(); + RAPIDJSON_TAIL(); + RAPIDJSON_TAIL(); + return result; + case 10: + RAPIDJSON_COPY(); + RAPIDJSON_TRANS(0x20); + RAPIDJSON_TAIL(); + return result; + case 11: + RAPIDJSON_COPY(); + RAPIDJSON_TRANS(0x60); + RAPIDJSON_TAIL(); + RAPIDJSON_TAIL(); + return result; + default: + return false; } #undef RAPIDJSON_COPY #undef RAPIDJSON_TRANS @@ -301,19 +301,17 @@ template struct UTF8 { static CharType TakeBOM(InputByteStream &is) { RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1); typename InputByteStream::Ch c = Take(is); - if (static_cast(c) != 0xEFu) - return c; + if (static_cast(c) != 0xEFu) return c; c = is.Take(); - if (static_cast(c) != 0xBBu) - return c; + if (static_cast(c) != 0xBBu) return c; c = is.Take(); - if (static_cast(c) != 0xBFu) - return c; + if (static_cast(c) != 0xBFu) return c; c = is.Take(); return c; } - template static Ch Take(InputByteStream &is) { + template + static Ch Take(InputByteStream &is) { RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1); return static_cast(is.Take()); } @@ -346,7 +344,8 @@ template struct UTF8 { and code points are represented by CPU's endianness. For streaming, use UTF16LE and UTF16BE, which handle endianness. */ -template struct UTF16 { +template +struct UTF16 { typedef CharType Ch; RAPIDJSON_STATIC_ASSERT(sizeof(Ch) >= 2); @@ -358,7 +357,7 @@ template struct UTF16 { if (codepoint <= 0xFFFF) { RAPIDJSON_ASSERT( codepoint < 0xD800 || - codepoint > 0xDFFF); // Code point itself cannot be surrogate pair + codepoint > 0xDFFF); // Code point itself cannot be surrogate pair os.Put(static_cast(codepoint)); } else { RAPIDJSON_ASSERT(codepoint <= 0x10FFFF); @@ -374,7 +373,7 @@ template struct UTF16 { if (codepoint <= 0xFFFF) { RAPIDJSON_ASSERT( codepoint < 0xD800 || - codepoint > 0xDFFF); // Code point itself cannot be surrogate pair + codepoint > 0xDFFF); // Code point itself cannot be surrogate pair PutUnsafe(os, static_cast(codepoint)); } else { RAPIDJSON_ASSERT(codepoint <= 0x10FFFF); @@ -419,7 +418,8 @@ template struct UTF16 { }; //! UTF-16 little endian encoding. -template struct UTF16LE : UTF16 { +template +struct UTF16LE : UTF16 { template static CharType TakeBOM(InputByteStream &is) { RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1); @@ -453,7 +453,8 @@ template struct UTF16LE : UTF16 { }; //! UTF-16 big endian encoding. -template struct UTF16BE : UTF16 { +template +struct UTF16BE : UTF16 { template static CharType TakeBOM(InputByteStream &is) { RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1); @@ -498,7 +499,8 @@ template struct UTF16BE : UTF16 { and code points are represented by CPU's endianness. For streaming, use UTF32LE and UTF32BE, which handle endianness. */ -template struct UTF32 { +template +struct UTF32 { typedef CharType Ch; RAPIDJSON_STATIC_ASSERT(sizeof(Ch) >= 4); @@ -536,7 +538,8 @@ template struct UTF32 { }; //! UTF-32 little endian enocoding. -template struct UTF32LE : UTF32 { +template +struct UTF32LE : UTF32 { template static CharType TakeBOM(InputByteStream &is) { RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1); @@ -574,7 +577,8 @@ template struct UTF32LE : UTF32 { }; //! UTF-32 big endian encoding. -template struct UTF32BE : UTF32 { +template +struct UTF32BE : UTF32 { template static CharType TakeBOM(InputByteStream &is) { RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1); @@ -619,7 +623,8 @@ template struct UTF32BE : UTF32 { \tparam CharType Code unit for storing 7-bit ASCII data. Default is char. \note implements Encoding concept */ -template struct ASCII { +template +struct ASCII { typedef CharType Ch; enum { supportUnicode = 0 }; @@ -657,7 +662,8 @@ template struct ASCII { return static_cast(c); } - template static Ch Take(InputByteStream &is) { + template + static Ch Take(InputByteStream &is) { RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1); return static_cast(is.Take()); } @@ -680,11 +686,11 @@ template struct ASCII { //! Runtime-specified UTF encoding type of a stream. enum UTFType { - kUTF8 = 0, //!< UTF-8. - kUTF16LE = 1, //!< UTF-16 little endian. - kUTF16BE = 2, //!< UTF-16 big endian. - kUTF32LE = 3, //!< UTF-32 little endian. - kUTF32BE = 4 //!< UTF-32 big endian. + kUTF8 = 0, //!< UTF-8. + kUTF16LE = 1, //!< UTF-16 little endian. + kUTF16BE = 2, //!< UTF-16 big endian. + kUTF32LE = 3, //!< UTF-32 little endian. + kUTF32BE = 4 //!< UTF-32 big endian. }; //! Dynamically select encoding according to stream's runtime-specified UTF @@ -692,12 +698,13 @@ enum UTFType { /*! \note This class can be used with AutoUTFInputtStream and * AutoUTFOutputStream, which provides GetType(). */ -template struct AutoUTF { +template +struct AutoUTF { typedef CharType Ch; enum { supportUnicode = 1 }; -#define RAPIDJSON_ENCODINGS_FUNC(x) \ +#define RAPIDJSON_ENCODINGS_FUNC(x) \ UTF8::x, UTF16LE::x, UTF16BE::x, UTF32LE::x, UTF32BE::x template @@ -739,15 +746,15 @@ template struct AutoUTF { // Transcoder //! Encoding conversion. -template struct Transcoder { +template +struct Transcoder { //! Take one Unicode codepoint from source encoding, convert it to target //! encoding and put it to the output stream. template static RAPIDJSON_FORCEINLINE bool Transcode(InputStream &is, OutputStream &os) { unsigned codepoint; - if (!SourceEncoding::Decode(is, &codepoint)) - return false; + if (!SourceEncoding::Decode(is, &codepoint)) return false; TargetEncoding::Encode(os, codepoint); return true; } @@ -756,8 +763,7 @@ template struct Transcoder { static RAPIDJSON_FORCEINLINE bool TranscodeUnsafe(InputStream &is, OutputStream &os) { unsigned codepoint; - if (!SourceEncoding::Decode(is, &codepoint)) - return false; + if (!SourceEncoding::Decode(is, &codepoint)) return false; TargetEncoding::EncodeUnsafe(os, codepoint); return true; } @@ -767,7 +773,7 @@ template struct Transcoder { static RAPIDJSON_FORCEINLINE bool Validate(InputStream &is, OutputStream &os) { return Transcode( - is, os); // Since source/target encoding is different, must transcode. + is, os); // Since source/target encoding is different, must transcode. } }; @@ -776,27 +782,28 @@ template inline void PutUnsafe(Stream &stream, typename Stream::Ch c); //! Specialization of Transcoder with same source and target encoding. -template struct Transcoder { +template +struct Transcoder { template static RAPIDJSON_FORCEINLINE bool Transcode(InputStream &is, OutputStream &os) { - os.Put(is.Take()); // Just copy one code unit. This semantic is different - // from primary template class. + os.Put(is.Take()); // Just copy one code unit. This semantic is different + // from primary template class. return true; } template static RAPIDJSON_FORCEINLINE bool TranscodeUnsafe(InputStream &is, OutputStream &os) { - PutUnsafe(os, is.Take()); // Just copy one code unit. This semantic is - // different from primary template class. + PutUnsafe(os, is.Take()); // Just copy one code unit. This semantic is + // different from primary template class. return true; } template static RAPIDJSON_FORCEINLINE bool Validate(InputStream &is, OutputStream &os) { - return Encoding::Validate(is, os); // source/target encoding are the same + return Encoding::Validate(is, os); // source/target encoding are the same } }; @@ -806,4 +813,4 @@ RAPIDJSON_NAMESPACE_END RAPIDJSON_DIAG_POP #endif -#endif // RAPIDJSON_ENCODINGS_H_ +#endif // RAPIDJSON_ENCODINGS_H_ diff --git a/livox_ros_driver/common/rapidjson/error/en.h b/livox_ros_driver/common/rapidjson/error/en.h index c8f1fcb..a08145d 100644 --- a/livox_ros_driver/common/rapidjson/error/en.h +++ b/livox_ros_driver/common/rapidjson/error/en.h @@ -37,61 +37,61 @@ RAPIDJSON_NAMESPACE_BEGIN \note User can make a copy of this function for localization. Using switch-case is safer for future modification of error codes. */ -inline const RAPIDJSON_ERROR_CHARTYPE * -GetParseError_En(ParseErrorCode parseErrorCode) { +inline const RAPIDJSON_ERROR_CHARTYPE* GetParseError_En( + ParseErrorCode parseErrorCode) { switch (parseErrorCode) { - case kParseErrorNone: - return RAPIDJSON_ERROR_STRING("No error."); - - case kParseErrorDocumentEmpty: - return RAPIDJSON_ERROR_STRING("The document is empty."); - case kParseErrorDocumentRootNotSingular: - return RAPIDJSON_ERROR_STRING( - "The document root must not be followed by other values."); - - case kParseErrorValueInvalid: - return RAPIDJSON_ERROR_STRING("Invalid value."); - - case kParseErrorObjectMissName: - return RAPIDJSON_ERROR_STRING("Missing a name for object member."); - case kParseErrorObjectMissColon: - return RAPIDJSON_ERROR_STRING( - "Missing a colon after a name of object member."); - case kParseErrorObjectMissCommaOrCurlyBracket: - return RAPIDJSON_ERROR_STRING( - "Missing a comma or '}' after an object member."); - - case kParseErrorArrayMissCommaOrSquareBracket: - return RAPIDJSON_ERROR_STRING( - "Missing a comma or ']' after an array element."); - - case kParseErrorStringUnicodeEscapeInvalidHex: - return RAPIDJSON_ERROR_STRING( - "Incorrect hex digit after \\u escape in string."); - case kParseErrorStringUnicodeSurrogateInvalid: - return RAPIDJSON_ERROR_STRING("The surrogate pair in string is invalid."); - case kParseErrorStringEscapeInvalid: - return RAPIDJSON_ERROR_STRING("Invalid escape character in string."); - case kParseErrorStringMissQuotationMark: - return RAPIDJSON_ERROR_STRING( - "Missing a closing quotation mark in string."); - case kParseErrorStringInvalidEncoding: - return RAPIDJSON_ERROR_STRING("Invalid encoding in string."); - - case kParseErrorNumberTooBig: - return RAPIDJSON_ERROR_STRING("Number too big to be stored in double."); - case kParseErrorNumberMissFraction: - return RAPIDJSON_ERROR_STRING("Miss fraction part in number."); - case kParseErrorNumberMissExponent: - return RAPIDJSON_ERROR_STRING("Miss exponent in number."); - - case kParseErrorTermination: - return RAPIDJSON_ERROR_STRING("Terminate parsing due to Handler error."); - case kParseErrorUnspecificSyntaxError: - return RAPIDJSON_ERROR_STRING("Unspecific syntax error."); - - default: - return RAPIDJSON_ERROR_STRING("Unknown error."); + case kParseErrorNone: + return RAPIDJSON_ERROR_STRING("No error."); + + case kParseErrorDocumentEmpty: + return RAPIDJSON_ERROR_STRING("The document is empty."); + case kParseErrorDocumentRootNotSingular: + return RAPIDJSON_ERROR_STRING( + "The document root must not be followed by other values."); + + case kParseErrorValueInvalid: + return RAPIDJSON_ERROR_STRING("Invalid value."); + + case kParseErrorObjectMissName: + return RAPIDJSON_ERROR_STRING("Missing a name for object member."); + case kParseErrorObjectMissColon: + return RAPIDJSON_ERROR_STRING( + "Missing a colon after a name of object member."); + case kParseErrorObjectMissCommaOrCurlyBracket: + return RAPIDJSON_ERROR_STRING( + "Missing a comma or '}' after an object member."); + + case kParseErrorArrayMissCommaOrSquareBracket: + return RAPIDJSON_ERROR_STRING( + "Missing a comma or ']' after an array element."); + + case kParseErrorStringUnicodeEscapeInvalidHex: + return RAPIDJSON_ERROR_STRING( + "Incorrect hex digit after \\u escape in string."); + case kParseErrorStringUnicodeSurrogateInvalid: + return RAPIDJSON_ERROR_STRING("The surrogate pair in string is invalid."); + case kParseErrorStringEscapeInvalid: + return RAPIDJSON_ERROR_STRING("Invalid escape character in string."); + case kParseErrorStringMissQuotationMark: + return RAPIDJSON_ERROR_STRING( + "Missing a closing quotation mark in string."); + case kParseErrorStringInvalidEncoding: + return RAPIDJSON_ERROR_STRING("Invalid encoding in string."); + + case kParseErrorNumberTooBig: + return RAPIDJSON_ERROR_STRING("Number too big to be stored in double."); + case kParseErrorNumberMissFraction: + return RAPIDJSON_ERROR_STRING("Miss fraction part in number."); + case kParseErrorNumberMissExponent: + return RAPIDJSON_ERROR_STRING("Miss exponent in number."); + + case kParseErrorTermination: + return RAPIDJSON_ERROR_STRING("Terminate parsing due to Handler error."); + case kParseErrorUnspecificSyntaxError: + return RAPIDJSON_ERROR_STRING("Unspecific syntax error."); + + default: + return RAPIDJSON_ERROR_STRING("Unknown error."); } } @@ -101,4 +101,4 @@ RAPIDJSON_NAMESPACE_END RAPIDJSON_DIAG_POP #endif -#endif // RAPIDJSON_ERROR_EN_H_ +#endif // RAPIDJSON_ERROR_EN_H_ diff --git a/livox_ros_driver/common/rapidjson/error/error.h b/livox_ros_driver/common/rapidjson/error/error.h index 7239528..4814b69 100644 --- a/livox_ros_driver/common/rapidjson/error/error.h +++ b/livox_ros_driver/common/rapidjson/error/error.h @@ -66,38 +66,41 @@ RAPIDJSON_NAMESPACE_BEGIN \see GenericReader::Parse, GenericReader::GetParseErrorCode */ enum ParseErrorCode { - kParseErrorNone = 0, //!< No error. - - kParseErrorDocumentEmpty, //!< The document is empty. - kParseErrorDocumentRootNotSingular, //!< The document root must not follow by - //!< other values. - - kParseErrorValueInvalid, //!< Invalid value. - - kParseErrorObjectMissName, //!< Missing a name for object member. - kParseErrorObjectMissColon, //!< Missing a colon after a name of object - //!< member. - kParseErrorObjectMissCommaOrCurlyBracket, //!< Missing a comma or '}' after an - //!< object member. - - kParseErrorArrayMissCommaOrSquareBracket, //!< Missing a comma or ']' after an - //!< array element. - - kParseErrorStringUnicodeEscapeInvalidHex, //!< Incorrect hex digit after \\u - //!< escape in string. - kParseErrorStringUnicodeSurrogateInvalid, //!< The surrogate pair in string is - //!< invalid. - kParseErrorStringEscapeInvalid, //!< Invalid escape character in string. - kParseErrorStringMissQuotationMark, //!< Missing a closing quotation mark in - //!< string. - kParseErrorStringInvalidEncoding, //!< Invalid encoding in string. - - kParseErrorNumberTooBig, //!< Number too big to be stored in double. - kParseErrorNumberMissFraction, //!< Miss fraction part in number. - kParseErrorNumberMissExponent, //!< Miss exponent in number. - - kParseErrorTermination, //!< Parsing was terminated. - kParseErrorUnspecificSyntaxError //!< Unspecific syntax error. + kParseErrorNone = 0, //!< No error. + + kParseErrorDocumentEmpty, //!< The document is empty. + kParseErrorDocumentRootNotSingular, //!< The document root must not follow by + //!< other values. + + kParseErrorValueInvalid, //!< Invalid value. + + kParseErrorObjectMissName, //!< Missing a name for object member. + kParseErrorObjectMissColon, //!< Missing a colon after a name of object + //!< member. + kParseErrorObjectMissCommaOrCurlyBracket, //!< Missing a comma or '}' after + //!an + //!< object member. + + kParseErrorArrayMissCommaOrSquareBracket, //!< Missing a comma or ']' after + //!an + //!< array element. + + kParseErrorStringUnicodeEscapeInvalidHex, //!< Incorrect hex digit after \\u + //!< escape in string. + kParseErrorStringUnicodeSurrogateInvalid, //!< The surrogate pair in string + //!is + //!< invalid. + kParseErrorStringEscapeInvalid, //!< Invalid escape character in string. + kParseErrorStringMissQuotationMark, //!< Missing a closing quotation mark in + //!< string. + kParseErrorStringInvalidEncoding, //!< Invalid encoding in string. + + kParseErrorNumberTooBig, //!< Number too big to be stored in double. + kParseErrorNumberMissFraction, //!< Miss fraction part in number. + kParseErrorNumberMissExponent, //!< Miss exponent in number. + + kParseErrorTermination, //!< Parsing was terminated. + kParseErrorUnspecificSyntaxError //!< Unspecific syntax error. }; //! Result of parsing (wraps ParseErrorCode) @@ -118,7 +121,7 @@ struct ParseResult { //!! Unspecified boolean type typedef bool (ParseResult::*BooleanType)() const; -public: + public: //! Default constructor, no error. ParseResult() : code_(kParseErrorNone), offset_(0) {} //! Constructor to set an error. @@ -157,7 +160,7 @@ struct ParseResult { offset_ = offset; } -private: + private: ParseErrorCode code_; size_t offset_; }; @@ -180,4 +183,4 @@ RAPIDJSON_NAMESPACE_END RAPIDJSON_DIAG_POP #endif -#endif // RAPIDJSON_ERROR_ERROR_H_ +#endif // RAPIDJSON_ERROR_ERROR_H_ diff --git a/livox_ros_driver/common/rapidjson/filereadstream.h b/livox_ros_driver/common/rapidjson/filereadstream.h index afbe5e0..250aabb 100644 --- a/livox_ros_driver/common/rapidjson/filereadstream.h +++ b/livox_ros_driver/common/rapidjson/filereadstream.h @@ -19,8 +19,8 @@ #ifndef RAPIDJSON_FILEREADSTREAM_H_ #define RAPIDJSON_FILEREADSTREAM_H_ -#include "stream.h" #include +#include "stream.h" #ifdef __clang__ RAPIDJSON_DIAG_PUSH @@ -36,8 +36,8 @@ RAPIDJSON_NAMESPACE_BEGIN \note implements Stream concept */ class FileReadStream { -public: - typedef char Ch; //!< Character type (byte). + public: + typedef char Ch; //!< Character type (byte). //! Constructor. /*! @@ -46,8 +46,14 @@ class FileReadStream { \param bufferSize size of buffer in bytes. Must >=4 bytes. */ 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) { + : fp_(fp), + buffer_(buffer), + bufferSize_(bufferSize), + bufferLast_(0), + current_(buffer_), + readCount_(0), + count_(0), + eof_(false) { RAPIDJSON_ASSERT(fp_ != 0); RAPIDJSON_ASSERT(bufferSize >= 4); Read(); @@ -80,7 +86,7 @@ class FileReadStream { return (current_ + 4 - !eof_ <= bufferLast_) ? current_ : 0; } -private: + private: void Read() { if (current_ < bufferLast_) ++current_; @@ -104,7 +110,7 @@ class FileReadStream { Ch *bufferLast_; Ch *current_; size_t readCount_; - size_t count_; //!< Number of characters read + size_t count_; //!< Number of characters read bool eof_; }; @@ -114,4 +120,4 @@ RAPIDJSON_NAMESPACE_END RAPIDJSON_DIAG_POP #endif -#endif // RAPIDJSON_FILESTREAM_H_ +#endif // RAPIDJSON_FILESTREAM_H_ diff --git a/livox_ros_driver/common/rapidjson/filewritestream.h b/livox_ros_driver/common/rapidjson/filewritestream.h index 6890fe2..f6defc1 100644 --- a/livox_ros_driver/common/rapidjson/filewritestream.h +++ b/livox_ros_driver/common/rapidjson/filewritestream.h @@ -19,8 +19,8 @@ #ifndef RAPIDJSON_FILEWRITESTREAM_H_ #define RAPIDJSON_FILEWRITESTREAM_H_ -#include "stream.h" #include +#include "stream.h" #ifdef __clang__ RAPIDJSON_DIAG_PUSH @@ -34,18 +34,19 @@ RAPIDJSON_NAMESPACE_BEGIN \note implements Stream concept */ class FileWriteStream { -public: - typedef char Ch; //!< Character type. Only support char. + public: + typedef char Ch; //!< Character type. Only support char. FileWriteStream(std::FILE *fp, char *buffer, size_t bufferSize) - : fp_(fp), buffer_(buffer), bufferEnd_(buffer + bufferSize), + : fp_(fp), + buffer_(buffer), + bufferEnd_(buffer + bufferSize), current_(buffer_) { RAPIDJSON_ASSERT(fp_ != 0); } void Put(char c) { - if (current_ >= bufferEnd_) - Flush(); + if (current_ >= bufferEnd_) Flush(); *current_++ = c; } @@ -100,7 +101,7 @@ class FileWriteStream { return 0; } -private: + private: // Prohibit copy constructor & assignment operator. FileWriteStream(const FileWriteStream &); FileWriteStream &operator=(const FileWriteStream &); @@ -113,7 +114,8 @@ class FileWriteStream { //! Implement specialized version of PutN() with memset() for better //! performance. -template <> inline void PutN(FileWriteStream &stream, char c, size_t n) { +template <> +inline void PutN(FileWriteStream &stream, char c, size_t n) { stream.PutN(c, n); } @@ -123,4 +125,4 @@ RAPIDJSON_NAMESPACE_END RAPIDJSON_DIAG_POP #endif -#endif // RAPIDJSON_FILESTREAM_H_ +#endif // RAPIDJSON_FILESTREAM_H_ diff --git a/livox_ros_driver/common/rapidjson/fwd.h b/livox_ros_driver/common/rapidjson/fwd.h index 09b31c7..cafb48e 100644 --- a/livox_ros_driver/common/rapidjson/fwd.h +++ b/livox_ros_driver/common/rapidjson/fwd.h @@ -25,37 +25,51 @@ RAPIDJSON_NAMESPACE_BEGIN // encodings.h -template struct UTF8; -template struct UTF16; -template struct UTF16BE; -template struct UTF16LE; -template struct UTF32; -template struct UTF32BE; -template struct UTF32LE; -template struct ASCII; -template struct AutoUTF; - -template struct Transcoder; +template +struct UTF8; +template +struct UTF16; +template +struct UTF16BE; +template +struct UTF16LE; +template +struct UTF32; +template +struct UTF32BE; +template +struct UTF32LE; +template +struct ASCII; +template +struct AutoUTF; + +template +struct Transcoder; // allocators.h class CrtAllocator; -template class MemoryPoolAllocator; +template +class MemoryPoolAllocator; // stream.h -template struct GenericStringStream; +template +struct GenericStringStream; typedef GenericStringStream> StringStream; -template struct GenericInsituStringStream; +template +struct GenericInsituStringStream; typedef GenericInsituStringStream> InsituStringStream; // stringbuffer.h -template class GenericStringBuffer; +template +class GenericStringBuffer; typedef GenericStringBuffer, CrtAllocator> StringBuffer; @@ -69,7 +83,8 @@ class FileWriteStream; // memorybuffer.h -template struct GenericMemoryBuffer; +template +struct GenericMemoryBuffer; typedef GenericMemoryBuffer MemoryBuffer; @@ -79,7 +94,8 @@ struct MemoryStream; // reader.h -template struct BaseReaderHandler; +template +struct BaseReaderHandler; template @@ -101,14 +117,17 @@ class PrettyWriter; // document.h -template class GenericMember; +template +class GenericMember; template class GenericMemberIterator; -template struct GenericStringRef; +template +struct GenericStringRef; -template class GenericValue; +template +class GenericValue; typedef GenericValue, MemoryPoolAllocator> Value; @@ -121,7 +140,8 @@ typedef GenericDocument, MemoryPoolAllocator, // pointer.h -template class GenericPointer; +template +class GenericPointer; typedef GenericPointer Pointer; @@ -130,7 +150,8 @@ typedef GenericPointer Pointer; template class IGenericRemoteSchemaDocumentProvider; -template class GenericSchemaDocument; +template +class GenericSchemaDocument; typedef GenericSchemaDocument SchemaDocument; typedef IGenericRemoteSchemaDocumentProvider @@ -146,4 +167,4 @@ typedef GenericSchemaValidator< RAPIDJSON_NAMESPACE_END -#endif // RAPIDJSON_RAPIDJSONFWD_H_ +#endif // RAPIDJSON_RAPIDJSONFWD_H_ diff --git a/livox_ros_driver/common/rapidjson/internal/biginteger.h b/livox_ros_driver/common/rapidjson/internal/biginteger.h index fcd2096..b60e006 100644 --- a/livox_ros_driver/common/rapidjson/internal/biginteger.h +++ b/livox_ros_driver/common/rapidjson/internal/biginteger.h @@ -22,7 +22,7 @@ #include "../rapidjson.h" #if defined(_MSC_VER) && !__INTEL_COMPILER && defined(_M_AMD64) -#include // for _umul128 +#include // for _umul128 #pragma intrinsic(_umul128) #endif @@ -30,7 +30,7 @@ RAPIDJSON_NAMESPACE_BEGIN namespace internal { class BigInteger { -public: + public: typedef uint64_t Type; BigInteger(const BigInteger &rhs) : count_(rhs.count_) { @@ -44,15 +44,14 @@ class BigInteger { digits_[0] = 0; size_t i = 0; const size_t kMaxDigitPerIteration = - 19; // 2^64 = 18446744073709551616 > 10^19 + 19; // 2^64 = 18446744073709551616 > 10^19 while (length >= kMaxDigitPerIteration) { AppendDecimal64(decimals + i, decimals + i + kMaxDigitPerIteration); length -= kMaxDigitPerIteration; i += kMaxDigitPerIteration; } - if (length > 0) - AppendDecimal64(decimals + i, decimals + i + length); + if (length > 0) AppendDecimal64(decimals + i, decimals + i + length); } BigInteger &operator=(const BigInteger &rhs) { @@ -73,26 +72,21 @@ class BigInteger { Type backup = digits_[0]; digits_[0] += u; for (size_t i = 0; i < count_ - 1; i++) { - if (digits_[i] >= backup) - return *this; // no carry + if (digits_[i] >= backup) return *this; // no carry backup = digits_[i + 1]; digits_[i + 1] += 1; } // Last carry - if (digits_[count_ - 1] < backup) - PushBack(1); + if (digits_[count_ - 1] < backup) PushBack(1); return *this; } BigInteger &operator*=(uint64_t u) { - if (u == 0) - return *this = 0; - if (u == 1) - return *this; - if (*this == 1) - return *this = u; + if (u == 0) return *this = 0; + if (u == 1) return *this; + if (*this == 1) return *this = u; uint64_t k = 0; for (size_t i = 0; i < count_; i++) { @@ -101,19 +95,15 @@ class BigInteger { k = hi; } - if (k > 0) - PushBack(k); + if (k > 0) PushBack(k); return *this; } BigInteger &operator*=(uint32_t u) { - if (u == 0) - return *this = 0; - if (u == 1) - return *this; - if (*this == 1) - return *this = u; + if (u == 0) return *this = 0; + if (u == 1) return *this; + if (*this == 1) return *this = u; uint64_t k = 0; for (size_t i = 0; i < count_; i++) { @@ -127,15 +117,13 @@ class BigInteger { k = p1 >> 32; } - if (k > 0) - PushBack(k); + if (k > 0) PushBack(k); return *this; } BigInteger &operator<<=(size_t shift) { - if (IsZero() || shift == 0) - return *this; + if (IsZero() || shift == 0) return *this; size_t offset = shift / kTypeBit; size_t interShift = shift % kTypeBit; @@ -151,8 +139,7 @@ class BigInteger { (digits_[i - 1] >> (kTypeBit - interShift)); digits_[offset] = digits_[0] << interShift; count_ += offset; - if (digits_[count_]) - count_++; + if (digits_[count_]) count_++; } std::memset(digits_, 0, offset * sizeof(Type)); @@ -183,14 +170,12 @@ class BigInteger { 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5, 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5, 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5}; - if (exp == 0) - return *this; + if (exp == 0) return *this; for (; exp >= 27; exp -= 27) - *this *= RAPIDJSON_UINT64_C2(0X6765C793, 0XFA10079D); // 5^27 + *this *= RAPIDJSON_UINT64_C2(0X6765C793, 0XFA10079D); // 5^27 for (; exp >= 13; exp -= 13) - *this *= static_cast(1220703125u); // 5^13 - if (exp > 0) - *this *= kPow5[exp - 1]; + *this *= static_cast(1220703125u); // 5^13 + if (exp > 0) *this *= kPow5[exp - 1]; return *this; } @@ -199,7 +184,7 @@ class BigInteger { bool Difference(const BigInteger &rhs, BigInteger *out) const { int cmp = Compare(rhs); RAPIDJSON_ASSERT(cmp != 0); - const BigInteger *a, *b; // Makes a > b + const BigInteger *a, *b; // Makes a > b bool ret; if (cmp < 0) { a = &rhs; @@ -214,20 +199,17 @@ class BigInteger { Type borrow = 0; for (size_t i = 0; i < a->count_; i++) { Type d = a->digits_[i] - borrow; - if (i < b->count_) - d -= b->digits_[i]; + if (i < b->count_) d -= b->digits_[i]; borrow = (d > a->digits_[i]) ? 1 : 0; out->digits_[i] = d; - if (d != 0) - out->count_ = i + 1; + if (d != 0) out->count_ = i + 1; } return ret; } int Compare(const BigInteger &rhs) const { - if (count_ != rhs.count_) - return count_ < rhs.count_ ? -1 : 1; + if (count_ != rhs.count_) return count_ < rhs.count_ ? -1 : 1; for (size_t i = count_; i-- > 0;) if (digits_[i] != rhs.digits_[i]) @@ -243,14 +225,14 @@ class BigInteger { } bool IsZero() const { return count_ == 1 && digits_[0] == 0; } -private: + private: void AppendDecimal64(const char *begin, const char *end) { uint64_t u = ParseUint64(begin, end); if (IsZero()) *this = u; else { unsigned exp = static_cast(end - begin); - (MultiplyPow5(exp) <<= exp) += u; // *this = *this * 10^exp + u + (MultiplyPow5(exp) <<= exp) += u; // *this = *this * 10^exp + u } } @@ -273,10 +255,9 @@ class BigInteger { uint64_t *outHigh) { #if defined(_MSC_VER) && defined(_M_AMD64) uint64_t low = _umul128(a, b, outHigh) + k; - if (low < k) - (*outHigh)++; + if (low < k) (*outHigh)++; return low; -#elif (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) && \ +#elif (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) && \ defined(__x86_64__) __extension__ typedef unsigned __int128 uint128; uint128 p = static_cast(a) * static_cast(b); @@ -287,22 +268,20 @@ class BigInteger { const uint64_t a0 = a & 0xFFFFFFFF, a1 = a >> 32, b0 = b & 0xFFFFFFFF, b1 = b >> 32; uint64_t x0 = a0 * b0, x1 = a0 * b1, x2 = a1 * b0, x3 = a1 * b1; - x1 += (x0 >> 32); // can't give carry + x1 += (x0 >> 32); // can't give carry x1 += x2; - if (x1 < x2) - x3 += (static_cast(1) << 32); + if (x1 < x2) x3 += (static_cast(1) << 32); uint64_t lo = (x1 << 32) + (x0 & 0xFFFFFFFF); uint64_t hi = x3 + (x1 >> 32); lo += k; - if (lo < k) - hi++; + if (lo < k) hi++; *outHigh = hi; return lo; #endif } - static const size_t kBitCount = 3328; // 64bit * 54 > 10^1000 + static const size_t kBitCount = 3328; // 64bit * 54 > 10^1000 static const size_t kCapacity = kBitCount / sizeof(Type); static const size_t kTypeBit = sizeof(Type) * 8; @@ -310,7 +289,7 @@ class BigInteger { size_t count_; }; -} // namespace internal +} // namespace internal RAPIDJSON_NAMESPACE_END -#endif // RAPIDJSON_BIGINTEGER_H_ +#endif // RAPIDJSON_BIGINTEGER_H_ diff --git a/livox_ros_driver/common/rapidjson/internal/clzll.h b/livox_ros_driver/common/rapidjson/internal/clzll.h index 34e20d0..8cb8b8a 100644 --- a/livox_ros_driver/common/rapidjson/internal/clzll.h +++ b/livox_ros_driver/common/rapidjson/internal/clzll.h @@ -33,7 +33,7 @@ RAPIDJSON_NAMESPACE_BEGIN namespace internal { -#if (defined(__GNUC__) && __GNUC__ >= 4) || \ +#if (defined(__GNUC__) && __GNUC__ >= 4) || \ RAPIDJSON_HAS_BUILTIN(__builtin_clzll) #define RAPIDJSON_CLZLL __builtin_clzll #else @@ -49,12 +49,11 @@ inline uint32_t clzll(uint64_t x) { _BitScanReverse64(&r, x); #else // Scan the high 32 bits. - if (_BitScanReverse(&r, static_cast(x >> 32))) - return 63 - (r + 32); + if (_BitScanReverse(&r, static_cast(x >> 32))) return 63 - (r + 32); // Scan the low 32 bits. _BitScanReverse(&r, static_cast(x & 0xFFFFFFFF)); -#endif // _WIN64 +#endif // _WIN64 return 63 - r; #else @@ -65,14 +64,14 @@ inline uint32_t clzll(uint64_t x) { } return r; -#endif // _MSC_VER +#endif // _MSC_VER } #define RAPIDJSON_CLZLL RAPIDJSON_NAMESPACE::internal::clzll -#endif // (defined(__GNUC__) && __GNUC__ >= 4) || - // RAPIDJSON_HAS_BUILTIN(__builtin_clzll) +#endif // (defined(__GNUC__) && __GNUC__ >= 4) || + // RAPIDJSON_HAS_BUILTIN(__builtin_clzll) -} // namespace internal +} // namespace internal RAPIDJSON_NAMESPACE_END -#endif // RAPIDJSON_CLZLL_H_ \ No newline at end of file +#endif // RAPIDJSON_CLZLL_H_ \ No newline at end of file diff --git a/livox_ros_driver/common/rapidjson/internal/diyfp.h b/livox_ros_driver/common/rapidjson/internal/diyfp.h index 9876f6a..bed2989 100644 --- a/livox_ros_driver/common/rapidjson/internal/diyfp.h +++ b/livox_ros_driver/common/rapidjson/internal/diyfp.h @@ -23,9 +23,9 @@ #ifndef RAPIDJSON_DIYFP_H_ #define RAPIDJSON_DIYFP_H_ +#include #include "../rapidjson.h" #include "clzll.h" -#include #if defined(_MSC_VER) && defined(_M_AMD64) && !defined(__INTEL_COMPILER) #include @@ -74,16 +74,16 @@ struct DiyFp { #if defined(_MSC_VER) && defined(_M_AMD64) uint64_t h; uint64_t l = _umul128(f, rhs.f, &h); - if (l & (uint64_t(1) << 63)) // rounding + if (l & (uint64_t(1) << 63)) // rounding h++; return DiyFp(h, e + rhs.e + 64); -#elif (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) && \ +#elif (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) && \ defined(__x86_64__) __extension__ typedef unsigned __int128 uint128; uint128 p = static_cast(f) * static_cast(rhs.f); uint64_t h = static_cast(p >> 64); uint64_t l = static_cast(p); - if (l & (uint64_t(1) << 63)) // rounding + if (l & (uint64_t(1) << 63)) // rounding h++; return DiyFp(h, e + rhs.e + 64); #else @@ -97,7 +97,7 @@ struct DiyFp { const uint64_t ad = a * d; const uint64_t bd = b * d; uint64_t tmp = (bd >> 32) + (ad & M32) + (bc & M32); - tmp += 1U << 31; /// mult_round + tmp += 1U << 31; /// mult_round return DiyFp(ac + (ad >> 32) + (bc >> 32) + (tmp >> 32), e + rhs.e + 64); #endif } @@ -270,17 +270,15 @@ inline DiyFp GetCachedPowerByIndex(size_t index) { } inline DiyFp GetCachedPower(int e, int *K) { - // int k = static_cast(ceil((-61 - e) * 0.30102999566398114)) + 374; double dk = (-61 - e) * 0.30102999566398114 + - 347; // dk must be positive, so can do ceiling in positive + 347; // dk must be positive, so can do ceiling in positive int k = static_cast(dk); - if (dk - k > 0.0) - k++; + if (dk - k > 0.0) k++; unsigned index = static_cast((k >> 3) + 1); - *K = -(-348 + - static_cast(index << 3)); // decimal exponent no need lookup table + *K = -(-348 + static_cast( + index << 3)); // decimal exponent no need lookup table return GetCachedPowerByIndex(index); } @@ -301,7 +299,7 @@ RAPIDJSON_DIAG_POP RAPIDJSON_DIAG_OFF(padded) #endif -} // namespace internal +} // namespace internal RAPIDJSON_NAMESPACE_END -#endif // RAPIDJSON_DIYFP_H_ +#endif // RAPIDJSON_DIYFP_H_ diff --git a/livox_ros_driver/common/rapidjson/internal/dtoa.h b/livox_ros_driver/common/rapidjson/internal/dtoa.h index 023f762..b64a79d 100644 --- a/livox_ros_driver/common/rapidjson/internal/dtoa.h +++ b/livox_ros_driver/common/rapidjson/internal/dtoa.h @@ -25,7 +25,7 @@ #include "diyfp.h" #include "ieee754.h" -#include "itoa.h" // GetDigitsLut() +#include "itoa.h" // GetDigitsLut() RAPIDJSON_NAMESPACE_BEGIN namespace internal { @@ -33,15 +33,14 @@ namespace internal { #ifdef __GNUC__ RAPIDJSON_DIAG_PUSH RAPIDJSON_DIAG_OFF(effc++) -RAPIDJSON_DIAG_OFF(array - - bounds) // some gcc versions generate wrong warnings - // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=59124 +RAPIDJSON_DIAG_OFF(array - bounds) // some gcc versions generate wrong warnings +// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=59124 #endif inline void GrisuRound(char *buffer, int len, uint64_t delta, uint64_t rest, uint64_t ten_kappa, uint64_t wp_w) { while (rest < wp_w && delta - rest >= ten_kappa && - (rest + ten_kappa < wp_w || /// closer + (rest + ten_kappa < wp_w || /// closer wp_w - rest > rest + ten_kappa - wp_w)) { buffer[len - 1]--; rest += ten_kappa; @@ -51,22 +50,14 @@ inline void GrisuRound(char *buffer, int len, uint64_t delta, uint64_t rest, inline int CountDecimalDigit32(uint32_t n) { // Simple pure C++ implementation was faster than __builtin_clz version in // this situation. - if (n < 10) - return 1; - if (n < 100) - return 2; - if (n < 1000) - return 3; - if (n < 10000) - return 4; - if (n < 100000) - return 5; - if (n < 1000000) - return 6; - if (n < 10000000) - return 7; - if (n < 100000000) - return 8; + if (n < 10) return 1; + if (n < 100) return 2; + if (n < 1000) return 3; + if (n < 10000) return 4; + if (n < 100000) return 5; + if (n < 1000000) return 6; + if (n < 10000000) return 7; + if (n < 100000000) return 8; // Will not reach 10 digits in DigitGen() // if (n < 1000000000) return 9; // return 10; @@ -82,49 +73,49 @@ inline void DigitGen(const DiyFp &W, const DiyFp &Mp, uint64_t delta, const DiyFp wp_w = Mp - W; uint32_t p1 = static_cast(Mp.f >> -one.e); uint64_t p2 = Mp.f & (one.f - 1); - int kappa = CountDecimalDigit32(p1); // kappa in [0, 9] + int kappa = CountDecimalDigit32(p1); // kappa in [0, 9] *len = 0; while (kappa > 0) { uint32_t d = 0; switch (kappa) { - case 9: - d = p1 / 100000000; - p1 %= 100000000; - break; - case 8: - d = p1 / 10000000; - p1 %= 10000000; - break; - case 7: - d = p1 / 1000000; - p1 %= 1000000; - break; - case 6: - d = p1 / 100000; - p1 %= 100000; - break; - case 5: - d = p1 / 10000; - p1 %= 10000; - break; - case 4: - d = p1 / 1000; - p1 %= 1000; - break; - case 3: - d = p1 / 100; - p1 %= 100; - break; - case 2: - d = p1 / 10; - p1 %= 10; - break; - case 1: - d = p1; - p1 = 0; - break; - default:; + case 9: + d = p1 / 100000000; + p1 %= 100000000; + break; + case 8: + d = p1 / 10000000; + p1 %= 10000000; + break; + case 7: + d = p1 / 1000000; + p1 %= 1000000; + break; + case 6: + d = p1 / 100000; + p1 %= 100000; + break; + case 5: + d = p1 / 10000; + p1 %= 10000; + break; + case 4: + d = p1 / 1000; + p1 %= 1000; + break; + case 3: + d = p1 / 100; + p1 %= 100; + break; + case 2: + d = p1 / 10; + p1 %= 10; + break; + case 1: + d = p1; + p1 = 0; + break; + default:; } if (d || *len) buffer[(*len)++] = static_cast('0' + static_cast(d)); @@ -143,8 +134,7 @@ inline void DigitGen(const DiyFp &W, const DiyFp &Mp, uint64_t delta, p2 *= 10; delta *= 10; char d = static_cast(p2 >> -one.e); - if (d || *len) - buffer[(*len)++] = static_cast('0' + d); + if (d || *len) buffer[(*len)++] = static_cast('0' + d); p2 &= one.f - 1; kappa--; if (p2 < delta) { @@ -194,12 +184,11 @@ inline char *WriteExponent(int K, char *buffer) { } inline char *Prettify(char *buffer, int length, int k, int maxDecimalPlaces) { - const int kk = length + k; // 10^(kk-1) <= v < 10^kk + const int kk = length + k; // 10^(kk-1) <= v < 10^kk if (0 <= k && kk <= 21) { // 1234e7 -> 12340000000 - for (int i = length; i < kk; i++) - buffer[i] = '0'; + for (int i = length; i < kk; i++) buffer[i] = '0'; buffer[kk] = '.'; buffer[kk + 1] = '0'; return &buffer[kk + 2]; @@ -212,9 +201,8 @@ inline char *Prettify(char *buffer, int length, int k, int maxDecimalPlaces) { // When maxDecimalPlaces = 2, 1.2345 -> 1.23, 1.102 -> 1.1 // Remove extra trailing zeros (at least one) after truncation. for (int i = kk + maxDecimalPlaces; i > kk + 1; i--) - if (buffer[i] != '0') - return &buffer[i + 1]; - return &buffer[kk + 2]; // Reserve one zero + if (buffer[i] != '0') return &buffer[i + 1]; + return &buffer[kk + 2]; // Reserve one zero } else return &buffer[length + 1]; } else if (-6 < kk && kk <= 0) { @@ -223,15 +211,13 @@ inline char *Prettify(char *buffer, int length, int k, int maxDecimalPlaces) { std::memmove(&buffer[offset], &buffer[0], static_cast(length)); buffer[0] = '0'; buffer[1] = '.'; - for (int i = 2; i < offset; i++) - buffer[i] = '0'; + for (int i = 2; i < offset; i++) buffer[i] = '0'; if (length - kk > maxDecimalPlaces) { // When maxDecimalPlaces = 2, 0.123 -> 0.12, 0.102 -> 0.1 // Remove extra trailing zeros (at least one) after truncation. for (int i = maxDecimalPlaces + 1; i > 2; i--) - if (buffer[i] != '0') - return &buffer[i + 1]; - return &buffer[3]; // Reserve one zero + if (buffer[i] != '0') return &buffer[i + 1]; + return &buffer[3]; // Reserve one zero } else return &buffer[length + offset]; } else if (kk < -maxDecimalPlaces) { @@ -257,8 +243,7 @@ inline char *dtoa(double value, char *buffer, int maxDecimalPlaces = 324) { RAPIDJSON_ASSERT(maxDecimalPlaces >= 1); Double d(value); if (d.IsZero()) { - if (d.Sign()) - *buffer++ = '-'; // -0.0, Issue #289 + if (d.Sign()) *buffer++ = '-'; // -0.0, Issue #289 buffer[0] = '0'; buffer[1] = '.'; buffer[2] = '0'; @@ -278,7 +263,7 @@ inline char *dtoa(double value, char *buffer, int maxDecimalPlaces = 324) { RAPIDJSON_DIAG_POP #endif -} // namespace internal +} // namespace internal RAPIDJSON_NAMESPACE_END -#endif // RAPIDJSON_DTOA_ +#endif // RAPIDJSON_DTOA_ diff --git a/livox_ros_driver/common/rapidjson/internal/ieee754.h b/livox_ros_driver/common/rapidjson/internal/ieee754.h index ca16659..246c4ac 100644 --- a/livox_ros_driver/common/rapidjson/internal/ieee754.h +++ b/livox_ros_driver/common/rapidjson/internal/ieee754.h @@ -25,7 +25,7 @@ RAPIDJSON_NAMESPACE_BEGIN namespace internal { class Double { -public: + public: Double() {} Double(double d) : d_(d) {} Double(uint64_t u) : u_(u) {} @@ -76,7 +76,7 @@ class Double { return order + 1074; } -private: + private: static const int kSignificandSize = 52; static const int kExponentBias = 0x3FF; static const int kDenormalExponent = 1 - kExponentBias; @@ -94,7 +94,7 @@ class Double { }; }; -} // namespace internal +} // namespace internal RAPIDJSON_NAMESPACE_END -#endif // RAPIDJSON_IEEE754_ +#endif // RAPIDJSON_IEEE754_ diff --git a/livox_ros_driver/common/rapidjson/internal/itoa.h b/livox_ros_driver/common/rapidjson/internal/itoa.h index a207485..ec1174c 100644 --- a/livox_ros_driver/common/rapidjson/internal/itoa.h +++ b/livox_ros_driver/common/rapidjson/internal/itoa.h @@ -52,12 +52,9 @@ inline char *u32toa(uint32_t value, char *buffer) { const uint32_t d1 = (value / 100) << 1; const uint32_t d2 = (value % 100) << 1; - if (value >= 1000) - *buffer++ = cDigitsLut[d1]; - if (value >= 100) - *buffer++ = cDigitsLut[d1 + 1]; - if (value >= 10) - *buffer++ = cDigitsLut[d2]; + if (value >= 1000) *buffer++ = cDigitsLut[d1]; + if (value >= 100) *buffer++ = cDigitsLut[d1 + 1]; + if (value >= 10) *buffer++ = cDigitsLut[d2]; *buffer++ = cDigitsLut[d2 + 1]; } else if (value < 100000000) { // value = bbbbcccc @@ -70,12 +67,9 @@ inline char *u32toa(uint32_t value, char *buffer) { const uint32_t d3 = (c / 100) << 1; const uint32_t d4 = (c % 100) << 1; - if (value >= 10000000) - *buffer++ = cDigitsLut[d1]; - if (value >= 1000000) - *buffer++ = cDigitsLut[d1 + 1]; - if (value >= 100000) - *buffer++ = cDigitsLut[d2]; + if (value >= 10000000) *buffer++ = cDigitsLut[d1]; + if (value >= 1000000) *buffer++ = cDigitsLut[d1 + 1]; + if (value >= 100000) *buffer++ = cDigitsLut[d2]; *buffer++ = cDigitsLut[d2 + 1]; *buffer++ = cDigitsLut[d3]; @@ -85,7 +79,7 @@ inline char *u32toa(uint32_t value, char *buffer) { } else { // value = aabbbbcccc in decimal - const uint32_t a = value / 100000000; // 1 to 42 + const uint32_t a = value / 100000000; // 1 to 42 value %= 100000000; if (a >= 10) { @@ -95,8 +89,8 @@ inline char *u32toa(uint32_t value, char *buffer) { } else *buffer++ = static_cast('0' + static_cast(a)); - const uint32_t b = value / 10000; // 0 to 9999 - const uint32_t c = value % 10000; // 0 to 9999 + const uint32_t b = value / 10000; // 0 to 9999 + const uint32_t c = value % 10000; // 0 to 9999 const uint32_t d1 = (b / 100) << 1; const uint32_t d2 = (b % 100) << 1; @@ -146,12 +140,9 @@ inline char *u64toa(uint64_t value, char *buffer) { const uint32_t d1 = (v / 100) << 1; const uint32_t d2 = (v % 100) << 1; - if (v >= 1000) - *buffer++ = cDigitsLut[d1]; - if (v >= 100) - *buffer++ = cDigitsLut[d1 + 1]; - if (v >= 10) - *buffer++ = cDigitsLut[d2]; + if (v >= 1000) *buffer++ = cDigitsLut[d1]; + if (v >= 100) *buffer++ = cDigitsLut[d1 + 1]; + if (v >= 10) *buffer++ = cDigitsLut[d2]; *buffer++ = cDigitsLut[d2 + 1]; } else { // value = bbbbcccc @@ -164,12 +155,9 @@ inline char *u64toa(uint64_t value, char *buffer) { const uint32_t d3 = (c / 100) << 1; const uint32_t d4 = (c % 100) << 1; - if (value >= 10000000) - *buffer++ = cDigitsLut[d1]; - if (value >= 1000000) - *buffer++ = cDigitsLut[d1 + 1]; - if (value >= 100000) - *buffer++ = cDigitsLut[d2]; + if (value >= 10000000) *buffer++ = cDigitsLut[d1]; + if (value >= 1000000) *buffer++ = cDigitsLut[d1 + 1]; + if (value >= 100000) *buffer++ = cDigitsLut[d2]; *buffer++ = cDigitsLut[d2 + 1]; *buffer++ = cDigitsLut[d3]; @@ -199,20 +187,13 @@ inline char *u64toa(uint64_t value, char *buffer) { const uint32_t d7 = (c1 / 100) << 1; const uint32_t d8 = (c1 % 100) << 1; - if (value >= kTen15) - *buffer++ = cDigitsLut[d1]; - if (value >= kTen14) - *buffer++ = cDigitsLut[d1 + 1]; - if (value >= kTen13) - *buffer++ = cDigitsLut[d2]; - if (value >= kTen12) - *buffer++ = cDigitsLut[d2 + 1]; - if (value >= kTen11) - *buffer++ = cDigitsLut[d3]; - if (value >= kTen10) - *buffer++ = cDigitsLut[d3 + 1]; - if (value >= kTen9) - *buffer++ = cDigitsLut[d4]; + if (value >= kTen15) *buffer++ = cDigitsLut[d1]; + if (value >= kTen14) *buffer++ = cDigitsLut[d1 + 1]; + if (value >= kTen13) *buffer++ = cDigitsLut[d2]; + if (value >= kTen12) *buffer++ = cDigitsLut[d2 + 1]; + if (value >= kTen11) *buffer++ = cDigitsLut[d3]; + if (value >= kTen10) *buffer++ = cDigitsLut[d3 + 1]; + if (value >= kTen9) *buffer++ = cDigitsLut[d4]; *buffer++ = cDigitsLut[d4 + 1]; *buffer++ = cDigitsLut[d5]; @@ -224,7 +205,7 @@ inline char *u64toa(uint64_t value, char *buffer) { *buffer++ = cDigitsLut[d8]; *buffer++ = cDigitsLut[d8 + 1]; } else { - const uint32_t a = static_cast(value / kTen16); // 1 to 1844 + const uint32_t a = static_cast(value / kTen16); // 1 to 1844 value %= kTen16; if (a < 10) @@ -301,7 +282,7 @@ inline char *i64toa(int64_t value, char *buffer) { return u64toa(u, buffer); } -} // namespace internal +} // namespace internal RAPIDJSON_NAMESPACE_END -#endif // RAPIDJSON_ITOA_ +#endif // RAPIDJSON_ITOA_ diff --git a/livox_ros_driver/common/rapidjson/internal/meta.h b/livox_ros_driver/common/rapidjson/internal/meta.h index 1d480c1..598f576 100644 --- a/livox_ros_driver/common/rapidjson/internal/meta.h +++ b/livox_ros_driver/common/rapidjson/internal/meta.h @@ -41,12 +41,16 @@ namespace internal { // Helper to wrap/convert arbitrary types to void, useful for arbitrary type // matching -template struct Void { typedef void Type; }; +template +struct Void { + typedef void Type; +}; /////////////////////////////////////////////////////////////////////////////// // BoolType, TrueType, FalseType // -template struct BoolType { +template +struct BoolType { static const bool Value = Cond; typedef BoolType Type; }; @@ -57,21 +61,33 @@ typedef BoolType FalseType; // SelectIf, BoolExpr, NotExpr, AndExpr, OrExpr // -template struct SelectIfImpl { - template struct Apply { typedef T1 Type; }; +template +struct SelectIfImpl { + template + struct Apply { + typedef T1 Type; + }; }; -template <> struct SelectIfImpl { - template struct Apply { typedef T2 Type; }; +template <> +struct SelectIfImpl { + template + struct Apply { + typedef T2 Type; + }; }; template struct SelectIfCond : SelectIfImpl::template Apply {}; template struct SelectIf : SelectIfCond {}; -template struct AndExprCond : FalseType {}; -template <> struct AndExprCond : TrueType {}; -template struct OrExprCond : TrueType {}; -template <> struct OrExprCond : FalseType {}; +template +struct AndExprCond : FalseType {}; +template <> +struct AndExprCond : TrueType {}; +template +struct OrExprCond : TrueType {}; +template <> +struct OrExprCond : FalseType {}; template struct BoolExpr : SelectIf::Type {}; @@ -84,20 +100,33 @@ struct OrExpr : OrExprCond::Type {}; /////////////////////////////////////////////////////////////////////////////// // AddConst, MaybeAddConst, RemoveConst -template struct AddConst { typedef const T Type; }; +template +struct AddConst { + typedef const T Type; +}; template struct MaybeAddConst : SelectIfCond {}; -template struct RemoveConst { typedef T Type; }; -template struct RemoveConst { typedef T Type; }; +template +struct RemoveConst { + typedef T Type; +}; +template +struct RemoveConst { + typedef T Type; +}; /////////////////////////////////////////////////////////////////////////////// // IsSame, IsConst, IsMoreConst, IsPointer // -template struct IsSame : FalseType {}; -template struct IsSame : TrueType {}; +template +struct IsSame : FalseType {}; +template +struct IsSame : TrueType {}; -template struct IsConst : FalseType {}; -template struct IsConst : TrueType {}; +template +struct IsConst : FalseType {}; +template +struct IsConst : TrueType {}; template struct IsMoreConst @@ -105,8 +134,10 @@ struct IsMoreConst IsSame::Type, typename RemoveConst::Type>, BoolType::Value >= IsConst::Value>>::Type {}; -template struct IsPointer : FalseType {}; -template struct IsPointer : TrueType {}; +template +struct IsPointer : FalseType {}; +template +struct IsPointer : TrueType {}; /////////////////////////////////////////////////////////////////////////////// // IsBaseOf @@ -116,16 +147,18 @@ template struct IsPointer : TrueType {}; template struct IsBaseOf : BoolType<::std::is_base_of::value> {}; -#else // simplified version adopted from Boost +#else // simplified version adopted from Boost -template struct IsBaseOfImpl { +template +struct IsBaseOfImpl { RAPIDJSON_STATIC_ASSERT(sizeof(B) != 0); RAPIDJSON_STATIC_ASSERT(sizeof(D) != 0); typedef char (&Yes)[1]; typedef char (&No)[2]; - template static Yes Check(const D *, T); + template + static Yes Check(const D *, T); static No Check(const B *, int); struct Host { @@ -139,21 +172,25 @@ template struct IsBaseOfImpl { template struct IsBaseOf : OrExpr, BoolExpr>>::Type {}; -#endif // RAPIDJSON_HAS_CXX11_TYPETRAITS +#endif // RAPIDJSON_HAS_CXX11_TYPETRAITS ////////////////////////////////////////////////////////////////////////// // EnableIf / DisableIf // -template struct EnableIfCond { +template +struct EnableIfCond { typedef T Type; }; -template struct EnableIfCond { /* empty */ +template +struct EnableIfCond { /* empty */ }; -template struct DisableIfCond { +template +struct DisableIfCond { typedef T Type; }; -template struct DisableIfCond { /* empty */ +template +struct DisableIfCond { /* empty */ }; template @@ -164,32 +201,34 @@ struct DisableIf : DisableIfCond {}; // SFINAE helpers struct SfinaeTag {}; -template struct RemoveSfinaeTag; -template struct RemoveSfinaeTag { +template +struct RemoveSfinaeTag; +template +struct RemoveSfinaeTag { typedef T Type; }; -#define RAPIDJSON_REMOVEFPTR_(type) \ - typename ::RAPIDJSON_NAMESPACE::internal::RemoveSfinaeTag< \ +#define RAPIDJSON_REMOVEFPTR_(type) \ + typename ::RAPIDJSON_NAMESPACE::internal::RemoveSfinaeTag< \ ::RAPIDJSON_NAMESPACE::internal::SfinaeTag &(*)type>::Type -#define RAPIDJSON_ENABLEIF(cond) \ - typename ::RAPIDJSON_NAMESPACE::internal::EnableIf::Type * = NULL -#define RAPIDJSON_DISABLEIF(cond) \ - typename ::RAPIDJSON_NAMESPACE::internal::DisableIf::Type * = NULL -#define RAPIDJSON_ENABLEIF_RETURN(cond, returntype) \ - typename ::RAPIDJSON_NAMESPACE::internal::EnableIf< \ +#define RAPIDJSON_ENABLEIF_RETURN(cond, returntype) \ + typename ::RAPIDJSON_NAMESPACE::internal::EnableIf< \ RAPIDJSON_REMOVEFPTR_(cond), RAPIDJSON_REMOVEFPTR_(returntype)>::Type -#define RAPIDJSON_DISABLEIF_RETURN(cond, returntype) \ - typename ::RAPIDJSON_NAMESPACE::internal::DisableIf< \ +#define RAPIDJSON_DISABLEIF_RETURN(cond, returntype) \ + typename ::RAPIDJSON_NAMESPACE::internal::DisableIf< \ RAPIDJSON_REMOVEFPTR_(cond), RAPIDJSON_REMOVEFPTR_(returntype)>::Type -} // namespace internal +} // namespace internal RAPIDJSON_NAMESPACE_END //@endcond @@ -201,4 +240,4 @@ RAPIDJSON_DIAG_POP RAPIDJSON_DIAG_POP #endif -#endif // RAPIDJSON_INTERNAL_META_H_ +#endif // RAPIDJSON_INTERNAL_META_H_ diff --git a/livox_ros_driver/common/rapidjson/internal/pow10.h b/livox_ros_driver/common/rapidjson/internal/pow10.h index 8255fa4..6f15f74 100644 --- a/livox_ros_driver/common/rapidjson/internal/pow10.h +++ b/livox_ros_driver/common/rapidjson/internal/pow10.h @@ -71,7 +71,7 @@ inline double Pow10(int n) { return e[n]; } -} // namespace internal +} // namespace internal RAPIDJSON_NAMESPACE_END -#endif // RAPIDJSON_POW10_ +#endif // RAPIDJSON_POW10_ diff --git a/livox_ros_driver/common/rapidjson/internal/regex.h b/livox_ros_driver/common/rapidjson/internal/regex.h index a52c57c..19f49da 100644 --- a/livox_ros_driver/common/rapidjson/internal/regex.h +++ b/livox_ros_driver/common/rapidjson/internal/regex.h @@ -29,7 +29,7 @@ RAPIDJSON_DIAG_OFF(padded) RAPIDJSON_DIAG_OFF(switch - enum) #elif defined(_MSC_VER) RAPIDJSON_DIAG_PUSH -RAPIDJSON_DIAG_OFF(4512) // assignment operator could not be generated +RAPIDJSON_DIAG_OFF(4512) // assignment operator could not be generated #endif #ifdef __GNUC__ @@ -47,21 +47,21 @@ namespace internal { /////////////////////////////////////////////////////////////////////////////// // DecodedStream -template class DecodedStream { -public: +template +class DecodedStream { + public: DecodedStream(SourceStream &ss) : ss_(ss), codepoint_() { Decode(); } unsigned Peek() { return codepoint_; } unsigned Take() { unsigned c = codepoint_; - if (c) // No further decoding when '\0' + if (c) // No further decoding when '\0' Decode(); return c; } -private: + private: void Decode() { - if (!Encoding::Decode(ss_, &codepoint_)) - codepoint_ = 0; + if (!Encoding::Decode(ss_, &codepoint_)) codepoint_ = 0; } SourceStream &ss_; @@ -72,10 +72,11 @@ template class DecodedStream { // GenericRegex static const SizeType kRegexInvalidState = ~SizeType( - 0); //!< Represents an invalid index in GenericRegex::State::out, out1 + 0); //!< Represents an invalid index in GenericRegex::State::out, out1 static const SizeType kRegexInvalidRange = ~SizeType(0); -template class GenericRegexSearch; +template +class GenericRegexSearch; //! Regular expression engine with subset of ECMAscript grammar. /*! @@ -112,16 +113,21 @@ template class GenericRegexSearch; */ template class GenericRegex { -public: + public: typedef Encoding EncodingType; typedef typename Encoding::Ch Ch; - template friend class GenericRegexSearch; + template + friend class GenericRegexSearch; GenericRegex(const Ch *source, Allocator *allocator = 0) : ownAllocator_(allocator ? 0 : RAPIDJSON_NEW(Allocator)()), allocator_(allocator ? allocator : ownAllocator_), - states_(allocator_, 256), ranges_(allocator_, 256), - root_(kRegexInvalidState), stateCount_(), rangeCount_(), anchorBegin_(), + states_(allocator_, 256), + ranges_(allocator_, 256), + root_(kRegexInvalidState), + stateCount_(), + rangeCount_(), + anchorBegin_(), anchorEnd_() { GenericStringStream ss(source); DecodedStream, Encoding> ds(ss); @@ -132,7 +138,7 @@ class GenericRegex { bool IsValid() const { return root_ != kRegexInvalidState; } -private: + private: enum Operator { kZeroOrOne, kZeroOrMore, @@ -142,19 +148,19 @@ class GenericRegex { kLeftParenthesis }; - static const unsigned kAnyCharacterClass = 0xFFFFFFFF; //!< For '.' + static const unsigned kAnyCharacterClass = 0xFFFFFFFF; //!< For '.' static const unsigned kRangeCharacterClass = 0xFFFFFFFE; static const unsigned kRangeNegationFlag = 0x80000000; struct Range { - unsigned start; // + unsigned start; // unsigned end; SizeType next; }; struct State { - SizeType out; //!< Equals to kInvalid for matching state - SizeType out1; //!< Equals to non-kInvalid for split + SizeType out; //!< Equals to kInvalid for matching state + SizeType out1; //!< Equals to non-kInvalid for split SizeType rangeStart; unsigned codepoint; }; @@ -162,7 +168,7 @@ class GenericRegex { struct Frag { Frag(SizeType s, SizeType o, SizeType m) : start(s), out(o), minIndex(m) {} SizeType start; - SizeType out; //!< link-list of all output states + SizeType out; //!< link-list of all output states SizeType minIndex; }; @@ -188,116 +194,108 @@ class GenericRegex { template void Parse(DecodedStream &ds) { - Stack operandStack(allocator_, 256); // Frag - Stack operatorStack(allocator_, 256); // Operator + Stack operandStack(allocator_, 256); // Frag + Stack operatorStack(allocator_, 256); // Operator Stack atomCountStack(allocator_, - 256); // unsigned (Atom per parenthesis) + 256); // unsigned (Atom per parenthesis) *atomCountStack.template Push() = 0; unsigned codepoint; while (ds.Peek() != 0) { switch (codepoint = ds.Take()) { - case '^': - anchorBegin_ = true; - break; + case '^': + anchorBegin_ = true; + break; - case '$': - anchorEnd_ = true; - break; + case '$': + anchorEnd_ = true; + break; - case '|': - while (!operatorStack.Empty() && - *operatorStack.template Top() < kAlternation) - if (!Eval(operandStack, *operatorStack.template Pop(1))) - return; - *operatorStack.template Push() = kAlternation; - *atomCountStack.template Top() = 0; - break; + case '|': + while (!operatorStack.Empty() && + *operatorStack.template Top() < kAlternation) + if (!Eval(operandStack, *operatorStack.template Pop(1))) + return; + *operatorStack.template Push() = kAlternation; + *atomCountStack.template Top() = 0; + break; - case '(': - *operatorStack.template Push() = kLeftParenthesis; - *atomCountStack.template Push() = 0; - break; + case '(': + *operatorStack.template Push() = kLeftParenthesis; + *atomCountStack.template Push() = 0; + break; - case ')': - while (!operatorStack.Empty() && - *operatorStack.template Top() != kLeftParenthesis) - if (!Eval(operandStack, *operatorStack.template Pop(1))) - return; - if (operatorStack.Empty()) - return; - operatorStack.template Pop(1); - atomCountStack.template Pop(1); - ImplicitConcatenation(atomCountStack, operatorStack); - break; + case ')': + while (!operatorStack.Empty() && + *operatorStack.template Top() != kLeftParenthesis) + if (!Eval(operandStack, *operatorStack.template Pop(1))) + return; + if (operatorStack.Empty()) return; + operatorStack.template Pop(1); + atomCountStack.template Pop(1); + ImplicitConcatenation(atomCountStack, operatorStack); + break; - case '?': - if (!Eval(operandStack, kZeroOrOne)) - return; - break; + case '?': + if (!Eval(operandStack, kZeroOrOne)) return; + break; - case '*': - if (!Eval(operandStack, kZeroOrMore)) - return; - break; + case '*': + if (!Eval(operandStack, kZeroOrMore)) return; + break; - case '+': - if (!Eval(operandStack, kOneOrMore)) - return; - break; + case '+': + if (!Eval(operandStack, kOneOrMore)) return; + break; + + case '{': { + unsigned n, m; + if (!ParseUnsigned(ds, &n)) return; - case '{': { - unsigned n, m; - if (!ParseUnsigned(ds, &n)) - return; + if (ds.Peek() == ',') { + ds.Take(); + if (ds.Peek() == '}') + m = kInfinityQuantifier; + else if (!ParseUnsigned(ds, &m) || m < n) + return; + } else + m = n; - if (ds.Peek() == ',') { + if (!EvalQuantifier(operandStack, n, m) || ds.Peek() != '}') return; ds.Take(); - if (ds.Peek() == '}') - m = kInfinityQuantifier; - else if (!ParseUnsigned(ds, &m) || m < n) - return; - } else - m = n; - - if (!EvalQuantifier(operandStack, n, m) || ds.Peek() != '}') - return; - ds.Take(); - } break; + } break; - case '.': - PushOperand(operandStack, kAnyCharacterClass); - ImplicitConcatenation(atomCountStack, operatorStack); - break; - - case '[': { - SizeType range; - if (!ParseRange(ds, &range)) - return; - SizeType s = NewState(kRegexInvalidState, kRegexInvalidState, - kRangeCharacterClass); - GetState(s).rangeStart = range; - *operandStack.template Push() = Frag(s, s, s); - } - ImplicitConcatenation(atomCountStack, operatorStack); - break; - - case '\\': // Escape character - if (!CharacterEscape(ds, &codepoint)) - return; // Unsupported escape character - // fall through to default - RAPIDJSON_DELIBERATE_FALLTHROUGH; - - default: // Pattern character - PushOperand(operandStack, codepoint); - ImplicitConcatenation(atomCountStack, operatorStack); + case '.': + PushOperand(operandStack, kAnyCharacterClass); + ImplicitConcatenation(atomCountStack, operatorStack); + break; + + case '[': { + SizeType range; + if (!ParseRange(ds, &range)) return; + SizeType s = NewState(kRegexInvalidState, kRegexInvalidState, + kRangeCharacterClass); + GetState(s).rangeStart = range; + *operandStack.template Push() = Frag(s, s, s); + } + ImplicitConcatenation(atomCountStack, operatorStack); + break; + + case '\\': // Escape character + if (!CharacterEscape(ds, &codepoint)) + return; // Unsupported escape character + // fall through to default + RAPIDJSON_DELIBERATE_FALLTHROUGH; + + default: // Pattern character + PushOperand(operandStack, codepoint); + ImplicitConcatenation(atomCountStack, operatorStack); } } while (!operatorStack.Empty()) - if (!Eval(operandStack, *operatorStack.template Pop(1))) - return; + if (!Eval(operandStack, *operatorStack.template Pop(1))) return; // Link the operand to matching state. if (operandStack.GetSize() == sizeof(Frag)) { @@ -340,8 +338,7 @@ class GenericRegex { SizeType Append(SizeType l1, SizeType l2) { SizeType old = l1; - while (GetState(l1).out != kRegexInvalidState) - l1 = GetState(l1).out; + while (GetState(l1).out != kRegexInvalidState) l1 = GetState(l1).out; GetState(l1).out = l2; return old; } @@ -355,61 +352,61 @@ class GenericRegex { bool Eval(Stack &operandStack, Operator op) { switch (op) { - case kConcatenation: - RAPIDJSON_ASSERT(operandStack.GetSize() >= sizeof(Frag) * 2); - { - Frag e2 = *operandStack.template Pop(1); - Frag e1 = *operandStack.template Pop(1); - Patch(e1.out, e2.start); - *operandStack.template Push() = - Frag(e1.start, e2.out, Min(e1.minIndex, e2.minIndex)); - } - return true; - - case kAlternation: - if (operandStack.GetSize() >= sizeof(Frag) * 2) { - Frag e2 = *operandStack.template Pop(1); - Frag e1 = *operandStack.template Pop(1); - SizeType s = NewState(e1.start, e2.start, 0); - *operandStack.template Push() = - Frag(s, Append(e1.out, e2.out), Min(e1.minIndex, e2.minIndex)); - return true; - } - return false; - - case kZeroOrOne: - if (operandStack.GetSize() >= sizeof(Frag)) { - Frag e = *operandStack.template Pop(1); - SizeType s = NewState(kRegexInvalidState, e.start, 0); - *operandStack.template Push() = - Frag(s, Append(e.out, s), e.minIndex); - return true; - } - return false; - - case kZeroOrMore: - if (operandStack.GetSize() >= sizeof(Frag)) { - Frag e = *operandStack.template Pop(1); - SizeType s = NewState(kRegexInvalidState, e.start, 0); - Patch(e.out, s); - *operandStack.template Push() = Frag(s, s, e.minIndex); - return true; - } - return false; - - case kOneOrMore: - if (operandStack.GetSize() >= sizeof(Frag)) { - Frag e = *operandStack.template Pop(1); - SizeType s = NewState(kRegexInvalidState, e.start, 0); - Patch(e.out, s); - *operandStack.template Push() = Frag(e.start, s, e.minIndex); + case kConcatenation: + RAPIDJSON_ASSERT(operandStack.GetSize() >= sizeof(Frag) * 2); + { + Frag e2 = *operandStack.template Pop(1); + Frag e1 = *operandStack.template Pop(1); + Patch(e1.out, e2.start); + *operandStack.template Push() = + Frag(e1.start, e2.out, Min(e1.minIndex, e2.minIndex)); + } return true; - } - return false; - default: - // syntax error (e.g. unclosed kLeftParenthesis) - return false; + case kAlternation: + if (operandStack.GetSize() >= sizeof(Frag) * 2) { + Frag e2 = *operandStack.template Pop(1); + Frag e1 = *operandStack.template Pop(1); + SizeType s = NewState(e1.start, e2.start, 0); + *operandStack.template Push() = + Frag(s, Append(e1.out, e2.out), Min(e1.minIndex, e2.minIndex)); + return true; + } + return false; + + case kZeroOrOne: + if (operandStack.GetSize() >= sizeof(Frag)) { + Frag e = *operandStack.template Pop(1); + SizeType s = NewState(kRegexInvalidState, e.start, 0); + *operandStack.template Push() = + Frag(s, Append(e.out, s), e.minIndex); + return true; + } + return false; + + case kZeroOrMore: + if (operandStack.GetSize() >= sizeof(Frag)) { + Frag e = *operandStack.template Pop(1); + SizeType s = NewState(kRegexInvalidState, e.start, 0); + Patch(e.out, s); + *operandStack.template Push() = Frag(s, s, e.minIndex); + return true; + } + return false; + + case kOneOrMore: + if (operandStack.GetSize() >= sizeof(Frag)) { + Frag e = *operandStack.template Pop(1); + SizeType s = NewState(kRegexInvalidState, e.start, 0); + Patch(e.out, s); + *operandStack.template Push() = Frag(e.start, s, e.minIndex); + return true; + } + return false; + + default: + // syntax error (e.g. unclosed kLeftParenthesis) + return false; } } @@ -418,37 +415,37 @@ class GenericRegex { RAPIDJSON_ASSERT(operandStack.GetSize() >= sizeof(Frag)); if (n == 0) { - if (m == 0) // a{0} not support + if (m == 0) // a{0} not support return false; else if (m == kInfinityQuantifier) - Eval(operandStack, kZeroOrMore); // a{0,} -> a* + Eval(operandStack, kZeroOrMore); // a{0,} -> a* else { - Eval(operandStack, kZeroOrOne); // a{0,5} -> a? + Eval(operandStack, kZeroOrOne); // a{0,5} -> a? for (unsigned i = 0; i < m - 1; i++) - CloneTopOperand(operandStack); // a{0,5} -> a? a? a? a? a? + CloneTopOperand(operandStack); // a{0,5} -> a? a? a? a? a? for (unsigned i = 0; i < m - 1; i++) - Eval(operandStack, kConcatenation); // a{0,5} -> a?a?a?a?a? + Eval(operandStack, kConcatenation); // a{0,5} -> a?a?a?a?a? } return true; } - for (unsigned i = 0; i < n - 1; i++) // a{3} -> a a a + for (unsigned i = 0; i < n - 1; i++) // a{3} -> a a a CloneTopOperand(operandStack); if (m == kInfinityQuantifier) - Eval(operandStack, kOneOrMore); // a{3,} -> a a a+ + Eval(operandStack, kOneOrMore); // a{3,} -> a a a+ else if (m > n) { - CloneTopOperand(operandStack); // a{3,5} -> a a a a - Eval(operandStack, kZeroOrOne); // a{3,5} -> a a a a? + CloneTopOperand(operandStack); // a{3,5} -> a a a a + Eval(operandStack, kZeroOrOne); // a{3,5} -> a a a a? for (unsigned i = n; i < m - 1; i++) - CloneTopOperand(operandStack); // a{3,5} -> a a a a? a? + CloneTopOperand(operandStack); // a{3,5} -> a a a a? a? for (unsigned i = n; i < m; i++) - Eval(operandStack, kConcatenation); // a{3,5} -> a a aa?a? + Eval(operandStack, kConcatenation); // a{3,5} -> a a aa?a? } for (unsigned i = 0; i < n - 1; i++) Eval(operandStack, - kConcatenation); // a{3} -> aaa, a{3,} -> aaa+, a{3.5} -> aaaa?a? + kConcatenation); // a{3} -> aaa, a{3,} -> aaa+, a{3.5} -> aaaa?a? return true; } @@ -458,17 +455,15 @@ class GenericRegex { void CloneTopOperand(Stack &operandStack) { const Frag src = *operandStack - .template Top(); // Copy constructor to prevent invalidation + .template Top(); // Copy constructor to prevent invalidation SizeType count = - stateCount_ - src.minIndex; // Assumes top operand contains states in - // [src->minIndex, stateCount_) + stateCount_ - src.minIndex; // Assumes top operand contains states in + // [src->minIndex, stateCount_) State *s = states_.template Push(count); memcpy(s, &GetState(src.minIndex), count * sizeof(State)); for (SizeType j = 0; j < count; j++) { - if (s[j].out != kRegexInvalidState) - s[j].out += count; - if (s[j].out1 != kRegexInvalidState) - s[j].out1 += count; + if (s[j].out != kRegexInvalidState) s[j].out += count; + if (s[j].out1 != kRegexInvalidState) s[j].out1 += count; } *operandStack.template Push() = Frag(src.start + count, src.out + count, src.minIndex + count); @@ -478,11 +473,10 @@ class GenericRegex { template bool ParseUnsigned(DecodedStream &ds, unsigned *u) { unsigned r = 0; - if (ds.Peek() < '0' || ds.Peek() > '9') - return false; + if (ds.Peek() < '0' || ds.Peek() > '9') return false; while (ds.Peek() >= '0' && ds.Peek() <= '9') { - if (r >= 429496729 && ds.Peek() > '5') // 2^32 - 1 = 4294967295 - return false; // overflow + if (r >= 429496729 && ds.Peek() > '5') // 2^32 - 1 = 4294967295 + return false; // overflow r = r * 10 + (ds.Take() - '0'); } *u = r; @@ -507,54 +501,51 @@ class GenericRegex { } switch (codepoint) { - case ']': - if (start == kRegexInvalidRange) - return false; // Error: nothing inside [] - if (step == 2) { // Add trailing '-' - SizeType r = NewRange('-'); - RAPIDJSON_ASSERT(current != kRegexInvalidRange); - GetRange(current).next = r; - } - if (negate) - GetRange(start).start |= kRangeNegationFlag; - *range = start; - return true; - - case '\\': - if (ds.Peek() == 'b') { - ds.Take(); - codepoint = 0x0008; // Escape backspace character - } else if (!CharacterEscape(ds, &codepoint)) - return false; - // fall through to default - RAPIDJSON_DELIBERATE_FALLTHROUGH; - - default: - switch (step) { - case 1: - if (codepoint == '-') { - step++; - break; + case ']': + if (start == kRegexInvalidRange) + return false; // Error: nothing inside [] + if (step == 2) { // Add trailing '-' + SizeType r = NewRange('-'); + RAPIDJSON_ASSERT(current != kRegexInvalidRange); + GetRange(current).next = r; } - // fall through to step 0 for other characters + if (negate) GetRange(start).start |= kRangeNegationFlag; + *range = start; + return true; + + case '\\': + if (ds.Peek() == 'b') { + ds.Take(); + codepoint = 0x0008; // Escape backspace character + } else if (!CharacterEscape(ds, &codepoint)) + return false; + // fall through to default RAPIDJSON_DELIBERATE_FALLTHROUGH; - case 0: { - SizeType r = NewRange(codepoint); - if (current != kRegexInvalidRange) - GetRange(current).next = r; - if (start == kRegexInvalidRange) - start = r; - current = r; - } - step = 1; - break; - default: - RAPIDJSON_ASSERT(step == 2); - GetRange(current).end = codepoint; - step = 0; - } + switch (step) { + case 1: + if (codepoint == '-') { + step++; + break; + } + // fall through to step 0 for other characters + RAPIDJSON_DELIBERATE_FALLTHROUGH; + + case 0: { + SizeType r = NewRange(codepoint); + if (current != kRegexInvalidRange) GetRange(current).next = r; + if (start == kRegexInvalidRange) start = r; + current = r; + } + step = 1; + break; + + default: + RAPIDJSON_ASSERT(step == 2); + GetRange(current).end = codepoint; + step = 0; + } } } return false; @@ -572,39 +563,39 @@ class GenericRegex { unsigned *escapedCodepoint) { unsigned codepoint; switch (codepoint = ds.Take()) { - case '^': - case '$': - case '|': - case '(': - case ')': - case '?': - case '*': - case '+': - case '.': - case '[': - case ']': - case '{': - case '}': - case '\\': - *escapedCodepoint = codepoint; - return true; - case 'f': - *escapedCodepoint = 0x000C; - return true; - case 'n': - *escapedCodepoint = 0x000A; - return true; - case 'r': - *escapedCodepoint = 0x000D; - return true; - case 't': - *escapedCodepoint = 0x0009; - return true; - case 'v': - *escapedCodepoint = 0x000B; - return true; - default: - return false; // Unsupported escape character + case '^': + case '$': + case '|': + case '(': + case ')': + case '?': + case '*': + case '+': + case '.': + case '[': + case ']': + case '{': + case '}': + case '\\': + *escapedCodepoint = codepoint; + return true; + case 'f': + *escapedCodepoint = 0x000C; + return true; + case 'n': + *escapedCodepoint = 0x000A; + return true; + case 'r': + *escapedCodepoint = 0x000D; + return true; + case 't': + *escapedCodepoint = 0x0009; + return true; + case 'v': + *escapedCodepoint = 0x000B; + return true; + default: + return false; // Unsupported escape character } } @@ -625,16 +616,19 @@ class GenericRegex { template class GenericRegexSearch { -public: + public: typedef typename RegexType::EncodingType Encoding; typedef typename Encoding::Ch Ch; GenericRegexSearch(const RegexType ®ex, Allocator *allocator = 0) - : regex_(regex), allocator_(allocator), ownAllocator_(0), - state0_(allocator, 0), state1_(allocator, 0), stateSet_() { + : regex_(regex), + allocator_(allocator), + ownAllocator_(0), + state0_(allocator, 0), + state1_(allocator, 0), + stateSet_() { RAPIDJSON_ASSERT(regex_.IsValid()); - if (!allocator_) - ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator)(); + if (!allocator_) ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator)(); stateSet_ = static_cast(allocator_->Malloc(GetStateSetSize())); state0_.template Reserve(regex_.stateCount_); state1_.template Reserve(regex_.stateCount_); @@ -645,7 +639,8 @@ class GenericRegexSearch { RAPIDJSON_DELETE(ownAllocator_); } - template bool Match(InputStream &is) { + template + bool Match(InputStream &is) { return SearchWithAnchoring(is, true, true); } @@ -654,7 +649,8 @@ class GenericRegexSearch { return Match(is); } - template bool Search(InputStream &is) { + template + bool Search(InputStream &is) { return SearchWithAnchoring(is, regex_.anchorBegin_, regex_.anchorEnd_); } @@ -663,7 +659,7 @@ class GenericRegexSearch { return Search(is); } -private: + private: typedef typename RegexType::State State; typedef typename RegexType::Range Range; @@ -690,11 +686,9 @@ class GenericRegexSearch { (sr.codepoint == RegexType::kRangeCharacterClass && MatchRange(sr.rangeStart, codepoint))) { matched = AddState(*next, sr.out) || matched; - if (!anchorEnd && matched) - return true; + if (!anchorEnd && matched) return true; } - if (!anchorBegin) - AddState(*next, regex_.root_); + if (!anchorBegin) AddState(*next, regex_.root_); } internal::Swap(current, next); } @@ -709,7 +703,7 @@ class GenericRegexSearch { RAPIDJSON_ASSERT(index != kRegexInvalidState); const State &s = regex_.GetState(index); - if (s.out1 != kRegexInvalidState) { // Split + if (s.out1 != kRegexInvalidState) { // Split bool matched = AddState(l, s.out); return AddState(l, s.out1) || matched; } else if (!(stateSet_[index >> 5] & (1u << (index & 31)))) { @@ -717,8 +711,8 @@ class GenericRegexSearch { *l.template PushUnsafe() = index; } return s.out == - kRegexInvalidState; // by using PushUnsafe() above, we can ensure s - // is not validated due to reallocation. + kRegexInvalidState; // by using PushUnsafe() above, we can ensure s + // is not validated due to reallocation. } bool MatchRange(SizeType rangeIndex, unsigned codepoint) const { @@ -745,7 +739,7 @@ class GenericRegexSearch { typedef GenericRegex> Regex; typedef GenericRegexSearch RegexSearch; -} // namespace internal +} // namespace internal RAPIDJSON_NAMESPACE_END #ifdef __GNUC__ @@ -756,4 +750,4 @@ RAPIDJSON_DIAG_POP RAPIDJSON_DIAG_POP #endif -#endif // RAPIDJSON_INTERNAL_REGEX_H_ +#endif // RAPIDJSON_INTERNAL_REGEX_H_ diff --git a/livox_ros_driver/common/rapidjson/internal/stack.h b/livox_ros_driver/common/rapidjson/internal/stack.h index 6d01331..bf80503 100644 --- a/livox_ros_driver/common/rapidjson/internal/stack.h +++ b/livox_ros_driver/common/rapidjson/internal/stack.h @@ -19,9 +19,9 @@ #ifndef RAPIDJSON_INTERNAL_STACK_H_ #define RAPIDJSON_INTERNAL_STACK_H_ +#include #include "../allocators.h" #include "swap.h" -#include #if defined(__clang__) RAPIDJSON_DIAG_PUSH @@ -37,18 +37,26 @@ namespace internal { //! A type-unsafe stack for storing different types of data. /*! \tparam Allocator Allocator for allocating stack memory. */ -template class Stack { -public: +template +class Stack { + public: // Optimization note: Do not allocate memory for stack_ in constructor. // Do it lazily when first Push() -> Expand() -> Resize(). Stack(Allocator *allocator, size_t stackCapacity) - : allocator_(allocator), ownAllocator_(0), stack_(0), stackTop_(0), - stackEnd_(0), initialCapacity_(stackCapacity) {} + : allocator_(allocator), + ownAllocator_(0), + stack_(0), + stackTop_(0), + stackEnd_(0), + initialCapacity_(stackCapacity) {} #if RAPIDJSON_HAS_CXX11_RVALUE_REFS Stack(Stack &&rhs) - : allocator_(rhs.allocator_), ownAllocator_(rhs.ownAllocator_), - stack_(rhs.stack_), stackTop_(rhs.stackTop_), stackEnd_(rhs.stackEnd_), + : allocator_(rhs.allocator_), + ownAllocator_(rhs.ownAllocator_), + stack_(rhs.stack_), + stackTop_(rhs.stackTop_), + stackEnd_(rhs.stackEnd_), initialCapacity_(rhs.initialCapacity_) { rhs.allocator_ = 0; rhs.ownAllocator_ = 0; @@ -98,7 +106,7 @@ template class Stack { void ShrinkToFit() { if (Empty()) { // If the stack is empty, completely deallocate the memory. - Allocator::Free(stack_); // NOLINT (+clang-analyzer-unix.Malloc) + Allocator::Free(stack_); // NOLINT (+clang-analyzer-unix.Malloc) stack_ = 0; stackTop_ = 0; stackEnd_ = 0; @@ -109,19 +117,22 @@ template class Stack { // Optimization note: try to minimize the size of this function for force // inline. Expansion is run very infrequently, so it is moved to another // (probably non-inline) function. - template RAPIDJSON_FORCEINLINE void Reserve(size_t count = 1) { + template + RAPIDJSON_FORCEINLINE void Reserve(size_t count = 1) { // Expand the stack if needed if (RAPIDJSON_UNLIKELY(static_cast(sizeof(T) * count) > (stackEnd_ - stackTop_))) Expand(count); } - template RAPIDJSON_FORCEINLINE T *Push(size_t count = 1) { + template + RAPIDJSON_FORCEINLINE T *Push(size_t count = 1) { Reserve(count); return PushUnsafe(count); } - template RAPIDJSON_FORCEINLINE T *PushUnsafe(size_t count = 1) { + template + RAPIDJSON_FORCEINLINE T *PushUnsafe(size_t count = 1) { RAPIDJSON_ASSERT(stackTop_); RAPIDJSON_ASSERT(static_cast(sizeof(T) * count) <= (stackEnd_ - stackTop_)); @@ -130,31 +141,42 @@ template class Stack { return ret; } - template T *Pop(size_t count) { + template + T *Pop(size_t count) { RAPIDJSON_ASSERT(GetSize() >= count * sizeof(T)); stackTop_ -= count * sizeof(T); return reinterpret_cast(stackTop_); } - template T *Top() { + template + T *Top() { RAPIDJSON_ASSERT(GetSize() >= sizeof(T)); return reinterpret_cast(stackTop_ - sizeof(T)); } - template const T *Top() const { + template + const T *Top() const { RAPIDJSON_ASSERT(GetSize() >= sizeof(T)); return reinterpret_cast(stackTop_ - sizeof(T)); } - template T *End() { return reinterpret_cast(stackTop_); } + template + T *End() { + return reinterpret_cast(stackTop_); + } - template const T *End() const { + template + const T *End() const { return reinterpret_cast(stackTop_); } - template T *Bottom() { return reinterpret_cast(stack_); } + template + T *Bottom() { + return reinterpret_cast(stack_); + } - template const T *Bottom() const { + template + const T *Bottom() const { return reinterpret_cast(stack_); } @@ -169,28 +191,27 @@ template class Stack { size_t GetSize() const { return static_cast(stackTop_ - stack_); } size_t GetCapacity() const { return static_cast(stackEnd_ - stack_); } -private: - template void Expand(size_t count) { + private: + template + void Expand(size_t count) { // Only expand the capacity if the current stack exists. Otherwise just // create a stack with initial capacity. size_t newCapacity; if (stack_ == 0) { - if (!allocator_) - ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator)(); + if (!allocator_) ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator)(); newCapacity = initialCapacity_; } else { newCapacity = GetCapacity(); newCapacity += (newCapacity + 1) / 2; } size_t newSize = GetSize() + sizeof(T) * count; - if (newCapacity < newSize) - newCapacity = newSize; + if (newCapacity < newSize) newCapacity = newSize; Resize(newCapacity); } void Resize(size_t newCapacity) { - const size_t size = GetSize(); // Backup the current size + const size_t size = GetSize(); // Backup the current size stack_ = static_cast( allocator_->Realloc(stack_, GetCapacity(), newCapacity)); stackTop_ = stack_ + size; @@ -199,7 +220,7 @@ template class Stack { void Destroy() { Allocator::Free(stack_); - RAPIDJSON_DELETE(ownAllocator_); // Only delete if it is owned by the stack + RAPIDJSON_DELETE(ownAllocator_); // Only delete if it is owned by the stack } // Prohibit copy constructor & assignment operator. @@ -214,11 +235,11 @@ template class Stack { size_t initialCapacity_; }; -} // namespace internal +} // namespace internal RAPIDJSON_NAMESPACE_END #if defined(__clang__) RAPIDJSON_DIAG_POP #endif -#endif // RAPIDJSON_STACK_H_ +#endif // RAPIDJSON_STACK_H_ diff --git a/livox_ros_driver/common/rapidjson/internal/strfunc.h b/livox_ros_driver/common/rapidjson/internal/strfunc.h index 863df3a..9024b2f 100644 --- a/livox_ros_driver/common/rapidjson/internal/strfunc.h +++ b/livox_ros_driver/common/rapidjson/internal/strfunc.h @@ -19,8 +19,8 @@ #ifndef RAPIDJSON_INTERNAL_STRFUNC_H_ #define RAPIDJSON_INTERNAL_STRFUNC_H_ -#include "../stream.h" #include +#include "../stream.h" RAPIDJSON_NAMESPACE_BEGIN namespace internal { @@ -32,19 +32,21 @@ namespace internal { \note This has the same semantics as strlen(), the return value is not number of Unicode codepoints. */ -template inline SizeType StrLen(const Ch *s) { +template +inline SizeType StrLen(const Ch *s) { RAPIDJSON_ASSERT(s != 0); const Ch *p = s; - while (*p) - ++p; + while (*p) ++p; return SizeType(p - s); } -template <> inline SizeType StrLen(const char *s) { +template <> +inline SizeType StrLen(const char *s) { return SizeType(std::strlen(s)); } -template <> inline SizeType StrLen(const wchar_t *s) { +template <> +inline SizeType StrLen(const wchar_t *s) { return SizeType(std::wcslen(s)); } @@ -59,15 +61,14 @@ bool CountStringCodePoint(const typename Encoding::Ch *s, SizeType length, SizeType count = 0; while (is.src_ < end) { unsigned codepoint; - if (!Encoding::Decode(is, &codepoint)) - return false; + if (!Encoding::Decode(is, &codepoint)) return false; count++; } *outCount = count; return true; } -} // namespace internal +} // namespace internal RAPIDJSON_NAMESPACE_END -#endif // RAPIDJSON_INTERNAL_STRFUNC_H_ +#endif // RAPIDJSON_INTERNAL_STRFUNC_H_ diff --git a/livox_ros_driver/common/rapidjson/internal/strtod.h b/livox_ros_driver/common/rapidjson/internal/strtod.h index 55b5e55..ea7ae43 100644 --- a/livox_ros_driver/common/rapidjson/internal/strtod.h +++ b/livox_ros_driver/common/rapidjson/internal/strtod.h @@ -19,12 +19,12 @@ #ifndef RAPIDJSON_STRTOD_ #define RAPIDJSON_STRTOD_ +#include +#include #include "biginteger.h" #include "diyfp.h" #include "ieee754.h" #include "pow10.h" -#include -#include RAPIDJSON_NAMESPACE_BEGIN namespace internal { @@ -48,12 +48,11 @@ inline double StrtodNormalPrecision(double d, int p) { return d; } -template inline T Min3(T a, T b, T c) { +template +inline T Min3(T a, T b, T c) { T m = a; - if (m > b) - m = b; - if (m > c) - m = c; + if (m > b) m = b; + if (m > c) m = c; return m; } @@ -127,7 +126,7 @@ inline bool StrtodFast(double d, int p, double *result) { p = 22; } - if (p >= -22 && p <= 22 && d <= 9007199254740991.0) { // 2^53 - 1 + if (p >= -22 && p <= 22 && d <= 9007199254740991.0) { // 2^53 - 1 *result = FastPath(d, p); return true; } else @@ -138,8 +137,8 @@ inline bool StrtodFast(double d, int p, double *result) { inline bool StrtodDiyFp(const char *decimals, int dLen, int dExp, double *result) { uint64_t significand = 0; - int i = 0; // 2^64 - 1 = 18446744073709551615, 1844674407370955161 = - // 0x1999999999999999 + int i = 0; // 2^64 - 1 = 18446744073709551615, 1844674407370955161 = + // 0x1999999999999999 for (; i < dLen; i++) { if (significand > RAPIDJSON_UINT64_C2(0x19999999, 0x99999999) || (significand == RAPIDJSON_UINT64_C2(0x19999999, 0x99999999) && @@ -148,7 +147,7 @@ inline bool StrtodDiyFp(const char *decimals, int dLen, int dExp, significand = significand * 10u + static_cast(decimals[i] - '0'); } - if (i < dLen && decimals[i] >= '5') // Rounding + if (i < dLen && decimals[i] >= '5') // Rounding significand++; int remaining = dLen - i; @@ -166,18 +165,19 @@ inline bool StrtodDiyFp(const char *decimals, int dLen, int dExp, DiyFp cachedPower = GetCachedPower10(dExp, &actualExp); if (actualExp != dExp) { static const DiyFp kPow10[] = { - DiyFp(RAPIDJSON_UINT64_C2(0xa0000000, 0x00000000), -60), // 10^1 - DiyFp(RAPIDJSON_UINT64_C2(0xc8000000, 0x00000000), -57), // 10^2 - DiyFp(RAPIDJSON_UINT64_C2(0xfa000000, 0x00000000), -54), // 10^3 - DiyFp(RAPIDJSON_UINT64_C2(0x9c400000, 0x00000000), -50), // 10^4 - DiyFp(RAPIDJSON_UINT64_C2(0xc3500000, 0x00000000), -47), // 10^5 - DiyFp(RAPIDJSON_UINT64_C2(0xf4240000, 0x00000000), -44), // 10^6 - DiyFp(RAPIDJSON_UINT64_C2(0x98968000, 0x00000000), -40) // 10^7 + DiyFp(RAPIDJSON_UINT64_C2(0xa0000000, 0x00000000), -60), // 10^1 + DiyFp(RAPIDJSON_UINT64_C2(0xc8000000, 0x00000000), -57), // 10^2 + DiyFp(RAPIDJSON_UINT64_C2(0xfa000000, 0x00000000), -54), // 10^3 + DiyFp(RAPIDJSON_UINT64_C2(0x9c400000, 0x00000000), -50), // 10^4 + DiyFp(RAPIDJSON_UINT64_C2(0xc3500000, 0x00000000), -47), // 10^5 + DiyFp(RAPIDJSON_UINT64_C2(0xf4240000, 0x00000000), -44), // 10^6 + DiyFp(RAPIDJSON_UINT64_C2(0x98968000, 0x00000000), -40) // 10^7 }; int adjustment = dExp - actualExp; RAPIDJSON_ASSERT(adjustment >= 1 && adjustment < 8); v = v * kPow10[adjustment - 1]; - if (dLen + adjustment > 19) // has more digits than decimal digits in 64-bit + if (dLen + adjustment > + 19) // has more digits than decimal digits in 64-bit error += kUlp / 2; } @@ -207,7 +207,7 @@ inline bool StrtodDiyFp(const char *decimals, int dLen, int dExp, if (precisionBits >= halfWay + static_cast(error)) { rounded.f++; if (rounded.f & (DiyFp::kDpHiddenBit - << 1)) { // rounding overflows mantissa (issue #340) + << 1)) { // rounding overflows mantissa (issue #340) rounded.f >>= 1; rounded.e++; } @@ -226,14 +226,14 @@ inline double StrtodBigInteger(double approx, const char *decimals, int dLen, Double a(approx); int cmp = CheckWithinHalfULP(a.Value(), dInt, dExp); if (cmp < 0) - return a.Value(); // within half ULP + return a.Value(); // within half ULP else if (cmp == 0) { // Round towards even if (a.Significand() & 1) return a.NextPositiveDouble(); else return a.Value(); - } else // adjustment + } else // adjustment return a.NextPositiveDouble(); } @@ -244,8 +244,7 @@ inline double StrtodFullPrecision(double d, int p, const char *decimals, RAPIDJSON_ASSERT(length >= 1); double result = 0.0; - if (StrtodFast(d, p, &result)) - return result; + if (StrtodFast(d, p, &result)) return result; RAPIDJSON_ASSERT(length <= INT_MAX); int dLen = static_cast(length); @@ -272,7 +271,7 @@ inline double StrtodFullPrecision(double d, int p, const char *decimals, dExp++; } - if (dLen == 0) { // Buffer only contains zeros. + if (dLen == 0) { // Buffer only contains zeros. return 0.0; } @@ -285,23 +284,20 @@ inline double StrtodFullPrecision(double d, int p, const char *decimals, // If too small, underflow to zero. // Any x <= 10^-324 is interpreted as zero. - if (dLen + dExp <= -324) - return 0.0; + if (dLen + dExp <= -324) return 0.0; // If too large, overflow to infinity. // Any x >= 10^309 is interpreted as +infinity. - if (dLen + dExp > 309) - return std::numeric_limits::infinity(); + if (dLen + dExp > 309) return std::numeric_limits::infinity(); - if (StrtodDiyFp(decimals, dLen, dExp, &result)) - return result; + if (StrtodDiyFp(decimals, dLen, dExp, &result)) return result; // Use approximation from StrtodDiyFp and make adjustment with BigInteger // comparison return StrtodBigInteger(result, decimals, dLen, dExp); } -} // namespace internal +} // namespace internal RAPIDJSON_NAMESPACE_END -#endif // RAPIDJSON_STRTOD_ +#endif // RAPIDJSON_STRTOD_ diff --git a/livox_ros_driver/common/rapidjson/internal/swap.h b/livox_ros_driver/common/rapidjson/internal/swap.h index 7faa194..db41b18 100644 --- a/livox_ros_driver/common/rapidjson/internal/swap.h +++ b/livox_ros_driver/common/rapidjson/internal/swap.h @@ -33,17 +33,18 @@ namespace internal { /*! \tparam T Type of the arguments to swap, should be instantiated with primitive C++ types only. \note This has the same semantics as std::swap(). */ -template inline void Swap(T &a, T &b) RAPIDJSON_NOEXCEPT { +template +inline void Swap(T &a, T &b) RAPIDJSON_NOEXCEPT { T tmp = a; a = b; b = tmp; } -} // namespace internal +} // namespace internal RAPIDJSON_NAMESPACE_END #if defined(__clang__) RAPIDJSON_DIAG_POP #endif -#endif // RAPIDJSON_INTERNAL_SWAP_H_ +#endif // RAPIDJSON_INTERNAL_SWAP_H_ diff --git a/livox_ros_driver/common/rapidjson/istreamwrapper.h b/livox_ros_driver/common/rapidjson/istreamwrapper.h index 2b9de65..b9663b0 100644 --- a/livox_ros_driver/common/rapidjson/istreamwrapper.h +++ b/livox_ros_driver/common/rapidjson/istreamwrapper.h @@ -19,17 +19,17 @@ #ifndef RAPIDJSON_ISTREAMWRAPPER_H_ #define RAPIDJSON_ISTREAMWRAPPER_H_ -#include "stream.h" #include #include +#include "stream.h" #ifdef __clang__ RAPIDJSON_DIAG_PUSH RAPIDJSON_DIAG_OFF(padded) #elif defined(_MSC_VER) RAPIDJSON_DIAG_PUSH -RAPIDJSON_DIAG_OFF( - 4351) // new behavior: elements of array 'array' will be default initialized +RAPIDJSON_DIAG_OFF(4351) // new behavior: elements of array 'array' will be + // default initialized #endif RAPIDJSON_NAMESPACE_BEGIN @@ -50,8 +50,9 @@ RAPIDJSON_NAMESPACE_BEGIN \tparam StreamType Class derived from \c std::basic_istream. */ -template class BasicIStreamWrapper { -public: +template +class BasicIStreamWrapper { + public: typedef typename StreamType::char_type Ch; //! Constructor. @@ -59,8 +60,14 @@ template class BasicIStreamWrapper { \param stream stream opened for read. */ BasicIStreamWrapper(StreamType &stream) - : stream_(stream), buffer_(peekBuffer_), bufferSize_(4), bufferLast_(0), - current_(buffer_), readCount_(0), count_(0), eof_(false) { + : stream_(stream), + buffer_(peekBuffer_), + bufferSize_(4), + bufferLast_(0), + current_(buffer_), + readCount_(0), + count_(0), + eof_(false) { Read(); } @@ -71,8 +78,13 @@ template class BasicIStreamWrapper { \param bufferSize size of buffer in bytes. Must >=4 bytes. */ BasicIStreamWrapper(StreamType &stream, char *buffer, size_t bufferSize) - : stream_(stream), buffer_(buffer), bufferSize_(bufferSize), - bufferLast_(0), current_(buffer_), readCount_(0), count_(0), + : stream_(stream), + buffer_(buffer), + bufferSize_(bufferSize), + bufferLast_(0), + current_(buffer_), + readCount_(0), + count_(0), eof_(false) { RAPIDJSON_ASSERT(bufferSize >= 4); Read(); @@ -105,7 +117,7 @@ template class BasicIStreamWrapper { return (current_ + 4 - !eof_ <= bufferLast_) ? current_ : 0; } -private: + private: BasicIStreamWrapper(); BasicIStreamWrapper(const BasicIStreamWrapper &); BasicIStreamWrapper &operator=(const BasicIStreamWrapper &); @@ -133,7 +145,7 @@ template class BasicIStreamWrapper { Ch *bufferLast_; Ch *current_; size_t readCount_; - size_t count_; //!< Number of characters read + size_t count_; //!< Number of characters read bool eof_; }; @@ -146,4 +158,4 @@ RAPIDJSON_DIAG_POP RAPIDJSON_NAMESPACE_END -#endif // RAPIDJSON_ISTREAMWRAPPER_H_ +#endif // RAPIDJSON_ISTREAMWRAPPER_H_ diff --git a/livox_ros_driver/common/rapidjson/memorybuffer.h b/livox_ros_driver/common/rapidjson/memorybuffer.h index b0e8da7..a827d6a 100644 --- a/livox_ros_driver/common/rapidjson/memorybuffer.h +++ b/livox_ros_driver/common/rapidjson/memorybuffer.h @@ -40,8 +40,9 @@ RAPIDJSON_NAMESPACE_BEGIN \tparam Allocator type for allocating memory buffer. \note implements Stream concept */ -template struct GenericMemoryBuffer { - typedef char Ch; // byte +template +struct GenericMemoryBuffer { + typedef char Ch; // byte GenericMemoryBuffer(Allocator *allocator = 0, size_t capacity = kDefaultCapacity) @@ -67,10 +68,11 @@ typedef GenericMemoryBuffer<> MemoryBuffer; //! Implement specialized version of PutN() with memset() for better //! performance. -template <> inline void PutN(MemoryBuffer &memoryBuffer, char c, size_t n) { +template <> +inline void PutN(MemoryBuffer &memoryBuffer, char c, size_t n) { std::memset(memoryBuffer.stack_.Push(n), c, n * sizeof(c)); } RAPIDJSON_NAMESPACE_END -#endif // RAPIDJSON_MEMORYBUFFER_H_ +#endif // RAPIDJSON_MEMORYBUFFER_H_ diff --git a/livox_ros_driver/common/rapidjson/memorystream.h b/livox_ros_driver/common/rapidjson/memorystream.h index 00468fe..f542ece 100644 --- a/livox_ros_driver/common/rapidjson/memorystream.h +++ b/livox_ros_driver/common/rapidjson/memorystream.h @@ -46,7 +46,7 @@ RAPIDJSON_NAMESPACE_BEGIN Stream concept */ struct MemoryStream { - typedef char Ch; // byte + typedef char Ch; // byte MemoryStream(const Ch *src, size_t size) : src_(src), begin_(src), end_(src + size), size_(size) {} @@ -69,10 +69,10 @@ struct MemoryStream { // For encoding detection only. const Ch *Peek4() const { return Tell() + 4 <= size_ ? src_ : 0; } - const Ch *src_; //!< Current read position. - const Ch *begin_; //!< Original head of the string. - const Ch *end_; //!< End of stream. - size_t size_; //!< Size of the stream. + const Ch *src_; //!< Current read position. + const Ch *begin_; //!< Original head of the string. + const Ch *end_; //!< End of stream. + size_t size_; //!< Size of the stream. }; RAPIDJSON_NAMESPACE_END @@ -81,4 +81,4 @@ RAPIDJSON_NAMESPACE_END RAPIDJSON_DIAG_POP #endif -#endif // RAPIDJSON_MEMORYBUFFER_H_ +#endif // RAPIDJSON_MEMORYBUFFER_H_ diff --git a/livox_ros_driver/common/rapidjson/msinttypes/inttypes.h b/livox_ros_driver/common/rapidjson/msinttypes/inttypes.h index 1915a69..bc32dad 100644 --- a/livox_ros_driver/common/rapidjson/msinttypes/inttypes.h +++ b/livox_ros_driver/common/rapidjson/msinttypes/inttypes.h @@ -34,11 +34,11 @@ // THL A29 Limited ("Tencent Modifications"). // All Tencent Modifications are Copyright (C) 2015 THL A29 Limited. -#ifndef _MSC_VER // [ +#ifndef _MSC_VER // [ #error "Use this header only with Microsoft Visual C++ compilers!" -#endif // _MSC_VER ] +#endif // _MSC_VER ] -#ifndef _MSC_INTTYPES_H_ // [ +#ifndef _MSC_INTTYPES_H_ // [ #define _MSC_INTTYPES_H_ #if _MSC_VER > 1000 @@ -61,8 +61,8 @@ typedef struct { // 7.8.1 Macros for format specifiers -#if !defined(__cplusplus) || \ - defined(__STDC_FORMAT_MACROS) // [ See footnote 185 at page 198 +#if !defined(__cplusplus) || \ + defined(__STDC_FORMAT_MACROS) // [ See footnote 185 at page 198 // The fprintf macros for signed integers are: #define PRId8 "d" @@ -194,13 +194,13 @@ typedef struct { #define SCNdMAX "I64d" #define SCNiMAX "I64i" -#ifdef _WIN64 // [ +#ifdef _WIN64 // [ #define SCNdPTR "I64d" #define SCNiPTR "I64i" -#else // _WIN64 ][ +#else // _WIN64 ][ #define SCNdPTR "ld" #define SCNiPTR "li" -#endif // _WIN64 ] +#endif // _WIN64 ] // The fscanf macros for unsigned integers are: #define SCNo8 "o" @@ -260,19 +260,19 @@ typedef struct { #define SCNxMAX "I64x" #define SCNXMAX "I64X" -#ifdef _WIN64 // [ +#ifdef _WIN64 // [ #define SCNoPTR "I64o" #define SCNuPTR "I64u" #define SCNxPTR "I64x" #define SCNXPTR "I64X" -#else // _WIN64 ][ +#else // _WIN64 ][ #define SCNoPTR "lo" #define SCNuPTR "lu" #define SCNxPTR "lx" #define SCNXPTR "lX" -#endif // _WIN64 ] +#endif // _WIN64 ] -#endif // __STDC_FORMAT_MACROS ] +#endif // __STDC_FORMAT_MACROS ] // 7.8.2 Functions for greatest-width integer types @@ -283,11 +283,11 @@ typedef struct { // This is modified version of div() function from Microsoft's div.c found // in %MSVC.NET%\crt\src\div.c -#ifdef STATIC_IMAXDIV // [ +#ifdef STATIC_IMAXDIV // [ static -#else // STATIC_IMAXDIV ][ +#else // STATIC_IMAXDIV ][ _inline -#endif // STATIC_IMAXDIV ] +#endif // STATIC_IMAXDIV ] imaxdiv_t __cdecl imaxdiv(intmax_t numer, intmax_t denom) { imaxdiv_t result; @@ -311,6 +311,6 @@ _inline #define wcstoimax _wcstoi64 #define wcstoumax _wcstoui64 -#endif // _MSC_VER >= 1800 +#endif // _MSC_VER >= 1800 -#endif // _MSC_INTTYPES_H_ ] +#endif // _MSC_INTTYPES_H_ ] diff --git a/livox_ros_driver/common/rapidjson/msinttypes/stdint.h b/livox_ros_driver/common/rapidjson/msinttypes/stdint.h index 5a78ad3..8fd0655 100644 --- a/livox_ros_driver/common/rapidjson/msinttypes/stdint.h +++ b/livox_ros_driver/common/rapidjson/msinttypes/stdint.h @@ -34,11 +34,11 @@ // THL A29 Limited ("Tencent Modifications"). // All Tencent Modifications are Copyright (C) 2015 THL A29 Limited. -#ifndef _MSC_VER // [ +#ifndef _MSC_VER // [ #error "Use this header only with Microsoft Visual C++ compilers!" -#endif // _MSC_VER ] +#endif // _MSC_VER ] -#ifndef _MSC_STDINT_H_ // [ +#ifndef _MSC_STDINT_H_ // [ #define _MSC_STDINT_H_ #if _MSC_VER > 1000 @@ -47,11 +47,11 @@ // 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. -#if _MSC_VER >= 1600 // [ +#if _MSC_VER >= 1600 // [ #include -#if !defined(__cplusplus) || \ - defined(__STDC_CONSTANT_MACROS) // [ See footnote 224 at page 260 +#if !defined(__cplusplus) || \ + defined(__STDC_CONSTANT_MACROS) // [ See footnote 224 at page 260 #undef INT8_C #undef INT16_C @@ -77,16 +77,16 @@ // 7.18.4.2 Macros for greatest-width integer constants // These #ifndef's are needed to prevent collisions with . // Check out Issue 9 for the details. -#ifndef INTMAX_C // [ +#ifndef INTMAX_C // [ #define INTMAX_C INT64_C -#endif // INTMAX_C ] -#ifndef UINTMAX_C // [ +#endif // INTMAX_C ] +#ifndef UINTMAX_C // [ #define UINTMAX_C UINT64_C -#endif // UINTMAX_C ] +#endif // UINTMAX_C ] -#endif // __STDC_CONSTANT_MACROS ] +#endif // __STDC_CONSTANT_MACROS ] -#else // ] _MSC_VER >= 1700 [ +#else // ] _MSC_VER >= 1700 [ #include @@ -157,13 +157,13 @@ typedef uint32_t uint_fast32_t; typedef uint64_t uint_fast64_t; // 7.18.1.4 Integer types capable of holding object pointers -#ifdef _WIN64 // [ +#ifdef _WIN64 // [ typedef signed __int64 intptr_t; typedef unsigned __int64 uintptr_t; -#else // _WIN64 ][ +#else // _WIN64 ][ typedef _W64 signed int intptr_t; typedef _W64 unsigned int uintptr_t; -#endif // _WIN64 ] +#endif // _WIN64 ] // 7.18.1.5 Greatest-width integer types typedef int64_t intmax_t; @@ -171,9 +171,9 @@ typedef uint64_t uintmax_t; // 7.18.2 Limits of specified-width integer types -#if !defined(__cplusplus) || \ - defined(__STDC_LIMIT_MACROS) // [ See footnote 220 at page 257 and - // footnote 221 at page 259 +#if !defined(__cplusplus) || \ + defined(__STDC_LIMIT_MACROS) // [ See footnote 220 at page 257 and +// footnote 221 at page 259 // 7.18.2.1 Limits of exact-width integer types #define INT8_MIN ((int8_t)_I8_MIN) @@ -218,15 +218,15 @@ typedef uint64_t uintmax_t; #define UINT_FAST64_MAX UINT64_MAX // 7.18.2.4 Limits of integer types capable of holding object pointers -#ifdef _WIN64 // [ +#ifdef _WIN64 // [ #define INTPTR_MIN INT64_MIN #define INTPTR_MAX INT64_MAX #define UINTPTR_MAX UINT64_MAX -#else // _WIN64 ][ +#else // _WIN64 ][ #define INTPTR_MIN INT32_MIN #define INTPTR_MAX INT32_MAX #define UINTPTR_MAX UINT32_MAX -#endif // _WIN64 ] +#endif // _WIN64 ] // 7.18.2.5 Limits of greatest-width integer types #define INTMAX_MIN INT64_MIN @@ -235,42 +235,42 @@ typedef uint64_t uintmax_t; // 7.18.3 Limits of other integer types -#ifdef _WIN64 // [ +#ifdef _WIN64 // [ #define PTRDIFF_MIN _I64_MIN #define PTRDIFF_MAX _I64_MAX -#else // _WIN64 ][ +#else // _WIN64 ][ #define PTRDIFF_MIN _I32_MIN #define PTRDIFF_MAX _I32_MAX -#endif // _WIN64 ] +#endif // _WIN64 ] #define SIG_ATOMIC_MIN INT_MIN #define SIG_ATOMIC_MAX INT_MAX -#ifndef SIZE_MAX // [ -#ifdef _WIN64 // [ +#ifndef SIZE_MAX // [ +#ifdef _WIN64 // [ #define SIZE_MAX _UI64_MAX -#else // _WIN64 ][ +#else // _WIN64 ][ #define SIZE_MAX _UI32_MAX -#endif // _WIN64 ] -#endif // SIZE_MAX ] +#endif // _WIN64 ] +#endif // SIZE_MAX ] // WCHAR_MIN and WCHAR_MAX are also defined in -#ifndef WCHAR_MIN // [ +#ifndef WCHAR_MIN // [ #define WCHAR_MIN 0 -#endif // WCHAR_MIN ] -#ifndef WCHAR_MAX // [ +#endif // WCHAR_MIN ] +#ifndef WCHAR_MAX // [ #define WCHAR_MAX _UI16_MAX -#endif // WCHAR_MAX ] +#endif // WCHAR_MAX ] #define WINT_MIN 0 #define WINT_MAX _UI16_MAX -#endif // __STDC_LIMIT_MACROS ] +#endif // __STDC_LIMIT_MACROS ] // 7.18.4 Limits of other integer types -#if !defined(__cplusplus) || \ - defined(__STDC_CONSTANT_MACROS) // [ See footnote 224 at page 260 +#if !defined(__cplusplus) || \ + defined(__STDC_CONSTANT_MACROS) // [ See footnote 224 at page 260 // 7.18.4.1 Macros for minimum-width integer constants @@ -287,15 +287,15 @@ typedef uint64_t uintmax_t; // 7.18.4.2 Macros for greatest-width integer constants // These #ifndef's are needed to prevent collisions with . // Check out Issue 9 for the details. -#ifndef INTMAX_C // [ +#ifndef INTMAX_C // [ #define INTMAX_C INT64_C -#endif // INTMAX_C ] -#ifndef UINTMAX_C // [ +#endif // INTMAX_C ] +#ifndef UINTMAX_C // [ #define UINTMAX_C UINT64_C -#endif // UINTMAX_C ] +#endif // UINTMAX_C ] -#endif // __STDC_CONSTANT_MACROS ] +#endif // __STDC_CONSTANT_MACROS ] -#endif // _MSC_VER >= 1600 ] +#endif // _MSC_VER >= 1600 ] -#endif // _MSC_STDINT_H_ ] +#endif // _MSC_STDINT_H_ ] diff --git a/livox_ros_driver/common/rapidjson/ostreamwrapper.h b/livox_ros_driver/common/rapidjson/ostreamwrapper.h index 441b035..56c50a7 100644 --- a/livox_ros_driver/common/rapidjson/ostreamwrapper.h +++ b/livox_ros_driver/common/rapidjson/ostreamwrapper.h @@ -19,8 +19,8 @@ #ifndef RAPIDJSON_OSTREAMWRAPPER_H_ #define RAPIDJSON_OSTREAMWRAPPER_H_ -#include "stream.h" #include +#include "stream.h" #ifdef __clang__ RAPIDJSON_DIAG_PUSH @@ -45,8 +45,9 @@ RAPIDJSON_NAMESPACE_BEGIN \tparam StreamType Class derived from \c std::basic_ostream. */ -template class BasicOStreamWrapper { -public: +template +class BasicOStreamWrapper { + public: typedef typename StreamType::char_type Ch; BasicOStreamWrapper(StreamType &stream) : stream_(stream) {} @@ -76,7 +77,7 @@ template class BasicOStreamWrapper { return 0; } -private: + private: BasicOStreamWrapper(const BasicOStreamWrapper &); BasicOStreamWrapper &operator=(const BasicOStreamWrapper &); @@ -92,4 +93,4 @@ RAPIDJSON_DIAG_POP RAPIDJSON_NAMESPACE_END -#endif // RAPIDJSON_OSTREAMWRAPPER_H_ +#endif // RAPIDJSON_OSTREAMWRAPPER_H_ diff --git a/livox_ros_driver/common/rapidjson/pointer.h b/livox_ros_driver/common/rapidjson/pointer.h index d047b19..218dd6c 100644 --- a/livox_ros_driver/common/rapidjson/pointer.h +++ b/livox_ros_driver/common/rapidjson/pointer.h @@ -27,28 +27,29 @@ RAPIDJSON_DIAG_PUSH RAPIDJSON_DIAG_OFF(switch - enum) #elif defined(_MSC_VER) RAPIDJSON_DIAG_PUSH -RAPIDJSON_DIAG_OFF(4512) // assignment operator could not be generated +RAPIDJSON_DIAG_OFF(4512) // assignment operator could not be generated #endif RAPIDJSON_NAMESPACE_BEGIN static const SizeType kPointerInvalidIndex = - ~SizeType(0); //!< Represents an invalid index in GenericPointer::Token + ~SizeType(0); //!< Represents an invalid index in GenericPointer::Token //! Error code of parsing. /*! \ingroup RAPIDJSON_ERRORS \see GenericPointer::GenericPointer, GenericPointer::GetParseErrorCode */ enum PointerParseErrorCode { - kPointerParseErrorNone = 0, //!< The parse is successful - - kPointerParseErrorTokenMustBeginWithSolidus, //!< A token must begin with a - //!< '/' - kPointerParseErrorInvalidEscape, //!< Invalid escape - kPointerParseErrorInvalidPercentEncoding, //!< Invalid percent encoding in URI - //!< fragment - kPointerParseErrorCharacterMustPercentEncode //!< A character must percent - //!< encoded in URI fragment + kPointerParseErrorNone = 0, //!< The parse is successful + + kPointerParseErrorTokenMustBeginWithSolidus, //!< A token must begin with a + //!< '/' + kPointerParseErrorInvalidEscape, //!< Invalid escape + kPointerParseErrorInvalidPercentEncoding, //!< Invalid percent encoding in + //!URI + //!< fragment + kPointerParseErrorCharacterMustPercentEncode //!< A character must percent + //!< encoded in URI fragment }; /////////////////////////////////////////////////////////////////////////////// @@ -87,10 +88,10 @@ enum PointerParseErrorCode { */ template class GenericPointer { -public: + public: typedef typename ValueType::EncodingType - EncodingType; //!< Encoding type from Value - typedef typename ValueType::Ch Ch; //!< Character type from Value + EncodingType; //!< Encoding type from Value + typedef typename ValueType::Ch Ch; //!< Character type from Value //! A token is the basic units of internal representation. /*! @@ -107,11 +108,12 @@ class GenericPointer { and allocation, using a special constructor. */ struct Token { - const Ch *name; //!< Name of the token. It has null character at the end but - //!< it can contain null character. - SizeType length; //!< Length of the name. - SizeType index; //!< A valid array index, if it is not equal to - //!< kPointerInvalidIndex. + const Ch + *name; //!< Name of the token. It has null character at the end but + //!< it can contain null character. + SizeType length; //!< Length of the name. + SizeType index; //!< A valid array index, if it is not equal to + //!< kPointerInvalidIndex. }; //!@name Constructors and destructor. @@ -119,8 +121,12 @@ class GenericPointer { //! Default constructor. GenericPointer(Allocator *allocator = 0) - : allocator_(allocator), ownAllocator_(), nameBuffer_(), tokens_(), - tokenCount_(), parseErrorOffset_(), + : allocator_(allocator), + ownAllocator_(), + nameBuffer_(), + tokens_(), + tokenCount_(), + parseErrorOffset_(), parseErrorCode_(kPointerParseErrorNone) {} //! Constructor that parses a string or URI fragment representation. @@ -130,8 +136,12 @@ class GenericPointer { no allocator is provided, it creates a self-owned one. */ explicit GenericPointer(const Ch *source, Allocator *allocator = 0) - : allocator_(allocator), ownAllocator_(), nameBuffer_(), tokens_(), - tokenCount_(), parseErrorOffset_(), + : allocator_(allocator), + ownAllocator_(), + nameBuffer_(), + tokens_(), + tokenCount_(), + parseErrorOffset_(), parseErrorCode_(kPointerParseErrorNone) { Parse(source, internal::StrLen(source)); } @@ -146,8 +156,12 @@ class GenericPointer { */ explicit GenericPointer(const std::basic_string &source, Allocator *allocator = 0) - : allocator_(allocator), ownAllocator_(), nameBuffer_(), tokens_(), - tokenCount_(), parseErrorOffset_(), + : allocator_(allocator), + ownAllocator_(), + nameBuffer_(), + tokens_(), + tokenCount_(), + parseErrorOffset_(), parseErrorCode_(kPointerParseErrorNone) { Parse(source.c_str(), source.size()); } @@ -163,8 +177,12 @@ class GenericPointer { overload without length. */ GenericPointer(const Ch *source, size_t length, Allocator *allocator = 0) - : allocator_(allocator), ownAllocator_(), nameBuffer_(), tokens_(), - tokenCount_(), parseErrorOffset_(), + : allocator_(allocator), + ownAllocator_(), + nameBuffer_(), + tokens_(), + tokenCount_(), + parseErrorOffset_(), parseErrorCode_(kPointerParseErrorNone) { Parse(source, length); } @@ -192,30 +210,43 @@ class GenericPointer { \endcode */ GenericPointer(const Token *tokens, size_t tokenCount) - : allocator_(), ownAllocator_(), nameBuffer_(), - tokens_(const_cast(tokens)), tokenCount_(tokenCount), - parseErrorOffset_(), parseErrorCode_(kPointerParseErrorNone) {} + : allocator_(), + ownAllocator_(), + nameBuffer_(), + tokens_(const_cast(tokens)), + tokenCount_(tokenCount), + parseErrorOffset_(), + parseErrorCode_(kPointerParseErrorNone) {} //! Copy constructor. GenericPointer(const GenericPointer &rhs) - : allocator_(rhs.allocator_), ownAllocator_(), nameBuffer_(), tokens_(), - tokenCount_(), parseErrorOffset_(), + : allocator_(rhs.allocator_), + ownAllocator_(), + nameBuffer_(), + tokens_(), + tokenCount_(), + parseErrorOffset_(), parseErrorCode_(kPointerParseErrorNone) { *this = rhs; } //! Copy constructor. GenericPointer(const GenericPointer &rhs, Allocator *allocator) - : allocator_(allocator), ownAllocator_(), nameBuffer_(), tokens_(), - tokenCount_(), parseErrorOffset_(), + : allocator_(allocator), + ownAllocator_(), + nameBuffer_(), + tokens_(), + tokenCount_(), + parseErrorOffset_(), parseErrorCode_(kPointerParseErrorNone) { *this = rhs; } //! Destructor. ~GenericPointer() { - if (nameBuffer_) // If user-supplied tokens constructor is used, nameBuffer_ - // is nullptr and tokens_ are not deallocated. + if (nameBuffer_) // If user-supplied tokens constructor is used, + // nameBuffer_ + // is nullptr and tokens_ are not deallocated. Allocator::Free(tokens_); RAPIDJSON_DELETE(ownAllocator_); } @@ -224,17 +255,16 @@ class GenericPointer { GenericPointer &operator=(const GenericPointer &rhs) { if (this != &rhs) { // Do not delete ownAllcator - if (nameBuffer_) - Allocator::Free(tokens_); + if (nameBuffer_) Allocator::Free(tokens_); tokenCount_ = rhs.tokenCount_; parseErrorOffset_ = rhs.parseErrorOffset_; parseErrorCode_ = rhs.parseErrorCode_; if (rhs.nameBuffer_) - CopyFromRaw(rhs); // Normally parsed tokens. + CopyFromRaw(rhs); // Normally parsed tokens. else { - tokens_ = rhs.tokens_; // User supplied const tokens. + tokens_ = rhs.tokens_; // User supplied const tokens. nameBuffer_ = 0; } } @@ -353,8 +383,7 @@ class GenericPointer { return Append(token, allocator); } else { Ch name[21]; - for (size_t i = 0; i <= length; i++) - name[i] = static_cast(buffer[i]); + for (size_t i = 0; i <= length; i++) name[i] = static_cast(buffer[i]); Token token = {name, length, index}; return Append(token, allocator); } @@ -440,13 +469,10 @@ class GenericPointer { \note Invalid pointers are always greater than valid ones. */ bool operator<(const GenericPointer &rhs) const { - if (!IsValid()) - return false; - if (!rhs.IsValid()) - return true; + if (!IsValid()) return false; + if (!rhs.IsValid()) return true; - if (tokenCount_ != rhs.tokenCount_) - return tokenCount_ < rhs.tokenCount_; + if (tokenCount_ != rhs.tokenCount_) return tokenCount_ < rhs.tokenCount_; for (size_t i = 0; i < tokenCount_; i++) { if (tokens_[i].index != rhs.tokens_[i].index) @@ -473,7 +499,8 @@ class GenericPointer { \tparam OutputStream Type of output stream. \param os The output stream. */ - template bool Stringify(OutputStream &os) const { + template + bool Stringify(OutputStream &os) const { return Stringify(os); } @@ -521,12 +548,11 @@ class GenericPointer { v = &((*v)[v->Size() - 1]); exist = false; } else { - if (t->index == kPointerInvalidIndex) { // must be object name - if (!v->IsObject()) - v->SetObject(); // Change to Object - } else { // object name or array index + if (t->index == kPointerInvalidIndex) { // must be object name + if (!v->IsObject()) v->SetObject(); // Change to Object + } else { // object name or array index if (!v->IsArray() && !v->IsObject()) - v->SetArray(); // Change to Array + v->SetArray(); // Change to Array } if (v->IsArray()) { @@ -545,7 +571,7 @@ class GenericPointer { v->AddMember(ValueType(t->name, t->length, allocator).Move(), ValueType().Move(), allocator); m = v->MemberEnd(); - v = &(--m)->value; // Assumes AddMember() appends at the end + v = &(--m)->value; // Assumes AddMember() appends at the end exist = false; } else v = &m->value; @@ -553,8 +579,7 @@ class GenericPointer { } } - if (alreadyExist) - *alreadyExist = exist; + if (alreadyExist) *alreadyExist = exist; return *v; } @@ -566,10 +591,10 @@ class GenericPointer { already exist. \return The resolved newly created, or already exists value. */ template - ValueType & - Create(GenericDocument &document, - bool *alreadyExist = 0) const { + ValueType &Create( + GenericDocument &document, + bool *alreadyExist = 0) const { return Create(document, document.GetAllocator(), alreadyExist); } @@ -599,22 +624,20 @@ class GenericPointer { ValueType *v = &root; for (const Token *t = tokens_; t != tokens_ + tokenCount_; ++t) { switch (v->GetType()) { - case kObjectType: { - typename ValueType::MemberIterator m = - v->FindMember(GenericValue( - GenericStringRef(t->name, t->length))); - if (m == v->MemberEnd()) - break; - v = &m->value; - } - continue; - case kArrayType: - if (t->index == kPointerInvalidIndex || t->index >= v->Size()) + case kObjectType: { + typename ValueType::MemberIterator m = + v->FindMember(GenericValue( + GenericStringRef(t->name, t->length))); + if (m == v->MemberEnd()) break; + v = &m->value; + } + continue; + case kArrayType: + if (t->index == kPointerInvalidIndex || t->index >= v->Size()) break; + v = &((*v)[t->index]); + continue; + default: break; - v = &((*v)[t->index]); - continue; - default: - break; } // Error: unresolved token @@ -652,18 +675,18 @@ class GenericPointer { the values if the specified value or its parents are not exist. \see Create() */ - ValueType & - GetWithDefault(ValueType &root, const ValueType &defaultValue, - typename ValueType::AllocatorType &allocator) const { + ValueType &GetWithDefault( + ValueType &root, const ValueType &defaultValue, + typename ValueType::AllocatorType &allocator) const { bool alreadyExist; ValueType &v = Create(root, allocator, &alreadyExist); return alreadyExist ? v : v.CopyFrom(defaultValue, allocator); } //! Query a value in a subtree with default null-terminated string. - ValueType & - GetWithDefault(ValueType &root, const Ch *defaultValue, - typename ValueType::AllocatorType &allocator) const { + ValueType &GetWithDefault( + ValueType &root, const Ch *defaultValue, + typename ValueType::AllocatorType &allocator) const { bool alreadyExist; ValueType &v = Create(root, allocator, &alreadyExist); return alreadyExist ? v : v.SetString(defaultValue, allocator); @@ -671,9 +694,9 @@ class GenericPointer { #if RAPIDJSON_HAS_STDSTRING //! Query a value in a subtree with default std::basic_string. - ValueType & - GetWithDefault(ValueType &root, const std::basic_string &defaultValue, - typename ValueType::AllocatorType &allocator) const { + ValueType &GetWithDefault( + ValueType &root, const std::basic_string &defaultValue, + typename ValueType::AllocatorType &allocator) const { bool alreadyExist; ValueType &v = Create(root, allocator, &alreadyExist); return alreadyExist ? v : v.SetString(defaultValue, allocator); @@ -796,8 +819,8 @@ class GenericPointer { //! Set a value in a document, with move semantics. template - ValueType & - Set(GenericDocument &document, ValueType &value) const { return Create(document) = value; @@ -805,8 +828,8 @@ class GenericPointer { //! Set a value in a document, with copy semantics. template - ValueType & - Set(GenericDocument &document, const ValueType &value) const { return Create(document).CopyFrom(value, document.GetAllocator()); @@ -814,8 +837,8 @@ class GenericPointer { //! Set a null-terminated string in a document. template - ValueType & - Set(GenericDocument &document, const Ch *value) const { return Create(document) = ValueType(value, document.GetAllocator()).Move(); @@ -824,8 +847,8 @@ class GenericPointer { #if RAPIDJSON_HAS_STDSTRING //! Sets a std::basic_string in a document. template - ValueType & - Set(GenericDocument &document, const std::basic_string &value) const { return Create(document) = ValueType(value, document.GetAllocator()).Move(); @@ -870,10 +893,10 @@ class GenericPointer { //! Swap a value with a value in a document. template - ValueType & - Swap(GenericDocument &document, - ValueType &value) const { + ValueType &Swap( + GenericDocument &document, + ValueType &value) const { return Create(document).Swap(value); } @@ -890,45 +913,44 @@ class GenericPointer { */ bool Erase(ValueType &root) const { RAPIDJSON_ASSERT(IsValid()); - if (tokenCount_ == 0) // Cannot erase the root + if (tokenCount_ == 0) // Cannot erase the root return false; ValueType *v = &root; const Token *last = tokens_ + (tokenCount_ - 1); for (const Token *t = tokens_; t != last; ++t) { switch (v->GetType()) { - case kObjectType: { - typename ValueType::MemberIterator m = - v->FindMember(GenericValue( - GenericStringRef(t->name, t->length))); - if (m == v->MemberEnd()) - return false; - v = &m->value; - } break; - case kArrayType: - if (t->index == kPointerInvalidIndex || t->index >= v->Size()) + case kObjectType: { + typename ValueType::MemberIterator m = + v->FindMember(GenericValue( + GenericStringRef(t->name, t->length))); + if (m == v->MemberEnd()) return false; + v = &m->value; + } break; + case kArrayType: + if (t->index == kPointerInvalidIndex || t->index >= v->Size()) + return false; + v = &((*v)[t->index]); + break; + default: return false; - v = &((*v)[t->index]); - break; - default: - return false; } } switch (v->GetType()) { - case kObjectType: - return v->EraseMember(GenericStringRef(last->name, last->length)); - case kArrayType: - if (last->index == kPointerInvalidIndex || last->index >= v->Size()) + case kObjectType: + return v->EraseMember(GenericStringRef(last->name, last->length)); + case kArrayType: + if (last->index == kPointerInvalidIndex || last->index >= v->Size()) + return false; + v->Erase(v->Begin() + last->index); + return true; + default: return false; - v->Erase(v->Begin() + last->index); - return true; - default: - return false; } } -private: + private: //! Clone the content from rhs to this. /*! \param rhs Source pointer. @@ -939,10 +961,10 @@ class GenericPointer { */ Ch *CopyFromRaw(const GenericPointer &rhs, size_t extraToken = 0, size_t extraNameBufferSize = 0) { - if (!allocator_) // allocator is independently owned. + if (!allocator_) // allocator is independently owned. ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator)(); - size_t nameBufferSize = rhs.tokenCount_; // null terminators for tokens + size_t nameBufferSize = rhs.tokenCount_; // null terminators for tokens for (Token *t = rhs.tokens_; t != rhs.tokens_ + rhs.tokenCount_; ++t) nameBufferSize += t->length; @@ -977,14 +999,16 @@ class GenericPointer { c == '~'); } - //! Parse a JSON String or its URI fragment representation into tokens. -#ifndef __clang__ // -Wdocumentation - /*! - \param source Either a JSON Pointer string, or its URI fragment - representation. Not need to be null terminated. \param length Length of the - source string. \note Source cannot be JSON String Representation of JSON - Pointer, e.g. In "/\u0000", \u0000 will not be unescaped. - */ +//! Parse a JSON String or its URI fragment representation into tokens. +#ifndef __clang__ // -Wdocumentation + /*! + \param source Either a JSON Pointer string, or its URI fragment + representation. Not need to be null terminated. \param length + Length of the + source string. \note Source cannot be JSON String + Representation of JSON + Pointer, e.g. In "/\u0000", \u0000 will not be unescaped. + */ #endif void Parse(const Ch *source, size_t length) { RAPIDJSON_ASSERT(source != NULL); @@ -992,14 +1016,12 @@ class GenericPointer { RAPIDJSON_ASSERT(tokens_ == 0); // Create own allocator if user did not supply. - if (!allocator_) - ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator)(); + if (!allocator_) ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator)(); // Count number of '/' as tokenCount tokenCount_ = 0; for (const Ch *s = source; s != source + length; s++) - if (*s == '/') - tokenCount_++; + if (*s == '/') tokenCount_++; Token *token = tokens_ = static_cast( allocator_->Malloc(tokenCount_ * sizeof(Token) + length * sizeof(Ch))); @@ -1020,7 +1042,7 @@ class GenericPointer { while (i < length) { RAPIDJSON_ASSERT(source[i] == '/'); - i++; // consumes '/' + i++; // consumes '/' token->name = name; bool isNumber = true; @@ -1076,15 +1098,13 @@ class GenericPointer { } // First check for index: all of characters are digit - if (c < '0' || c > '9') - isNumber = false; + if (c < '0' || c > '9') isNumber = false; *name++ = c; } token->length = static_cast(name - token->name); - if (token->length == 0) - isNumber = false; - *name++ = '\0'; // Null terminator + if (token->length == 0) isNumber = false; + *name++ = '\0'; // Null terminator // Second check for index: more than one digit cannot have leading zero if (isNumber && token->length > 1 && token->name[0] == '0') @@ -1095,7 +1115,7 @@ class GenericPointer { if (isNumber) { for (size_t j = 0; j < token->length; j++) { SizeType m = n * 10 + static_cast(token->name[j] - '0'); - if (m < n) { // overflow detection + if (m < n) { // overflow detection isNumber = false; break; } @@ -1108,7 +1128,7 @@ class GenericPointer { } RAPIDJSON_ASSERT(name <= - nameBuffer_ + length); // Should not overflow buffer + nameBuffer_ + length); // Should not overflow buffer parseErrorCode_ = kPointerParseErrorNone; return; @@ -1131,8 +1151,7 @@ class GenericPointer { bool Stringify(OutputStream &os) const { RAPIDJSON_ASSERT(IsValid()); - if (uriFragment) - os.Put('#'); + if (uriFragment) os.Put('#'); for (Token *t = tokens_; t != tokens_ + tokenCount_; ++t) { os.Put('/'); @@ -1166,7 +1185,7 @@ class GenericPointer { mark invalid, and to be checked by IsValid(). */ class PercentDecodeStream { - public: + public: typedef typename ValueType::Ch Ch; //! Constructor @@ -1178,7 +1197,7 @@ class GenericPointer { : src_(source), head_(source), end_(end), valid_(true) {} Ch Take() { - if (*src_ != '%' || src_ + 3 > end_) { // %XY triplet + if (*src_ != '%' || src_ + 3 > end_) { // %XY triplet valid_ = false; return 0; } @@ -1205,19 +1224,20 @@ class GenericPointer { size_t Tell() const { return static_cast(src_ - head_); } bool IsValid() const { return valid_; } - private: - const Ch *src_; //!< Current read position. - const Ch *head_; //!< Original head of the string. - const Ch *end_; //!< Past-the-end position. - bool valid_; //!< Whether the parsing is valid. + private: + const Ch *src_; //!< Current read position. + const Ch *head_; //!< Original head of the string. + const Ch *end_; //!< Past-the-end position. + bool valid_; //!< Whether the parsing is valid. }; //! A helper stream to encode character (UTF-8 code unit) into percent-encoded //! sequence. - template class PercentEncodeStream { - public: + template + class PercentEncodeStream { + public: PercentEncodeStream(OutputStream &os) : os_(os) {} - void Put(char c) { // UTF-8 must be byte + void Put(char c) { // UTF-8 must be byte unsigned char u = static_cast(c); static const char hexDigits[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', @@ -1227,18 +1247,18 @@ class GenericPointer { os_.Put(static_cast(hexDigits[u & 15])); } - private: + private: OutputStream &os_; }; - Allocator *allocator_; //!< The current allocator. It is either user-supplied - //!< or equal to ownAllocator_. - Allocator *ownAllocator_; //!< Allocator owned by this Pointer. - Ch *nameBuffer_; //!< A buffer containing all names in tokens. - Token *tokens_; //!< A list of tokens. - size_t tokenCount_; //!< Number of tokens in tokens_. - size_t parseErrorOffset_; //!< Offset in code unit when parsing fail. - PointerParseErrorCode parseErrorCode_; //!< Parsing error code. + Allocator *allocator_; //!< The current allocator. It is either user-supplied + //!< or equal to ownAllocator_. + Allocator *ownAllocator_; //!< Allocator owned by this Pointer. + Ch *nameBuffer_; //!< A buffer containing all names in tokens. + Token *tokens_; //!< A list of tokens. + size_t tokenCount_; //!< Number of tokens in tokens_. + size_t parseErrorOffset_; //!< Offset in code unit when parsing fail. + PointerParseErrorCode parseErrorCode_; //!< Parsing error code. }; //! GenericPointer for Value (UTF-8, default allocator). @@ -1250,10 +1270,9 @@ typedef GenericPointer Pointer; ////////////////////////////////////////////////////////////////////////////// template -typename T::ValueType & -CreateValueByPointer(T &root, - const GenericPointer &pointer, - typename T::AllocatorType &a) { +typename T::ValueType &CreateValueByPointer( + T &root, const GenericPointer &pointer, + typename T::AllocatorType &a) { return pointer.Create(root, a); } @@ -1274,8 +1293,8 @@ typename DocumentType::ValueType &CreateValueByPointer( } template -typename DocumentType::ValueType & -CreateValueByPointer(DocumentType &document, const CharType (&source)[N]) { +typename DocumentType::ValueType &CreateValueByPointer( + DocumentType &document, const CharType (&source)[N]) { return GenericPointer(source, N - 1) .Create(document); } @@ -1283,17 +1302,16 @@ CreateValueByPointer(DocumentType &document, const CharType (&source)[N]) { ////////////////////////////////////////////////////////////////////////////// template -typename T::ValueType * -GetValueByPointer(T &root, const GenericPointer &pointer, - size_t *unresolvedTokenIndex = 0) { +typename T::ValueType *GetValueByPointer( + T &root, const GenericPointer &pointer, + size_t *unresolvedTokenIndex = 0) { return pointer.Get(root, unresolvedTokenIndex); } template -const typename T::ValueType * -GetValueByPointer(const T &root, - const GenericPointer &pointer, - size_t *unresolvedTokenIndex = 0) { +const typename T::ValueType *GetValueByPointer( + const T &root, const GenericPointer &pointer, + size_t *unresolvedTokenIndex = 0) { return pointer.Get(root, unresolvedTokenIndex); } @@ -1305,9 +1323,9 @@ typename T::ValueType *GetValueByPointer(T &root, const CharType (&source)[N], } template -const typename T::ValueType * -GetValueByPointer(const T &root, const CharType (&source)[N], - size_t *unresolvedTokenIndex = 0) { +const typename T::ValueType *GetValueByPointer( + const T &root, const CharType (&source)[N], + size_t *unresolvedTokenIndex = 0) { return GenericPointer(source, N - 1) .Get(root, unresolvedTokenIndex); } @@ -1349,19 +1367,17 @@ GetValueByPointerWithDefault( } template -typename T::ValueType & -GetValueByPointerWithDefault(T &root, const CharType (&source)[N], - const typename T::ValueType &defaultValue, - typename T::AllocatorType &a) { +typename T::ValueType &GetValueByPointerWithDefault( + T &root, const CharType (&source)[N], + const typename T::ValueType &defaultValue, typename T::AllocatorType &a) { return GenericPointer(source, N - 1) .GetWithDefault(root, defaultValue, a); } template -typename T::ValueType & -GetValueByPointerWithDefault(T &root, const CharType (&source)[N], - const typename T::Ch *defaultValue, - typename T::AllocatorType &a) { +typename T::ValueType &GetValueByPointerWithDefault( + T &root, const CharType (&source)[N], const typename T::Ch *defaultValue, + typename T::AllocatorType &a) { return GenericPointer(source, N - 1) .GetWithDefault(root, defaultValue, a); } @@ -1435,10 +1451,9 @@ typename DocumentType::ValueType &GetValueByPointerWithDefault( } template -typename DocumentType::ValueType & -GetValueByPointerWithDefault(DocumentType &document, - const CharType (&source)[N], - const typename DocumentType::Ch *defaultValue) { +typename DocumentType::ValueType &GetValueByPointerWithDefault( + DocumentType &document, const CharType (&source)[N], + const typename DocumentType::Ch *defaultValue) { return GenericPointer(source, N - 1) .GetWithDefault(document, defaultValue); } @@ -1466,33 +1481,32 @@ GetValueByPointerWithDefault(DocumentType &document, ////////////////////////////////////////////////////////////////////////////// template -typename T::ValueType & -SetValueByPointer(T &root, const GenericPointer &pointer, - typename T::ValueType &value, typename T::AllocatorType &a) { +typename T::ValueType &SetValueByPointer( + T &root, const GenericPointer &pointer, + typename T::ValueType &value, typename T::AllocatorType &a) { return pointer.Set(root, value, a); } template -typename T::ValueType & -SetValueByPointer(T &root, const GenericPointer &pointer, - const typename T::ValueType &value, - typename T::AllocatorType &a) { +typename T::ValueType &SetValueByPointer( + T &root, const GenericPointer &pointer, + const typename T::ValueType &value, typename T::AllocatorType &a) { return pointer.Set(root, value, a); } template -typename T::ValueType & -SetValueByPointer(T &root, const GenericPointer &pointer, - const typename T::Ch *value, typename T::AllocatorType &a) { +typename T::ValueType &SetValueByPointer( + T &root, const GenericPointer &pointer, + const typename T::Ch *value, typename T::AllocatorType &a) { return pointer.Set(root, value, a); } #if RAPIDJSON_HAS_STDSTRING template -typename T::ValueType & -SetValueByPointer(T &root, const GenericPointer &pointer, - const std::basic_string &value, - typename T::AllocatorType &a) { +typename T::ValueType &SetValueByPointer( + T &root, const GenericPointer &pointer, + const std::basic_string &value, + typename T::AllocatorType &a) { return pointer.Set(root, value, a); } #endif @@ -1532,10 +1546,10 @@ typename T::ValueType &SetValueByPointer(T &root, const CharType (&source)[N], #if RAPIDJSON_HAS_STDSTRING template -typename T::ValueType & -SetValueByPointer(T &root, const CharType (&source)[N], - const std::basic_string &value, - typename T::AllocatorType &a) { +typename T::ValueType &SetValueByPointer( + T &root, const CharType (&source)[N], + const std::basic_string &value, + typename T::AllocatorType &a) { return GenericPointer(source, N - 1) .Set(root, value, a); } @@ -1598,34 +1612,34 @@ SetValueByPointer( } template -typename DocumentType::ValueType & -SetValueByPointer(DocumentType &document, const CharType (&source)[N], - typename DocumentType::ValueType &value) { +typename DocumentType::ValueType &SetValueByPointer( + DocumentType &document, const CharType (&source)[N], + typename DocumentType::ValueType &value) { return GenericPointer(source, N - 1) .Set(document, value); } template -typename DocumentType::ValueType & -SetValueByPointer(DocumentType &document, const CharType (&source)[N], - const typename DocumentType::ValueType &value) { +typename DocumentType::ValueType &SetValueByPointer( + DocumentType &document, const CharType (&source)[N], + const typename DocumentType::ValueType &value) { return GenericPointer(source, N - 1) .Set(document, value); } template -typename DocumentType::ValueType & -SetValueByPointer(DocumentType &document, const CharType (&source)[N], - const typename DocumentType::Ch *value) { +typename DocumentType::ValueType &SetValueByPointer( + DocumentType &document, const CharType (&source)[N], + const typename DocumentType::Ch *value) { return GenericPointer(source, N - 1) .Set(document, value); } #if RAPIDJSON_HAS_STDSTRING template -typename DocumentType::ValueType & -SetValueByPointer(DocumentType &document, const CharType (&source)[N], - const std::basic_string &value) { +typename DocumentType::ValueType &SetValueByPointer( + DocumentType &document, const CharType (&source)[N], + const std::basic_string &value) { return GenericPointer(source, N - 1) .Set(document, value); } @@ -1644,10 +1658,9 @@ SetValueByPointer(DocumentType &document, const CharType (&source)[N], ////////////////////////////////////////////////////////////////////////////// template -typename T::ValueType & -SwapValueByPointer(T &root, - const GenericPointer &pointer, - typename T::ValueType &value, typename T::AllocatorType &a) { +typename T::ValueType &SwapValueByPointer( + T &root, const GenericPointer &pointer, + typename T::ValueType &value, typename T::AllocatorType &a) { return pointer.Swap(root, value, a); } @@ -1668,9 +1681,9 @@ typename DocumentType::ValueType &SwapValueByPointer( } template -typename DocumentType::ValueType & -SwapValueByPointer(DocumentType &document, const CharType (&source)[N], - typename DocumentType::ValueType &value) { +typename DocumentType::ValueType &SwapValueByPointer( + DocumentType &document, const CharType (&source)[N], + typename DocumentType::ValueType &value) { return GenericPointer(source, N - 1) .Swap(document, value); } @@ -1696,4 +1709,4 @@ RAPIDJSON_NAMESPACE_END RAPIDJSON_DIAG_POP #endif -#endif // RAPIDJSON_POINTER_H_ +#endif // RAPIDJSON_POINTER_H_ diff --git a/livox_ros_driver/common/rapidjson/prettywriter.h b/livox_ros_driver/common/rapidjson/prettywriter.h index e194c78..f24bd0f 100644 --- a/livox_ros_driver/common/rapidjson/prettywriter.h +++ b/livox_ros_driver/common/rapidjson/prettywriter.h @@ -37,8 +37,8 @@ RAPIDJSON_NAMESPACE_BEGIN /*! \see PrettyWriter::SetFormatOptions */ enum PrettyFormatOptions { - kFormatDefault = 0, //!< Default pretty formatting. - kFormatSingleLineArray = 1 //!< Format arrays on a single line. + kFormatDefault = 0, //!< Default pretty formatting. + kFormatSingleLineArray = 1 //!< Format arrays on a single line. }; //! Writer with indentation and spacing. @@ -54,7 +54,7 @@ template , unsigned writeFlags = kWriteDefaultFlags> class PrettyWriter : public Writer { -public: + public: typedef Writer Base; @@ -67,7 +67,9 @@ class PrettyWriter : public Writer(rhs)), indentChar_(rhs.indentChar_), + : Base(std::forward(rhs)), + indentChar_(rhs.indentChar_), indentCharCount_(rhs.indentCharCount_), formatOptions_(rhs.formatOptions_) {} #endif @@ -177,13 +180,13 @@ class PrettyWriter : public Writer= - sizeof(typename Base::Level)); // not inside an Object + sizeof(typename Base::Level)); // not inside an Object RAPIDJSON_ASSERT(!Base::level_stack_.template Top() - ->inArray); // currently inside an Array, not Object + ->inArray); // currently inside an Array, not Object RAPIDJSON_ASSERT( 0 == Base::level_stack_.template Top()->valueCount % - 2); // Object has a Key without a Value + 2); // Object has a Key without a Value bool empty = Base::level_stack_.template Pop(1)->valueCount == @@ -196,7 +199,7 @@ class PrettyWriter : public Writer(); if (level->inArray) { if (level->valueCount > 0) { Base::os_->Put( - ','); // add comma if it is not the first element in array - if (formatOptions_ & kFormatSingleLineArray) - Base::os_->Put(' '); + ','); // add comma if it is not the first element in array + if (formatOptions_ & kFormatSingleLineArray) Base::os_->Put(' '); } if (!(formatOptions_ & kFormatSingleLineArray)) { Base::os_->Put('\n'); WriteIndent(); } - } else { // in object + } else { // in object if (level->valueCount > 0) { if (level->valueCount % 2 == 0) { Base::os_->Put(','); @@ -287,16 +289,15 @@ class PrettyWriter : public WriterPut('\n'); - if (level->valueCount % 2 == 0) - WriteIndent(); + if (level->valueCount % 2 == 0) WriteIndent(); } if (!level->inArray && level->valueCount % 2 == 0) - RAPIDJSON_ASSERT(type == kStringType); // if it's in object, then even - // number should be a name + RAPIDJSON_ASSERT(type == kStringType); // if it's in object, then even + // number should be a name level->valueCount++; } else { RAPIDJSON_ASSERT( - !Base::hasRoot_); // Should only has one and only one root. + !Base::hasRoot_); // Should only has one and only one root. Base::hasRoot_ = true; } } @@ -313,7 +314,7 @@ class PrettyWriter : public Writer // malloc(), realloc(), free(), size_t -#include // memset(), memcpy(), memmove(), memcmp() +#include // malloc(), realloc(), free(), size_t +#include // memset(), memcpy(), memmove(), memcmp() /////////////////////////////////////////////////////////////////////////////// // RAPIDJSON_VERSION_STRING @@ -81,8 +81,8 @@ #define RAPIDJSON_MAJOR_VERSION 1 #define RAPIDJSON_MINOR_VERSION 1 #define RAPIDJSON_PATCH_VERSION 0 -#define RAPIDJSON_VERSION_STRING \ - RAPIDJSON_STRINGIFY( \ +#define RAPIDJSON_VERSION_STRING \ + RAPIDJSON_STRINGIFY( \ RAPIDJSON_MAJOR_VERSION.RAPIDJSON_MINOR_VERSION.RAPIDJSON_PATCH_VERSION) /////////////////////////////////////////////////////////////////////////////// @@ -136,9 +136,9 @@ #ifndef RAPIDJSON_HAS_STDSTRING #ifdef RAPIDJSON_DOXYGEN_RUNNING -#define RAPIDJSON_HAS_STDSTRING 1 // force generation of documentation +#define RAPIDJSON_HAS_STDSTRING 1 // force generation of documentation #else -#define RAPIDJSON_HAS_STDSTRING 0 // no std::string support by default +#define RAPIDJSON_HAS_STDSTRING 0 // no std::string support by default #endif /*! \def RAPIDJSON_HAS_STDSTRING \ingroup RAPIDJSON_CONFIG @@ -150,11 +150,11 @@ \hideinitializer */ -#endif // !defined(RAPIDJSON_HAS_STDSTRING) +#endif // !defined(RAPIDJSON_HAS_STDSTRING) #if RAPIDJSON_HAS_STDSTRING #include -#endif // RAPIDJSON_HAS_STDSTRING +#endif // RAPIDJSON_HAS_STDSTRING /////////////////////////////////////////////////////////////////////////////// // RAPIDJSON_NO_INT64DEFINE @@ -171,7 +171,7 @@ */ #ifndef RAPIDJSON_NO_INT64DEFINE //!@cond RAPIDJSON_HIDDEN_FROM_DOXYGEN -#if defined(_MSC_VER) && (_MSC_VER < 1800) // Visual Studio 2013 +#if defined(_MSC_VER) && (_MSC_VER < 1800) // Visual Studio 2013 #include "msinttypes/inttypes.h" #include "msinttypes/stdint.h" #else @@ -183,7 +183,7 @@ #ifdef RAPIDJSON_DOXYGEN_RUNNING #define RAPIDJSON_NO_INT64DEFINE #endif -#endif // RAPIDJSON_NO_INT64TYPEDEF +#endif // RAPIDJSON_NO_INT64TYPEDEF /////////////////////////////////////////////////////////////////////////////// // RAPIDJSON_FORCEINLINE @@ -198,12 +198,12 @@ #define RAPIDJSON_FORCEINLINE #endif //!@endcond -#endif // RAPIDJSON_FORCEINLINE +#endif // RAPIDJSON_FORCEINLINE /////////////////////////////////////////////////////////////////////////////// // RAPIDJSON_ENDIAN -#define RAPIDJSON_LITTLEENDIAN 0 //!< Little endian machine -#define RAPIDJSON_BIGENDIAN 1 //!< Big endian machine +#define RAPIDJSON_LITTLEENDIAN 0 //!< Little endian machine +#define RAPIDJSON_BIGENDIAN 1 //!< Big endian machine //! Endianness of the machine. /*! @@ -228,7 +228,7 @@ #define RAPIDJSON_ENDIAN RAPIDJSON_BIGENDIAN #else # error Unknown machine endianness detected. User needs to define RAPIDJSON_ENDIAN. -#endif // __BYTE_ORDER__ +#endif // __BYTE_ORDER__ // Detect with GLIBC's endian.h #elif defined(__GLIBC__) #include @@ -238,22 +238,22 @@ #define RAPIDJSON_ENDIAN RAPIDJSON_BIGENDIAN #else # error Unknown machine endianness detected. User needs to define RAPIDJSON_ENDIAN. -#endif // __GLIBC__ +#endif // __GLIBC__ // Detect with _LITTLE_ENDIAN and _BIG_ENDIAN macro #elif defined(_LITTLE_ENDIAN) && !defined(_BIG_ENDIAN) #define RAPIDJSON_ENDIAN RAPIDJSON_LITTLEENDIAN #elif defined(_BIG_ENDIAN) && !defined(_LITTLE_ENDIAN) #define RAPIDJSON_ENDIAN RAPIDJSON_BIGENDIAN // Detect with architecture macros -#elif defined(__sparc) || defined(__sparc__) || defined(_POWER) || \ - defined(__powerpc__) || defined(__ppc__) || defined(__hpux) || \ - defined(__hppa) || defined(_MIPSEB) || defined(_POWER) || \ +#elif defined(__sparc) || defined(__sparc__) || defined(_POWER) || \ + defined(__powerpc__) || defined(__ppc__) || defined(__hpux) || \ + defined(__hppa) || defined(_MIPSEB) || defined(_POWER) || \ defined(__s390__) #define RAPIDJSON_ENDIAN RAPIDJSON_BIGENDIAN -#elif defined(__i386__) || defined(__alpha__) || defined(__ia64) || \ - defined(__ia64__) || defined(_M_IX86) || defined(_M_IA64) || \ - defined(_M_ALPHA) || defined(__amd64) || defined(__amd64__) || \ - defined(_M_AMD64) || defined(__x86_64) || defined(__x86_64__) || \ +#elif defined(__i386__) || defined(__alpha__) || defined(__ia64) || \ + defined(__ia64__) || defined(_M_IX86) || defined(_M_IA64) || \ + defined(_M_ALPHA) || defined(__amd64) || defined(__amd64__) || \ + defined(_M_AMD64) || defined(__x86_64) || defined(__x86_64__) || \ defined(_M_X64) || defined(__bfin__) #define RAPIDJSON_ENDIAN RAPIDJSON_LITTLEENDIAN #elif defined(_MSC_VER) && (defined(_M_ARM) || defined(_M_ARM64)) @@ -263,20 +263,20 @@ #else # error Unknown machine endianness detected. User needs to define RAPIDJSON_ENDIAN. #endif -#endif // RAPIDJSON_ENDIAN +#endif // RAPIDJSON_ENDIAN /////////////////////////////////////////////////////////////////////////////// // RAPIDJSON_64BIT //! Whether using 64-bit architecture #ifndef RAPIDJSON_64BIT -#if defined(__LP64__) || (defined(__x86_64__) && defined(__ILP32__)) || \ +#if defined(__LP64__) || (defined(__x86_64__) && defined(__ILP32__)) || \ defined(_WIN64) || defined(__EMSCRIPTEN__) #define RAPIDJSON_64BIT 1 #else #define RAPIDJSON_64BIT 0 #endif -#endif // RAPIDJSON_64BIT +#endif // RAPIDJSON_64BIT /////////////////////////////////////////////////////////////////////////////// // RAPIDJSON_ALIGN @@ -289,7 +289,7 @@ User can customize by defining the RAPIDJSON_ALIGN function macro. */ #ifndef RAPIDJSON_ALIGN -#define RAPIDJSON_ALIGN(x) \ +#define RAPIDJSON_ALIGN(x) \ (((x) + static_cast(7u)) & ~static_cast(7u)) #endif @@ -303,7 +303,7 @@ Use this macro to define 64-bit constants by a pair of 32-bit integer. */ #ifndef RAPIDJSON_UINT64_C2 -#define RAPIDJSON_UINT64_C2(high32, low32) \ +#define RAPIDJSON_UINT64_C2(high32, low32) \ ((static_cast(high32) << 32) | static_cast(low32)) #endif @@ -320,13 +320,13 @@ form 24 bytes to 16 bytes in 64-bit architecture. */ #ifndef RAPIDJSON_48BITPOINTER_OPTIMIZATION -#if defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || \ +#if defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || \ defined(__x86_64) || defined(_M_X64) || defined(_M_AMD64) #define RAPIDJSON_48BITPOINTER_OPTIMIZATION 1 #else #define RAPIDJSON_48BITPOINTER_OPTIMIZATION 0 #endif -#endif // RAPIDJSON_48BITPOINTER_OPTIMIZATION +#endif // RAPIDJSON_48BITPOINTER_OPTIMIZATION #if RAPIDJSON_48BITPOINTER_OPTIMIZATION == 1 #if RAPIDJSON_64BIT != 1 @@ -337,9 +337,9 @@ (reinterpret_cast(p) & \ static_cast(RAPIDJSON_UINT64_C2(0xFFFF0000, 0x00000000))) | \ reinterpret_cast(reinterpret_cast(x)))) -#define RAPIDJSON_GETPOINTER(type, p) \ - (reinterpret_cast( \ - reinterpret_cast(p) & \ +#define RAPIDJSON_GETPOINTER(type, p) \ + (reinterpret_cast( \ + reinterpret_cast(p) & \ static_cast(RAPIDJSON_UINT64_C2(0x0000FFFF, 0xFFFFFFFF)))) #else #define RAPIDJSON_SETPOINTER(type, p, x) (p = (x)) @@ -375,7 +375,7 @@ If any of these symbols is defined, RapidJSON defines the macro \c RAPIDJSON_SIMD to indicate the availability of the optimized code. */ -#if defined(RAPIDJSON_SSE2) || defined(RAPIDJSON_SSE42) || \ +#if defined(RAPIDJSON_SSE2) || defined(RAPIDJSON_SSE42) || \ defined(RAPIDJSON_NEON) || defined(RAPIDJSON_DOXYGEN_RUNNING) #define RAPIDJSON_SIMD #endif @@ -431,7 +431,7 @@ RAPIDJSON_NAMESPACE_END #ifndef RAPIDJSON_ASSERT #include #define RAPIDJSON_ASSERT(x) assert(x) -#endif // RAPIDJSON_ASSERT +#endif // RAPIDJSON_ASSERT /////////////////////////////////////////////////////////////////////////////// // RAPIDJSON_STATIC_ASSERT @@ -440,8 +440,8 @@ RAPIDJSON_NAMESPACE_END #ifndef RAPIDJSON_STATIC_ASSERT #if __cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1800) #define RAPIDJSON_STATIC_ASSERT(x) static_assert(x, RAPIDJSON_STRINGIFY(x)) -#endif // C++11 -#endif // RAPIDJSON_STATIC_ASSERT +#endif // C++11 +#endif // RAPIDJSON_STATIC_ASSERT // Adopt C++03 implementation from boost #ifndef RAPIDJSON_STATIC_ASSERT @@ -449,11 +449,14 @@ RAPIDJSON_NAMESPACE_END //!@cond RAPIDJSON_HIDDEN_FROM_DOXYGEN #endif RAPIDJSON_NAMESPACE_BEGIN -template struct STATIC_ASSERTION_FAILURE; -template <> struct STATIC_ASSERTION_FAILURE { +template +struct STATIC_ASSERTION_FAILURE; +template <> +struct STATIC_ASSERTION_FAILURE { enum { value = 1 }; }; -template struct StaticAssertTest {}; +template +struct StaticAssertTest {}; RAPIDJSON_NAMESPACE_END #if defined(__GNUC__) || defined(__clang__) @@ -470,12 +473,12 @@ RAPIDJSON_NAMESPACE_END \param x compile-time condition \hideinitializer */ -#define RAPIDJSON_STATIC_ASSERT(x) \ - typedef ::RAPIDJSON_NAMESPACE::StaticAssertTest)> \ - RAPIDJSON_JOIN(StaticAssertTypedef, __LINE__) \ +#define RAPIDJSON_STATIC_ASSERT(x) \ + typedef ::RAPIDJSON_NAMESPACE::StaticAssertTest)> \ + RAPIDJSON_JOIN(StaticAssertTypedef, __LINE__) \ RAPIDJSON_STATIC_ASSERT_UNUSED_ATTRIBUTE -#endif // RAPIDJSON_STATIC_ASSERT +#endif // RAPIDJSON_STATIC_ASSERT /////////////////////////////////////////////////////////////////////////////// // RAPIDJSON_LIKELY, RAPIDJSON_UNLIKELY @@ -512,8 +515,8 @@ RAPIDJSON_NAMESPACE_END //!@cond RAPIDJSON_HIDDEN_FROM_DOXYGEN #define RAPIDJSON_MULTILINEMACRO_BEGIN do { -#define RAPIDJSON_MULTILINEMACRO_END \ - } \ +#define RAPIDJSON_MULTILINEMACRO_END \ + } \ while ((void)0, 0) // adopted from Boost @@ -529,20 +532,20 @@ RAPIDJSON_NAMESPACE_END // RAPIDJSON_DIAG_PUSH/POP, RAPIDJSON_DIAG_OFF #if defined(__GNUC__) -#define RAPIDJSON_GNUC \ +#define RAPIDJSON_GNUC \ RAPIDJSON_VERSION_CODE(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__) #endif -#if defined(__clang__) || (defined(RAPIDJSON_GNUC) && \ +#if defined(__clang__) || (defined(RAPIDJSON_GNUC) && \ RAPIDJSON_GNUC >= RAPIDJSON_VERSION_CODE(4, 2, 0)) #define RAPIDJSON_PRAGMA(x) _Pragma(RAPIDJSON_STRINGIFY(x)) #define RAPIDJSON_DIAG_PRAGMA(x) RAPIDJSON_PRAGMA(GCC diagnostic x) -#define RAPIDJSON_DIAG_OFF(x) \ +#define RAPIDJSON_DIAG_OFF(x) \ RAPIDJSON_DIAG_PRAGMA(ignored RAPIDJSON_STRINGIFY(RAPIDJSON_JOIN(-W, x))) // push/pop support in Clang and GCC>=4.6 -#if defined(__clang__) || (defined(RAPIDJSON_GNUC) && \ +#if defined(__clang__) || (defined(RAPIDJSON_GNUC) && \ RAPIDJSON_GNUC >= RAPIDJSON_VERSION_CODE(4, 6, 0)) #define RAPIDJSON_DIAG_PUSH RAPIDJSON_DIAG_PRAGMA(push) #define RAPIDJSON_DIAG_POP RAPIDJSON_DIAG_PRAGMA(pop) @@ -567,41 +570,41 @@ RAPIDJSON_NAMESPACE_END #define RAPIDJSON_DIAG_PUSH /* ignored */ #define RAPIDJSON_DIAG_POP /* ignored */ -#endif // RAPIDJSON_DIAG_* +#endif // RAPIDJSON_DIAG_* /////////////////////////////////////////////////////////////////////////////// // C++11 features #ifndef RAPIDJSON_HAS_CXX11_RVALUE_REFS #if defined(__clang__) -#if __has_feature(cxx_rvalue_references) && \ - (defined(_MSC_VER) || defined(_LIBCPP_VERSION) || \ +#if __has_feature(cxx_rvalue_references) && \ + (defined(_MSC_VER) || defined(_LIBCPP_VERSION) || \ defined(__GLIBCXX__) && __GLIBCXX__ >= 20080306) #define RAPIDJSON_HAS_CXX11_RVALUE_REFS 1 #else #define RAPIDJSON_HAS_CXX11_RVALUE_REFS 0 #endif -#elif (defined(RAPIDJSON_GNUC) && \ - (RAPIDJSON_GNUC >= RAPIDJSON_VERSION_CODE(4, 3, 0)) && \ - defined(__GXX_EXPERIMENTAL_CXX0X__)) || \ - (defined(_MSC_VER) && _MSC_VER >= 1600) || \ - (defined(__SUNPRO_CC) && __SUNPRO_CC >= 0x5140 && \ +#elif (defined(RAPIDJSON_GNUC) && \ + (RAPIDJSON_GNUC >= RAPIDJSON_VERSION_CODE(4, 3, 0)) && \ + defined(__GXX_EXPERIMENTAL_CXX0X__)) || \ + (defined(_MSC_VER) && _MSC_VER >= 1600) || \ + (defined(__SUNPRO_CC) && __SUNPRO_CC >= 0x5140 && \ defined(__GXX_EXPERIMENTAL_CXX0X__)) #define RAPIDJSON_HAS_CXX11_RVALUE_REFS 1 #else #define RAPIDJSON_HAS_CXX11_RVALUE_REFS 0 #endif -#endif // RAPIDJSON_HAS_CXX11_RVALUE_REFS +#endif // RAPIDJSON_HAS_CXX11_RVALUE_REFS #ifndef RAPIDJSON_HAS_CXX11_NOEXCEPT #if defined(__clang__) #define RAPIDJSON_HAS_CXX11_NOEXCEPT __has_feature(cxx_noexcept) -#elif (defined(RAPIDJSON_GNUC) && \ - (RAPIDJSON_GNUC >= RAPIDJSON_VERSION_CODE(4, 6, 0)) && \ - defined(__GXX_EXPERIMENTAL_CXX0X__)) || \ - (defined(_MSC_VER) && _MSC_VER >= 1900) || \ - (defined(__SUNPRO_CC) && __SUNPRO_CC >= 0x5140 && \ +#elif (defined(RAPIDJSON_GNUC) && \ + (RAPIDJSON_GNUC >= RAPIDJSON_VERSION_CODE(4, 6, 0)) && \ + defined(__GXX_EXPERIMENTAL_CXX0X__)) || \ + (defined(_MSC_VER) && _MSC_VER >= 1900) || \ + (defined(__SUNPRO_CC) && __SUNPRO_CC >= 0x5140 && \ defined(__GXX_EXPERIMENTAL_CXX0X__)) #define RAPIDJSON_HAS_CXX11_NOEXCEPT 1 #else @@ -626,17 +629,17 @@ RAPIDJSON_NAMESPACE_END #ifndef RAPIDJSON_HAS_CXX11_RANGE_FOR #if defined(__clang__) #define RAPIDJSON_HAS_CXX11_RANGE_FOR __has_feature(cxx_range_for) -#elif (defined(RAPIDJSON_GNUC) && \ - (RAPIDJSON_GNUC >= RAPIDJSON_VERSION_CODE(4, 6, 0)) && \ - defined(__GXX_EXPERIMENTAL_CXX0X__)) || \ - (defined(_MSC_VER) && _MSC_VER >= 1700) || \ - (defined(__SUNPRO_CC) && __SUNPRO_CC >= 0x5140 && \ +#elif (defined(RAPIDJSON_GNUC) && \ + (RAPIDJSON_GNUC >= RAPIDJSON_VERSION_CODE(4, 6, 0)) && \ + defined(__GXX_EXPERIMENTAL_CXX0X__)) || \ + (defined(_MSC_VER) && _MSC_VER >= 1700) || \ + (defined(__SUNPRO_CC) && __SUNPRO_CC >= 0x5140 && \ defined(__GXX_EXPERIMENTAL_CXX0X__)) #define RAPIDJSON_HAS_CXX11_RANGE_FOR 1 #else #define RAPIDJSON_HAS_CXX11_RANGE_FOR 0 #endif -#endif // RAPIDJSON_HAS_CXX11_RANGE_FOR +#endif // RAPIDJSON_HAS_CXX11_RANGE_FOR /////////////////////////////////////////////////////////////////////////////// // C++17 features @@ -673,11 +676,11 @@ RAPIDJSON_NAMESPACE_END #define RAPIDJSON_NOEXCEPT_ASSERT(x) #else #define RAPIDJSON_NOEXCEPT_ASSERT(x) RAPIDJSON_ASSERT(x) -#endif // RAPIDJSON_HAS_CXX11_NOEXCEPT +#endif // RAPIDJSON_HAS_CXX11_NOEXCEPT #else #define RAPIDJSON_NOEXCEPT_ASSERT(x) RAPIDJSON_ASSERT(x) -#endif // RAPIDJSON_ASSERT_THROWS -#endif // RAPIDJSON_NOEXCEPT_ASSERT +#endif // RAPIDJSON_ASSERT_THROWS +#endif // RAPIDJSON_NOEXCEPT_ASSERT /////////////////////////////////////////////////////////////////////////////// // new/delete @@ -702,15 +705,15 @@ RAPIDJSON_NAMESPACE_BEGIN //! Type of JSON value enum Type { - kNullType = 0, //!< null - kFalseType = 1, //!< false - kTrueType = 2, //!< true - kObjectType = 3, //!< object - kArrayType = 4, //!< array - kStringType = 5, //!< string - kNumberType = 6 //!< number + kNullType = 0, //!< null + kFalseType = 1, //!< false + kTrueType = 2, //!< true + kObjectType = 3, //!< object + kArrayType = 4, //!< array + kStringType = 5, //!< string + kNumberType = 6 //!< number }; RAPIDJSON_NAMESPACE_END -#endif // RAPIDJSON_RAPIDJSON_H_ +#endif // RAPIDJSON_RAPIDJSON_H_ diff --git a/livox_ros_driver/common/rapidjson/reader.h b/livox_ros_driver/common/rapidjson/reader.h index 06eed86..3a7203a 100644 --- a/livox_ros_driver/common/rapidjson/reader.h +++ b/livox_ros_driver/common/rapidjson/reader.h @@ -21,6 +21,7 @@ /*! \file reader.h */ +#include #include "allocators.h" #include "encodedstream.h" #include "internal/clzll.h" @@ -28,7 +29,6 @@ #include "internal/stack.h" #include "internal/strtod.h" #include "stream.h" -#include #if defined(RAPIDJSON_SIMD) && defined(_MSC_VER) #include @@ -49,8 +49,8 @@ RAPIDJSON_DIAG_OFF(padded) RAPIDJSON_DIAG_OFF(switch - enum) #elif defined(_MSC_VER) RAPIDJSON_DIAG_PUSH -RAPIDJSON_DIAG_OFF(4127) // conditional expression is constant -RAPIDJSON_DIAG_OFF(4702) // unreachable code +RAPIDJSON_DIAG_OFF(4127) // conditional expression is constant +RAPIDJSON_DIAG_OFF(4702) // unreachable code #endif #ifdef __GNUC__ @@ -61,14 +61,14 @@ RAPIDJSON_DIAG_OFF(effc++) //!@cond RAPIDJSON_HIDDEN_FROM_DOXYGEN #define RAPIDJSON_NOTHING /* deliberately empty */ #ifndef RAPIDJSON_PARSE_ERROR_EARLY_RETURN -#define RAPIDJSON_PARSE_ERROR_EARLY_RETURN(value) \ - RAPIDJSON_MULTILINEMACRO_BEGIN \ - if (RAPIDJSON_UNLIKELY(HasParseError())) { \ - return value; \ - } \ +#define RAPIDJSON_PARSE_ERROR_EARLY_RETURN(value) \ + RAPIDJSON_MULTILINEMACRO_BEGIN \ + if (RAPIDJSON_UNLIKELY(HasParseError())) { \ + return value; \ + } \ RAPIDJSON_MULTILINEMACRO_END #endif -#define RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID \ +#define RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID \ RAPIDJSON_PARSE_ERROR_EARLY_RETURN(RAPIDJSON_NOTHING) //!@endcond @@ -89,8 +89,8 @@ RAPIDJSON_DIAG_OFF(effc++) #define RAPIDJSON_PARSE_ERROR_NORETURN(parseErrorCode,offset) \ throw ParseException(parseErrorCode, #parseErrorCode, offset) - #include "rapidjson/error/error.h" // rapidjson::ParseResult #include // std::runtime_error + #include "rapidjson/error/error.h" // rapidjson::ParseResult struct ParseException : std::runtime_error, rapidjson::ParseResult { ParseException(rapidjson::ParseErrorCode code, const char* msg, size_t @@ -103,10 +103,10 @@ RAPIDJSON_DIAG_OFF(effc++) \see RAPIDJSON_PARSE_ERROR, rapidjson::GenericReader::Parse */ #ifndef RAPIDJSON_PARSE_ERROR_NORETURN -#define RAPIDJSON_PARSE_ERROR_NORETURN(parseErrorCode, offset) \ - RAPIDJSON_MULTILINEMACRO_BEGIN \ - RAPIDJSON_ASSERT(!HasParseError()); /* Error can only be assigned once */ \ - SetParseError(parseErrorCode, offset); \ +#define RAPIDJSON_PARSE_ERROR_NORETURN(parseErrorCode, offset) \ + RAPIDJSON_MULTILINEMACRO_BEGIN \ + RAPIDJSON_ASSERT(!HasParseError()); /* Error can only be assigned once */ \ + SetParseError(parseErrorCode, offset); \ RAPIDJSON_MULTILINEMACRO_END #endif @@ -122,14 +122,14 @@ RAPIDJSON_DIAG_OFF(effc++) \hideinitializer */ #ifndef RAPIDJSON_PARSE_ERROR -#define RAPIDJSON_PARSE_ERROR(parseErrorCode, offset) \ - RAPIDJSON_MULTILINEMACRO_BEGIN \ - RAPIDJSON_PARSE_ERROR_NORETURN(parseErrorCode, offset); \ - RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; \ +#define RAPIDJSON_PARSE_ERROR(parseErrorCode, offset) \ + RAPIDJSON_MULTILINEMACRO_BEGIN \ + RAPIDJSON_PARSE_ERROR_NORETURN(parseErrorCode, offset); \ + RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; \ RAPIDJSON_MULTILINEMACRO_END #endif -#include "error/error.h" // ParseErrorCode, ParseResult +#include "error/error.h" // ParseErrorCode, ParseResult RAPIDJSON_NAMESPACE_BEGIN @@ -151,29 +151,29 @@ RAPIDJSON_NAMESPACE_BEGIN * Document::ParseStream */ enum ParseFlag { - kParseNoFlags = 0, //!< No flags are set. - kParseInsituFlag = 1, //!< In-situ(destructive) parsing. - kParseValidateEncodingFlag = 2, //!< Validate encoding of JSON strings. - kParseIterativeFlag = 4, //!< Iterative(constant complexity in terms of - //!< function call stack size) parsing. + kParseNoFlags = 0, //!< No flags are set. + kParseInsituFlag = 1, //!< In-situ(destructive) parsing. + kParseValidateEncodingFlag = 2, //!< Validate encoding of JSON strings. + kParseIterativeFlag = 4, //!< Iterative(constant complexity in terms of + //!< function call stack size) parsing. kParseStopWhenDoneFlag = - 8, //!< After parsing a complete JSON root from stream, stop further - //!< processing the rest of stream. When this flag is used, parser will - //!< not generate kParseErrorDocumentRootNotSingular error. + 8, //!< After parsing a complete JSON root from stream, stop further + //!< processing the rest of stream. When this flag is used, parser will + //!< not generate kParseErrorDocumentRootNotSingular error. kParseFullPrecisionFlag = - 16, //!< Parse number in full precision (but slower). + 16, //!< Parse number in full precision (but slower). kParseCommentsFlag = - 32, //!< Allow one-line (//) and multi-line (/**/) comments. + 32, //!< Allow one-line (//) and multi-line (/**/) comments. kParseNumbersAsStringsFlag = - 64, //!< Parse all numbers (ints/doubles) as strings. + 64, //!< Parse all numbers (ints/doubles) as strings. kParseTrailingCommasFlag = - 128, //!< Allow trailing commas at the end of objects and arrays. - kParseNanAndInfFlag = - 256, //!< Allow parsing NaN, Inf, Infinity, -Inf and -Infinity as doubles. + 128, //!< Allow trailing commas at the end of objects and arrays. + kParseNanAndInfFlag = 256, //!< Allow parsing NaN, Inf, Infinity, -Inf and + //!-Infinity as doubles. kParseDefaultFlags = - RAPIDJSON_PARSE_DEFAULT_FLAGS //!< Default parse flags. Can be customized - //!< by defining - //!< RAPIDJSON_PARSE_DEFAULT_FLAGS + RAPIDJSON_PARSE_DEFAULT_FLAGS //!< Default parse flags. Can be customized + //!< by defining + //!< RAPIDJSON_PARSE_DEFAULT_FLAGS }; /////////////////////////////////////////////////////////////////////////////// @@ -251,31 +251,33 @@ template ::copyOptimization> class StreamLocalCopy; //! Do copy optimization. -template class StreamLocalCopy { -public: +template +class StreamLocalCopy { + public: StreamLocalCopy(Stream &original) : s(original), original_(original) {} ~StreamLocalCopy() { original_ = s; } Stream s; -private: + private: StreamLocalCopy &operator=(const StreamLocalCopy &) /* = delete */; Stream &original_; }; //! Keep reference. -template class StreamLocalCopy { -public: +template +class StreamLocalCopy { + public: StreamLocalCopy(Stream &original) : s(original) {} Stream &s; -private: + private: StreamLocalCopy &operator=(const StreamLocalCopy &) /* = delete */; }; -} // namespace internal +} // namespace internal /////////////////////////////////////////////////////////////////////////////// // SkipWhitespace @@ -284,18 +286,17 @@ template class StreamLocalCopy { /*! \param is A input stream for skipping white spaces. \note This function has SSE2/SSE4.2 specialization. */ -template void SkipWhitespace(InputStream &is) { +template +void SkipWhitespace(InputStream &is) { internal::StreamLocalCopy copy(is); InputStream &s(copy.s); typename InputStream::Ch c; - while ((c = s.Peek()) == ' ' || c == '\n' || c == '\r' || c == '\t') - s.Take(); + while ((c = s.Peek()) == ' ' || c == '\n' || c == '\r' || c == '\t') s.Take(); } inline const char *SkipWhitespace(const char *p, const char *end) { - while (p != end && (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t')) - ++p; + while (p != end && (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t')) ++p; return p; } @@ -325,11 +326,10 @@ inline const char *SkipWhitespace_SIMD(const char *p) { for (;; p += 16) { const __m128i s = _mm_load_si128(reinterpret_cast(p)); - const int r = - _mm_cmpistri(w, s, - _SIDD_UBYTE_OPS | _SIDD_CMP_EQUAL_ANY | - _SIDD_LEAST_SIGNIFICANT | _SIDD_NEGATIVE_POLARITY); - if (r != 16) // some of characters is non-whitespace + const int r = _mm_cmpistri(w, s, _SIDD_UBYTE_OPS | _SIDD_CMP_EQUAL_ANY | + _SIDD_LEAST_SIGNIFICANT | + _SIDD_NEGATIVE_POLARITY); + if (r != 16) // some of characters is non-whitespace return p + r; } } @@ -348,11 +348,10 @@ inline const char *SkipWhitespace_SIMD(const char *p, const char *end) { for (; p <= end - 16; p += 16) { const __m128i s = _mm_loadu_si128(reinterpret_cast(p)); - const int r = - _mm_cmpistri(w, s, - _SIDD_UBYTE_OPS | _SIDD_CMP_EQUAL_ANY | - _SIDD_LEAST_SIGNIFICANT | _SIDD_NEGATIVE_POLARITY); - if (r != 16) // some of characters is non-whitespace + const int r = _mm_cmpistri(w, s, _SIDD_UBYTE_OPS | _SIDD_CMP_EQUAL_ANY | + _SIDD_LEAST_SIGNIFICANT | + _SIDD_NEGATIVE_POLARITY); + if (r != 16) // some of characters is non-whitespace return p + r; } @@ -380,7 +379,7 @@ inline const char *SkipWhitespace_SIMD(const char *p) { return p; // The rest of string -#define C16(c) \ +#define C16(c) \ { c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c } static const char whitespaces[4][16] = {C16(' '), C16('\n'), C16('\r'), C16('\t')}; @@ -402,8 +401,8 @@ inline const char *SkipWhitespace_SIMD(const char *p) { x = _mm_or_si128(x, _mm_cmpeq_epi8(s, w2)); x = _mm_or_si128(x, _mm_cmpeq_epi8(s, w3)); unsigned short r = static_cast(~_mm_movemask_epi8(x)); - if (r != 0) { // some of characters may be non-whitespace -#ifdef _MSC_VER // Find the index of first non-whitespace + if (r != 0) { // some of characters may be non-whitespace +#ifdef _MSC_VER // Find the index of first non-whitespace unsigned long offset; _BitScanForward(&offset, r); return p + offset; @@ -422,7 +421,7 @@ inline const char *SkipWhitespace_SIMD(const char *p, const char *end) { return p; // The rest of string -#define C16(c) \ +#define C16(c) \ { c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c } static const char whitespaces[4][16] = {C16(' '), C16('\n'), C16('\r'), C16('\t')}; @@ -444,8 +443,8 @@ inline const char *SkipWhitespace_SIMD(const char *p, const char *end) { x = _mm_or_si128(x, _mm_cmpeq_epi8(s, w2)); x = _mm_or_si128(x, _mm_cmpeq_epi8(s, w3)); unsigned short r = static_cast(~_mm_movemask_epi8(x)); - if (r != 0) { // some of characters may be non-whitespace -#ifdef _MSC_VER // Find the index of first non-whitespace + if (r != 0) { // some of characters may be non-whitespace +#ifdef _MSC_VER // Find the index of first non-whitespace unsigned long offset; _BitScanForward(&offset, r); return p + offset; @@ -490,10 +489,10 @@ inline const char *SkipWhitespace_SIMD(const char *p) { x = vorrq_u8(x, vceqq_u8(s, w2)); x = vorrq_u8(x, vceqq_u8(s, w3)); - x = vmvnq_u8(x); // Negate - x = vrev64q_u8(x); // Rev in 64 - uint64_t low = vgetq_lane_u64(vreinterpretq_u64_u8(x), 0); // extract - uint64_t high = vgetq_lane_u64(vreinterpretq_u64_u8(x), 1); // extract + x = vmvnq_u8(x); // Negate + x = vrev64q_u8(x); // Rev in 64 + uint64_t low = vgetq_lane_u64(vreinterpretq_u64_u8(x), 0); // extract + uint64_t high = vgetq_lane_u64(vreinterpretq_u64_u8(x), 1); // extract if (low == 0) { if (high != 0) { @@ -526,10 +525,10 @@ inline const char *SkipWhitespace_SIMD(const char *p, const char *end) { x = vorrq_u8(x, vceqq_u8(s, w2)); x = vorrq_u8(x, vceqq_u8(s, w3)); - x = vmvnq_u8(x); // Negate - x = vrev64q_u8(x); // Rev in 64 - uint64_t low = vgetq_lane_u64(vreinterpretq_u64_u8(x), 0); // extract - uint64_t high = vgetq_lane_u64(vreinterpretq_u64_u8(x), 1); // extract + x = vmvnq_u8(x); // Negate + x = vrev64q_u8(x); // Rev in 64 + uint64_t low = vgetq_lane_u64(vreinterpretq_u64_u8(x), 0); // extract + uint64_t high = vgetq_lane_u64(vreinterpretq_u64_u8(x), 1); // extract if (low == 0) { if (high != 0) { @@ -545,16 +544,18 @@ inline const char *SkipWhitespace_SIMD(const char *p, const char *end) { return SkipWhitespace(p, end); } -#endif // RAPIDJSON_NEON +#endif // RAPIDJSON_NEON #ifdef RAPIDJSON_SIMD //! Template function specialization for InsituStringStream -template <> inline void SkipWhitespace(InsituStringStream &is) { +template <> +inline void SkipWhitespace(InsituStringStream &is) { is.src_ = const_cast(SkipWhitespace_SIMD(is.src_)); } //! Template function specialization for StringStream -template <> inline void SkipWhitespace(StringStream &is) { +template <> +inline void SkipWhitespace(StringStream &is) { is.src_ = SkipWhitespace_SIMD(is.src_); } @@ -562,7 +563,7 @@ template <> inline void SkipWhitespace(EncodedInputStream, MemoryStream> &is) { is.is_.src_ = SkipWhitespace_SIMD(is.is_.src_, is.is_.end_); } -#endif // RAPIDJSON_SIMD +#endif // RAPIDJSON_SIMD /////////////////////////////////////////////////////////////////////////////// // GenericReader @@ -587,8 +588,8 @@ inline void SkipWhitespace(EncodedInputStream, MemoryStream> &is) { template class GenericReader { -public: - typedef typename SourceEncoding::Ch Ch; //!< SourceEncoding character type + public: + typedef typename SourceEncoding::Ch Ch; //!< SourceEncoding character type //! Constructor. /*! \param stackAllocator Optional allocator for allocating stack memory. @@ -598,7 +599,8 @@ class GenericReader { */ GenericReader(StackAllocator *stackAllocator = 0, size_t stackCapacity = kDefaultStackCapacity) - : stack_(stackAllocator, stackCapacity), parseResult_(), + : stack_(stackAllocator, stackCapacity), + parseResult_(), state_(IterativeParsingStartState) {} //! Parse JSON text. @@ -711,8 +713,7 @@ class GenericReader { // If we parsed anything other than a delimiter, we invoked the handler, // so we can return true now. - if (!IsIterativeParsingDelimiterState(n)) - return true; + if (!IsIterativeParsingDelimiterState(n)) return true; } // We reached the end of file. @@ -742,12 +743,12 @@ class GenericReader { //! Get the position of last parsing error in input, 0 otherwise. size_t GetErrorOffset() const { return parseResult_.Offset(); } -protected: + protected: void SetParseError(ParseErrorCode code, size_t offset) { parseResult_.Set(code, offset); } -private: + private: // Prohibit copy constructor & assignment operator. GenericReader(const GenericReader &); GenericReader &operator=(const GenericReader &); @@ -759,7 +760,7 @@ class GenericReader { explicit ClearStackOnExit(GenericReader &r) : r_(r) {} ~ClearStackOnExit() { r_.ClearStack(); } - private: + private: GenericReader &r_; ClearStackOnExit(const ClearStackOnExit &); ClearStackOnExit &operator=(const ClearStackOnExit &); @@ -777,8 +778,7 @@ class GenericReader { RAPIDJSON_PARSE_ERROR(kParseErrorUnspecificSyntaxError, is.Tell()); else if (Consume(is, '*')) { - if (Consume(is, '/')) - break; + if (Consume(is, '/')) break; } else is.Take(); } @@ -797,7 +797,7 @@ class GenericReader { template void ParseObject(InputStream &is, Handler &handler) { RAPIDJSON_ASSERT(is.Peek() == '{'); - is.Take(); // Skip '{' + is.Take(); // Skip '{' if (RAPIDJSON_UNLIKELY(!handler.StartObject())) RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell()); @@ -806,7 +806,7 @@ class GenericReader { RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; if (Consume(is, '}')) { - if (RAPIDJSON_UNLIKELY(!handler.EndObject(0))) // empty object + if (RAPIDJSON_UNLIKELY(!handler.EndObject(0))) // empty object RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell()); return; } @@ -836,21 +836,21 @@ class GenericReader { ++memberCount; switch (is.Peek()) { - case ',': - is.Take(); - SkipWhitespaceAndComments(is); - RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; - break; - case '}': - is.Take(); - if (RAPIDJSON_UNLIKELY(!handler.EndObject(memberCount))) - RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell()); - return; - default: - RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissCommaOrCurlyBracket, - is.Tell()); - break; // This useless break is only for making warning and coverage - // happy + case ',': + is.Take(); + SkipWhitespaceAndComments(is); + RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; + break; + case '}': + is.Take(); + if (RAPIDJSON_UNLIKELY(!handler.EndObject(memberCount))) + RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell()); + return; + default: + RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissCommaOrCurlyBracket, + is.Tell()); + break; // This useless break is only for making warning and coverage + // happy } if (parseFlags & kParseTrailingCommasFlag) { @@ -868,7 +868,7 @@ class GenericReader { template void ParseArray(InputStream &is, Handler &handler) { RAPIDJSON_ASSERT(is.Peek() == '['); - is.Take(); // Skip '[' + is.Take(); // Skip '[' if (RAPIDJSON_UNLIKELY(!handler.StartArray())) RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell()); @@ -877,7 +877,7 @@ class GenericReader { RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; if (Consume(is, ']')) { - if (RAPIDJSON_UNLIKELY(!handler.EndArray(0))) // empty array + if (RAPIDJSON_UNLIKELY(!handler.EndArray(0))) // empty array RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell()); return; } @@ -986,8 +986,9 @@ class GenericReader { return codepoint; } - template class StackStream { - public: + template + class StackStream { + public: typedef CharType Ch; StackStream(internal::Stack &stack) @@ -1006,7 +1007,7 @@ class GenericReader { Ch *Pop() { return stack_.template Pop(length_); } - private: + private: StackStream(const StackStream &); StackStream &operator=(const StackStream &); @@ -1022,7 +1023,7 @@ class GenericReader { InputStream &s(copy.s); RAPIDJSON_ASSERT(s.Peek() == '\"'); - s.Take(); // Skip '\"' + s.Take(); // Skip '\"' bool success = false; if (parseFlags & kParseInsituFlag) { @@ -1075,9 +1076,9 @@ class GenericReader { ScanCopyUnescapedString(is, os); Ch c = is.Peek(); - if (RAPIDJSON_UNLIKELY(c == '\\')) { // Escape - size_t escapeOffset = is.Tell(); // For invalid escaping, report the - // initial '\\' as error offset + if (RAPIDJSON_UNLIKELY(c == '\\')) { // Escape + size_t escapeOffset = is.Tell(); // For invalid escaping, report the + // initial '\\' as error offset is.Take(); Ch e = is.Peek(); if ((sizeof(Ch) == 1 || unsigned(e) < 256) && @@ -1085,7 +1086,7 @@ class GenericReader { is.Take(); os.Put(static_cast( escape[static_cast(e)])); - } else if (RAPIDJSON_LIKELY(e == 'u')) { // Unicode + } else if (RAPIDJSON_LIKELY(e == 'u')) { // Unicode is.Take(); unsigned codepoint = ParseHex4(is, escapeOffset); RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; @@ -1105,13 +1106,13 @@ class GenericReader { TEncoding::Encode(os, codepoint); } else RAPIDJSON_PARSE_ERROR(kParseErrorStringEscapeInvalid, escapeOffset); - } else if (RAPIDJSON_UNLIKELY(c == '"')) { // Closing double quote + } else if (RAPIDJSON_UNLIKELY(c == '"')) { // Closing double quote is.Take(); - os.Put('\0'); // null-terminate the string + os.Put('\0'); // null-terminate the string return; } else if (RAPIDJSON_UNLIKELY(static_cast(c) < - 0x20)) { // RFC 4627: unescaped = %x20-21 / - // %x23-5B / %x5D-10FFFF + 0x20)) { // RFC 4627: unescaped = %x20-21 / + // %x23-5B / %x5D-10FFFF if (c == '\0') RAPIDJSON_PARSE_ERROR(kParseErrorStringMissQuotationMark, is.Tell()); else @@ -1135,8 +1136,8 @@ class GenericReader { #if defined(RAPIDJSON_SSE2) || defined(RAPIDJSON_SSE42) // StringStream -> StackStream - static RAPIDJSON_FORCEINLINE void - ScanCopyUnescapedString(StringStream &is, StackStream &os) { + static RAPIDJSON_FORCEINLINE void ScanCopyUnescapedString( + StringStream &is, StackStream &os) { const char *p = is.src_; // Scan one by one until alignment (unaligned load may cross page boundary @@ -1173,12 +1174,12 @@ class GenericReader { const __m128i t1 = _mm_cmpeq_epi8(s, dq); const __m128i t2 = _mm_cmpeq_epi8(s, bs); const __m128i t3 = _mm_cmpeq_epi8( - _mm_max_epu8(s, sp), sp); // s < 0x20 <=> max(s, 0x1F) == 0x1F + _mm_max_epu8(s, sp), sp); // s < 0x20 <=> max(s, 0x1F) == 0x1F const __m128i x = _mm_or_si128(_mm_or_si128(t1, t2), t3); unsigned short r = static_cast(_mm_movemask_epi8(x)); - if (RAPIDJSON_UNLIKELY(r != 0)) { // some of characters is escaped + if (RAPIDJSON_UNLIKELY(r != 0)) { // some of characters is escaped SizeType length; -#ifdef _MSC_VER // Find the index of first escaped +#ifdef _MSC_VER // Find the index of first escaped unsigned long offset; _BitScanForward(&offset, r); length = offset; @@ -1187,8 +1188,7 @@ class GenericReader { #endif if (length != 0) { char *q = reinterpret_cast(os.Push(length)); - for (size_t i = 0; i < length; i++) - q[i] = p[i]; + for (size_t i = 0; i < length; i++) q[i] = p[i]; p += length; } @@ -1201,8 +1201,8 @@ class GenericReader { } // InsituStringStream -> InsituStringStream - static RAPIDJSON_FORCEINLINE void - ScanCopyUnescapedString(InsituStringStream &is, InsituStringStream &os) { + static RAPIDJSON_FORCEINLINE void ScanCopyUnescapedString( + InsituStringStream &is, InsituStringStream &os) { RAPIDJSON_ASSERT(&is == &os); (void)os; @@ -1249,20 +1249,19 @@ class GenericReader { const __m128i t1 = _mm_cmpeq_epi8(s, dq); const __m128i t2 = _mm_cmpeq_epi8(s, bs); const __m128i t3 = _mm_cmpeq_epi8( - _mm_max_epu8(s, sp), sp); // s < 0x20 <=> max(s, 0x1F) == 0x1F + _mm_max_epu8(s, sp), sp); // s < 0x20 <=> max(s, 0x1F) == 0x1F const __m128i x = _mm_or_si128(_mm_or_si128(t1, t2), t3); unsigned short r = static_cast(_mm_movemask_epi8(x)); - if (RAPIDJSON_UNLIKELY(r != 0)) { // some of characters is escaped + if (RAPIDJSON_UNLIKELY(r != 0)) { // some of characters is escaped size_t length; -#ifdef _MSC_VER // Find the index of first escaped +#ifdef _MSC_VER // Find the index of first escaped unsigned long offset; _BitScanForward(&offset, r); length = offset; #else length = static_cast(__builtin_ffs(r) - 1); #endif - for (const char *pend = p + length; p != pend;) - *q++ = *p++; + for (const char *pend = p + length; p != pend;) *q++ = *p++; break; } _mm_storeu_si128(reinterpret_cast<__m128i *>(q), s); @@ -1274,8 +1273,8 @@ class GenericReader { // When read/write pointers are the same for insitu stream, just skip // unescaped characters - static RAPIDJSON_FORCEINLINE void - SkipUnescapedString(InsituStringStream &is) { + static RAPIDJSON_FORCEINLINE void SkipUnescapedString( + InsituStringStream &is) { RAPIDJSON_ASSERT(is.src_ == is.dst_); char *p = is.src_; @@ -1312,12 +1311,12 @@ class GenericReader { const __m128i t1 = _mm_cmpeq_epi8(s, dq); const __m128i t2 = _mm_cmpeq_epi8(s, bs); const __m128i t3 = _mm_cmpeq_epi8( - _mm_max_epu8(s, sp), sp); // s < 0x20 <=> max(s, 0x1F) == 0x1F + _mm_max_epu8(s, sp), sp); // s < 0x20 <=> max(s, 0x1F) == 0x1F const __m128i x = _mm_or_si128(_mm_or_si128(t1, t2), t3); unsigned short r = static_cast(_mm_movemask_epi8(x)); - if (RAPIDJSON_UNLIKELY(r != 0)) { // some of characters is escaped + if (RAPIDJSON_UNLIKELY(r != 0)) { // some of characters is escaped size_t length; -#ifdef _MSC_VER // Find the index of first escaped +#ifdef _MSC_VER // Find the index of first escaped unsigned long offset; _BitScanForward(&offset, r); length = offset; @@ -1333,8 +1332,8 @@ class GenericReader { } #elif defined(RAPIDJSON_NEON) // StringStream -> StackStream - static RAPIDJSON_FORCEINLINE void - ScanCopyUnescapedString(StringStream &is, StackStream &os) { + static RAPIDJSON_FORCEINLINE void ScanCopyUnescapedString( + StringStream &is, StackStream &os) { const char *p = is.src_; // Scan one by one until alignment (unaligned load may cross page boundary @@ -1362,9 +1361,9 @@ class GenericReader { x = vorrq_u8(x, vceqq_u8(s, s2)); x = vorrq_u8(x, vcltq_u8(s, s3)); - x = vrev64q_u8(x); // Rev in 64 - uint64_t low = vgetq_lane_u64(vreinterpretq_u64_u8(x), 0); // extract - uint64_t high = vgetq_lane_u64(vreinterpretq_u64_u8(x), 1); // extract + x = vrev64q_u8(x); // Rev in 64 + uint64_t low = vgetq_lane_u64(vreinterpretq_u64_u8(x), 0); // extract + uint64_t high = vgetq_lane_u64(vreinterpretq_u64_u8(x), 1); // extract SizeType length = 0; bool escaped = false; @@ -1379,11 +1378,10 @@ class GenericReader { length = lz >> 3; escaped = true; } - if (RAPIDJSON_UNLIKELY(escaped)) { // some of characters is escaped + if (RAPIDJSON_UNLIKELY(escaped)) { // some of characters is escaped if (length != 0) { char *q = reinterpret_cast(os.Push(length)); - for (size_t i = 0; i < length; i++) - q[i] = p[i]; + for (size_t i = 0; i < length; i++) q[i] = p[i]; p += length; } @@ -1396,8 +1394,8 @@ class GenericReader { } // InsituStringStream -> InsituStringStream - static RAPIDJSON_FORCEINLINE void - ScanCopyUnescapedString(InsituStringStream &is, InsituStringStream &os) { + static RAPIDJSON_FORCEINLINE void ScanCopyUnescapedString( + InsituStringStream &is, InsituStringStream &os) { RAPIDJSON_ASSERT(&is == &os); (void)os; @@ -1435,9 +1433,9 @@ class GenericReader { x = vorrq_u8(x, vceqq_u8(s, s2)); x = vorrq_u8(x, vcltq_u8(s, s3)); - x = vrev64q_u8(x); // Rev in 64 - uint64_t low = vgetq_lane_u64(vreinterpretq_u64_u8(x), 0); // extract - uint64_t high = vgetq_lane_u64(vreinterpretq_u64_u8(x), 1); // extract + x = vrev64q_u8(x); // Rev in 64 + uint64_t low = vgetq_lane_u64(vreinterpretq_u64_u8(x), 0); // extract + uint64_t high = vgetq_lane_u64(vreinterpretq_u64_u8(x), 1); // extract SizeType length = 0; bool escaped = false; @@ -1452,7 +1450,7 @@ class GenericReader { length = lz >> 3; escaped = true; } - if (RAPIDJSON_UNLIKELY(escaped)) { // some of characters is escaped + if (RAPIDJSON_UNLIKELY(escaped)) { // some of characters is escaped for (const char *pend = p + length; p != pend;) { *q++ = *p++; } @@ -1467,8 +1465,8 @@ class GenericReader { // When read/write pointers are the same for insitu stream, just skip // unescaped characters - static RAPIDJSON_FORCEINLINE void - SkipUnescapedString(InsituStringStream &is) { + static RAPIDJSON_FORCEINLINE void SkipUnescapedString( + InsituStringStream &is) { RAPIDJSON_ASSERT(is.src_ == is.dst_); char *p = is.src_; @@ -1496,9 +1494,9 @@ class GenericReader { x = vorrq_u8(x, vceqq_u8(s, s2)); x = vorrq_u8(x, vcltq_u8(s, s3)); - x = vrev64q_u8(x); // Rev in 64 - uint64_t low = vgetq_lane_u64(vreinterpretq_u64_u8(x), 0); // extract - uint64_t high = vgetq_lane_u64(vreinterpretq_u64_u8(x), 1); // extract + x = vrev64q_u8(x); // Rev in 64 + uint64_t low = vgetq_lane_u64(vreinterpretq_u64_u8(x), 0); // extract + uint64_t high = vgetq_lane_u64(vreinterpretq_u64_u8(x), 1); // extract if (low == 0) { if (high != 0) { @@ -1515,14 +1513,14 @@ class GenericReader { is.src_ = is.dst_ = p; } -#endif // RAPIDJSON_NEON +#endif // RAPIDJSON_NEON template class NumberStream; template class NumberStream { - public: + public: typedef typename InputStream::Ch Ch; NumberStream(GenericReader &reader, InputStream &s) : is(s) { @@ -1538,7 +1536,7 @@ class GenericReader { size_t Length() { return 0; } const char *Pop() { return 0; } - protected: + protected: NumberStream &operator=(const NumberStream &); InputStream &is; @@ -1549,7 +1547,7 @@ class GenericReader { : public NumberStream { typedef NumberStream Base; - public: + public: NumberStream(GenericReader &reader, InputStream &is) : Base(reader, is), stackStream(reader.stack_) {} @@ -1567,7 +1565,7 @@ class GenericReader { return stackStream.Pop(); } - private: + private: StackStream stackStream; }; @@ -1576,7 +1574,7 @@ class GenericReader { : public NumberStream { typedef NumberStream Base; - public: + public: NumberStream(GenericReader &reader, InputStream &is) : Base(reader, is) {} RAPIDJSON_FORCEINLINE Ch Take() { return Base::TakePush(); } @@ -1613,7 +1611,7 @@ class GenericReader { if (minus) while (RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) { - if (RAPIDJSON_UNLIKELY(i >= 214748364)) { // 2^31 = 2147483648 + if (RAPIDJSON_UNLIKELY(i >= 214748364)) { // 2^31 = 2147483648 if (RAPIDJSON_LIKELY(i != 214748364 || s.Peek() > '8')) { i64 = i; use64bit = true; @@ -1625,7 +1623,7 @@ class GenericReader { } else while (RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) { - if (RAPIDJSON_UNLIKELY(i >= 429496729)) { // 2^32 - 1 = 4294967295 + if (RAPIDJSON_UNLIKELY(i >= 429496729)) { // 2^32 - 1 = 4294967295 if (RAPIDJSON_LIKELY(i != 429496729 || s.Peek() > '5')) { i64 = i; use64bit = true; @@ -1673,7 +1671,7 @@ class GenericReader { if (RAPIDJSON_UNLIKELY( i64 >= RAPIDJSON_UINT64_C2( - 0x0CCCCCCC, 0xCCCCCCCC))) // 2^63 = 9223372036854775808 + 0x0CCCCCCC, 0xCCCCCCCC))) // 2^63 = 9223372036854775808 if (RAPIDJSON_LIKELY( i64 != RAPIDJSON_UINT64_C2(0x0CCCCCCC, 0xCCCCCCCC) || s.Peek() > '8')) { @@ -1689,7 +1687,7 @@ class GenericReader { if (RAPIDJSON_UNLIKELY( i64 >= RAPIDJSON_UINT64_C2( 0x19999999, - 0x99999999))) // 2^64 - 1 = 18446744073709551615 + 0x99999999))) // 2^64 - 1 = 18446744073709551615 if (RAPIDJSON_LIKELY( i64 != RAPIDJSON_UINT64_C2(0x19999999, 0x99999999) || s.Peek() > '5')) { @@ -1721,18 +1719,16 @@ class GenericReader { if (!useDouble) { #if RAPIDJSON_64BIT // Use i64 to store significand in 64-bit architecture - if (!use64bit) - i64 = i; + if (!use64bit) i64 = i; while (RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) { if (i64 > RAPIDJSON_UINT64_C2(0x1FFFFF, - 0xFFFFFFFF)) // 2^53 - 1 for fast path + 0xFFFFFFFF)) // 2^53 - 1 for fast path break; else { i64 = i64 * 10 + static_cast(s.TakePush() - '0'); --expFrac; - if (i64 != 0) - significandDigit++; + if (i64 != 0) significandDigit++; } } @@ -1748,13 +1744,12 @@ class GenericReader { if (significandDigit < 17) { d = d * 10.0 + (s.TakePush() - '0'); --expFrac; - if (RAPIDJSON_LIKELY(d > 0.0)) - significandDigit++; + if (RAPIDJSON_LIKELY(d > 0.0)) significandDigit++; } else s.TakePush(); } } else - decimalPosition = s.Length(); // decimal position at the end of integer. + decimalPosition = s.Length(); // decimal position at the end of integer. // Parse exp = e [ minus / plus ] 1*DIGIT int exp = 0; @@ -1787,11 +1782,11 @@ class GenericReader { if (RAPIDJSON_UNLIKELY(exp > maxExp)) { while (RAPIDJSON_UNLIKELY( s.Peek() >= '0' && - s.Peek() <= '9')) // Consume the rest of exponent + s.Peek() <= '9')) // Consume the rest of exponent s.Take(); } } - } else { // positive exp + } else { // positive exp int maxExp = 308 - expFrac; while (RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) { exp = exp * 10 + static_cast(s.Take() - '0'); @@ -1802,8 +1797,7 @@ class GenericReader { } else RAPIDJSON_PARSE_ERROR(kParseErrorNumberMissExponent, s.Tell()); - if (expMinus) - exp = -exp; + if (expMinus) exp = -exp; } // Finish parsing, call event according to the type of number. @@ -1811,7 +1805,7 @@ class GenericReader { if (parseFlags & kParseNumbersAsStringsFlag) { if (parseFlags & kParseInsituFlag) { - s.Pop(); // Pop stack no matter if it will be used or not. + s.Pop(); // Pop stack no matter if it will be used or not. typename InputStream::Ch *head = is.PutBegin(); const size_t length = s.Tell() - startOffset; RAPIDJSON_ASSERT(length <= 0xFFFFFFFF); @@ -1835,7 +1829,7 @@ class GenericReader { } else { size_t length = s.Length(); const char *decimal = - s.Pop(); // Pop stack no matter if it will be used or not. + s.Pop(); // Pop stack no matter if it will be used or not. if (useDouble) { int p = exp + expFrac; @@ -1877,27 +1871,27 @@ class GenericReader { template void ParseValue(InputStream &is, Handler &handler) { switch (is.Peek()) { - case 'n': - ParseNull(is, handler); - break; - case 't': - ParseTrue(is, handler); - break; - case 'f': - ParseFalse(is, handler); - break; - case '"': - ParseString(is, handler); - break; - case '{': - ParseObject(is, handler); - break; - case '[': - ParseArray(is, handler); - break; - default: - ParseNumber(is, handler); - break; + case 'n': + ParseNull(is, handler); + break; + case 't': + ParseTrue(is, handler); + break; + case 'f': + ParseFalse(is, handler); + break; + case '"': + ParseString(is, handler); + break; + case '{': + ParseObject(is, handler); + break; + case '[': + ParseArray(is, handler); + break; + default: + ParseNumber(is, handler); + break; } } @@ -1905,8 +1899,8 @@ class GenericReader { // States enum IterativeParsingState { - IterativeParsingFinishState = 0, // sink states at top - IterativeParsingErrorState, // sink states at top + IterativeParsingFinishState = 0, // sink states at top + IterativeParsingErrorState, // sink states at top IterativeParsingStartState, // Object states @@ -1952,14 +1946,13 @@ class GenericReader { }; RAPIDJSON_FORCEINLINE Token Tokenize(Ch c) const { - //!@cond RAPIDJSON_HIDDEN_FROM_DOXYGEN #define N NumberToken #define N16 N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N // Maps from ASCII to Token static const unsigned char tokenMap[256] = { - N16, // 00~0F - N16, // 10~1F + N16, // 00~0F + N16, // 10~1F N, N, StringToken, N, N, N, @@ -1967,7 +1960,7 @@ class GenericReader { N, N, N, N, CommaToken, N, - N, N, // 20~2F + N, N, // 20~2F N, N, N, N, N, N, @@ -1975,8 +1968,8 @@ class GenericReader { N, N, ColonToken, N, N, N, - N, N, // 30~3F - N16, // 40~4F + N, N, // 30~3F + N16, // 40~4F N, N, N, N, N, N, @@ -1984,7 +1977,7 @@ class GenericReader { N, N, N, LeftBracketToken, N, RightBracketToken, - N, N, // 50~5F + N, N, // 50~5F N, N, N, N, N, N, @@ -1992,7 +1985,7 @@ class GenericReader { N, N, N, N, N, N, - NullToken, N, // 60~6F + NullToken, N, // 60~6F N, N, N, N, TrueToken, N, @@ -2000,11 +1993,11 @@ class GenericReader { N, N, N, LeftCurlyBracketToken, N, RightCurlyBracketToken, - N, N, // 70~7F + N, N, // 70~7F N16, N16, N16, N16, N16, N16, - N16, N16 // 80~FF + N16, N16 // 80~FF }; #undef N #undef N16 @@ -2036,59 +2029,59 @@ class GenericReader { IterativeParsingErrorState}, // Start { - IterativeParsingArrayInitialState, // Left bracket - IterativeParsingErrorState, // Right bracket - IterativeParsingObjectInitialState, // Left curly bracket - IterativeParsingErrorState, // Right curly bracket - IterativeParsingErrorState, // Comma - IterativeParsingErrorState, // Colon - IterativeParsingValueState, // String - IterativeParsingValueState, // False - IterativeParsingValueState, // True - IterativeParsingValueState, // Null - IterativeParsingValueState // Number + IterativeParsingArrayInitialState, // Left bracket + IterativeParsingErrorState, // Right bracket + IterativeParsingObjectInitialState, // Left curly bracket + IterativeParsingErrorState, // Right curly bracket + IterativeParsingErrorState, // Comma + IterativeParsingErrorState, // Colon + IterativeParsingValueState, // String + IterativeParsingValueState, // False + IterativeParsingValueState, // True + IterativeParsingValueState, // Null + IterativeParsingValueState // Number }, // ObjectInitial { - IterativeParsingErrorState, // Left bracket - IterativeParsingErrorState, // Right bracket - IterativeParsingErrorState, // Left curly bracket - IterativeParsingObjectFinishState, // Right curly bracket - IterativeParsingErrorState, // Comma - IterativeParsingErrorState, // Colon - IterativeParsingMemberKeyState, // String - IterativeParsingErrorState, // False - IterativeParsingErrorState, // True - IterativeParsingErrorState, // Null - IterativeParsingErrorState // Number + IterativeParsingErrorState, // Left bracket + IterativeParsingErrorState, // Right bracket + IterativeParsingErrorState, // Left curly bracket + IterativeParsingObjectFinishState, // Right curly bracket + IterativeParsingErrorState, // Comma + IterativeParsingErrorState, // Colon + IterativeParsingMemberKeyState, // String + IterativeParsingErrorState, // False + IterativeParsingErrorState, // True + IterativeParsingErrorState, // Null + IterativeParsingErrorState // Number }, // MemberKey { - IterativeParsingErrorState, // Left bracket - IterativeParsingErrorState, // Right bracket - IterativeParsingErrorState, // Left curly bracket - IterativeParsingErrorState, // Right curly bracket - IterativeParsingErrorState, // Comma - IterativeParsingKeyValueDelimiterState, // Colon - IterativeParsingErrorState, // String - IterativeParsingErrorState, // False - IterativeParsingErrorState, // True - IterativeParsingErrorState, // Null - IterativeParsingErrorState // Number + IterativeParsingErrorState, // Left bracket + IterativeParsingErrorState, // Right bracket + IterativeParsingErrorState, // Left curly bracket + IterativeParsingErrorState, // Right curly bracket + IterativeParsingErrorState, // Comma + IterativeParsingKeyValueDelimiterState, // Colon + IterativeParsingErrorState, // String + IterativeParsingErrorState, // False + IterativeParsingErrorState, // True + IterativeParsingErrorState, // Null + IterativeParsingErrorState // Number }, // MemberValue { - IterativeParsingErrorState, // Left bracket - IterativeParsingErrorState, // Right bracket - IterativeParsingErrorState, // Left curly bracket - IterativeParsingObjectFinishState, // Right curly bracket - IterativeParsingMemberDelimiterState, // Comma - IterativeParsingErrorState, // Colon - IterativeParsingErrorState, // String - IterativeParsingErrorState, // False - IterativeParsingErrorState, // True - IterativeParsingErrorState, // Null - IterativeParsingErrorState // Number + IterativeParsingErrorState, // Left bracket + IterativeParsingErrorState, // Right bracket + IterativeParsingErrorState, // Left curly bracket + IterativeParsingObjectFinishState, // Right curly bracket + IterativeParsingMemberDelimiterState, // Comma + IterativeParsingErrorState, // Colon + IterativeParsingErrorState, // String + IterativeParsingErrorState, // False + IterativeParsingErrorState, // True + IterativeParsingErrorState, // Null + IterativeParsingErrorState // Number }, // ObjectFinish(sink state) {IterativeParsingErrorState, IterativeParsingErrorState, @@ -2099,33 +2092,33 @@ class GenericReader { IterativeParsingErrorState}, // ArrayInitial { - IterativeParsingArrayInitialState, // Left bracket(push Element - // state) - IterativeParsingArrayFinishState, // Right bracket - IterativeParsingObjectInitialState, // Left curly bracket(push - // Element state) - IterativeParsingErrorState, // Right curly bracket - IterativeParsingErrorState, // Comma - IterativeParsingErrorState, // Colon - IterativeParsingElementState, // String - IterativeParsingElementState, // False - IterativeParsingElementState, // True - IterativeParsingElementState, // Null - IterativeParsingElementState // Number + IterativeParsingArrayInitialState, // Left bracket(push Element + // state) + IterativeParsingArrayFinishState, // Right bracket + IterativeParsingObjectInitialState, // Left curly bracket(push + // Element state) + IterativeParsingErrorState, // Right curly bracket + IterativeParsingErrorState, // Comma + IterativeParsingErrorState, // Colon + IterativeParsingElementState, // String + IterativeParsingElementState, // False + IterativeParsingElementState, // True + IterativeParsingElementState, // Null + IterativeParsingElementState // Number }, // Element { - IterativeParsingErrorState, // Left bracket - IterativeParsingArrayFinishState, // Right bracket - IterativeParsingErrorState, // Left curly bracket - IterativeParsingErrorState, // Right curly bracket - IterativeParsingElementDelimiterState, // Comma - IterativeParsingErrorState, // Colon - IterativeParsingErrorState, // String - IterativeParsingErrorState, // False - IterativeParsingErrorState, // True - IterativeParsingErrorState, // Null - IterativeParsingErrorState // Number + IterativeParsingErrorState, // Left bracket + IterativeParsingArrayFinishState, // Right bracket + IterativeParsingErrorState, // Left curly bracket + IterativeParsingErrorState, // Right curly bracket + IterativeParsingElementDelimiterState, // Comma + IterativeParsingErrorState, // Colon + IterativeParsingErrorState, // String + IterativeParsingErrorState, // False + IterativeParsingErrorState, // True + IterativeParsingErrorState, // Null + IterativeParsingErrorState // Number }, // ArrayFinish(sink state) {IterativeParsingErrorState, IterativeParsingErrorState, @@ -2143,51 +2136,51 @@ class GenericReader { IterativeParsingErrorState}, // ElementDelimiter { - IterativeParsingArrayInitialState, // Left bracket(push Element - // state) - IterativeParsingArrayFinishState, // Right bracket - IterativeParsingObjectInitialState, // Left curly bracket(push - // Element state) - IterativeParsingErrorState, // Right curly bracket - IterativeParsingErrorState, // Comma - IterativeParsingErrorState, // Colon - IterativeParsingElementState, // String - IterativeParsingElementState, // False - IterativeParsingElementState, // True - IterativeParsingElementState, // Null - IterativeParsingElementState // Number + IterativeParsingArrayInitialState, // Left bracket(push Element + // state) + IterativeParsingArrayFinishState, // Right bracket + IterativeParsingObjectInitialState, // Left curly bracket(push + // Element state) + IterativeParsingErrorState, // Right curly bracket + IterativeParsingErrorState, // Comma + IterativeParsingErrorState, // Colon + IterativeParsingElementState, // String + IterativeParsingElementState, // False + IterativeParsingElementState, // True + IterativeParsingElementState, // Null + IterativeParsingElementState // Number }, // MemberDelimiter { - IterativeParsingErrorState, // Left bracket - IterativeParsingErrorState, // Right bracket - IterativeParsingErrorState, // Left curly bracket - IterativeParsingObjectFinishState, // Right curly bracket - IterativeParsingErrorState, // Comma - IterativeParsingErrorState, // Colon - IterativeParsingMemberKeyState, // String - IterativeParsingErrorState, // False - IterativeParsingErrorState, // True - IterativeParsingErrorState, // Null - IterativeParsingErrorState // Number + IterativeParsingErrorState, // Left bracket + IterativeParsingErrorState, // Right bracket + IterativeParsingErrorState, // Left curly bracket + IterativeParsingObjectFinishState, // Right curly bracket + IterativeParsingErrorState, // Comma + IterativeParsingErrorState, // Colon + IterativeParsingMemberKeyState, // String + IterativeParsingErrorState, // False + IterativeParsingErrorState, // True + IterativeParsingErrorState, // Null + IterativeParsingErrorState // Number }, // KeyValueDelimiter { IterativeParsingArrayInitialState, // Left bracket(push MemberValue // state) IterativeParsingErrorState, // Right bracket - IterativeParsingObjectInitialState, // Left curly bracket(push - // MemberValue state) - IterativeParsingErrorState, // Right curly bracket - IterativeParsingErrorState, // Comma - IterativeParsingErrorState, // Colon - IterativeParsingMemberValueState, // String - IterativeParsingMemberValueState, // False - IterativeParsingMemberValueState, // True - IterativeParsingMemberValueState, // Null - IterativeParsingMemberValueState // Number + IterativeParsingObjectInitialState, // Left curly bracket(push + // MemberValue state) + IterativeParsingErrorState, // Right curly bracket + IterativeParsingErrorState, // Comma + IterativeParsingErrorState, // Colon + IterativeParsingMemberValueState, // String + IterativeParsingMemberValueState, // False + IterativeParsingMemberValueState, // True + IterativeParsingMemberValueState, // Null + IterativeParsingMemberValueState // Number }, - }; // End of G + }; // End of G return static_cast(G[state][token]); } @@ -2204,157 +2197,155 @@ class GenericReader { (void)token; switch (dst) { - case IterativeParsingErrorState: - return dst; - - case IterativeParsingObjectInitialState: - case IterativeParsingArrayInitialState: { - // Push the state(Element or MemeberValue) if we are nested in another - // array or value of member. In this way we can get the correct state on - // ObjectFinish or ArrayFinish by frame pop. - IterativeParsingState n = src; - if (src == IterativeParsingArrayInitialState || - src == IterativeParsingElementDelimiterState) - n = IterativeParsingElementState; - else if (src == IterativeParsingKeyValueDelimiterState) - n = IterativeParsingMemberValueState; - // Push current state. - *stack_.template Push(1) = n; - // Initialize and push the member/element count. - *stack_.template Push(1) = 0; - // Call handler - bool hr = (dst == IterativeParsingObjectInitialState) - ? handler.StartObject() - : handler.StartArray(); - // On handler short circuits the parsing. - if (!hr) { - RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorTermination, is.Tell()); - return IterativeParsingErrorState; - } else { - is.Take(); + case IterativeParsingErrorState: return dst; - } - } - - case IterativeParsingMemberKeyState: - ParseString(is, handler, true); - if (HasParseError()) - return IterativeParsingErrorState; - else - return dst; - - case IterativeParsingKeyValueDelimiterState: - RAPIDJSON_ASSERT(token == ColonToken); - is.Take(); - return dst; - case IterativeParsingMemberValueState: - // Must be non-compound value. Or it would be ObjectInitial or - // ArrayInitial state. - ParseValue(is, handler); - if (HasParseError()) { - return IterativeParsingErrorState; + case IterativeParsingObjectInitialState: + case IterativeParsingArrayInitialState: { + // Push the state(Element or MemeberValue) if we are nested in another + // array or value of member. In this way we can get the correct state on + // ObjectFinish or ArrayFinish by frame pop. + IterativeParsingState n = src; + if (src == IterativeParsingArrayInitialState || + src == IterativeParsingElementDelimiterState) + n = IterativeParsingElementState; + else if (src == IterativeParsingKeyValueDelimiterState) + n = IterativeParsingMemberValueState; + // Push current state. + *stack_.template Push(1) = n; + // Initialize and push the member/element count. + *stack_.template Push(1) = 0; + // Call handler + bool hr = (dst == IterativeParsingObjectInitialState) + ? handler.StartObject() + : handler.StartArray(); + // On handler short circuits the parsing. + if (!hr) { + RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorTermination, is.Tell()); + return IterativeParsingErrorState; + } else { + is.Take(); + return dst; + } } - return dst; - case IterativeParsingElementState: - // Must be non-compound value. Or it would be ObjectInitial or - // ArrayInitial state. - ParseValue(is, handler); - if (HasParseError()) { - return IterativeParsingErrorState; - } - return dst; + case IterativeParsingMemberKeyState: + ParseString(is, handler, true); + if (HasParseError()) + return IterativeParsingErrorState; + else + return dst; - case IterativeParsingMemberDelimiterState: - case IterativeParsingElementDelimiterState: - is.Take(); - // Update member/element count. - *stack_.template Top() = *stack_.template Top() + 1; - return dst; - - case IterativeParsingObjectFinishState: { - // Transit from delimiter is only allowed when trailing commas are enabled - if (!(parseFlags & kParseTrailingCommasFlag) && - src == IterativeParsingMemberDelimiterState) { - RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorObjectMissName, is.Tell()); - return IterativeParsingErrorState; - } - // Get member count. - SizeType c = *stack_.template Pop(1); - // If the object is not empty, count the last member. - if (src == IterativeParsingMemberValueState) - ++c; - // Restore the state. - IterativeParsingState n = - static_cast(*stack_.template Pop(1)); - // Transit to Finish state if this is the topmost scope. - if (n == IterativeParsingStartState) - n = IterativeParsingFinishState; - // Call handler - bool hr = handler.EndObject(c); - // On handler short circuits the parsing. - if (!hr) { - RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorTermination, is.Tell()); - return IterativeParsingErrorState; - } else { + case IterativeParsingKeyValueDelimiterState: + RAPIDJSON_ASSERT(token == ColonToken); is.Take(); - return n; - } - } + return dst; - case IterativeParsingArrayFinishState: { - // Transit from delimiter is only allowed when trailing commas are enabled - if (!(parseFlags & kParseTrailingCommasFlag) && - src == IterativeParsingElementDelimiterState) { - RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorValueInvalid, is.Tell()); - return IterativeParsingErrorState; - } - // Get element count. - SizeType c = *stack_.template Pop(1); - // If the array is not empty, count the last element. - if (src == IterativeParsingElementState) - ++c; - // Restore the state. - IterativeParsingState n = - static_cast(*stack_.template Pop(1)); - // Transit to Finish state if this is the topmost scope. - if (n == IterativeParsingStartState) - n = IterativeParsingFinishState; - // Call handler - bool hr = handler.EndArray(c); - // On handler short circuits the parsing. - if (!hr) { - RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorTermination, is.Tell()); - return IterativeParsingErrorState; - } else { - is.Take(); - return n; - } - } + case IterativeParsingMemberValueState: + // Must be non-compound value. Or it would be ObjectInitial or + // ArrayInitial state. + ParseValue(is, handler); + if (HasParseError()) { + return IterativeParsingErrorState; + } + return dst; - default: - // This branch is for IterativeParsingValueState actually. - // Use `default:` rather than - // `case IterativeParsingValueState:` is for code coverage. + case IterativeParsingElementState: + // Must be non-compound value. Or it would be ObjectInitial or + // ArrayInitial state. + ParseValue(is, handler); + if (HasParseError()) { + return IterativeParsingErrorState; + } + return dst; - // The IterativeParsingStartState is not enumerated in this switch-case. - // It is impossible for that case. And it can be caught by following - // assertion. + case IterativeParsingMemberDelimiterState: + case IterativeParsingElementDelimiterState: + is.Take(); + // Update member/element count. + *stack_.template Top() = *stack_.template Top() + 1; + return dst; - // The IterativeParsingFinishState is not enumerated in this switch-case - // either. It is a "derivative" state which cannot triggered from - // Predict() directly. Therefore it cannot happen here. And it can be - // caught by following assertion. - RAPIDJSON_ASSERT(dst == IterativeParsingValueState); + case IterativeParsingObjectFinishState: { + // Transit from delimiter is only allowed when trailing commas are + // enabled + if (!(parseFlags & kParseTrailingCommasFlag) && + src == IterativeParsingMemberDelimiterState) { + RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorObjectMissName, is.Tell()); + return IterativeParsingErrorState; + } + // Get member count. + SizeType c = *stack_.template Pop(1); + // If the object is not empty, count the last member. + if (src == IterativeParsingMemberValueState) ++c; + // Restore the state. + IterativeParsingState n = static_cast( + *stack_.template Pop(1)); + // Transit to Finish state if this is the topmost scope. + if (n == IterativeParsingStartState) n = IterativeParsingFinishState; + // Call handler + bool hr = handler.EndObject(c); + // On handler short circuits the parsing. + if (!hr) { + RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorTermination, is.Tell()); + return IterativeParsingErrorState; + } else { + is.Take(); + return n; + } + } - // Must be non-compound value. Or it would be ObjectInitial or - // ArrayInitial state. - ParseValue(is, handler); - if (HasParseError()) { - return IterativeParsingErrorState; + case IterativeParsingArrayFinishState: { + // Transit from delimiter is only allowed when trailing commas are + // enabled + if (!(parseFlags & kParseTrailingCommasFlag) && + src == IterativeParsingElementDelimiterState) { + RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorValueInvalid, is.Tell()); + return IterativeParsingErrorState; + } + // Get element count. + SizeType c = *stack_.template Pop(1); + // If the array is not empty, count the last element. + if (src == IterativeParsingElementState) ++c; + // Restore the state. + IterativeParsingState n = static_cast( + *stack_.template Pop(1)); + // Transit to Finish state if this is the topmost scope. + if (n == IterativeParsingStartState) n = IterativeParsingFinishState; + // Call handler + bool hr = handler.EndArray(c); + // On handler short circuits the parsing. + if (!hr) { + RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorTermination, is.Tell()); + return IterativeParsingErrorState; + } else { + is.Take(); + return n; + } } - return IterativeParsingFinishState; + + default: + // This branch is for IterativeParsingValueState actually. + // Use `default:` rather than + // `case IterativeParsingValueState:` is for code coverage. + + // The IterativeParsingStartState is not enumerated in this switch-case. + // It is impossible for that case. And it can be caught by following + // assertion. + + // The IterativeParsingFinishState is not enumerated in this switch-case + // either. It is a "derivative" state which cannot triggered from + // Predict() directly. Therefore it cannot happen here. And it can be + // caught by following assertion. + RAPIDJSON_ASSERT(dst == IterativeParsingValueState); + + // Must be non-compound value. Or it would be ObjectInitial or + // ArrayInitial state. + ParseValue(is, handler); + if (HasParseError()) { + return IterativeParsingErrorState; + } + return IterativeParsingFinishState; } } @@ -2366,43 +2357,43 @@ class GenericReader { } switch (src) { - case IterativeParsingStartState: - RAPIDJSON_PARSE_ERROR(kParseErrorDocumentEmpty, is.Tell()); - return; - case IterativeParsingFinishState: - RAPIDJSON_PARSE_ERROR(kParseErrorDocumentRootNotSingular, is.Tell()); - return; - case IterativeParsingObjectInitialState: - case IterativeParsingMemberDelimiterState: - RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissName, is.Tell()); - return; - case IterativeParsingMemberKeyState: - RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissColon, is.Tell()); - return; - case IterativeParsingMemberValueState: - RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissCommaOrCurlyBracket, - is.Tell()); - return; - case IterativeParsingKeyValueDelimiterState: - case IterativeParsingArrayInitialState: - case IterativeParsingElementDelimiterState: - RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, is.Tell()); - return; - default: - RAPIDJSON_ASSERT(src == IterativeParsingElementState); - RAPIDJSON_PARSE_ERROR(kParseErrorArrayMissCommaOrSquareBracket, - is.Tell()); - return; + case IterativeParsingStartState: + RAPIDJSON_PARSE_ERROR(kParseErrorDocumentEmpty, is.Tell()); + return; + case IterativeParsingFinishState: + RAPIDJSON_PARSE_ERROR(kParseErrorDocumentRootNotSingular, is.Tell()); + return; + case IterativeParsingObjectInitialState: + case IterativeParsingMemberDelimiterState: + RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissName, is.Tell()); + return; + case IterativeParsingMemberKeyState: + RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissColon, is.Tell()); + return; + case IterativeParsingMemberValueState: + RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissCommaOrCurlyBracket, + is.Tell()); + return; + case IterativeParsingKeyValueDelimiterState: + case IterativeParsingArrayInitialState: + case IterativeParsingElementDelimiterState: + RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, is.Tell()); + return; + default: + RAPIDJSON_ASSERT(src == IterativeParsingElementState); + RAPIDJSON_PARSE_ERROR(kParseErrorArrayMissCommaOrSquareBracket, + is.Tell()); + return; } } - RAPIDJSON_FORCEINLINE bool - IsIterativeParsingDelimiterState(IterativeParsingState s) const { + RAPIDJSON_FORCEINLINE bool IsIterativeParsingDelimiterState( + IterativeParsingState s) const { return s >= IterativeParsingElementDelimiterState; } - RAPIDJSON_FORCEINLINE bool - IsIterativeParsingCompleteState(IterativeParsingState s) const { + RAPIDJSON_FORCEINLINE bool IsIterativeParsingCompleteState( + IterativeParsingState s) const { return s <= IterativeParsingErrorState; } @@ -2436,21 +2427,20 @@ class GenericReader { } // Handle the end of file. - if (state != IterativeParsingFinishState) - HandleError(state, is); + if (state != IterativeParsingFinishState) HandleError(state, is); return parseResult_; } static const size_t kDefaultStackCapacity = - 256; //!< Default stack capacity in bytes for storing a single decoded - //!< string. + 256; //!< Default stack capacity in bytes for storing a single decoded + //!< string. internal::Stack - stack_; //!< A stack for storing decoded string temporarily during - //!< non-destructive parsing. + stack_; //!< A stack for storing decoded string temporarily during + //!< non-destructive parsing. ParseResult parseResult_; IterativeParsingState state_; -}; // class GenericReader +}; // class GenericReader //! Reader with UTF8 encoding and default allocator. typedef GenericReader, UTF8<>> Reader; @@ -2465,4 +2455,4 @@ RAPIDJSON_DIAG_POP RAPIDJSON_DIAG_POP #endif -#endif // RAPIDJSON_READER_H_ +#endif // RAPIDJSON_READER_H_ diff --git a/livox_ros_driver/common/rapidjson/schema.h b/livox_ros_driver/common/rapidjson/schema.h index 9a2fa7f..b9dc8c8 100644 --- a/livox_ros_driver/common/rapidjson/schema.h +++ b/livox_ros_driver/common/rapidjson/schema.h @@ -19,10 +19,10 @@ #ifndef RAPIDJSON_SCHEMA_H_ #define RAPIDJSON_SCHEMA_H_ +#include // abs, floor #include "document.h" #include "pointer.h" #include "stringbuffer.h" -#include // abs, floor #if !defined(RAPIDJSON_SCHEMA_USE_INTERNALREGEX) #define RAPIDJSON_SCHEMA_USE_INTERNALREGEX 1 @@ -30,8 +30,8 @@ #define RAPIDJSON_SCHEMA_USE_INTERNALREGEX 0 #endif -#if !RAPIDJSON_SCHEMA_USE_INTERNALREGEX && \ - defined(RAPIDJSON_SCHEMA_USE_STDREGEX) && \ +#if !RAPIDJSON_SCHEMA_USE_INTERNALREGEX && \ + defined(RAPIDJSON_SCHEMA_USE_STDREGEX) && \ (__cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1800)) #define RAPIDJSON_SCHEMA_USE_STDREGEX 1 #else @@ -70,7 +70,7 @@ RAPIDJSON_DIAG_OFF(exit - time - destructors) RAPIDJSON_DIAG_OFF(c++ 98 - compat - pedantic) RAPIDJSON_DIAG_OFF(variadic - macros) #elif defined(_MSC_VER) -RAPIDJSON_DIAG_OFF(4512) // assignment operator could not be generated +RAPIDJSON_DIAG_OFF(4512) // assignment operator could not be generated #endif RAPIDJSON_NAMESPACE_BEGIN @@ -109,41 +109,43 @@ inline void PrintValidatorPointers(unsigned depth, const wchar_t *s, d); } -} // namespace internal +} // namespace internal -#endif // RAPIDJSON_SCHEMA_VERBOSE +#endif // RAPIDJSON_SCHEMA_VERBOSE /////////////////////////////////////////////////////////////////////////////// // RAPIDJSON_INVALID_KEYWORD_RETURN #if RAPIDJSON_SCHEMA_VERBOSE -#define RAPIDJSON_INVALID_KEYWORD_VERBOSE(keyword) \ +#define RAPIDJSON_INVALID_KEYWORD_VERBOSE(keyword) \ internal::PrintInvalidKeyword(keyword) #else #define RAPIDJSON_INVALID_KEYWORD_VERBOSE(keyword) #endif -#define RAPIDJSON_INVALID_KEYWORD_RETURN(keyword) \ - RAPIDJSON_MULTILINEMACRO_BEGIN \ - context.invalidKeyword = keyword.GetString(); \ - RAPIDJSON_INVALID_KEYWORD_VERBOSE(keyword.GetString()); \ - return false; \ +#define RAPIDJSON_INVALID_KEYWORD_RETURN(keyword) \ + RAPIDJSON_MULTILINEMACRO_BEGIN \ + context.invalidKeyword = keyword.GetString(); \ + RAPIDJSON_INVALID_KEYWORD_VERBOSE(keyword.GetString()); \ + return false; \ RAPIDJSON_MULTILINEMACRO_END /////////////////////////////////////////////////////////////////////////////// // Forward declarations -template class GenericSchemaDocument; +template +class GenericSchemaDocument; namespace internal { -template class Schema; +template +class Schema; /////////////////////////////////////////////////////////////////////////////// // ISchemaValidator class ISchemaValidator { -public: + public: virtual ~ISchemaValidator() {} virtual bool IsValid() const = 0; }; @@ -151,8 +153,9 @@ class ISchemaValidator { /////////////////////////////////////////////////////////////////////////////// // ISchemaStateFactory -template class ISchemaStateFactory { -public: +template +class ISchemaStateFactory { + public: virtual ~ISchemaStateFactory() {} virtual ISchemaValidator *CreateSchemaValidator(const SchemaType &) = 0; virtual void DestroySchemaValidator(ISchemaValidator *validator) = 0; @@ -166,8 +169,9 @@ template class ISchemaStateFactory { /////////////////////////////////////////////////////////////////////////////// // IValidationErrorHandler -template class IValidationErrorHandler { -public: +template +class IValidationErrorHandler { + public: typedef typename SchemaType::Ch Ch; typedef typename SchemaType::SValue SValue; @@ -219,10 +223,10 @@ template class IValidationErrorHandler { virtual void DisallowedValue() = 0; virtual void StartDisallowedType() = 0; - virtual void - AddExpectedType(const typename SchemaType::ValueType &expectedType) = 0; - virtual void - EndDisallowedType(const typename SchemaType::ValueType &actualType) = 0; + virtual void AddExpectedType( + const typename SchemaType::ValueType &expectedType) = 0; + virtual void EndDisallowedType( + const typename SchemaType::ValueType &actualType) = 0; virtual void NotAllOf(ISchemaValidator **subvalidators, SizeType count) = 0; virtual void NoneOf(ISchemaValidator **subvalidators, SizeType count) = 0; virtual void NotOneOf(ISchemaValidator **subvalidators, SizeType count) = 0; @@ -233,8 +237,9 @@ template class IValidationErrorHandler { // Hasher // For comparison of compound value -template class Hasher { -public: +template +class Hasher { + public: typedef typename Encoding::Ch Ch; Hasher(Allocator *allocator = 0, size_t stackCapacity = kDefaultSize) @@ -295,7 +300,7 @@ template class Hasher { uint64_t *kv = stack_.template Pop(memberCount * 2); for (SizeType i = 0; i < memberCount; i++) h ^= Hash(kv[i * 2], - kv[i * 2 + 1]); // Use xor to achieve member order insensitive + kv[i * 2 + 1]); // Use xor to achieve member order insensitive *stack_.template Push() = h; return true; } @@ -305,7 +310,7 @@ template class Hasher { uint64_t h = Hash(0, kArrayType); uint64_t *e = stack_.template Pop(elementCount); for (SizeType i = 0; i < elementCount; i++) - h = Hash(h, e[i]); // Use hash to achieve element order sensitive + h = Hash(h, e[i]); // Use hash to achieve element order sensitive *stack_.template Push() = h; return true; } @@ -317,7 +322,7 @@ template class Hasher { return *stack_.template Top(); } -private: + private: static const size_t kDefaultSize = 256; struct Number { union U { @@ -337,8 +342,7 @@ template class Hasher { // FNV-1a from http://isthe.com/chongo/tech/comp/fnv/ uint64_t h = Hash(RAPIDJSON_UINT64_C2(0x84222325, 0xcbf29ce4), type); const unsigned char *d = static_cast(data); - for (size_t i = 0; i < len; i++) - h = Hash(h, d[i]); + for (size_t i = 0; i < len; i++) h = Hash(h, d[i]); *stack_.template Push() = h; return true; } @@ -356,7 +360,8 @@ template class Hasher { /////////////////////////////////////////////////////////////////////////////// // SchemaValidationContext -template struct SchemaValidationContext { +template +struct SchemaValidationContext { typedef Schema SchemaType; typedef ISchemaStateFactory SchemaValidatorFactoryType; typedef IValidationErrorHandler ErrorHandlerType; @@ -371,17 +376,27 @@ template struct SchemaValidationContext { SchemaValidationContext(SchemaValidatorFactoryType &f, ErrorHandlerType &eh, const SchemaType *s) - : factory(f), error_handler(eh), schema(s), valueSchema(), - invalidKeyword(), hasher(), arrayElementHashCodes(), validators(), - validatorCount(), patternPropertiesValidators(), - patternPropertiesValidatorCount(), patternPropertiesSchemas(), + : factory(f), + error_handler(eh), + schema(s), + valueSchema(), + invalidKeyword(), + hasher(), + arrayElementHashCodes(), + validators(), + validatorCount(), + patternPropertiesValidators(), + patternPropertiesValidatorCount(), + patternPropertiesSchemas(), patternPropertiesSchemaCount(), - valuePatternValidatorType(kPatternValidatorOnly), propertyExist(), - inArray(false), valueUniqueness(false), arrayUniqueness(false) {} + valuePatternValidatorType(kPatternValidatorOnly), + propertyExist(), + inArray(false), + valueUniqueness(false), + arrayUniqueness(false) {} ~SchemaValidationContext() { - if (hasher) - factory.DestroryHasher(hasher); + if (hasher) factory.DestroryHasher(hasher); if (validators) { for (SizeType i = 0; i < validatorCount; i++) factory.DestroySchemaValidator(validators[i]); @@ -392,10 +407,8 @@ template struct SchemaValidationContext { factory.DestroySchemaValidator(patternPropertiesValidators[i]); factory.FreeState(patternPropertiesValidators); } - if (patternPropertiesSchemas) - factory.FreeState(patternPropertiesSchemas); - if (propertyExist) - factory.FreeState(propertyExist); + if (patternPropertiesSchemas) factory.FreeState(patternPropertiesSchemas); + if (propertyExist) factory.FreeState(propertyExist); } SchemaValidatorFactoryType &factory; @@ -403,8 +416,8 @@ template struct SchemaValidationContext { const SchemaType *schema; const SchemaType *valueSchema; const Ch *invalidKeyword; - void *hasher; // Only validator access - void *arrayElementHashCodes; // Only validator access this + void *hasher; // Only validator access + void *arrayElementHashCodes; // Only validator access this ISchemaValidator **validators; SizeType validatorCount; ISchemaValidator **patternPropertiesValidators; @@ -423,8 +436,9 @@ template struct SchemaValidationContext { /////////////////////////////////////////////////////////////////////////////// // Schema -template class Schema { -public: +template +class Schema { + public: typedef typename SchemaDocumentType::ValueType ValueType; typedef typename SchemaDocumentType::AllocatorType AllocatorType; typedef typename SchemaDocumentType::PointerType PointerType; @@ -439,26 +453,46 @@ template class Schema { Schema(SchemaDocumentType *schemaDocument, const PointerType &p, const ValueType &value, const ValueType &document, AllocatorType *allocator) - : allocator_(allocator), uri_(schemaDocument->GetURI(), *allocator), - pointer_(p, allocator), typeless_(schemaDocument->GetTypeless()), - enum_(), enumCount_(), not_(), - type_((1 << kTotalSchemaType) - 1), // typeless - validatorCount_(), notValidatorIndex_(), properties_(), - additionalPropertiesSchema_(), patternProperties_(), - patternPropertyCount_(), propertyCount_(), minProperties_(), - maxProperties_(SizeType(~0)), additionalProperties_(true), - hasDependencies_(), hasRequired_(), hasSchemaDependencies_(), - additionalItemsSchema_(), itemsList_(), itemsTuple_(), - itemsTupleCount_(), minItems_(), maxItems_(SizeType(~0)), - additionalItems_(true), uniqueItems_(false), pattern_(), minLength_(0), - maxLength_(~SizeType(0)), exclusiveMinimum_(false), - exclusiveMaximum_(false), defaultValueLength_(0) { + : allocator_(allocator), + uri_(schemaDocument->GetURI(), *allocator), + pointer_(p, allocator), + typeless_(schemaDocument->GetTypeless()), + enum_(), + enumCount_(), + not_(), + type_((1 << kTotalSchemaType) - 1), // typeless + validatorCount_(), + notValidatorIndex_(), + properties_(), + additionalPropertiesSchema_(), + patternProperties_(), + patternPropertyCount_(), + propertyCount_(), + minProperties_(), + maxProperties_(SizeType(~0)), + additionalProperties_(true), + hasDependencies_(), + hasRequired_(), + hasSchemaDependencies_(), + additionalItemsSchema_(), + itemsList_(), + itemsTuple_(), + itemsTupleCount_(), + minItems_(), + maxItems_(SizeType(~0)), + additionalItems_(true), + uniqueItems_(false), + pattern_(), + minLength_(0), + maxLength_(~SizeType(0)), + exclusiveMinimum_(false), + exclusiveMaximum_(false), + defaultValueLength_(0) { typedef typename SchemaDocumentType::ValueType ValueType; typedef typename ValueType::ConstValueIterator ConstValueIterator; typedef typename ValueType::ConstMemberIterator ConstMemberIterator; - if (!value.IsObject()) - return; + if (!value.IsObject()) return; if (const ValueType *v = GetMember(value, GetTypeString())) { type_ = 0; @@ -516,8 +550,7 @@ template class Schema { if (required && required->IsArray()) for (ConstValueIterator itr = required->Begin(); itr != required->End(); ++itr) - if (itr->IsString()) - AddUniqueElement(allProperties, *itr); + if (itr->IsString()) AddUniqueElement(allProperties, *itr); if (dependencies && dependencies->IsObject()) for (ConstMemberIterator itr = dependencies->MemberBegin(); @@ -526,8 +559,7 @@ template class Schema { if (itr->value.IsArray()) for (ConstValueIterator i = itr->value.Begin(); i != itr->value.End(); ++i) - if (i->IsString()) - AddUniqueElement(allProperties, *i); + if (i->IsString()) AddUniqueElement(allProperties, *i); } if (allProperties.Size() > 0) { @@ -631,9 +663,9 @@ template class Schema { // Array if (const ValueType *v = GetMember(value, GetItemsString())) { PointerType q = p.Append(GetItemsString(), allocator_); - if (v->IsObject()) // List validation + if (v->IsObject()) // List validation schemaDocument->CreateSchema(&itemsList_, q, *v, document); - else if (v->IsArray()) { // Tuple validation + else if (v->IsArray()) { // Tuple validation itemsTuple_ = static_cast( allocator_->Malloc(sizeof(const Schema *) * v->Size())); SizeType index = 0; @@ -668,12 +700,10 @@ template class Schema { // Number if (const ValueType *v = GetMember(value, GetMinimumString())) - if (v->IsNumber()) - minimum_.CopyFrom(*v, *allocator_); + if (v->IsNumber()) minimum_.CopyFrom(*v, *allocator_); if (const ValueType *v = GetMember(value, GetMaximumString())) - if (v->IsNumber()) - maximum_.CopyFrom(*v, *allocator_); + if (v->IsNumber()) maximum_.CopyFrom(*v, *allocator_); AssignIfExist(exclusiveMinimum_, value, GetExclusiveMinimumString()); AssignIfExist(exclusiveMaximum_, value, GetExclusiveMaximumString()); @@ -684,15 +714,13 @@ template class Schema { // Default if (const ValueType *v = GetMember(value, GetDefaultValueString())) - if (v->IsString()) - defaultValueLength_ = v->GetStringLength(); + if (v->IsString()) defaultValueLength_ = v->GetStringLength(); } ~Schema() { AllocatorType::Free(enum_); if (properties_) { - for (SizeType i = 0; i < propertyCount_; i++) - properties_[i].~Property(); + for (SizeType i = 0; i < propertyCount_; i++) properties_[i].~Property(); AllocatorType::Free(properties_); } if (patternProperties_) { @@ -715,8 +743,7 @@ template class Schema { bool BeginValue(Context &context) const { if (context.inArray) { - if (uniqueItems_) - context.valueUniqueness = true; + if (uniqueItems_) context.valueUniqueness = true; if (itemsList_) context.valueSchema = itemsList_; @@ -768,7 +795,7 @@ template class Schema { RAPIDJSON_INVALID_KEYWORD_RETURN(GetPatternPropertiesString()); } } else if (!patternValid && - !otherValid) { // kPatternValidatorWithAdditionalProperty) + !otherValid) { // kPatternValidatorWithAdditionalProperty) context.error_handler.PropertyViolations( context.patternPropertiesValidators, count + 1); RAPIDJSON_INVALID_KEYWORD_RETURN(GetPatternPropertiesString()); @@ -778,8 +805,7 @@ template class Schema { if (enum_) { const uint64_t h = context.factory.GetHashCode(context.hasher); for (SizeType i = 0; i < enumCount_; i++) - if (enum_[i] == h) - goto foundEnum; + if (enum_[i] == h) goto foundEnum; context.error_handler.DisallowedValue(); RAPIDJSON_INVALID_KEYWORD_RETURN(GetEnumString()); foundEnum:; @@ -795,8 +821,7 @@ template class Schema { if (anyOf_.schemas) { for (SizeType i = anyOf_.begin; i < anyOf_.begin + anyOf_.count; i++) - if (context.validators[i]->IsValid()) - goto foundAny; + if (context.validators[i]->IsValid()) goto foundAny; context.error_handler.NoneOf(&context.validators[anyOf_.begin], anyOf_.count); RAPIDJSON_INVALID_KEYWORD_RETURN(GetAnyOfString()); @@ -846,26 +871,22 @@ template class Schema { } bool Int(Context &context, int i) const { - if (!CheckInt(context, i)) - return false; + if (!CheckInt(context, i)) return false; return CreateParallelValidator(context); } bool Uint(Context &context, unsigned u) const { - if (!CheckUint(context, u)) - return false; + if (!CheckUint(context, u)) return false; return CreateParallelValidator(context); } bool Int64(Context &context, int64_t i) const { - if (!CheckInt(context, i)) - return false; + if (!CheckInt(context, i)) return false; return CreateParallelValidator(context); } bool Uint64(Context &context, uint64_t u) const { - if (!CheckUint(context, u)) - return false; + if (!CheckUint(context, u)) return false; return CreateParallelValidator(context); } @@ -875,11 +896,9 @@ template class Schema { RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString()); } - if (!minimum_.IsNull() && !CheckDoubleMinimum(context, d)) - return false; + if (!minimum_.IsNull() && !CheckDoubleMinimum(context, d)) return false; - if (!maximum_.IsNull() && !CheckDoubleMaximum(context, d)) - return false; + if (!maximum_.IsNull() && !CheckDoubleMaximum(context, d)) return false; if (!multipleOf_.IsNull() && !CheckDoubleMultipleOf(context, d)) return false; @@ -927,9 +946,9 @@ template class Schema { std::memset(context.propertyExist, 0, sizeof(bool) * propertyCount_); } - if (patternProperties_) { // pre-allocate schema array + if (patternProperties_) { // pre-allocate schema array SizeType count = - patternPropertyCount_ + 1; // extra for valuePatternValidatorType + patternPropertyCount_ + 1; // extra for valuePatternValidatorType context.patternPropertiesSchemas = static_cast( context.factory.MallocState(sizeof(const SchemaType *) * count)); context.patternPropertiesSchemaCount = 0; @@ -965,8 +984,7 @@ template class Schema { } else context.valueSchema = properties_[index].schema; - if (context.propertyExist) - context.propertyExist[index] = true; + if (context.propertyExist) context.propertyExist[index] = true; return true; } @@ -989,7 +1007,7 @@ template class Schema { } if (context.patternPropertiesSchemaCount == - 0) { // patternProperties are not additional properties + 0) { // patternProperties are not additional properties context.error_handler.DisallowedProperty(str, len); RAPIDJSON_INVALID_KEYWORD_RETURN(GetAdditionalPropertiesString()); } @@ -1077,13 +1095,13 @@ template class Schema { return true; } - // Generate functions for string literal according to Ch -#define RAPIDJSON_STRING_(name, ...) \ - static const ValueType &Get##name##String() { \ - static const Ch s[] = {__VA_ARGS__, '\0'}; \ - static const ValueType v( \ - s, static_cast(sizeof(s) / sizeof(Ch) - 1)); \ - return v; \ +// Generate functions for string literal according to Ch +#define RAPIDJSON_STRING_(name, ...) \ + static const ValueType &Get##name##String() { \ + static const Ch s[] = {__VA_ARGS__, '\0'}; \ + static const ValueType v( \ + s, static_cast(sizeof(s) / sizeof(Ch) - 1)); \ + return v; \ } RAPIDJSON_STRING_(Null, 'n', 'u', 'l', 'l') @@ -1135,7 +1153,7 @@ template class Schema { #undef RAPIDJSON_STRING_ -private: + private: enum SchemaValueType { kNullSchemaType, kBooleanSchemaType, @@ -1159,15 +1177,14 @@ template class Schema { SchemaArray() : schemas(), count() {} ~SchemaArray() { AllocatorType::Free(schemas); } const SchemaType **schemas; - SizeType begin; // begin index of context.validators + SizeType begin; // begin index of context.validators SizeType count; }; template void AddUniqueElement(V1 &a, const V2 &v) { for (typename V1::ConstValueIterator itr = a.Begin(); itr != a.End(); ++itr) - if (*itr == v) - return; + if (*itr == v) return; V1 c(v, *allocator_); a.PushBack(c, *allocator_); } @@ -1181,8 +1198,7 @@ template class Schema { static void AssignIfExist(bool &out, const ValueType &value, const ValueType &name) { if (const ValueType *v = GetMember(value, name)) - if (v->IsBool()) - out = v->GetBool(); + if (v->IsBool()) out = v->GetBool(); } static void AssignIfExist(SizeType &out, const ValueType &value, @@ -1255,14 +1271,15 @@ template class Schema { return std::regex_search(str, str + length, r, *pattern); } #else - template RegexType *CreatePattern(const ValueType &) { + template + RegexType *CreatePattern(const ValueType &) { return 0; } static bool IsPatternMatch(const RegexType *, const Ch *, SizeType) { return true; } -#endif // RAPIDJSON_SCHEMA_USE_STDREGEX +#endif // RAPIDJSON_SCHEMA_USE_STDREGEX void AddType(const ValueType &type) { if (type == GetNullString()) @@ -1292,14 +1309,11 @@ template class Schema { sizeof(ISchemaValidator *) * validatorCount_)); context.validatorCount = validatorCount_; - if (allOf_.schemas) - CreateSchemaValidators(context, allOf_); + if (allOf_.schemas) CreateSchemaValidators(context, allOf_); - if (anyOf_.schemas) - CreateSchemaValidators(context, anyOf_); + if (anyOf_.schemas) CreateSchemaValidators(context, anyOf_); - if (oneOf_.schemas) - CreateSchemaValidators(context, oneOf_); + if (oneOf_.schemas) CreateSchemaValidators(context, oneOf_); if (not_) context.validators[notValidatorIndex_] = @@ -1354,7 +1368,7 @@ template class Schema { } else if (minimum_.IsUint64()) { context.error_handler.BelowMinimum(i, minimum_, exclusiveMinimum_); RAPIDJSON_INVALID_KEYWORD_RETURN( - GetMinimumString()); // i <= max(int64_t) < minimum.GetUint64() + GetMinimumString()); // i <= max(int64_t) < minimum.GetUint64() } else if (!CheckDoubleMinimum(context, static_cast(i))) return false; } @@ -1368,7 +1382,7 @@ template class Schema { } } else if (maximum_.IsUint64()) { } - /* do nothing */ // i <= max(int64_t) < maximum_.GetUint64() + /* do nothing */ // i <= max(int64_t) < maximum_.GetUint64() else if (!CheckDoubleMaximum(context, static_cast(i))) return false; } @@ -1401,7 +1415,7 @@ template class Schema { RAPIDJSON_INVALID_KEYWORD_RETURN(GetMinimumString()); } } else if (minimum_.IsInt64()) - /* do nothing */; // i >= 0 > minimum.Getint64() + /* do nothing */; // i >= 0 > minimum.Getint64() else if (!CheckDoubleMinimum(context, static_cast(i))) return false; } @@ -1416,7 +1430,7 @@ template class Schema { } else if (maximum_.IsInt64()) { context.error_handler.AboveMaximum(i, maximum_, exclusiveMaximum_); RAPIDJSON_INVALID_KEYWORD_RETURN( - GetMaximumString()); // i >= 0 > maximum_ + GetMaximumString()); // i >= 0 > maximum_ } else if (!CheckDoubleMaximum(context, static_cast(i))) return false; } @@ -1467,16 +1481,12 @@ template class Schema { ErrorHandler &eh = context.error_handler; eh.StartDisallowedType(); - if (type_ & (1 << kNullSchemaType)) - eh.AddExpectedType(GetNullString()); + if (type_ & (1 << kNullSchemaType)) eh.AddExpectedType(GetNullString()); if (type_ & (1 << kBooleanSchemaType)) eh.AddExpectedType(GetBooleanString()); - if (type_ & (1 << kObjectSchemaType)) - eh.AddExpectedType(GetObjectString()); - if (type_ & (1 << kArraySchemaType)) - eh.AddExpectedType(GetArrayString()); - if (type_ & (1 << kStringSchemaType)) - eh.AddExpectedType(GetStringString()); + if (type_ & (1 << kObjectSchemaType)) eh.AddExpectedType(GetObjectString()); + if (type_ & (1 << kArraySchemaType)) eh.AddExpectedType(GetArrayString()); + if (type_ & (1 << kStringSchemaType)) eh.AddExpectedType(GetStringString()); if (type_ & (1 << kNumberSchemaType)) eh.AddExpectedType(GetNumberString()); @@ -1488,8 +1498,11 @@ template class Schema { struct Property { Property() - : schema(), dependenciesSchema(), dependenciesValidatorIndex(), - dependencies(), required(false) {} + : schema(), + dependenciesSchema(), + dependenciesValidatorIndex(), + dependencies(), + required(false) {} ~Property() { AllocatorType::Free(dependencies); } SValue name; const SchemaType *schema; @@ -1521,7 +1534,7 @@ template class Schema { SchemaArray anyOf_; SchemaArray oneOf_; const SchemaType *not_; - unsigned type_; // bitmask of kSchemaType + unsigned type_; // bitmask of kSchemaType SizeType validatorCount_; SizeType notValidatorIndex_; @@ -1559,7 +1572,8 @@ template class Schema { SizeType defaultValueLength_; }; -template struct TokenHelper { +template +struct TokenHelper { RAPIDJSON_FORCEINLINE static void AppendIndexToken(Stack &documentStack, SizeType index) { *documentStack.template Push() = '/'; @@ -1574,17 +1588,18 @@ template struct TokenHelper { }; // Partial specialized version for char to prevent buffer copying. -template struct TokenHelper { +template +struct TokenHelper { RAPIDJSON_FORCEINLINE static void AppendIndexToken(Stack &documentStack, SizeType index) { if (sizeof(SizeType) == 4) { - char *buffer = documentStack.template Push(1 + 10); // '/' + uint + char *buffer = documentStack.template Push(1 + 10); // '/' + uint *buffer++ = '/'; const char *end = internal::u32toa(index, buffer); documentStack.template Pop( static_cast(10 - (end - buffer))); } else { - char *buffer = documentStack.template Push(1 + 20); // '/' + uint64 + char *buffer = documentStack.template Push(1 + 20); // '/' + uint64 *buffer++ = '/'; const char *end = internal::u64toa(index, buffer); documentStack.template Pop( @@ -1593,14 +1608,14 @@ template struct TokenHelper { } }; -} // namespace internal +} // namespace internal /////////////////////////////////////////////////////////////////////////////// // IGenericRemoteSchemaDocumentProvider template class IGenericRemoteSchemaDocumentProvider { -public: + public: typedef typename SchemaDocumentType::Ch Ch; virtual ~IGenericRemoteSchemaDocumentProvider() {} @@ -1623,7 +1638,7 @@ class IGenericRemoteSchemaDocumentProvider { */ template class GenericSchemaDocument { -public: + public: typedef ValueT ValueType; typedef IGenericRemoteSchemaDocumentProvider IRemoteSchemaDocumentProviderType; @@ -1634,7 +1649,8 @@ class GenericSchemaDocument { typedef GenericPointer PointerType; typedef GenericValue URIType; friend class internal::Schema; - template friend class GenericSchemaValidator; + template + friend class GenericSchemaValidator; //! Constructor. /*! @@ -1651,11 +1667,14 @@ class GenericSchemaDocument { const ValueType &document, const Ch *uri = 0, SizeType uriLength = 0, IRemoteSchemaDocumentProviderType *remoteProvider = 0, Allocator *allocator = 0) - : remoteProvider_(remoteProvider), allocator_(allocator), ownAllocator_(), - root_(), typeless_(), schemaMap_(allocator, kInitialSchemaMapSize), + : remoteProvider_(remoteProvider), + allocator_(allocator), + ownAllocator_(), + root_(), + typeless_(), + schemaMap_(allocator, kInitialSchemaMapSize), schemaRef_(allocator, kInitialSchemaRefSize) { - if (!allocator_) - ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator)(); + if (!allocator_) ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator)(); Ch noUri[1] = {0}; uri_.SetString(uri ? uri : noUri, uriLength, *allocator_); @@ -1674,8 +1693,7 @@ class GenericSchemaDocument { while (!schemaRef_.Empty()) { SchemaRefEntry *refEntry = schemaRef_.template Pop(1); if (const SchemaType *s = GetSchema(refEntry->target)) { - if (refEntry->schema) - *refEntry->schema = s; + if (refEntry->schema) *refEntry->schema = s; // Create entry in map if not exist if (!GetSchema(refEntry->source)) { @@ -1690,7 +1708,7 @@ class GenericSchemaDocument { RAPIDJSON_ASSERT(root_ != 0); - schemaRef_.ShrinkToFit(); // Deallocate all memory for ref + schemaRef_.ShrinkToFit(); // Deallocate all memory for ref } #if RAPIDJSON_HAS_CXX11_RVALUE_REFS @@ -1729,7 +1747,7 @@ class GenericSchemaDocument { //! Get the root schema. const SchemaType &GetRoot() const { return *root_; } -private: + private: //! Prohibit copying GenericSchemaDocument(const GenericSchemaDocument &); //! Prohibit assignment @@ -1762,13 +1780,11 @@ class GenericSchemaDocument { void CreateSchemaRecursive(const SchemaType **schema, const PointerType &pointer, const ValueType &v, const ValueType &document) { - if (schema) - *schema = typeless_; + if (schema) *schema = typeless_; if (v.GetType() == kObjectType) { const SchemaType *s = GetSchema(pointer); - if (!s) - CreateSchema(schema, pointer, v, document); + if (!s) CreateSchema(schema, pointer, v, document); for (typename ValueType::ConstMemberIterator itr = v.MemberBegin(); itr != v.MemberEnd(); ++itr) @@ -1788,8 +1804,7 @@ class GenericSchemaDocument { SchemaType(this, pointer, v, document, allocator_); new (schemaMap_.template Push()) SchemaEntry(pointer, s, true, allocator_); - if (schema) - *schema = s; + if (schema) *schema = s; } } } @@ -1800,26 +1815,24 @@ class GenericSchemaDocument { static const ValueType kRefValue(kRefString, 4); typename ValueType::ConstMemberIterator itr = v.FindMember(kRefValue); - if (itr == v.MemberEnd()) - return false; + if (itr == v.MemberEnd()) return false; if (itr->value.IsString()) { SizeType len = itr->value.GetStringLength(); if (len > 0) { const Ch *s = itr->value.GetString(); SizeType i = 0; - while (i < len && s[i] != '#') // Find the first # + while (i < len && s[i] != '#') // Find the first # i++; - if (i > 0) { // Remote reference, resolve immediately + if (i > 0) { // Remote reference, resolve immediately if (remoteProvider_) { if (const GenericSchemaDocument *remoteDocument = remoteProvider_->GetRemoteDocument(s, i)) { PointerType pointer(&s[i], len - i, allocator_); if (pointer.IsValid()) { if (const SchemaType *sc = remoteDocument->GetSchema(pointer)) { - if (schema) - *schema = sc; + if (schema) *schema = sc; new (schemaMap_.template Push()) SchemaEntry( source, const_cast(sc), false, allocator_); return true; @@ -1827,12 +1840,11 @@ class GenericSchemaDocument { } } } - } else if (s[i] == '#') { // Local reference, defer resolution + } else if (s[i] == '#') { // Local reference, defer resolution PointerType pointer(&s[i], len - i, allocator_); if (pointer.IsValid()) { if (const ValueType *nv = pointer.Get(document)) - if (HandleRefSchema(source, schema, *nv, document)) - return true; + if (HandleRefSchema(source, schema, *nv, document)) return true; new (schemaRef_.template Push()) SchemaRefEntry(source, pointer, schema, allocator_); @@ -1847,16 +1859,14 @@ class GenericSchemaDocument { const SchemaType *GetSchema(const PointerType &pointer) const { for (const SchemaEntry *target = schemaMap_.template Bottom(); target != schemaMap_.template End(); ++target) - if (pointer == target->pointer) - return target->schema; + if (pointer == target->pointer) return target->schema; return 0; } PointerType GetPointer(const SchemaType *schema) const { for (const SchemaEntry *target = schemaMap_.template Bottom(); target != schemaMap_.template End(); ++target) - if (schema == target->schema) - return target->pointer; + if (schema == target->schema) return target->pointer; return PointerType(); } @@ -1868,11 +1878,11 @@ class GenericSchemaDocument { IRemoteSchemaDocumentProviderType *remoteProvider_; Allocator *allocator_; Allocator *ownAllocator_; - const SchemaType *root_; //!< Root schema. + const SchemaType *root_; //!< Root schema. SchemaType *typeless_; - internal::Stack schemaMap_; // Stores created Pointer -> Schemas + internal::Stack schemaMap_; // Stores created Pointer -> Schemas internal::Stack - schemaRef_; // Stores Pointer from $ref and schema which holds the $ref + schemaRef_; // Stores Pointer from $ref and schema which holds the $ref URIType uri_; }; @@ -1906,7 +1916,7 @@ class GenericSchemaValidator : public internal::ISchemaStateFactory< public internal::ISchemaValidator, public internal::IValidationErrorHandler< typename SchemaDocumentType::SchemaType> { -public: + public: typedef typename SchemaDocumentType::SchemaType SchemaType; typedef typename SchemaDocumentType::PointerType PointerType; typedef typename SchemaType::EncodingType EncodingType; @@ -1927,11 +1937,17 @@ class GenericSchemaValidator : public internal::ISchemaStateFactory< const SchemaDocumentType &schemaDocument, StateAllocator *allocator = 0, size_t schemaStackCapacity = kDefaultSchemaStackCapacity, size_t documentStackCapacity = kDefaultDocumentStackCapacity) - : schemaDocument_(&schemaDocument), root_(schemaDocument.GetRoot()), - stateAllocator_(allocator), ownStateAllocator_(0), + : schemaDocument_(&schemaDocument), + root_(schemaDocument.GetRoot()), + stateAllocator_(allocator), + ownStateAllocator_(0), schemaStack_(allocator, schemaStackCapacity), - documentStack_(allocator, documentStackCapacity), outputHandler_(0), - error_(kObjectType), currentError_(), missingDependents_(), valid_(true) + documentStack_(allocator, documentStackCapacity), + outputHandler_(0), + error_(kObjectType), + currentError_(), + missingDependents_(), + valid_(true) #if RAPIDJSON_SCHEMA_VERBOSE , depth_(0) @@ -1952,12 +1968,17 @@ class GenericSchemaValidator : public internal::ISchemaStateFactory< StateAllocator *allocator = 0, size_t schemaStackCapacity = kDefaultSchemaStackCapacity, size_t documentStackCapacity = kDefaultDocumentStackCapacity) - : schemaDocument_(&schemaDocument), root_(schemaDocument.GetRoot()), - stateAllocator_(allocator), ownStateAllocator_(0), + : schemaDocument_(&schemaDocument), + root_(schemaDocument.GetRoot()), + stateAllocator_(allocator), + ownStateAllocator_(0), schemaStack_(allocator, schemaStackCapacity), documentStack_(allocator, documentStackCapacity), - outputHandler_(&outputHandler), error_(kObjectType), currentError_(), - missingDependents_(), valid_(true) + outputHandler_(&outputHandler), + error_(kObjectType), + currentError_(), + missingDependents_(), + valid_(true) #if RAPIDJSON_SCHEMA_VERBOSE , depth_(0) @@ -1973,8 +1994,7 @@ class GenericSchemaValidator : public internal::ISchemaStateFactory< //! Reset the internal states. void Reset() { - while (!schemaStack_.Empty()) - PopSchema(); + while (!schemaStack_.Empty()) PopSchema(); documentStack_.Clear(); error_.SetObject(); currentError_.SetNull(); @@ -2109,8 +2129,7 @@ class GenericSchemaValidator : public internal::ISchemaStateFactory< GetStateAllocator()); } bool EndMissingProperties() { - if (currentError_.Empty()) - return false; + if (currentError_.Empty()) return false; ValueType error(kObjectType); error.AddMember(GetMissingString(), currentError_, GetStateAllocator()); currentError_ = error; @@ -2149,8 +2168,7 @@ class GenericSchemaValidator : public internal::ISchemaStateFactory< GetStateAllocator()); } bool EndDependencyErrors() { - if (currentError_.ObjectEmpty()) - return false; + if (currentError_.ObjectEmpty()) return false; ValueType error(kObjectType); error.AddMember(GetErrorsString(), currentError_, GetStateAllocator()); currentError_ = error; @@ -2193,12 +2211,12 @@ class GenericSchemaValidator : public internal::ISchemaStateFactory< AddCurrentError(SchemaType::GetNotString()); } -#define RAPIDJSON_STRING_(name, ...) \ - static const StringRefType &Get##name##String() { \ - static const Ch s[] = {__VA_ARGS__, '\0'}; \ - static const StringRefType v( \ - s, static_cast(sizeof(s) / sizeof(Ch) - 1)); \ - return v; \ +#define RAPIDJSON_STRING_(name, ...) \ + static const StringRefType &Get##name##String() { \ + static const Ch s[] = {__VA_ARGS__, '\0'}; \ + static const StringRefType v( \ + s, static_cast(sizeof(s) / sizeof(Ch) - 1)); \ + return v; \ } RAPIDJSON_STRING_(InstanceRef, 'i', 'n', 's', 't', 'a', 'n', 'c', 'e', 'R', @@ -2216,47 +2234,46 @@ class GenericSchemaValidator : public internal::ISchemaStateFactory< #undef RAPIDJSON_STRING_ #if RAPIDJSON_SCHEMA_VERBOSE -#define RAPIDJSON_SCHEMA_HANDLE_BEGIN_VERBOSE_() \ - RAPIDJSON_MULTILINEMACRO_BEGIN \ - *documentStack_.template Push() = '\0'; \ - documentStack_.template Pop(1); \ - internal::PrintInvalidDocument(documentStack_.template Bottom()); \ +#define RAPIDJSON_SCHEMA_HANDLE_BEGIN_VERBOSE_() \ + RAPIDJSON_MULTILINEMACRO_BEGIN \ + *documentStack_.template Push() = '\0'; \ + documentStack_.template Pop(1); \ + internal::PrintInvalidDocument(documentStack_.template Bottom()); \ RAPIDJSON_MULTILINEMACRO_END #else #define RAPIDJSON_SCHEMA_HANDLE_BEGIN_VERBOSE_() #endif -#define RAPIDJSON_SCHEMA_HANDLE_BEGIN_(method, arg1) \ - if (!valid_) \ - return false; \ - if (!BeginValue() || !CurrentSchema().method arg1) { \ - RAPIDJSON_SCHEMA_HANDLE_BEGIN_VERBOSE_(); \ - return valid_ = false; \ - } - -#define RAPIDJSON_SCHEMA_HANDLE_PARALLEL_(method, arg2) \ - for (Context *context = schemaStack_.template Bottom(); \ - context != schemaStack_.template End(); context++) { \ - if (context->hasher) \ - static_cast(context->hasher)->method arg2; \ - if (context->validators) \ - for (SizeType i_ = 0; i_ < context->validatorCount; i_++) \ - static_cast(context->validators[i_]) \ - ->method arg2; \ - if (context->patternPropertiesValidators) \ - for (SizeType i_ = 0; i_ < context->patternPropertiesValidatorCount; \ - i_++) \ - static_cast( \ - context->patternPropertiesValidators[i_]) \ - ->method arg2; \ - } - -#define RAPIDJSON_SCHEMA_HANDLE_END_(method, arg2) \ +#define RAPIDJSON_SCHEMA_HANDLE_BEGIN_(method, arg1) \ + if (!valid_) return false; \ + if (!BeginValue() || !CurrentSchema().method arg1) { \ + RAPIDJSON_SCHEMA_HANDLE_BEGIN_VERBOSE_(); \ + return valid_ = false; \ + } + +#define RAPIDJSON_SCHEMA_HANDLE_PARALLEL_(method, arg2) \ + for (Context *context = schemaStack_.template Bottom(); \ + context != schemaStack_.template End(); context++) { \ + if (context->hasher) \ + static_cast(context->hasher)->method arg2; \ + if (context->validators) \ + for (SizeType i_ = 0; i_ < context->validatorCount; i_++) \ + static_cast(context->validators[i_]) \ + ->method arg2; \ + if (context->patternPropertiesValidators) \ + for (SizeType i_ = 0; i_ < context->patternPropertiesValidatorCount; \ + i_++) \ + static_cast( \ + context->patternPropertiesValidators[i_]) \ + ->method arg2; \ + } + +#define RAPIDJSON_SCHEMA_HANDLE_END_(method, arg2) \ return valid_ = EndValue() && (!outputHandler_ || outputHandler_->method arg2) -#define RAPIDJSON_SCHEMA_HANDLE_VALUE_(method, arg1, arg2) \ - RAPIDJSON_SCHEMA_HANDLE_BEGIN_(method, arg1); \ - RAPIDJSON_SCHEMA_HANDLE_PARALLEL_(method, arg2); \ +#define RAPIDJSON_SCHEMA_HANDLE_VALUE_(method, arg1, arg2) \ + RAPIDJSON_SCHEMA_HANDLE_BEGIN_(method, arg1); \ + RAPIDJSON_SCHEMA_HANDLE_PARALLEL_(method, arg2); \ RAPIDJSON_SCHEMA_HANDLE_END_(method, arg2) bool Null() { RAPIDJSON_SCHEMA_HANDLE_VALUE_(Null, (CurrentContext()), ()); } @@ -2294,8 +2311,7 @@ class GenericSchemaValidator : public internal::ISchemaStateFactory< } bool Key(const Ch *str, SizeType len, bool copy) { - if (!valid_) - return false; + if (!valid_) return false; AppendToken(str, len); if (!CurrentSchema().Key(CurrentContext(), str, len, copy)) return valid_ = false; @@ -2304,8 +2320,7 @@ class GenericSchemaValidator : public internal::ISchemaStateFactory< } bool EndObject(SizeType memberCount) { - if (!valid_) - return false; + if (!valid_) return false; RAPIDJSON_SCHEMA_HANDLE_PARALLEL_(EndObject, (memberCount)); if (!CurrentSchema().EndObject(CurrentContext(), memberCount)) return valid_ = false; @@ -2319,8 +2334,7 @@ class GenericSchemaValidator : public internal::ISchemaStateFactory< } bool EndArray(SizeType elementCount) { - if (!valid_) - return false; + if (!valid_) return false; RAPIDJSON_SCHEMA_HANDLE_PARALLEL_(EndArray, (elementCount)); if (!CurrentSchema().EndArray(CurrentContext(), elementCount)) return valid_ = false; @@ -2372,7 +2386,7 @@ class GenericSchemaValidator : public internal::ISchemaStateFactory< virtual void FreeState(void *p) { StateAllocator::Free(p); } -private: + private: typedef typename SchemaType::Context Context; typedef GenericValue, StateAllocator> HashCodeArray; typedef internal::Hasher HasherType; @@ -2386,11 +2400,17 @@ class GenericSchemaValidator : public internal::ISchemaStateFactory< StateAllocator *allocator = 0, size_t schemaStackCapacity = kDefaultSchemaStackCapacity, size_t documentStackCapacity = kDefaultDocumentStackCapacity) - : schemaDocument_(&schemaDocument), root_(root), - stateAllocator_(allocator), ownStateAllocator_(0), + : schemaDocument_(&schemaDocument), + root_(root), + stateAllocator_(allocator), + ownStateAllocator_(0), schemaStack_(allocator, schemaStackCapacity), - documentStack_(allocator, documentStackCapacity), outputHandler_(0), - error_(kObjectType), currentError_(), missingDependents_(), valid_(true) + documentStack_(allocator, documentStackCapacity), + outputHandler_(0), + error_(kObjectType), + currentError_(), + missingDependents_(), + valid_(true) #if RAPIDJSON_SCHEMA_VERBOSE , depth_(depth) @@ -2417,8 +2437,7 @@ class GenericSchemaValidator : public internal::ISchemaStateFactory< CurrentContext() .arrayElementIndex); - if (!CurrentSchema().BeginValue(CurrentContext())) - return false; + if (!CurrentSchema().BeginValue(CurrentContext())) return false; SizeType count = CurrentContext().patternPropertiesSchemaCount; const SchemaType **sa = CurrentContext().patternPropertiesSchemas; @@ -2445,8 +2464,7 @@ class GenericSchemaValidator : public internal::ISchemaStateFactory< } bool EndValue() { - if (!CurrentSchema().EndValue(CurrentContext())) - return false; + if (!CurrentSchema().EndValue(CurrentContext())) return false; #if RAPIDJSON_SCHEMA_VERBOSE GenericStringBuffer sb; @@ -2495,7 +2513,8 @@ class GenericSchemaValidator : public internal::ISchemaStateFactory< void AppendToken(const Ch *str, SizeType len) { documentStack_.template Reserve( - 1 + len * 2); // worst case all characters are escaped as two characters + 1 + + len * 2); // worst case all characters are escaped as two characters *documentStack_.template PushUnsafe() = '/'; for (SizeType i = 0; i < len; i++) { if (str[i] == '~') { @@ -2575,10 +2594,10 @@ class GenericSchemaValidator : public internal::ISchemaStateFactory< } } - void - AddNumberError(const typename SchemaType::ValueType &keyword, - ValueType &actual, const SValue &expected, - const typename SchemaType::ValueType &(*exclusive)() = 0) { + void AddNumberError( + const typename SchemaType::ValueType &keyword, ValueType &actual, + const SValue &expected, + const typename SchemaType::ValueType &(*exclusive)() = 0) { currentError_.SetObject(); currentError_.AddMember(GetActualString(), actual, GetStateAllocator()); currentError_.AddMember(GetExpectedString(), @@ -2618,11 +2637,11 @@ class GenericSchemaValidator : public internal::ISchemaStateFactory< StateAllocator *stateAllocator_; StateAllocator *ownStateAllocator_; internal::Stack - schemaStack_; //!< stack to store the current path of schema - //!< (BaseSchemaType *) + schemaStack_; //!< stack to store the current path of schema + //!< (BaseSchemaType *) internal::Stack - documentStack_; //!< stack to store the current path of validating - //!< document (Ch) + documentStack_; //!< stack to store the current path of validating + //!< document (Ch) OutputHandler *outputHandler_; ValueType error_; ValueType currentError_; @@ -2653,7 +2672,7 @@ template class SchemaValidatingReader { -public: + public: typedef typename SchemaDocumentType::PointerType PointerType; typedef typename InputStream::Ch Ch; typedef GenericValue ValueType; @@ -2664,10 +2683,14 @@ class SchemaValidatingReader { \param sd Schema document. */ SchemaValidatingReader(InputStream &is, const SchemaDocumentType &sd) - : is_(is), sd_(sd), invalidSchemaKeyword_(), error_(kObjectType), + : is_(is), + sd_(sd), + invalidSchemaKeyword_(), + error_(kObjectType), isValid_(true) {} - template bool operator()(Handler &handler) { + template + bool operator()(Handler &handler) { GenericReader reader; @@ -2701,7 +2724,7 @@ class SchemaValidatingReader { } const ValueType &GetError() const { return error_; } -private: + private: InputStream &is_; const SchemaDocumentType &sd_; @@ -2717,4 +2740,4 @@ class SchemaValidatingReader { RAPIDJSON_NAMESPACE_END RAPIDJSON_DIAG_POP -#endif // RAPIDJSON_SCHEMA_H_ +#endif // RAPIDJSON_SCHEMA_H_ diff --git a/livox_ros_driver/common/rapidjson/stream.h b/livox_ros_driver/common/rapidjson/stream.h index e690472..a446c1a 100644 --- a/livox_ros_driver/common/rapidjson/stream.h +++ b/livox_ros_driver/common/rapidjson/stream.h @@ -75,7 +75,8 @@ next character. Ch Take(); configuration. See TEST(Reader, CustomStringStream) in readertest.cpp for example. */ -template struct StreamTraits { +template +struct StreamTraits { //! Whether to make local copy of stream for optimization during parsing. /*! By default, for safety, streams do not use local copy optimization. @@ -102,8 +103,7 @@ inline void PutUnsafe(Stream &stream, typename Stream::Ch c) { template inline void PutN(Stream &stream, Ch c, size_t n) { PutReserve(stream, n); - for (size_t i = 0; i < n; i++) - PutUnsafe(stream, c); + for (size_t i = 0; i < n; i++) PutUnsafe(stream, c); } /////////////////////////////////////////////////////////////////////////////// @@ -117,13 +117,13 @@ inline void PutN(Stream &stream, Ch c, size_t n) { #if defined(_MSC_VER) && _MSC_VER <= 1800 RAPIDJSON_DIAG_PUSH -RAPIDJSON_DIAG_OFF(4702) // unreachable code -RAPIDJSON_DIAG_OFF(4512) // assignment operator could not be generated +RAPIDJSON_DIAG_OFF(4702) // unreachable code +RAPIDJSON_DIAG_OFF(4512) // assignment operator could not be generated #endif template > class GenericStreamWrapper { -public: + public: typedef typename Encoding::Ch Ch; GenericStreamWrapper(InputStream &is) : is_(is) {} @@ -142,7 +142,7 @@ class GenericStreamWrapper { UTFType GetType() const { return is_.GetType(); } bool HasBOM() const { return is_.HasBOM(); } -protected: + protected: InputStream &is_; }; @@ -156,7 +156,8 @@ RAPIDJSON_DIAG_POP //! Read-only string stream. /*! \note implements Stream concept */ -template struct GenericStringStream { +template +struct GenericStringStream { typedef typename Encoding::Ch Ch; GenericStringStream(const Ch *src) : src_(src), head_(src) {} @@ -176,8 +177,8 @@ template struct GenericStringStream { return 0; } - const Ch *src_; //!< Current read position. - const Ch *head_; //!< Original head of the string. + const Ch *src_; //!< Current read position. + const Ch *head_; //!< Original head of the string. }; template @@ -195,7 +196,8 @@ typedef GenericStringStream> StringStream; /*! This string stream is particularly designed for in-situ parsing. \note implements Stream concept */ -template struct GenericInsituStringStream { +template +struct GenericInsituStringStream { typedef typename Encoding::Ch Ch; GenericInsituStringStream(Ch *src) : src_(src), dst_(0), head_(src) {} @@ -237,4 +239,4 @@ typedef GenericInsituStringStream> InsituStringStream; RAPIDJSON_NAMESPACE_END -#endif // RAPIDJSON_STREAM_H_ +#endif // RAPIDJSON_STREAM_H_ diff --git a/livox_ros_driver/common/rapidjson/stringbuffer.h b/livox_ros_driver/common/rapidjson/stringbuffer.h index 03e0a8f..42b2bb1 100644 --- a/livox_ros_driver/common/rapidjson/stringbuffer.h +++ b/livox_ros_driver/common/rapidjson/stringbuffer.h @@ -23,7 +23,7 @@ #include "stream.h" #if RAPIDJSON_HAS_CXX11_RVALUE_REFS -#include // std::move +#include // std::move #endif #include "internal/stack.h" @@ -43,7 +43,7 @@ RAPIDJSON_NAMESPACE_BEGIN */ template class GenericStringBuffer { -public: + public: typedef typename Encoding::Ch Ch; GenericStringBuffer(Allocator *allocator = 0, @@ -54,8 +54,7 @@ class GenericStringBuffer { GenericStringBuffer(GenericStringBuffer &&rhs) : stack_(std::move(rhs.stack_)) {} GenericStringBuffer &operator=(GenericStringBuffer &&rhs) { - if (&rhs != this) - stack_ = std::move(rhs.stack_); + if (&rhs != this) stack_ = std::move(rhs.stack_); return *this; } #endif @@ -94,7 +93,7 @@ class GenericStringBuffer { static const size_t kDefaultCapacity = 256; mutable internal::Stack stack_; -private: + private: // Prohibit copy constructor & assignment operator. GenericStringBuffer(const GenericStringBuffer &); GenericStringBuffer &operator=(const GenericStringBuffer &); @@ -128,4 +127,4 @@ RAPIDJSON_NAMESPACE_END RAPIDJSON_DIAG_POP #endif -#endif // RAPIDJSON_STRINGBUFFER_H_ +#endif // RAPIDJSON_STRINGBUFFER_H_ diff --git a/livox_ros_driver/common/rapidjson/writer.h b/livox_ros_driver/common/rapidjson/writer.h index 3f3ae08..69f9b05 100644 --- a/livox_ros_driver/common/rapidjson/writer.h +++ b/livox_ros_driver/common/rapidjson/writer.h @@ -19,6 +19,7 @@ #ifndef RAPIDJSON_WRITER_H_ #define RAPIDJSON_WRITER_H_ +#include // placement new #include "internal/clzll.h" #include "internal/dtoa.h" #include "internal/itoa.h" @@ -27,7 +28,6 @@ #include "internal/strfunc.h" #include "stream.h" #include "stringbuffer.h" -#include // placement new #if defined(RAPIDJSON_SIMD) && defined(_MSC_VER) #include @@ -48,7 +48,7 @@ RAPIDJSON_DIAG_OFF(unreachable - code) RAPIDJSON_DIAG_OFF(c++ 98 - compat) #elif defined(_MSC_VER) RAPIDJSON_DIAG_PUSH -RAPIDJSON_DIAG_OFF(4127) // conditional expression is constant +RAPIDJSON_DIAG_OFF(4127) // conditional expression is constant #endif RAPIDJSON_NAMESPACE_BEGIN @@ -68,13 +68,13 @@ RAPIDJSON_NAMESPACE_BEGIN //! Combination of writeFlags enum WriteFlag { - kWriteNoFlags = 0, //!< No flags are set. - kWriteValidateEncodingFlag = 1, //!< Validate encoding of JSON strings. - kWriteNanAndInfFlag = 2, //!< Allow writing of Infinity, -Infinity and NaN. + kWriteNoFlags = 0, //!< No flags are set. + kWriteValidateEncodingFlag = 1, //!< Validate encoding of JSON strings. + kWriteNanAndInfFlag = 2, //!< Allow writing of Infinity, -Infinity and NaN. kWriteDefaultFlags = - RAPIDJSON_WRITE_DEFAULT_FLAGS //!< Default write flags. Can be customized - //!< by defining - //!< RAPIDJSON_WRITE_DEFAULT_FLAGS + RAPIDJSON_WRITE_DEFAULT_FLAGS //!< Default write flags. Can be customized + //!< by defining + //!< RAPIDJSON_WRITE_DEFAULT_FLAGS }; //! JSON writer @@ -100,7 +100,7 @@ template , typename StackAllocator = CrtAllocator, unsigned writeFlags = kWriteDefaultFlags> class Writer { -public: + public: typedef typename SourceEncoding::Ch Ch; static const int kDefaultMaxDecimalPlaces = 324; @@ -112,18 +112,24 @@ class Writer { */ explicit Writer(OutputStream &os, StackAllocator *stackAllocator = 0, size_t levelDepth = kDefaultLevelDepth) - : os_(&os), level_stack_(stackAllocator, levelDepth * sizeof(Level)), - maxDecimalPlaces_(kDefaultMaxDecimalPlaces), hasRoot_(false) {} + : os_(&os), + level_stack_(stackAllocator, levelDepth * sizeof(Level)), + maxDecimalPlaces_(kDefaultMaxDecimalPlaces), + hasRoot_(false) {} explicit Writer(StackAllocator *allocator = 0, size_t levelDepth = kDefaultLevelDepth) - : os_(0), level_stack_(allocator, levelDepth * sizeof(Level)), - maxDecimalPlaces_(kDefaultMaxDecimalPlaces), hasRoot_(false) {} + : os_(0), + level_stack_(allocator, levelDepth * sizeof(Level)), + maxDecimalPlaces_(kDefaultMaxDecimalPlaces), + hasRoot_(false) {} #if RAPIDJSON_HAS_CXX11_RVALUE_REFS Writer(Writer &&rhs) - : os_(rhs.os_), level_stack_(std::move(rhs.level_stack_)), - maxDecimalPlaces_(rhs.maxDecimalPlaces_), hasRoot_(rhs.hasRoot_) { + : os_(rhs.os_), + level_stack_(std::move(rhs.level_stack_)), + maxDecimalPlaces_(rhs.maxDecimalPlaces_), + hasRoot_(rhs.hasRoot_) { rhs.os_ = 0; } #endif @@ -265,11 +271,12 @@ class Writer { bool EndObject(SizeType memberCount = 0) { (void)memberCount; RAPIDJSON_ASSERT(level_stack_.GetSize() >= - sizeof(Level)); // not inside an Object + sizeof(Level)); // not inside an Object RAPIDJSON_ASSERT(!level_stack_.template Top() - ->inArray); // currently inside an Array, not Object - RAPIDJSON_ASSERT(0 == level_stack_.template Top()->valueCount % - 2); // Object has a Key without a Value + ->inArray); // currently inside an Array, not Object + RAPIDJSON_ASSERT(0 == + level_stack_.template Top()->valueCount % + 2); // Object has a Key without a Value level_stack_.template Pop(1); return EndValue(WriteEndObject()); } @@ -320,12 +327,12 @@ class Writer { */ void Flush() { os_->Flush(); } -protected: + protected: //! Information for each nested level struct Level { Level(bool inArray_) : valueCount(0), inArray(inArray_) {} - size_t valueCount; //!< number of values in this level - bool inArray; //!< true if in array, otherwise in object + size_t valueCount; //!< number of values in this level + bool inArray; //!< true if in array, otherwise in object }; static const size_t kDefaultLevelDepth = 32; @@ -395,8 +402,7 @@ class Writer { bool WriteDouble(double d) { if (internal::Double(d).IsNanOrInf()) { - if (!(writeFlags & kWriteNanAndInfFlag)) - return false; + if (!(writeFlags & kWriteNanAndInfFlag)) return false; if (internal::Double(d).IsNan()) { PutReserve(*os_, 3); PutUnsafe(*os_, 'N'); @@ -437,22 +443,22 @@ class Writer { // 0 1 2 3 4 5 6 7 8 9 A B C D E // F 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'b', 't', - 'n', 'u', 'f', 'r', 'u', 'u', // 00 + 'n', 'u', 'f', 'r', 'u', 'u', // 00 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', - 'u', 'u', 'u', 'u', 'u', 'u', // 10 + 'u', 'u', 'u', 'u', 'u', 'u', // 10 0, 0, '"', 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, // 20 - Z16, Z16, // 30~4F + 0, 0, 0, 0, 0, 0, // 20 + Z16, Z16, // 30~4F 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, '\\', 0, 0, 0, // 50 - Z16, Z16, Z16, Z16, Z16, Z16, Z16, Z16, Z16, Z16 // 60~FF + 0, 0, '\\', 0, 0, 0, // 50 + Z16, Z16, Z16, Z16, Z16, Z16, Z16, Z16, Z16, Z16 // 60~FF #undef Z16 }; if (TargetEncoding::supportUnicode) - PutReserve(*os_, 2 + length * 6); // "\uxxxx..." + PutReserve(*os_, 2 + length * 6); // "\uxxxx..." else - PutReserve(*os_, 2 + length * 12); // "\uxxxx\uyyyy..." + PutReserve(*os_, 2 + length * 12); // "\uxxxx\uyyyy..." PutUnsafe(*os_, '\"'); GenericStringStream is(str); @@ -554,27 +560,27 @@ class Writer { void Prefix(Type type) { (void)type; if (RAPIDJSON_LIKELY(level_stack_.GetSize() != - 0)) { // this value is not at root + 0)) { // this value is not at root Level *level = level_stack_.template Top(); if (level->valueCount > 0) { if (level->inArray) - os_->Put(','); // add comma if it is not the first element in array - else // in object + os_->Put(','); // add comma if it is not the first element in array + else // in object os_->Put((level->valueCount % 2 == 0) ? ',' : ':'); } if (!level->inArray && level->valueCount % 2 == 0) - RAPIDJSON_ASSERT(type == kStringType); // if it's in object, then even - // number should be a name + RAPIDJSON_ASSERT(type == kStringType); // if it's in object, then even + // number should be a name level->valueCount++; } else { - RAPIDJSON_ASSERT(!hasRoot_); // Should only has one and only one root. + RAPIDJSON_ASSERT(!hasRoot_); // Should only has one and only one root. hasRoot_ = true; } } // Flush the value if it is the top level one. bool EndValue(bool ret) { - if (RAPIDJSON_UNLIKELY(level_stack_.Empty())) // end of json text + if (RAPIDJSON_UNLIKELY(level_stack_.Empty())) // end of json text Flush(); return ret; } @@ -584,7 +590,7 @@ class Writer { int maxDecimalPlaces_; bool hasRoot_; -private: + private: // Prohibit copy constructor & assignment operator. Writer(const Writer &); Writer &operator=(const Writer &); @@ -592,40 +598,44 @@ class Writer { // Full specialization for StringStream to prevent memory copying -template <> inline bool Writer::WriteInt(int i) { +template <> +inline bool Writer::WriteInt(int i) { char *buffer = os_->Push(11); const char *end = internal::i32toa(i, buffer); os_->Pop(static_cast(11 - (end - buffer))); return true; } -template <> inline bool Writer::WriteUint(unsigned u) { +template <> +inline bool Writer::WriteUint(unsigned u) { char *buffer = os_->Push(10); const char *end = internal::u32toa(u, buffer); os_->Pop(static_cast(10 - (end - buffer))); return true; } -template <> inline bool Writer::WriteInt64(int64_t i64) { +template <> +inline bool Writer::WriteInt64(int64_t i64) { char *buffer = os_->Push(21); const char *end = internal::i64toa(i64, buffer); os_->Pop(static_cast(21 - (end - buffer))); return true; } -template <> inline bool Writer::WriteUint64(uint64_t u) { +template <> +inline bool Writer::WriteUint64(uint64_t u) { char *buffer = os_->Push(20); const char *end = internal::u64toa(u, buffer); os_->Pop(static_cast(20 - (end - buffer))); return true; } -template <> inline bool Writer::WriteDouble(double d) { +template <> +inline bool Writer::WriteDouble(double d) { if (internal::Double(d).IsNanOrInf()) { // Note: This code path can only be reached if // (RAPIDJSON_WRITE_DEFAULT_FLAGS & kWriteNanAndInfFlag). - if (!(kWriteDefaultFlags & kWriteNanAndInfFlag)) - return false; + if (!(kWriteDefaultFlags & kWriteNanAndInfFlag)) return false; if (internal::Double(d).IsNan()) { PutReserve(*os_, 3); PutUnsafe(*os_, 'N'); @@ -659,11 +669,9 @@ template <> inline bool Writer::WriteDouble(double d) { template <> inline bool Writer::ScanWriteUnescapedString(StringStream &is, size_t length) { - if (length < 16) - return RAPIDJSON_LIKELY(is.Tell() < length); + if (length < 16) return RAPIDJSON_LIKELY(is.Tell() < length); - if (!RAPIDJSON_LIKELY(is.Tell() < length)) - return false; + if (!RAPIDJSON_LIKELY(is.Tell() < length)) return false; const char *p = is.src_; const char *end = is.head_ + length; @@ -671,8 +679,7 @@ inline bool Writer::ScanWriteUnescapedString(StringStream &is, (reinterpret_cast(p) + 15) & static_cast(~15)); const char *endAligned = reinterpret_cast( reinterpret_cast(end) & static_cast(~15)); - if (nextAligned > end) - return true; + if (nextAligned > end) return true; while (p != nextAligned) if (*p < 0x20 || *p == '\"' || *p == '\\') { @@ -703,12 +710,12 @@ inline bool Writer::ScanWriteUnescapedString(StringStream &is, const __m128i t1 = _mm_cmpeq_epi8(s, dq); const __m128i t2 = _mm_cmpeq_epi8(s, bs); const __m128i t3 = _mm_cmpeq_epi8(_mm_max_epu8(s, sp), - sp); // s < 0x20 <=> max(s, 0x1F) == 0x1F + sp); // s < 0x20 <=> max(s, 0x1F) == 0x1F const __m128i x = _mm_or_si128(_mm_or_si128(t1, t2), t3); unsigned short r = static_cast(_mm_movemask_epi8(x)); - if (RAPIDJSON_UNLIKELY(r != 0)) { // some of characters is escaped + if (RAPIDJSON_UNLIKELY(r != 0)) { // some of characters is escaped SizeType len; -#ifdef _MSC_VER // Find the index of first escaped +#ifdef _MSC_VER // Find the index of first escaped unsigned long offset; _BitScanForward(&offset, r); len = offset; @@ -716,8 +723,7 @@ inline bool Writer::ScanWriteUnescapedString(StringStream &is, len = static_cast(__builtin_ffs(r) - 1); #endif char *q = reinterpret_cast(os_->PushUnsafe(len)); - for (size_t i = 0; i < len; i++) - q[i] = p[i]; + for (size_t i = 0; i < len; i++) q[i] = p[i]; p += len; break; @@ -732,11 +738,9 @@ inline bool Writer::ScanWriteUnescapedString(StringStream &is, template <> inline bool Writer::ScanWriteUnescapedString(StringStream &is, size_t length) { - if (length < 16) - return RAPIDJSON_LIKELY(is.Tell() < length); + if (length < 16) return RAPIDJSON_LIKELY(is.Tell() < length); - if (!RAPIDJSON_LIKELY(is.Tell() < length)) - return false; + if (!RAPIDJSON_LIKELY(is.Tell() < length)) return false; const char *p = is.src_; const char *end = is.head_ + length; @@ -744,8 +748,7 @@ inline bool Writer::ScanWriteUnescapedString(StringStream &is, (reinterpret_cast(p) + 15) & static_cast(~15)); const char *endAligned = reinterpret_cast( reinterpret_cast(end) & static_cast(~15)); - if (nextAligned > end) - return true; + if (nextAligned > end) return true; while (p != nextAligned) if (*p < 0x20 || *p == '\"' || *p == '\\') { @@ -767,9 +770,9 @@ inline bool Writer::ScanWriteUnescapedString(StringStream &is, x = vorrq_u8(x, vceqq_u8(s, s2)); x = vorrq_u8(x, vcltq_u8(s, s3)); - x = vrev64q_u8(x); // Rev in 64 - uint64_t low = vgetq_lane_u64(vreinterpretq_u64_u8(x), 0); // extract - uint64_t high = vgetq_lane_u64(vreinterpretq_u64_u8(x), 1); // extract + x = vrev64q_u8(x); // Rev in 64 + uint64_t low = vgetq_lane_u64(vreinterpretq_u64_u8(x), 0); // extract + uint64_t high = vgetq_lane_u64(vreinterpretq_u64_u8(x), 1); // extract SizeType len = 0; bool escaped = false; @@ -784,10 +787,9 @@ inline bool Writer::ScanWriteUnescapedString(StringStream &is, len = lz >> 3; escaped = true; } - if (RAPIDJSON_UNLIKELY(escaped)) { // some of characters is escaped + if (RAPIDJSON_UNLIKELY(escaped)) { // some of characters is escaped char *q = reinterpret_cast(os_->PushUnsafe(len)); - for (size_t i = 0; i < len; i++) - q[i] = p[i]; + for (size_t i = 0; i < len; i++) q[i] = p[i]; p += len; break; @@ -798,7 +800,7 @@ inline bool Writer::ScanWriteUnescapedString(StringStream &is, is.src_ = p; return RAPIDJSON_LIKELY(is.Tell() < length); } -#endif // RAPIDJSON_NEON +#endif // RAPIDJSON_NEON RAPIDJSON_NAMESPACE_END @@ -806,4 +808,4 @@ RAPIDJSON_NAMESPACE_END RAPIDJSON_DIAG_POP #endif -#endif // RAPIDJSON_RAPIDJSON_H_ +#endif // RAPIDJSON_RAPIDJSON_H_ diff --git a/livox_ros_driver/common/rapidxml/rapidxml.hpp b/livox_ros_driver/common/rapidxml/rapidxml.hpp index 54e43fb..8ca8e37 100644 --- a/livox_ros_driver/common/rapidxml/rapidxml.hpp +++ b/livox_ros_driver/common/rapidxml/rapidxml.hpp @@ -9,9 +9,9 @@ // If standard library is disabled, user must provide implementations of // required functions and typedefs #if !defined(RAPIDXML_NO_STDLIB) -#include // For assert -#include // For std::size_t -#include // For placement new +#include // For assert +#include // For std::size_t +#include // For placement new #endif // On MSVC, disable "conditional expression is constant" warning (level 4). @@ -19,7 +19,7 @@ // code #ifdef _MSC_VER #pragma warning(push) -#pragma warning(disable : 4127) // Conditional expression is constant +#pragma warning(disable : 4127) // Conditional expression is constant #endif /////////////////////////////////////////////////////////////////////////// @@ -27,10 +27,10 @@ #if defined(RAPIDXML_NO_EXCEPTIONS) -#define RAPIDXML_PARSE_ERROR(what, where) \ - { \ - parse_error_handler(what, where); \ - assert(0); \ +#define RAPIDXML_PARSE_ERROR(what, where) \ + { \ + parse_error_handler(what, where); \ + assert(0); \ } namespace rapidxml { @@ -51,11 +51,11 @@ namespace rapidxml { //! \param what Human readable description of the error. //! \param where Pointer to character data where error was detected. void parse_error_handler(const char *what, void *where); -} // namespace rapidxml +} // namespace rapidxml #else -#include // For std::exception +#include // For std::exception #define RAPIDXML_PARSE_ERROR(what, where) throw parse_error(what, where) @@ -73,8 +73,7 @@ namespace rapidxml { //!

//! This class derives from std::exception class. class parse_error : public std::exception { - -public: + public: //! Constructs parse error parse_error(const char *what, void *where) : m_what(what), m_where(where) {} @@ -86,15 +85,16 @@ class parse_error : public std::exception { //! Ch should be the same as char type of xml_document that produced the //! error. \return Pointer to location within the parsed string where error //! occured. - template Ch *where() const { + template + Ch *where() const { return reinterpret_cast(m_where); } -private: + private: const char *m_what; void *m_where; }; -} // namespace rapidxml +} // namespace rapidxml #endif @@ -102,7 +102,7 @@ class parse_error : public std::exception { // Pool sizes #ifndef RAPIDXML_STATIC_POOL_SIZE - // Size of static memory block of memory_pool. +// Size of static memory block of memory_pool. // Define RAPIDXML_STATIC_POOL_SIZE before including rapidxml.hpp if you want to // override the default value. No dynamic memory allocations are performed by // memory_pool until static memory is exhausted. @@ -110,7 +110,7 @@ class parse_error : public std::exception { #endif #ifndef RAPIDXML_DYNAMIC_POOL_SIZE - // Size of dynamic memory block of memory_pool. +// Size of dynamic memory block of memory_pool. // Define RAPIDXML_DYNAMIC_POOL_SIZE before including rapidxml.hpp if you want // to override the default value. After the static block is exhausted, dynamic // blocks with approximately this size are allocated by memory_pool. @@ -118,7 +118,7 @@ class parse_error : public std::exception { #endif #ifndef RAPIDXML_ALIGNMENT - // Memory allocation alignment. +// Memory allocation alignment. // Define RAPIDXML_ALIGNMENT before including rapidxml.hpp if you want to // override the default value, which is the size of pointer. All memory // allocations for nodes, attributes and strings will be aligned to this value. @@ -129,24 +129,30 @@ class parse_error : public std::exception { namespace rapidxml { // Forward declarations -template class xml_node; -template class xml_attribute; -template class xml_document; +template +class xml_node; +template +class xml_attribute; +template +class xml_document; //! Enumeration listing all node types produced by the parser. //! Use xml_node::type() function to query node type. enum node_type { - node_document, //!< A document node. Name and value are empty. - node_element, //!< An element node. Name contains element name. Value contains - //!< text of first data node. - node_data, //!< A data node. Name is empty. Value contains data text. - node_cdata, //!< A CDATA node. Name is empty. Value contains data text. - node_comment, //!< A comment node. Name is empty. Value contains comment text. - node_declaration, //!< A declaration node. Name and value are empty. - //!< Declaration parameters (version, encoding and - //!< standalone) are in node attributes. - node_doctype, //!< A DOCTYPE node. Name is empty. Value contains DOCTYPE text. - node_pi //!< A PI node. Name contains target. Value contains instructions. + node_document, //!< A document node. Name and value are empty. + node_element, //!< An element node. Name contains element name. Value + //!contains + //!< text of first data node. + node_data, //!< A data node. Name is empty. Value contains data text. + node_cdata, //!< A CDATA node. Name is empty. Value contains data text. + node_comment, //!< A comment node. Name is empty. Value contains comment + //!text. + node_declaration, //!< A declaration node. Name and value are empty. + //!< Declaration parameters (version, encoding and + //!< standalone) are in node attributes. + node_doctype, //!< A DOCTYPE node. Name is empty. Value contains DOCTYPE + //!text. + node_pi //!< A PI node. Name contains target. Value contains instructions. }; /////////////////////////////////////////////////////////////////////// @@ -280,33 +286,35 @@ namespace internal { // Struct that contains lookup tables for the parser // It must be a template to allow correct linking (because it has static data // members, which are defined in a header file). -template struct lookup_tables { - static const unsigned char lookup_whitespace[256]; // Whitespace table - static const unsigned char lookup_node_name[256]; // Node name table - static const unsigned char lookup_text[256]; // Text table - static const unsigned char lookup_text_pure_no_ws[256]; // Text table - static const unsigned char lookup_text_pure_with_ws[256]; // Text table - static const unsigned char lookup_attribute_name[256]; // Attribute name table +template +struct lookup_tables { + static const unsigned char lookup_whitespace[256]; // Whitespace table + static const unsigned char lookup_node_name[256]; // Node name table + static const unsigned char lookup_text[256]; // Text table + static const unsigned char lookup_text_pure_no_ws[256]; // Text table + static const unsigned char lookup_text_pure_with_ws[256]; // Text table + static const unsigned char + lookup_attribute_name[256]; // Attribute name table static const unsigned char - lookup_attribute_data_1[256]; // Attribute data table with single quote + lookup_attribute_data_1[256]; // Attribute data table with single quote static const unsigned char - lookup_attribute_data_1_pure[256]; // Attribute data table with single - // quote + lookup_attribute_data_1_pure[256]; // Attribute data table with single + // quote static const unsigned char - lookup_attribute_data_2[256]; // Attribute data table with double quotes + lookup_attribute_data_2[256]; // Attribute data table with double quotes static const unsigned char - lookup_attribute_data_2_pure[256]; // Attribute data table with double - // quotes - static const unsigned char lookup_digits[256]; // Digits + lookup_attribute_data_2_pure[256]; // Attribute data table with double + // quotes + static const unsigned char lookup_digits[256]; // Digits static const unsigned char - lookup_upcase[256]; // To uppercase conversion table for ASCII characters + lookup_upcase[256]; // To uppercase conversion table for ASCII characters }; // Find length of the string -template inline std::size_t measure(const Ch *p) { +template +inline std::size_t measure(const Ch *p) { const Ch *tmp = p; - while (*tmp) - ++tmp; + while (*tmp) ++tmp; return tmp - p; } @@ -314,12 +322,10 @@ template inline std::size_t measure(const Ch *p) { template inline bool compare(const Ch *p1, std::size_t size1, const Ch *p2, std::size_t size2, bool case_sensitive) { - if (size1 != size2) - return false; + if (size1 != size2) return false; if (case_sensitive) { for (const Ch *end = p1 + size1; p1 < end; ++p1, ++p2) - if (*p1 != *p2) - return false; + if (*p1 != *p2) return false; } else { for (const Ch *end = p1 + size1; p1 < end; ++p1, ++p2) if (lookup_tables<0>::lookup_upcase[static_cast(*p1)] != @@ -328,7 +334,7 @@ inline bool compare(const Ch *p1, std::size_t size1, const Ch *p2, } return true; } -} // namespace internal +} // namespace internal //! \endcond /////////////////////////////////////////////////////////////////////// @@ -370,14 +376,14 @@ inline bool compare(const Ch *p1, std::size_t size1, const Ch *p2, //! to obtain best wasted memory to performance compromise. //! To do it, define their values before rapidxml.hpp file is included. //! \param Ch Character type of created nodes. -template class memory_pool { - -public: +template +class memory_pool { + public: //! \cond internal typedef void *(alloc_func)( - std::size_t); // Type of user-defined function used to allocate memory + std::size_t); // Type of user-defined function used to allocate memory typedef void(free_func)( - void *); // Type of user-defined function used to free memory + void *); // Type of user-defined function used to free memory //! \endcond //! Constructs empty pool with default allocator functions. @@ -461,13 +467,12 @@ template class memory_pool { //! be specified and null terminated. \return Pointer to allocated char array. //! This pointer will never be NULL. Ch *allocate_string(const Ch *source = 0, std::size_t size = 0) { - assert(source || size); // Either source or size (or both) must be specified - if (size == 0) - size = internal::measure(source) + 1; + assert(source || + size); // Either source or size (or both) must be specified + if (size == 0) size = internal::measure(source) + 1; Ch *result = static_cast(allocate_aligned(size * sizeof(Ch))); if (source) - for (std::size_t i = 0; i < size; ++i) - result[i] = source[i]; + for (std::size_t i = 0; i < size; ++i) result[i] = source[i]; return result; } @@ -537,12 +542,12 @@ template class memory_pool { //! \param ff Free function, or 0 to restore default function void set_allocator(alloc_func *af, free_func *ff) { assert(m_begin == m_static_memory && - m_ptr == align(m_begin)); // Verify that no memory is allocated yet + m_ptr == align(m_begin)); // Verify that no memory is allocated yet m_alloc_func = af; m_free_func = ff; } -private: + private: struct header { char *previous_begin; }; @@ -563,17 +568,17 @@ template class memory_pool { char *allocate_raw(std::size_t size) { // Allocate void *memory; - if (m_alloc_func) // Allocate memory using either user-specified allocation - // function or global operator new[] + if (m_alloc_func) // Allocate memory using either user-specified allocation + // function or global operator new[] { memory = m_alloc_func(size); - assert(memory); // Allocator is not allowed to return 0, on failure it - // must either throw, stop the program or use longjmp + assert(memory); // Allocator is not allowed to return 0, on failure it + // must either throw, stop the program or use longjmp } else { memory = new char[size]; #ifdef RAPIDXML_NO_EXCEPTIONS - if (!memory) // If exceptions are disabled, verify memory allocation, - // because new will not be able to throw bad_alloc + if (!memory) // If exceptions are disabled, verify memory allocation, + // because new will not be able to throw bad_alloc RAPIDXML_PARSE_ERROR("out of memory", 0); #endif } @@ -589,14 +594,13 @@ template class memory_pool { // Calculate required pool size (may be bigger than // RAPIDXML_DYNAMIC_POOL_SIZE) std::size_t pool_size = RAPIDXML_DYNAMIC_POOL_SIZE; - if (pool_size < size) - pool_size = size; + if (pool_size < size) pool_size = size; // Allocate - std::size_t alloc_size = - sizeof(header) + (2 * RAPIDXML_ALIGNMENT - 2) + - pool_size; // 2 alignments required in worst case: one for header, one - // for actual allocation + std::size_t alloc_size = sizeof(header) + (2 * RAPIDXML_ALIGNMENT - 2) + + pool_size; // 2 alignments required in worst + // case: one for header, one + // for actual allocation char *raw_memory = allocate_raw(alloc_size); // Setup new pool in allocated memory @@ -616,12 +620,13 @@ template class memory_pool { return result; } - char *m_begin; // Start of raw memory making up current pool - char *m_ptr; // First free byte in current pool - char *m_end; // One past last available byte in current pool - char m_static_memory[RAPIDXML_STATIC_POOL_SIZE]; // Static raw memory - alloc_func *m_alloc_func; // Allocator function, or 0 if default is to be used - free_func *m_free_func; // Free function, or 0 if default is to be used + char *m_begin; // Start of raw memory making up current pool + char *m_ptr; // First free byte in current pool + char *m_end; // One past last available byte in current pool + char m_static_memory[RAPIDXML_STATIC_POOL_SIZE]; // Static raw memory + alloc_func + *m_alloc_func; // Allocator function, or 0 if default is to be used + free_func *m_free_func; // Free function, or 0 if default is to be used }; /////////////////////////////////////////////////////////////////////////// @@ -630,9 +635,9 @@ template class memory_pool { //! Base class for xml_node and xml_attribute implementing common functions: //! name(), name_size(), value(), value_size() and parent(). //! \param Ch Character type to use -template class xml_base { - -public: +template +class xml_base { + public: /////////////////////////////////////////////////////////////////////////// // Construction & destruction @@ -732,18 +737,18 @@ template class xml_base { //! \return Pointer to parent node, or 0 if there is no parent. xml_node *parent() const { return m_parent; } -protected: + protected: // Return empty string static Ch *nullstr() { static Ch zero = Ch('\0'); return &zero; } - Ch *m_name; // Name of node, or 0 if no name - Ch *m_value; // Value of node, or 0 if no value - std::size_t m_name_size; // Length of node name, or undefined of no name - std::size_t m_value_size; // Length of node value, or undefined if no value - xml_node *m_parent; // Pointer to parent node, or 0 if none + Ch *m_name; // Name of node, or 0 if no name + Ch *m_value; // Value of node, or 0 if no value + std::size_t m_name_size; // Length of node name, or undefined of no name + std::size_t m_value_size; // Length of node value, or undefined if no value + xml_node *m_parent; // Pointer to parent node, or 0 if none }; //! Class representing attribute node of XML document. @@ -752,11 +757,11 @@ template class xml_base { //! parse, both name and value of attribute will point to interior of source //! text used for parsing. Thus, this text must persist in memory for the //! lifetime of attribute. \param Ch Character type to use. -template class xml_attribute : public xml_base { - +template +class xml_attribute : public xml_base { friend class xml_node; -public: + public: /////////////////////////////////////////////////////////////////////////// // Construction & destruction @@ -773,8 +778,7 @@ template class xml_attribute : public xml_base { //! no parent document. xml_document *document() const { if (xml_node *node = this->parent()) { - while (node->parent()) - node = node->parent(); + while (node->parent()) node = node->parent(); return node->type() == node_document ? static_cast *>(node) : 0; @@ -794,8 +798,7 @@ template class xml_attribute : public xml_base { std::size_t name_size = 0, bool case_sensitive = true) const { if (name) { - if (name_size == 0) - name_size = internal::measure(name); + if (name_size == 0) name_size = internal::measure(name); for (xml_attribute *attribute = m_prev_attribute; attribute; attribute = attribute->m_prev_attribute) if (internal::compare(attribute->name(), attribute->name_size(), name, @@ -818,8 +821,7 @@ template class xml_attribute : public xml_base { std::size_t name_size = 0, bool case_sensitive = true) const { if (name) { - if (name_size == 0) - name_size = internal::measure(name); + if (name_size == 0) name_size = internal::measure(name); for (xml_attribute *attribute = m_next_attribute; attribute; attribute = attribute->m_next_attribute) if (internal::compare(attribute->name(), attribute->name_size(), name, @@ -830,13 +832,13 @@ template class xml_attribute : public xml_base { return this->m_parent ? m_next_attribute : 0; } -private: + private: xml_attribute - *m_prev_attribute; // Pointer to previous sibling of attribute, or 0 if - // none; only valid if parent is non-zero + *m_prev_attribute; // Pointer to previous sibling of attribute, or 0 if + // none; only valid if parent is non-zero xml_attribute - *m_next_attribute; // Pointer to next sibling of attribute, or 0 if none; - // only valid if parent is non-zero + *m_next_attribute; // Pointer to next sibling of attribute, or 0 if none; + // only valid if parent is non-zero }; /////////////////////////////////////////////////////////////////////////// @@ -850,9 +852,9 @@ template class xml_attribute : public xml_base { //! any, will point interior of source text used for parsing. Thus, this text //! must persist in the memory for the lifetime of node. \param Ch Character //! type to use. -template class xml_node : public xml_base { - -public: +template +class xml_node : public xml_base { + public: /////////////////////////////////////////////////////////////////////////// // Construction & destruction @@ -877,8 +879,7 @@ template class xml_node : public xml_base { //! parent document. xml_document *document() const { xml_node *node = const_cast *>(this); - while (node->parent()) - node = node->parent(); + while (node->parent()) node = node->parent(); return node->type() == node_document ? static_cast *>(node) : 0; } @@ -894,8 +895,7 @@ template class xml_node : public xml_base { xml_node *first_node(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const { if (name) { - if (name_size == 0) - name_size = internal::measure(name); + if (name_size == 0) name_size = internal::measure(name); for (xml_node *child = m_first_node; child; child = child->next_sibling()) if (internal::compare(child->name(), child->name_size(), name, @@ -918,10 +918,10 @@ template class xml_node : public xml_base { //! found. xml_node *last_node(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const { - assert(m_first_node); // Cannot query for last child if node has no children + assert( + m_first_node); // Cannot query for last child if node has no children if (name) { - if (name_size == 0) - name_size = internal::measure(name); + if (name_size == 0) name_size = internal::measure(name); for (xml_node *child = m_last_node; child; child = child->previous_sibling()) if (internal::compare(child->name(), child->name_size(), name, @@ -944,10 +944,9 @@ template class xml_node : public xml_base { //! or 0 if not found. xml_node *previous_sibling(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const { - assert(this->m_parent); // Cannot query for siblings if node has no parent + assert(this->m_parent); // Cannot query for siblings if node has no parent if (name) { - if (name_size == 0) - name_size = internal::measure(name); + if (name_size == 0) name_size = internal::measure(name); for (xml_node *sibling = m_prev_sibling; sibling; sibling = sibling->m_prev_sibling) if (internal::compare(sibling->name(), sibling->name_size(), name, @@ -970,10 +969,9 @@ template class xml_node : public xml_base { //! or 0 if not found. xml_node *next_sibling(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const { - assert(this->m_parent); // Cannot query for siblings if node has no parent + assert(this->m_parent); // Cannot query for siblings if node has no parent if (name) { - if (name_size == 0) - name_size = internal::measure(name); + if (name_size == 0) name_size = internal::measure(name); for (xml_node *sibling = m_next_sibling; sibling; sibling = sibling->m_next_sibling) if (internal::compare(sibling->name(), sibling->name_size(), name, @@ -996,8 +994,7 @@ template class xml_node : public xml_base { std::size_t name_size = 0, bool case_sensitive = true) const { if (name) { - if (name_size == 0) - name_size = internal::measure(name); + if (name_size == 0) name_size = internal::measure(name); for (xml_attribute *attribute = m_first_attribute; attribute; attribute = attribute->m_next_attribute) if (internal::compare(attribute->name(), attribute->name_size(), name, @@ -1020,8 +1017,7 @@ template class xml_node : public xml_base { std::size_t name_size = 0, bool case_sensitive = true) const { if (name) { - if (name_size == 0) - name_size = internal::measure(name); + if (name_size == 0) name_size = internal::measure(name); for (xml_attribute *attribute = m_last_attribute; attribute; attribute = attribute->m_prev_attribute) if (internal::compare(attribute->name(), attribute->name_size(), name, @@ -1251,7 +1247,7 @@ template class xml_node : public xml_base { m_first_attribute = 0; } -private: + private: /////////////////////////////////////////////////////////////////////////// // Restrictions @@ -1274,22 +1270,22 @@ template class xml_node : public xml_base { // 3. prev_sibling and next_sibling are valid only if node has a parent, // otherwise they contain garbage - node_type m_type; // Type of node; always valid + node_type m_type; // Type of node; always valid xml_node - *m_first_node; // Pointer to first child node, or 0 if none; always valid - xml_node *m_last_node; // Pointer to last child node, or 0 if none; this - // value is only valid if m_first_node is non-zero - xml_attribute *m_first_attribute; // Pointer to first attribute of node, - // or 0 if none; always valid - xml_attribute * - m_last_attribute; // Pointer to last attribute of node, or 0 if none; this - // value is only valid if m_first_attribute is non-zero + *m_first_node; // Pointer to first child node, or 0 if none; always valid + xml_node *m_last_node; // Pointer to last child node, or 0 if none; this + // value is only valid if m_first_node is non-zero + xml_attribute *m_first_attribute; // Pointer to first attribute of node, + // or 0 if none; always valid + xml_attribute *m_last_attribute; // Pointer to last attribute of node, or + // 0 if none; this + // value is only valid if m_first_attribute is non-zero xml_node - *m_prev_sibling; // Pointer to previous sibling of node, or 0 if none; - // this value is only valid if m_parent is non-zero + *m_prev_sibling; // Pointer to previous sibling of node, or 0 if none; + // this value is only valid if m_parent is non-zero xml_node - *m_next_sibling; // Pointer to next sibling of node, or 0 if none; this - // value is only valid if m_parent is non-zero + *m_next_sibling; // Pointer to next sibling of node, or 0 if none; this + // value is only valid if m_parent is non-zero }; /////////////////////////////////////////////////////////////////////////// @@ -1304,8 +1300,7 @@ template class xml_node : public xml_base { //! xml_node. \param Ch Character type to use. template class xml_document : public xml_node, public memory_pool { - -public: + public: //! Constructs empty XML document xml_document() : xml_node(node_document) {} @@ -1320,7 +1315,8 @@ class xml_document : public xml_node, public memory_pool { //! nodes and attributes (if any), but does not clear memory pool. \param text //! XML data to parse; pointer is non-const to denote fact that this data may //! be modified by the parser. - template void parse(Ch *text) { + template + void parse(Ch *text) { assert(text); // Remove current contents @@ -1334,12 +1330,11 @@ class xml_document : public xml_node, public memory_pool { while (1) { // Skip whitespace before node skip(text); - if (*text == 0) - break; + if (*text == 0) break; // Parse and append new child if (*text == Ch('<')) { - ++text; // Skip '<' + ++text; // Skip '<' if (xml_node *node = parse_node(text)) this->append_node(node); } else @@ -1355,7 +1350,7 @@ class xml_document : public xml_node, public memory_pool { memory_pool::clear(); } -private: + private: /////////////////////////////////////////////////////////////////////// // Internal character utility functions @@ -1408,7 +1403,8 @@ class xml_document : public xml_node, public memory_pool { }; // Detect attribute value character - template struct attribute_value_pred { + template + struct attribute_value_pred { static unsigned char test(Ch ch) { if (Quote == Ch('\'')) return internal::lookup_tables< @@ -1416,12 +1412,13 @@ class xml_document : public xml_node, public memory_pool { if (Quote == Ch('\"')) return internal::lookup_tables< 0>::lookup_attribute_data_2[static_cast(ch)]; - return 0; // Should never be executed, to avoid warnings on Comeau + return 0; // Should never be executed, to avoid warnings on Comeau } }; // Detect attribute value character - template struct attribute_value_pure_pred { + template + struct attribute_value_pure_pred { static unsigned char test(Ch ch) { if (Quote == Ch('\'')) return internal::lookup_tables< @@ -1429,7 +1426,7 @@ class xml_document : public xml_node, public memory_pool { if (Quote == Ch('\"')) return internal::lookup_tables< 0>::lookup_attribute_data_2_pure[static_cast(ch)]; - return 0; // Should never be executed, to avoid warnings on Comeau + return 0; // Should never be executed, to avoid warnings on Comeau } }; @@ -1444,17 +1441,17 @@ class xml_document : public xml_node, public memory_pool { text += 1; } else { // Insert UTF8 sequence - if (code < 0x80) // 1 byte sequence + if (code < 0x80) // 1 byte sequence { text[0] = static_cast(code); text += 1; - } else if (code < 0x800) // 2 byte sequence + } else if (code < 0x800) // 2 byte sequence { text[1] = static_cast((code | 0x80) & 0xBF); code >>= 6; text[0] = static_cast(code | 0xC0); text += 2; - } else if (code < 0x10000) // 3 byte sequence + } else if (code < 0x10000) // 3 byte sequence { text[2] = static_cast((code | 0x80) & 0xBF); code >>= 6; @@ -1462,7 +1459,7 @@ class xml_document : public xml_node, public memory_pool { code >>= 6; text[0] = static_cast(code | 0xE0); text += 3; - } else if (code < 0x110000) // 4 byte sequence + } else if (code < 0x110000) // 4 byte sequence { text[3] = static_cast((code | 0x80) & 0xBF); code >>= 6; @@ -1472,7 +1469,7 @@ class xml_document : public xml_node, public memory_pool { code >>= 6; text[0] = static_cast(code | 0xF0); text += 4; - } else // Invalid, only codes up to 0x10FFFF are allowed in Unicode + } else // Invalid, only codes up to 0x10FFFF are allowed in Unicode { RAPIDXML_PARSE_ERROR("invalid numeric character entity", text); } @@ -1480,10 +1477,10 @@ class xml_document : public xml_node, public memory_pool { } // Skip characters until predicate evaluates to true - template static void skip(Ch *&text) { + template + static void skip(Ch *&text) { Ch *tmp = text; - while (StopPred::test(*tmp)) - ++tmp; + while (StopPred::test(*tmp)) ++tmp; text = tmp; } @@ -1515,94 +1512,91 @@ class xml_document : public xml_node, public memory_pool { // Test if replacement is needed if (src[0] == Ch('&')) { switch (src[1]) { - - // & ' - case Ch('a'): - if (src[2] == Ch('m') && src[3] == Ch('p') && src[4] == Ch(';')) { - *dest = Ch('&'); - ++dest; - src += 5; - continue; - } - if (src[2] == Ch('p') && src[3] == Ch('o') && src[4] == Ch('s') && - src[5] == Ch(';')) { - *dest = Ch('\''); - ++dest; - src += 6; - continue; - } - break; - - // " - case Ch('q'): - if (src[2] == Ch('u') && src[3] == Ch('o') && src[4] == Ch('t') && - src[5] == Ch(';')) { - *dest = Ch('"'); - ++dest; - src += 6; - continue; - } - break; - - // > - case Ch('g'): - if (src[2] == Ch('t') && src[3] == Ch(';')) { - *dest = Ch('>'); - ++dest; - src += 4; - continue; - } - break; - - // < - case Ch('l'): - if (src[2] == Ch('t') && src[3] == Ch(';')) { - *dest = Ch('<'); - ++dest; - src += 4; - continue; - } - break; - - // &#...; - assumes ASCII - case Ch('#'): - if (src[2] == Ch('x')) { - unsigned long code = 0; - src += 3; // Skip &#x - while (1) { - unsigned char digit = internal::lookup_tables< - 0>::lookup_digits[static_cast(*src)]; - if (digit == 0xFF) - break; - code = code * 16 + digit; - ++src; + // & ' + case Ch('a'): + if (src[2] == Ch('m') && src[3] == Ch('p') && src[4] == Ch(';')) { + *dest = Ch('&'); + ++dest; + src += 5; + continue; } - insert_coded_character(dest, - code); // Put character in output - } else { - unsigned long code = 0; - src += 2; // Skip &# - while (1) { - unsigned char digit = internal::lookup_tables< - 0>::lookup_digits[static_cast(*src)]; - if (digit == 0xFF) - break; - code = code * 10 + digit; - ++src; + if (src[2] == Ch('p') && src[3] == Ch('o') && src[4] == Ch('s') && + src[5] == Ch(';')) { + *dest = Ch('\''); + ++dest; + src += 6; + continue; } - insert_coded_character(dest, - code); // Put character in output - } - if (*src == Ch(';')) - ++src; - else - RAPIDXML_PARSE_ERROR("expected ;", src); - continue; - - // Something else - default: - // Ignore, just copy '&' verbatim - break; + break; + + // " + case Ch('q'): + if (src[2] == Ch('u') && src[3] == Ch('o') && src[4] == Ch('t') && + src[5] == Ch(';')) { + *dest = Ch('"'); + ++dest; + src += 6; + continue; + } + break; + + // > + case Ch('g'): + if (src[2] == Ch('t') && src[3] == Ch(';')) { + *dest = Ch('>'); + ++dest; + src += 4; + continue; + } + break; + + // < + case Ch('l'): + if (src[2] == Ch('t') && src[3] == Ch(';')) { + *dest = Ch('<'); + ++dest; + src += 4; + continue; + } + break; + + // &#...; - assumes ASCII + case Ch('#'): + if (src[2] == Ch('x')) { + unsigned long code = 0; + src += 3; // Skip &#x + while (1) { + unsigned char digit = internal::lookup_tables< + 0>::lookup_digits[static_cast(*src)]; + if (digit == 0xFF) break; + code = code * 16 + digit; + ++src; + } + insert_coded_character(dest, + code); // Put character in output + } else { + unsigned long code = 0; + src += 2; // Skip &# + while (1) { + unsigned char digit = internal::lookup_tables< + 0>::lookup_digits[static_cast(*src)]; + if (digit == 0xFF) break; + code = code * 10 + digit; + ++src; + } + insert_coded_character(dest, + code); // Put character in output + } + if (*src == Ch(';')) + ++src; + else + RAPIDXML_PARSE_ERROR("expected ;", src); + continue; + + // Something else + default: + // Ignore, just copy '&' verbatim + break; } } } @@ -1612,11 +1606,10 @@ class xml_document : public xml_node, public memory_pool { // Test if condensing is needed if (whitespace_pred::test(*src)) { *dest = Ch(' '); - ++dest; // Put single space in dest - ++src; // Skip first whitespace char + ++dest; // Put single space in dest + ++src; // Skip first whitespace char // Skip remaining whitespace chars - while (whitespace_pred::test(*src)) - ++src; + while (whitespace_pred::test(*src)) ++src; continue; } } @@ -1634,26 +1627,27 @@ class xml_document : public xml_node, public memory_pool { // Internal parsing functions // Parse BOM, if any - template void parse_bom(Ch *&text) { + template + void parse_bom(Ch *&text) { // UTF-8? if (static_cast(text[0]) == 0xEF && static_cast(text[1]) == 0xBB && static_cast(text[2]) == 0xBF) { - text += 3; // Skup utf-8 bom + text += 3; // Skup utf-8 bom } } // Parse XML declaration ( xml_node *parse_xml_declaration(Ch *&text) { + template + xml_node *parse_xml_declaration(Ch *&text) { // If parsing of declaration is disabled if (!(Flags & parse_declaration_node)) { // Skip until end of declaration while (text[0] != Ch('?') || text[1] != Ch('>')) { - if (!text[0]) - RAPIDXML_PARSE_ERROR("unexpected end of data", text); + if (!text[0]) RAPIDXML_PARSE_ERROR("unexpected end of data", text); ++text; } - text += 2; // Skip '?>' + text += 2; // Skip '?>' return 0; } @@ -1675,17 +1669,17 @@ class xml_document : public xml_node, public memory_pool { } // Parse XML comment (' - return 0; // Do not produce comment node + text += 3; // Skip '-->' + return 0; // Do not produce comment node } // Remember value start @@ -1693,8 +1687,7 @@ class xml_document : public xml_node, public memory_pool { // Skip until end of comment while (text[0] != Ch('-') || text[1] != Ch('-') || text[2] != Ch('>')) { - if (!text[0]) - RAPIDXML_PARSE_ERROR("unexpected end of data", text); + if (!text[0]) RAPIDXML_PARSE_ERROR("unexpected end of data", text); ++text; } @@ -1703,15 +1696,15 @@ class xml_document : public xml_node, public memory_pool { comment->value(value, text - value); // Place zero terminator after comment value - if (!(Flags & parse_no_string_terminators)) - *text = Ch('\0'); + if (!(Flags & parse_no_string_terminators)) *text = Ch('\0'); - text += 3; // Skip '-->' + text += 3; // Skip '-->' return comment; } // Parse DOCTYPE - template xml_node *parse_doctype(Ch *&text) { + template + xml_node *parse_doctype(Ch *&text) { // Remember value start Ch *value = text; @@ -1719,35 +1712,35 @@ class xml_document : public xml_node, public memory_pool { while (*text != Ch('>')) { // Determine character type switch (*text) { - - // If '[' encountered, scan for matching ending ']' using naive algorithm - // with depth This works for all W3C test files except for 2 most wicked - case Ch('['): { - ++text; // Skip '[' - int depth = 1; - while (depth > 0) { - switch (*text) { - case Ch('['): - ++depth; - break; - case Ch(']'): - --depth; - break; - case 0: - RAPIDXML_PARSE_ERROR("unexpected end of data", text); + // If '[' encountered, scan for matching ending ']' using naive + // algorithm + // with depth This works for all W3C test files except for 2 most wicked + case Ch('['): { + ++text; // Skip '[' + int depth = 1; + while (depth > 0) { + switch (*text) { + case Ch('['): + ++depth; + break; + case Ch(']'): + --depth; + break; + case 0: + RAPIDXML_PARSE_ERROR("unexpected end of data", text); + } + ++text; } - ++text; + break; } - break; - } - // Error on end of text - case Ch('\0'): - RAPIDXML_PARSE_ERROR("unexpected end of data", text); + // Error on end of text + case Ch('\0'): + RAPIDXML_PARSE_ERROR("unexpected end of data", text); - // Other character, skip it - default: - ++text; + // Other character, skip it + default: + ++text; } } @@ -1758,19 +1751,19 @@ class xml_document : public xml_node, public memory_pool { doctype->value(value, text - value); // Place zero terminator after value - if (!(Flags & parse_no_string_terminators)) - *text = Ch('\0'); + if (!(Flags & parse_no_string_terminators)) *text = Ch('\0'); - text += 1; // skip '>' + text += 1; // skip '>' return doctype; } else { - text += 1; // skip '>' + text += 1; // skip '>' return 0; } } // Parse PI - template xml_node *parse_pi(Ch *&text) { + template + xml_node *parse_pi(Ch *&text) { // If creation of PI nodes is enabled if (Flags & parse_pi_nodes) { // Create pi node @@ -1779,8 +1772,7 @@ class xml_document : public xml_node, public memory_pool { // Extract PI target name Ch *name = text; skip(text); - if (text == name) - RAPIDXML_PARSE_ERROR("expected PI target", text); + if (text == name) RAPIDXML_PARSE_ERROR("expected PI target", text); pi->name(name, text - name); // Skip whitespace between pi target and pi @@ -1806,7 +1798,7 @@ class xml_document : public xml_node, public memory_pool { pi->value()[pi->value_size()] = Ch('\0'); } - text += 2; // Skip '?>' + text += 2; // Skip '?>' return pi; } else { // Skip to '?>' @@ -1815,7 +1807,7 @@ class xml_document : public xml_node, public memory_pool { RAPIDXML_PARSE_ERROR("unexpected end of data", text); ++text; } - text += 2; // Skip '?>' + text += 2; // Skip '?>' return 0; } } @@ -1827,8 +1819,7 @@ class xml_document : public xml_node, public memory_pool { template Ch parse_and_append_data(xml_node *node, Ch *&text, Ch *contents_start) { // Backup to contents start if whitespace trimming is disabled - if (!(Flags & parse_trim_whitespace)) - text = contents_start; + if (!(Flags & parse_trim_whitespace)) text = contents_start; // Skip until end of data Ch *value = text, *end; @@ -1845,12 +1836,10 @@ class xml_document : public xml_node, public memory_pool { if (Flags & parse_normalize_whitespace) { // Whitespace is already condensed to single space characters by // skipping function, so just trim 1 char off the end - if (*(end - 1) == Ch(' ')) - --end; + if (*(end - 1) == Ch(' ')) --end; } else { // Backup until non-whitespace character is found - while (whitespace_pred::test(*(end - 1))) - --end; + while (whitespace_pred::test(*(end - 1))) --end; } } @@ -1864,15 +1853,14 @@ class xml_document : public xml_node, public memory_pool { // Add data to parent node if no data exists yet if (!(Flags & parse_no_element_values)) - if (*node->value() == Ch('\0')) - node->value(value, end - value); + if (*node->value() == Ch('\0')) node->value(value, end - value); // Place zero terminator after value if (!(Flags & parse_no_string_terminators)) { Ch ch = *text; *end = Ch('\0'); - return ch; // Return character that ends data; this is required because - // zero terminator overwritten it + return ch; // Return character that ends data; this is required because + // zero terminator overwritten it } // Return character that ends data @@ -1880,24 +1868,23 @@ class xml_document : public xml_node, public memory_pool { } // Parse CDATA - template xml_node *parse_cdata(Ch *&text) { + template + xml_node *parse_cdata(Ch *&text) { // If CDATA is disabled if (Flags & parse_no_data_nodes) { // Skip until end of cdata while (text[0] != Ch(']') || text[1] != Ch(']') || text[2] != Ch('>')) { - if (!text[0]) - RAPIDXML_PARSE_ERROR("unexpected end of data", text); + if (!text[0]) RAPIDXML_PARSE_ERROR("unexpected end of data", text); ++text; } - text += 3; // Skip ]]> - return 0; // Do not produce CDATA node + text += 3; // Skip ]]> + return 0; // Do not produce CDATA node } // Skip until end of cdata Ch *value = text; while (text[0] != Ch(']') || text[1] != Ch(']') || text[2] != Ch('>')) { - if (!text[0]) - RAPIDXML_PARSE_ERROR("unexpected end of data", text); + if (!text[0]) RAPIDXML_PARSE_ERROR("unexpected end of data", text); ++text; } @@ -1906,23 +1893,22 @@ class xml_document : public xml_node, public memory_pool { cdata->value(value, text - value); // Place zero terminator after value - if (!(Flags & parse_no_string_terminators)) - *text = Ch('\0'); + if (!(Flags & parse_no_string_terminators)) *text = Ch('\0'); - text += 3; // Skip ]]> + text += 3; // Skip ]]> return cdata; } // Parse element node - template xml_node *parse_element(Ch *&text) { + template + xml_node *parse_element(Ch *&text) { // Create element node xml_node *element = this->allocate_node(node_element); // Extract element name Ch *name = text; skip(text); - if (text == name) - RAPIDXML_PARSE_ERROR("expected element name", text); + if (text == name) RAPIDXML_PARSE_ERROR("expected element name", text); element->name(name, text - name); // Skip whitespace between element name and attributes or > @@ -1937,8 +1923,7 @@ class xml_document : public xml_node, public memory_pool { parse_node_contents(text, element); } else if (*text == Ch('/')) { ++text; - if (*text != Ch('>')) - RAPIDXML_PARSE_ERROR("expected >", text); + if (*text != Ch('>')) RAPIDXML_PARSE_ERROR("expected >", text); ++text; } else RAPIDXML_PARSE_ERROR("expected >", text); @@ -1952,86 +1937,87 @@ class xml_document : public xml_node, public memory_pool { } // Determine node type, and parse it - template xml_node *parse_node(Ch *&text) { + template + xml_node *parse_node(Ch *&text) { // Parse proper node type switch (text[0]) { + // <... + default: + // Parse and append element node + return parse_element(text); + + // (text); + } else { + // Parse PI + return parse_pi(text); + } - // <... - default: - // Parse and append element node - return parse_element(text); - - // (text); - } else { - // Parse PI - return parse_pi(text); - } - - // (text); + } + break; - // Parse proper subset of (text); + } + break; - // (text); - } - break; - - // (text); - } - break; - - // (text); - } + // (text); + } - } // switch + } // switch - // Attempt to skip other, unrecognized node types starting with ')) { - if (*text == 0) - RAPIDXML_PARSE_ERROR("unexpected end of data", text); - ++text; - } - ++text; // Skip '>' - return 0; // No node recognized + // Attempt to skip other, unrecognized node types starting with ')) { + if (*text == 0) RAPIDXML_PARSE_ERROR("unexpected end of data", text); + ++text; + } + ++text; // Skip '>' + return 0; // No node recognized } } // Parse contents of the node - children, data etc. - template void parse_node_contents(Ch *&text, xml_node *node) { + template + void parse_node_contents(Ch *&text, xml_node *node) { // For all children and text while (1) { // Skip whitespace between > and node contents Ch *contents_start = - text; // Store start of node contents before whitespace is skipped + text; // Store start of node contents before whitespace is skipped skip(text); Ch next_char = *text; @@ -2043,45 +2029,43 @@ class xml_document : public xml_node, public memory_pool { // Determine what comes next: node closing, child node, data node, or 0? switch (next_char) { - - // Node closing or child node - case Ch('<'): - if (text[1] == Ch('/')) { - // Node closing - text += 2; // Skip '(text); - if (!internal::compare(node->name(), node->name_size(), - closing_name, text - closing_name, true)) - RAPIDXML_PARSE_ERROR("invalid closing tag name", text); + // Node closing or child node + case Ch('<'): + if (text[1] == Ch('/')) { + // Node closing + text += 2; // Skip '(text); + if (!internal::compare(node->name(), node->name_size(), + closing_name, text - closing_name, true)) + RAPIDXML_PARSE_ERROR("invalid closing tag name", text); + } else { + // No validation, just skip name + skip(text); + } + // Skip remaining whitespace after node name + skip(text); + if (*text != Ch('>')) RAPIDXML_PARSE_ERROR("expected >", text); + ++text; // Skip '>' + return; // Node closed, finished parsing contents } else { - // No validation, just skip name - skip(text); + // Child node + ++text; // Skip '<' + if (xml_node *child = parse_node(text)) + node->append_node(child); } - // Skip remaining whitespace after node name - skip(text); - if (*text != Ch('>')) - RAPIDXML_PARSE_ERROR("expected >", text); - ++text; // Skip '>' - return; // Node closed, finished parsing contents - } else { - // Child node - ++text; // Skip '<' - if (xml_node *child = parse_node(text)) - node->append_node(child); - } - break; + break; - // End of data - error - case Ch('\0'): - RAPIDXML_PARSE_ERROR("unexpected end of data", text); + // End of data - error + case Ch('\0'): + RAPIDXML_PARSE_ERROR("unexpected end of data", text); - // Data node - default: - next_char = parse_and_append_data(node, text, contents_start); - goto after_data_node; // Bypass regular processing after data nodes + // Data node + default: + next_char = parse_and_append_data(node, text, contents_start); + goto after_data_node; // Bypass regular processing after data nodes } } } @@ -2093,10 +2077,9 @@ class xml_document : public xml_node, public memory_pool { while (attribute_name_pred::test(*text)) { // Extract attribute name Ch *name = text; - ++text; // Skip first character of attribute name + ++text; // Skip first character of attribute name skip(text); - if (text == name) - RAPIDXML_PARSE_ERROR("expected attribute name", name); + if (text == name) RAPIDXML_PARSE_ERROR("expected attribute name", name); // Create new attribute xml_attribute *attribute = this->allocate_attribute(); @@ -2107,8 +2090,7 @@ class xml_document : public xml_node, public memory_pool { skip(text); // Skip = - if (*text != Ch('=')) - RAPIDXML_PARSE_ERROR("expected =", text); + if (*text != Ch('=')) RAPIDXML_PARSE_ERROR("expected =", text); ++text; // Add terminating zero after name @@ -2127,8 +2109,9 @@ class xml_document : public xml_node, public memory_pool { // Extract attribute value and expand char refs in it Ch *value = text, *end; const int AttFlags = - Flags & ~parse_normalize_whitespace; // No whitespace normalization in - // attributes + Flags & + ~parse_normalize_whitespace; // No whitespace normalization in + // attributes if (quote == Ch('\'')) end = skip_and_expand_character_refs, @@ -2143,9 +2126,8 @@ class xml_document : public xml_node, public memory_pool { attribute->value(value, end - value); // Make sure that end quote is present - if (*text != quote) - RAPIDXML_PARSE_ERROR("expected ' or \"", text); - ++text; // Skip quote + if (*text != quote) RAPIDXML_PARSE_ERROR("expected ' or \"", text); + ++text; // Skip quote // Add terminating zero after value if (!(Flags & parse_no_string_terminators)) @@ -2164,66 +2146,66 @@ namespace internal { template const unsigned char lookup_tables::lookup_whitespace[256] = { // 0 1 2 3 4 5 6 7 8 9 A B C D E F - 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, // 0 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 1 - 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 2 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 3 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 4 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 5 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 6 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 7 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 8 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 9 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // A - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // B - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // C - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // D - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // E - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 // F + 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, // 0 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 1 + 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 2 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 3 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 4 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 5 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 6 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 7 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 8 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 9 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // A + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // B + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // C + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // D + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // E + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 // F }; // Node name (anything but space \n \r \t / > ? \0) template const unsigned char lookup_tables::lookup_node_name[256] = { // 0 1 2 3 4 5 6 7 8 9 A B C D E F - 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, // 0 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 - 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, // 2 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, // 3 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F + 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, // 0 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, // 2 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, // 3 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F }; // Text (i.e. PCDATA) (anything but < \0) template const unsigned char lookup_tables::lookup_text[256] = { // 0 1 2 3 4 5 6 7 8 9 A B C D E F - 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 2 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, // 3 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 2 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, // 3 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F }; // Text (i.e. PCDATA) that does not require processing when ws normalization is @@ -2231,22 +2213,22 @@ const unsigned char lookup_tables::lookup_text[256] = { template const unsigned char lookup_tables::lookup_text_pure_no_ws[256] = { // 0 1 2 3 4 5 6 7 8 9 A B C D E F - 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 - 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 2 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, // 3 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 + 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 2 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, // 3 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F }; // Text (i.e. PCDATA) that does not require processing when ws normalizationis @@ -2254,66 +2236,66 @@ const unsigned char lookup_tables::lookup_text_pure_no_ws[256] = { template const unsigned char lookup_tables::lookup_text_pure_with_ws[256] = { // 0 1 2 3 4 5 6 7 8 9 A B C D E F - 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, // 0 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 - 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 2 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, // 3 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F + 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, // 0 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 + 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 2 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, // 3 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F }; // Attribute name (anything but space \n \r \t / < > = ? ! \0) template const unsigned char lookup_tables::lookup_attribute_name[256] = { // 0 1 2 3 4 5 6 7 8 9 A B C D E F - 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, // 0 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 - 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, // 2 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, // 3 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F + 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, // 0 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 + 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, // 2 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, // 3 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F }; // Attribute data with single quote (anything but ' \0) template const unsigned char lookup_tables::lookup_attribute_data_1[256] = { // 0 1 2 3 4 5 6 7 8 9 A B C D E F - 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 - 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, // 2 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 3 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 + 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, // 2 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 3 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F }; // Attribute data with single quote that does not require processing (anything @@ -2321,44 +2303,44 @@ const unsigned char lookup_tables::lookup_attribute_data_1[256] = { template const unsigned char lookup_tables::lookup_attribute_data_1_pure[256] = { // 0 1 2 3 4 5 6 7 8 9 A B C D E F - 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 - 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, // 2 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 3 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 + 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, // 2 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 3 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F }; // Attribute data with double quote (anything but " \0) template const unsigned char lookup_tables::lookup_attribute_data_2[256] = { // 0 1 2 3 4 5 6 7 8 9 A B C D E F - 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 - 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 2 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 3 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 + 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 2 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 3 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F }; // Attribute data with double quote that does not require processing (anything @@ -2366,22 +2348,22 @@ const unsigned char lookup_tables::lookup_attribute_data_2[256] = { template const unsigned char lookup_tables::lookup_attribute_data_2_pure[256] = { // 0 1 2 3 4 5 6 7 8 9 A B C D E F - 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 - 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 2 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 3 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 + 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 2 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 3 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F }; // Digits (dec and hex, 255 denotes end of numeric character reference) @@ -2389,37 +2371,37 @@ template const unsigned char lookup_tables::lookup_digits[256] = { // 0 1 2 3 4 5 6 7 8 9 A B C D E F 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, // 0 + 255, 255, 255, 255, 255, 255, 255, 255, // 0 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, // 1 + 255, 255, 255, 255, 255, 255, 255, 255, // 1 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, // 2 + 255, 255, 255, 255, 255, 255, 255, 255, // 2 0, 1, 2, 3, 4, 5, 6, 7, - 8, 9, 255, 255, 255, 255, 255, 255, // 3 + 8, 9, 255, 255, 255, 255, 255, 255, // 3 255, 10, 11, 12, 13, 14, 15, 255, - 255, 255, 255, 255, 255, 255, 255, 255, // 4 + 255, 255, 255, 255, 255, 255, 255, 255, // 4 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, // 5 + 255, 255, 255, 255, 255, 255, 255, 255, // 5 255, 10, 11, 12, 13, 14, 15, 255, - 255, 255, 255, 255, 255, 255, 255, 255, // 6 + 255, 255, 255, 255, 255, 255, 255, 255, // 6 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, // 7 + 255, 255, 255, 255, 255, 255, 255, 255, // 7 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, // 8 + 255, 255, 255, 255, 255, 255, 255, 255, // 8 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, // 9 + 255, 255, 255, 255, 255, 255, 255, 255, // 9 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, // A + 255, 255, 255, 255, 255, 255, 255, 255, // A 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, // B + 255, 255, 255, 255, 255, 255, 255, 255, // B 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, // C + 255, 255, 255, 255, 255, 255, 255, 255, // C 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, // D + 255, 255, 255, 255, 255, 255, 255, 255, // D 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, // E + 255, 255, 255, 255, 255, 255, 255, 255, // E 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255 // F + 255, 255, 255, 255, 255, 255, 255, 255 // F }; // Upper case conversion @@ -2427,42 +2409,42 @@ template const unsigned char lookup_tables::lookup_upcase[256] = { // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A B C D E F 0, 1, 2, 3, 4, 5, 6, 7, - 8, 9, 10, 11, 12, 13, 14, 15, // 0 + 8, 9, 10, 11, 12, 13, 14, 15, // 0 16, 17, 18, 19, 20, 21, 22, 23, - 24, 25, 26, 27, 28, 29, 30, 31, // 1 + 24, 25, 26, 27, 28, 29, 30, 31, // 1 32, 33, 34, 35, 36, 37, 38, 39, - 40, 41, 42, 43, 44, 45, 46, 47, // 2 + 40, 41, 42, 43, 44, 45, 46, 47, // 2 48, 49, 50, 51, 52, 53, 54, 55, - 56, 57, 58, 59, 60, 61, 62, 63, // 3 + 56, 57, 58, 59, 60, 61, 62, 63, // 3 64, 65, 66, 67, 68, 69, 70, 71, - 72, 73, 74, 75, 76, 77, 78, 79, // 4 + 72, 73, 74, 75, 76, 77, 78, 79, // 4 80, 81, 82, 83, 84, 85, 86, 87, - 88, 89, 90, 91, 92, 93, 94, 95, // 5 + 88, 89, 90, 91, 92, 93, 94, 95, // 5 96, 65, 66, 67, 68, 69, 70, 71, - 72, 73, 74, 75, 76, 77, 78, 79, // 6 + 72, 73, 74, 75, 76, 77, 78, 79, // 6 80, 81, 82, 83, 84, 85, 86, 87, - 88, 89, 90, 123, 124, 125, 126, 127, // 7 + 88, 89, 90, 123, 124, 125, 126, 127, // 7 128, 129, 130, 131, 132, 133, 134, 135, - 136, 137, 138, 139, 140, 141, 142, 143, // 8 + 136, 137, 138, 139, 140, 141, 142, 143, // 8 144, 145, 146, 147, 148, 149, 150, 151, - 152, 153, 154, 155, 156, 157, 158, 159, // 9 + 152, 153, 154, 155, 156, 157, 158, 159, // 9 160, 161, 162, 163, 164, 165, 166, 167, - 168, 169, 170, 171, 172, 173, 174, 175, // A + 168, 169, 170, 171, 172, 173, 174, 175, // A 176, 177, 178, 179, 180, 181, 182, 183, - 184, 185, 186, 187, 188, 189, 190, 191, // B + 184, 185, 186, 187, 188, 189, 190, 191, // B 192, 193, 194, 195, 196, 197, 198, 199, - 200, 201, 202, 203, 204, 205, 206, 207, // C + 200, 201, 202, 203, 204, 205, 206, 207, // C 208, 209, 210, 211, 212, 213, 214, 215, - 216, 217, 218, 219, 220, 221, 222, 223, // D + 216, 217, 218, 219, 220, 221, 222, 223, // D 224, 225, 226, 227, 228, 229, 230, 231, - 232, 233, 234, 235, 236, 237, 238, 239, // E + 232, 233, 234, 235, 236, 237, 238, 239, // E 240, 241, 242, 243, 244, 245, 246, 247, - 248, 249, 250, 251, 252, 253, 254, 255 // F + 248, 249, 250, 251, 252, 253, 254, 255 // F }; -} // namespace internal - //! \endcond +} // namespace internal +//! \endcond -} // namespace rapidxml +} // namespace rapidxml // Undefine internal macros #undef RAPIDXML_PARSE_ERROR diff --git a/livox_ros_driver/common/rapidxml/rapidxml_iterators.hpp b/livox_ros_driver/common/rapidxml/rapidxml_iterators.hpp index 304b1bf..6ccba4e 100644 --- a/livox_ros_driver/common/rapidxml/rapidxml_iterators.hpp +++ b/livox_ros_driver/common/rapidxml/rapidxml_iterators.hpp @@ -11,9 +11,9 @@ namespace rapidxml { //! Iterator of child nodes of xml_node -template class node_iterator { - -public: +template +class node_iterator { + public: typedef typename xml_node value_type; typedef typename xml_node &reference; typedef typename xml_node *pointer; @@ -62,14 +62,14 @@ template class node_iterator { bool operator!=(const node_iterator &rhs) { return m_node != rhs.m_node; } -private: + private: xml_node *m_node; }; //! Iterator of child attributes of xml_node -template class attribute_iterator { - -public: +template +class attribute_iterator { + public: typedef typename xml_attribute value_type; typedef typename xml_attribute &reference; typedef typename xml_attribute *pointer; @@ -123,10 +123,10 @@ template class attribute_iterator { return m_attribute != rhs.m_attribute; } -private: + private: xml_attribute *m_attribute; }; -} // namespace rapidxml +} // namespace rapidxml #endif diff --git a/livox_ros_driver/common/rapidxml/rapidxml_print.hpp b/livox_ros_driver/common/rapidxml/rapidxml_print.hpp index b97aa9d..7e27b8b 100644 --- a/livox_ros_driver/common/rapidxml/rapidxml_print.hpp +++ b/livox_ros_driver/common/rapidxml/rapidxml_print.hpp @@ -19,9 +19,9 @@ namespace rapidxml { /////////////////////////////////////////////////////////////////////// // Printing flags -const int print_no_indenting = - 0x1; //!< Printer flag instructing the printer to suppress indenting of XML. - //!< See print() function. +const int print_no_indenting = 0x1; //!< Printer flag instructing the printer + //!to suppress indenting of XML. + //!< See print() function. /////////////////////////////////////////////////////////////////////// // Internal @@ -35,8 +35,7 @@ namespace internal { // Copy characters from given range to given output iterator template inline OutIt copy_chars(const Ch *begin, const Ch *end, OutIt out) { - while (begin != end) - *out++ = *begin++; + while (begin != end) *out++ = *begin++; return out; } @@ -47,49 +46,49 @@ inline OutIt copy_and_expand_chars(const Ch *begin, const Ch *end, Ch noexpand, OutIt out) { while (begin != end) { if (*begin == noexpand) { - *out++ = *begin; // No expansion, copy character + *out++ = *begin; // No expansion, copy character } else { switch (*begin) { - case Ch('<'): - *out++ = Ch('&'); - *out++ = Ch('l'); - *out++ = Ch('t'); - *out++ = Ch(';'); - break; - case Ch('>'): - *out++ = Ch('&'); - *out++ = Ch('g'); - *out++ = Ch('t'); - *out++ = Ch(';'); - break; - case Ch('\''): - *out++ = Ch('&'); - *out++ = Ch('a'); - *out++ = Ch('p'); - *out++ = Ch('o'); - *out++ = Ch('s'); - *out++ = Ch(';'); - break; - case Ch('"'): - *out++ = Ch('&'); - *out++ = Ch('q'); - *out++ = Ch('u'); - *out++ = Ch('o'); - *out++ = Ch('t'); - *out++ = Ch(';'); - break; - case Ch('&'): - *out++ = Ch('&'); - *out++ = Ch('a'); - *out++ = Ch('m'); - *out++ = Ch('p'); - *out++ = Ch(';'); - break; - default: - *out++ = *begin; // No expansion, copy character + case Ch('<'): + *out++ = Ch('&'); + *out++ = Ch('l'); + *out++ = Ch('t'); + *out++ = Ch(';'); + break; + case Ch('>'): + *out++ = Ch('&'); + *out++ = Ch('g'); + *out++ = Ch('t'); + *out++ = Ch(';'); + break; + case Ch('\''): + *out++ = Ch('&'); + *out++ = Ch('a'); + *out++ = Ch('p'); + *out++ = Ch('o'); + *out++ = Ch('s'); + *out++ = Ch(';'); + break; + case Ch('"'): + *out++ = Ch('&'); + *out++ = Ch('q'); + *out++ = Ch('u'); + *out++ = Ch('o'); + *out++ = Ch('t'); + *out++ = Ch(';'); + break; + case Ch('&'): + *out++ = Ch('&'); + *out++ = Ch('a'); + *out++ = Ch('m'); + *out++ = Ch('p'); + *out++ = Ch(';'); + break; + default: + *out++ = *begin; // No expansion, copy character } } - ++begin; // Step to next character + ++begin; // Step to next character } return out; } @@ -97,8 +96,7 @@ inline OutIt copy_and_expand_chars(const Ch *begin, const Ch *end, Ch noexpand, // Fill given output iterator with repetitions of the same character template inline OutIt fill_chars(OutIt out, int n, Ch ch) { - for (int i = 0; i < n; ++i) - *out++ = ch; + for (int i = 0; i < n; ++i) *out++ = ch; return out; } @@ -106,8 +104,7 @@ inline OutIt fill_chars(OutIt out, int n, Ch ch) { template inline bool find_char(const Ch *begin, const Ch *end) { while (begin != end) - if (*begin++ == ch) - return true; + if (*begin++ == ch) return true; return false; } @@ -120,56 +117,54 @@ inline OutIt print_node(OutIt out, const xml_node *node, int flags, int indent) { // Print proper node type switch (node->type()) { - - // Document - case node_document: - out = print_children(out, node, flags, indent); - break; - - // Element - case node_element: - out = print_element_node(out, node, flags, indent); - break; - - // Data - case node_data: - out = print_data_node(out, node, flags, indent); - break; - - // CDATA - case node_cdata: - out = print_cdata_node(out, node, flags, indent); - break; - - // Declaration - case node_declaration: - out = print_declaration_node(out, node, flags, indent); - break; - - // Comment - case node_comment: - out = print_comment_node(out, node, flags, indent); - break; - - // Doctype - case node_doctype: - out = print_doctype_node(out, node, flags, indent); - break; - - // Pi - case node_pi: - out = print_pi_node(out, node, flags, indent); - break; + // Document + case node_document: + out = print_children(out, node, flags, indent); + break; + + // Element + case node_element: + out = print_element_node(out, node, flags, indent); + break; + + // Data + case node_data: + out = print_data_node(out, node, flags, indent); + break; + + // CDATA + case node_cdata: + out = print_cdata_node(out, node, flags, indent); + break; + + // Declaration + case node_declaration: + out = print_declaration_node(out, node, flags, indent); + break; + + // Comment + case node_comment: + out = print_comment_node(out, node, flags, indent); + break; + + // Doctype + case node_doctype: + out = print_doctype_node(out, node, flags, indent); + break; + + // Pi + case node_pi: + out = print_pi_node(out, node, flags, indent); + break; // Unknown - default: - assert(0); - break; + default: + assert(0); + break; } // If indenting not disabled, add line break after node - if (!(flags & print_no_indenting)) - *out = Ch('\n'), ++out; + if (!(flags & print_no_indenting)) *out = Ch('\n'), ++out; // Return modified iterator return out; @@ -197,9 +192,9 @@ inline OutIt print_attributes(OutIt out, const xml_node *node, int flags) { attribute->name() + attribute->name_size(), out); *out = Ch('='), ++out; // Print attribute value using appropriate quote type - if (find_char(attribute->value(), - attribute->value() + - attribute->value_size())) { + if (find_char( + attribute->value(), + attribute->value() + attribute->value_size())) { *out = Ch('\''), ++out; out = copy_and_expand_chars( attribute->value(), attribute->value() + attribute->value_size(), @@ -222,8 +217,7 @@ template inline OutIt print_data_node(OutIt out, const xml_node *node, int flags, int indent) { assert(node->type() == node_data); - if (!(flags & print_no_indenting)) - out = fill_chars(out, indent, Ch('\t')); + if (!(flags & print_no_indenting)) out = fill_chars(out, indent, Ch('\t')); out = copy_and_expand_chars(node->value(), node->value() + node->value_size(), Ch(0), out); return out; @@ -234,8 +228,7 @@ template inline OutIt print_cdata_node(OutIt out, const xml_node *node, int flags, int indent) { assert(node->type() == node_cdata); - if (!(flags & print_no_indenting)) - out = fill_chars(out, indent, Ch('\t')); + if (!(flags & print_no_indenting)) out = fill_chars(out, indent, Ch('\t')); *out = Ch('<'); ++out; *out = Ch('!'); @@ -271,8 +264,7 @@ inline OutIt print_element_node(OutIt out, const xml_node *node, int flags, assert(node->type() == node_element); // Print element name and attributes, if any - if (!(flags & print_no_indenting)) - out = fill_chars(out, indent, Ch('\t')); + if (!(flags & print_no_indenting)) out = fill_chars(out, indent, Ch('\t')); *out = Ch('<'), ++out; out = copy_chars(node->name(), node->name() + node->name_size(), out); out = print_attributes(out, node, flags); @@ -298,8 +290,7 @@ inline OutIt print_element_node(OutIt out, const xml_node *node, int flags, child->value(), child->value() + child->value_size(), Ch(0), out); } else { // Print all children with full indenting - if (!(flags & print_no_indenting)) - *out = Ch('\n'), ++out; + if (!(flags & print_no_indenting)) *out = Ch('\n'), ++out; out = print_children(out, node, flags, indent + 1); if (!(flags & print_no_indenting)) out = fill_chars(out, indent, Ch('\t')); @@ -319,8 +310,7 @@ template inline OutIt print_declaration_node(OutIt out, const xml_node *node, int flags, int indent) { // Print declaration start - if (!(flags & print_no_indenting)) - out = fill_chars(out, indent, Ch('\t')); + if (!(flags & print_no_indenting)) out = fill_chars(out, indent, Ch('\t')); *out = Ch('<'), ++out; *out = Ch('?'), ++out; *out = Ch('x'), ++out; @@ -342,8 +332,7 @@ template inline OutIt print_comment_node(OutIt out, const xml_node *node, int flags, int indent) { assert(node->type() == node_comment); - if (!(flags & print_no_indenting)) - out = fill_chars(out, indent, Ch('\t')); + if (!(flags & print_no_indenting)) out = fill_chars(out, indent, Ch('\t')); *out = Ch('<'), ++out; *out = Ch('!'), ++out; *out = Ch('-'), ++out; @@ -360,8 +349,7 @@ template inline OutIt print_doctype_node(OutIt out, const xml_node *node, int flags, int indent) { assert(node->type() == node_doctype); - if (!(flags & print_no_indenting)) - out = fill_chars(out, indent, Ch('\t')); + if (!(flags & print_no_indenting)) out = fill_chars(out, indent, Ch('\t')); *out = Ch('<'), ++out; *out = Ch('!'), ++out; *out = Ch('D'), ++out; @@ -382,8 +370,7 @@ template inline OutIt print_pi_node(OutIt out, const xml_node *node, int flags, int indent) { assert(node->type() == node_pi); - if (!(flags & print_no_indenting)) - out = fill_chars(out, indent, Ch('\t')); + if (!(flags & print_no_indenting)) out = fill_chars(out, indent, Ch('\t')); *out = Ch('<'), ++out; *out = Ch('?'), ++out; out = copy_chars(node->name(), node->name() + node->name_size(), out); @@ -394,7 +381,7 @@ inline OutIt print_pi_node(OutIt out, const xml_node *node, int flags, return out; } -} // namespace internal +} // namespace internal //! \endcond /////////////////////////////////////////////////////////////////////////// @@ -436,6 +423,6 @@ inline std::basic_ostream &operator<<(std::basic_ostream &out, #endif -} // namespace rapidxml +} // namespace rapidxml #endif diff --git a/livox_ros_driver/common/rapidxml/rapidxml_utils.hpp b/livox_ros_driver/common/rapidxml/rapidxml_utils.hpp index b8916ba..9e54d4f 100644 --- a/livox_ros_driver/common/rapidxml/rapidxml_utils.hpp +++ b/livox_ros_driver/common/rapidxml/rapidxml_utils.hpp @@ -8,18 +8,18 @@ //! that can be useful in certain simple scenarios. They should probably not be //! used if maximizing performance is the main objective. -#include "rapidxml.hpp" #include #include #include #include +#include "rapidxml.hpp" namespace rapidxml { //! Represents data loaded from a file -template class file { - -public: +template +class file { + public: //! Loads file into the memory. Data will be automatically destroyed by the //! destructor. \param filename Filename to load. file(const char *filename) { @@ -27,8 +27,7 @@ template class file { // Open stream basic_ifstream stream(filename, ios::binary); - if (!stream) - throw runtime_error(string("cannot open file ") + filename); + if (!stream) throw runtime_error(string("cannot open file ") + filename); stream.unsetf(ios::skipws); // Determine stream size @@ -67,13 +66,14 @@ template class file { //! \return Size of file data, in characters. std::size_t size() const { return m_data.size(); } -private: - std::vector m_data; // File data + private: + std::vector m_data; // File data }; //! Counts children of node. Time complexity is O(n). //! \return Number of children of node -template inline std::size_t count_children(xml_node *node) { +template +inline std::size_t count_children(xml_node *node) { xml_node *child = node->first_node(); std::size_t count = 0; while (child) { @@ -85,7 +85,8 @@ template inline std::size_t count_children(xml_node *node) { //! Counts attributes of node. Time complexity is O(n). //! \return Number of attributes of node -template inline std::size_t count_attributes(xml_node *node) { +template +inline std::size_t count_attributes(xml_node *node) { xml_attribute *attr = node->first_attribute(); std::size_t count = 0; while (attr) { @@ -95,6 +96,6 @@ template inline std::size_t count_attributes(xml_node *node) { return count; } -} // namespace rapidxml +} // namespace rapidxml #endif diff --git a/livox_ros_driver/config/livox_hub_config.json b/livox_ros_driver/config/livox_hub_config.json index bc92e95..9da0e25 100644 --- a/livox_ros_driver/config/livox_hub_config.json +++ b/livox_ros_driver/config/livox_hub_config.json @@ -7,27 +7,23 @@ "lidar_config": [ { "broadcast_code": "0TFDG3B006H2Z11", - "enable_fan": true, "return_mode": 0, - "imu_rate": 1 + "imu_rate": 0 }, { "broadcast_code": "0TFDG3U99101291", - "enable_fan": true, "return_mode": 0, - "imu_rate": 1 + "imu_rate": 0 }, { "broadcast_code": "1HDDG8M00100191", - "enable_fan": true, "return_mode": 0, - "imu_rate": 1 + "imu_rate": 0 }, { "broadcast_code": "1PQDG8E00100321", - "enable_fan": true, "return_mode": 0, - "imu_rate": 1 + "imu_rate": 0 } ] } diff --git a/livox_ros_driver/config/livox_lidar_config.json b/livox_ros_driver/config/livox_lidar_config.json index c22bf4d..0e8f709 100644 --- a/livox_ros_driver/config/livox_lidar_config.json +++ b/livox_ros_driver/config/livox_lidar_config.json @@ -1,9 +1,8 @@ { "lidar_config": [ { - "broadcast_code": "0T9DFBC00401611", + "broadcast_code": "1PQDH5B00100041", "enable_connect": false, - "enable_fan": true, "return_mode": 0, "coordinate": 0, "imu_rate": 0, @@ -13,7 +12,6 @@ { "broadcast_code": "0TFDG3U99101431", "enable_connect": false, - "enable_fan": true, "return_mode": 0, "coordinate": 0, "imu_rate": 0, diff --git a/livox_ros_driver/livox_ros_driver/include/livox_ros_driver.h b/livox_ros_driver/livox_ros_driver/include/livox_ros_driver.h index 093ed39..76ed618 100644 --- a/livox_ros_driver/livox_ros_driver/include/livox_ros_driver.h +++ b/livox_ros_driver/livox_ros_driver/include/livox_ros_driver.h @@ -26,15 +26,15 @@ #define LIVOX_ROS_DRIVER_INClUDE_LIVOX_ROS_DRIVER_H_ #define LIVOX_ROS_DRIVER_VER_MAJOR 2 -#define LIVOX_ROS_DRIVER_VER_MINOR 5 +#define LIVOX_ROS_DRIVER_VER_MINOR 6 #define LIVOX_ROS_DRIVER_VER_PATCH 0 #define GET_STRING(n) GET_STRING_DIRECT(n) #define GET_STRING_DIRECT(n) #n -#define LIVOX_ROS_DRIVER_VERSION_STRING \ - GET_STRING(LIVOX_ROS_DRIVER_VER_MAJOR) \ - "." GET_STRING(LIVOX_ROS_DRIVER_VER_MINOR) "." GET_STRING( \ +#define LIVOX_ROS_DRIVER_VERSION_STRING \ + GET_STRING(LIVOX_ROS_DRIVER_VER_MAJOR) \ + "." GET_STRING(LIVOX_ROS_DRIVER_VER_MINOR) "." GET_STRING( \ LIVOX_ROS_DRIVER_VER_PATCH) #endif diff --git a/livox_ros_driver/livox_ros_driver/lddc.cpp b/livox_ros_driver/livox_ros_driver/lddc.cpp index 2f5ae50..047ec1a 100644 --- a/livox_ros_driver/livox_ros_driver/lddc.cpp +++ b/livox_ros_driver/livox_ros_driver/lddc.cpp @@ -34,20 +34,21 @@ #include #include -#include "lds_lidar.h" -#include "lds_lvx.h" #include #include +#include "lds_lidar.h" +#include "lds_lvx.h" namespace livox_ros { -typedef pcl::PointCloud PointCloud; - /** Lidar Data Distribute Control--------------------------------------------*/ Lddc::Lddc(int format, int multi_topic, int data_src, int output_type, double frq, std::string &frame_id) - : transfer_format_(format), use_multi_topic_(multi_topic), - data_src_(data_src), output_type_(output_type), publish_frq_(frq), \ + : transfer_format_(format), + use_multi_topic_(multi_topic), + data_src_(data_src), + output_type_(output_type), + publish_frq_(frq), frame_id_(frame_id) { publish_period_ns_ = kNsPerSecond / publish_frq_; lds_ = nullptr; @@ -60,7 +61,6 @@ Lddc::Lddc(int format, int multi_topic, int data_src, int output_type, }; Lddc::~Lddc() { - if (global_pub_) { delete global_pub_; } @@ -87,63 +87,50 @@ Lddc::~Lddc() { } int32_t Lddc::GetPublishStartTime(LidarDevice *lidar, LidarDataQueue *queue, - uint64_t *start_time,StoragePacket *storage_packet) { - QueueProPop(queue, storage_packet); - uint64_t timestamp = GetStoragePacketTimestamp(storage_packet, - lidar->data_src); + uint64_t *start_time, + StoragePacket *storage_packet) { + QueuePrePop(queue, storage_packet); + uint64_t timestamp = + GetStoragePacketTimestamp(storage_packet, lidar->data_src); uint32_t remaining_time = timestamp % publish_period_ns_; uint32_t diff_time = publish_period_ns_ - remaining_time; /** Get start time, down to the period boundary */ if (diff_time > (publish_period_ns_ / 4)) { - //ROS_INFO("0 : %u", diff_time); + // ROS_INFO("0 : %u", diff_time); *start_time = timestamp - remaining_time; return 0; } else if (diff_time <= lidar->packet_interval_max) { *start_time = timestamp; return 0; } else { - /** Skip some packets up to the period boundary*/ - //ROS_INFO("2 : %u", diff_time); + /** Skip some packets up to the period boundary*/ + // ROS_INFO("2 : %u", diff_time); do { if (QueueIsEmpty(queue)) { break; } - QueuePopUpdate(queue); /* skip packet */ - QueueProPop(queue, storage_packet); + QueuePopUpdate(queue); /* skip packet */ + QueuePrePop(queue, storage_packet); uint32_t last_remaning_time = remaining_time; - timestamp = GetStoragePacketTimestamp(storage_packet, - lidar->data_src); + timestamp = GetStoragePacketTimestamp(storage_packet, lidar->data_src); remaining_time = timestamp % publish_period_ns_; /** Flip to another period */ if (last_remaning_time > remaining_time) { - //ROS_INFO("Flip to another period, exit"); + // ROS_INFO("Flip to another period, exit"); break; } diff_time = publish_period_ns_ - remaining_time; } while (diff_time > lidar->packet_interval); - + /* the remaning packets in queue maybe not enough after skip */ return -1; } } -uint32_t Lddc::PublishPointcloud2(LidarDataQueue *queue, uint32_t packet_num, - uint8_t handle) { - uint64_t timestamp = 0; - uint64_t last_timestamp = 0; - uint32_t published_packet = 0; - - StoragePacket storage_packet; - LidarDevice *lidar = &lds_->lidars_[handle]; - if (GetPublishStartTime(lidar, queue, &last_timestamp, &storage_packet)) { - /* the remaning packets in queue maybe not enough after skip */ - return 0; - } - - sensor_msgs::PointCloud2 cloud; +void Lddc::InitPointcloud2MsgHeader(sensor_msgs::PointCloud2& cloud) { cloud.header.frame_id.assign(frame_id_); cloud.height = 1; - cloud.width = 0; + cloud.width = 0; cloud.fields.resize(6); cloud.fields[0].offset = 0; cloud.fields[0].name = "x"; @@ -169,44 +156,61 @@ uint32_t Lddc::PublishPointcloud2(LidarDataQueue *queue, uint32_t packet_num, cloud.fields[5].name = "line"; cloud.fields[5].count = 1; cloud.fields[5].datatype = sensor_msgs::PointField::UINT8; + cloud.point_step = sizeof(LivoxPointXyzrtl); +} + +uint32_t Lddc::PublishPointcloud2(LidarDataQueue *queue, uint32_t packet_num, + uint8_t handle) { + uint64_t timestamp = 0; + uint64_t last_timestamp = 0; + uint32_t published_packet = 0; + + StoragePacket storage_packet; + LidarDevice *lidar = &lds_->lidars_[handle]; + if (GetPublishStartTime(lidar, queue, &last_timestamp, &storage_packet)) { + /* the remaning packets in queue maybe not enough after skip */ + return 0; + } + sensor_msgs::PointCloud2 cloud; + InitPointcloud2MsgHeader(cloud); cloud.data.resize(packet_num * kMaxPointPerEthPacket * sizeof(LivoxPointXyzrtl)); cloud.point_step = sizeof(LivoxPointXyzrtl); + uint8_t *point_base = cloud.data.data(); uint8_t data_source = lidar->data_src; + uint32_t line_num = GetLaserLineNumber(lidar->info.type); + uint32_t echo_num = GetEchoNumPerPoint(lidar->raw_data_type); + uint32_t is_zero_packet = 0; while ((published_packet < packet_num) && !QueueIsEmpty(queue)) { - QueueProPop(queue, &storage_packet); + QueuePrePop(queue, &storage_packet); LivoxEthPacket *raw_packet = reinterpret_cast(storage_packet.raw_data); timestamp = GetStoragePacketTimestamp(&storage_packet, data_source); int64_t packet_gap = timestamp - last_timestamp; - if ((packet_gap > lidar->packet_interval_max) && + if ((packet_gap > lidar->packet_interval_max) && lidar->data_is_pubulished) { - //ROS_INFO("Lidar[%d] packet time interval is %ldns", handle, packet_gap); + // ROS_INFO("Lidar[%d] packet time interval is %ldns", handle, + // packet_gap); if (kSourceLvxFile != data_source) { - point_base = FillZeroPointXyzrtl(point_base, storage_packet.point_num); - cloud.width += storage_packet.point_num; - last_timestamp = last_timestamp + lidar->packet_interval; - if (!published_packet) { - cloud.header.stamp = ros::Time(last_timestamp / 1000000000.0); - } - ++published_packet; - continue; + timestamp = last_timestamp + lidar->packet_interval; + ZeroPointDataOfStoragePacket(&storage_packet); + is_zero_packet = 1; } } /** Use the first packet timestamp as pointcloud2 msg timestamp */ - if (!published_packet) { + if (!published_packet) { cloud.header.stamp = ros::Time(timestamp / 1000000000.0); } - cloud.width += storage_packet.point_num; + uint32_t single_point_num = storage_packet.point_num * echo_num; if (kSourceLvxFile != data_source) { PointConvertHandler pf_point_convert = GetConvertHandler(lidar->raw_data_type); if (pf_point_convert) { - point_base = pf_point_convert( - point_base, raw_packet, lidar->extrinsic_parameter); + point_base = pf_point_convert(point_base, raw_packet, + lidar->extrinsic_parameter, line_num); } else { /** Skip the packet */ ROS_INFO("Lidar[%d] unkown packet type[%d]", handle, @@ -214,20 +218,23 @@ uint32_t Lddc::PublishPointcloud2(LidarDataQueue *queue, uint32_t packet_num, break; } } else { - point_base = LivoxPointToPxyzrtl( - point_base, raw_packet, lidar->extrinsic_parameter); + point_base = LivoxPointToPxyzrtl(point_base, raw_packet, + lidar->extrinsic_parameter, line_num); } - QueuePopUpdate(queue); - last_timestamp = timestamp; + if (!is_zero_packet) { + QueuePopUpdate(queue); + } else { + is_zero_packet = 0; + } + cloud.width += single_point_num; ++published_packet; + last_timestamp = timestamp; } - - cloud.row_step = cloud.width * cloud.point_step; + cloud.row_step = cloud.width * cloud.point_step; cloud.is_bigendian = false; - cloud.is_dense = true; + cloud.is_dense = true; cloud.data.resize(cloud.row_step); /** Adjust to the real size */ - ros::Publisher *p_publisher = Lddc::GetCurrentPublisher(handle); if (kOutputToRos == output_type_) { p_publisher->publish(cloud); @@ -237,14 +244,26 @@ uint32_t Lddc::PublishPointcloud2(LidarDataQueue *queue, uint32_t packet_num, cloud); } } - if (!lidar->data_is_pubulished) { lidar->data_is_pubulished = true; } - return published_packet; } +void Lddc::FillPointsToPclMsg(PointCloud::Ptr& pcl_msg, \ + LivoxPointXyzrtl* src_point, uint32_t num) { + LivoxPointXyzrtl* point_xyzrtl = (LivoxPointXyzrtl*)src_point; + for (uint32_t i = 0; i < num; i++) { + pcl::PointXYZI point; + point.x = point_xyzrtl->x; + point.y = point_xyzrtl->y; + point.z = point_xyzrtl->z; + point.intensity = point_xyzrtl->reflectivity; + ++point_xyzrtl; + pcl_msg->points.push_back(point); + } +} + /* for pcl::pxyzi */ uint32_t Lddc::PublishPointcloudData(LidarDataQueue *queue, uint32_t packet_num, uint8_t handle) { @@ -253,22 +272,24 @@ uint32_t Lddc::PublishPointcloudData(LidarDataQueue *queue, uint32_t packet_num, uint32_t published_packet = 0; StoragePacket storage_packet; - LidarDevice *lidar = &lds_->lidars_[handle]; + LidarDevice *lidar = &lds_->lidars_[handle]; if (GetPublishStartTime(lidar, queue, &last_timestamp, &storage_packet)) { /* the remaning packets in queue maybe not enough after skip */ return 0; } - /* init point cloud data struct */ PointCloud::Ptr cloud(new PointCloud); cloud->header.frame_id.assign(frame_id_); - /* cloud->header.stamp = ros::Time::now(); */ cloud->height = 1; - cloud->width = 0; + cloud->width = 0; + uint8_t point_buf[2048]; + uint32_t is_zero_packet = 0; uint8_t data_source = lidar->data_src; + uint32_t line_num = GetLaserLineNumber(lidar->info.type); + uint32_t echo_num = GetEchoNumPerPoint(lidar->raw_data_type); while ((published_packet < packet_num) && !QueueIsEmpty(queue)) { - QueueProPop(queue, &storage_packet); + QueuePrePop(queue, &storage_packet); LivoxEthPacket *raw_packet = reinterpret_cast(storage_packet.raw_data); timestamp = GetStoragePacketTimestamp(&storage_packet, data_source); @@ -276,29 +297,23 @@ uint32_t Lddc::PublishPointcloudData(LidarDataQueue *queue, uint32_t packet_num, if ((packet_gap > lidar->packet_interval_max) && lidar->data_is_pubulished) { //ROS_INFO("Lidar[%d] packet time interval is %ldns", handle, packet_gap); - pcl::PointXYZI point = {0}; /* fill zero points */ - for (uint32_t i = 0; i < storage_packet.point_num; i++) { - cloud->points.push_back(point); - } - last_timestamp = last_timestamp + lidar->packet_interval; - if (!published_packet) { - cloud->header.stamp = last_timestamp / 1000.0; // to pcl ros time stamp + if (kSourceLvxFile != data_source) { + timestamp = last_timestamp + lidar->packet_interval; + ZeroPointDataOfStoragePacket(&storage_packet); + is_zero_packet = 1; } - ++published_packet; - continue; } if (!published_packet) { - cloud->header.stamp = timestamp / 1000.0; // to pcl ros time stamp + cloud->header.stamp = timestamp / 1000.0; // to pcl ros time stamp } - cloud->width += storage_packet.point_num; + uint32_t single_point_num = storage_packet.point_num * echo_num; - uint8_t point_buf[2048]; if (kSourceLvxFile != data_source) { PointConvertHandler pf_point_convert = GetConvertHandler(lidar->raw_data_type); if (pf_point_convert) { - pf_point_convert(point_buf, raw_packet, - lidar->extrinsic_parameter); + pf_point_convert(point_buf, raw_packet, lidar->extrinsic_parameter, \ + line_num); } else { /* Skip the packet */ ROS_INFO("Lidar[%d] unkown packet type[%d]", handle, @@ -306,24 +321,19 @@ uint32_t Lddc::PublishPointcloudData(LidarDataQueue *queue, uint32_t packet_num, break; } } else { - LivoxPointToPxyzrtl(point_buf, raw_packet, - lidar->extrinsic_parameter); + LivoxPointToPxyzrtl(point_buf, raw_packet, lidar->extrinsic_parameter, \ + line_num); } - LivoxPointXyzrtl *dst_point = (LivoxPointXyzrtl *)point_buf; - for (uint32_t i = 0; i < storage_packet.point_num; i++) { - pcl::PointXYZI point; - point.x = dst_point->x; - point.y = dst_point->y; - point.z = dst_point->z; - point.intensity = dst_point->reflectivity; - ++dst_point; - cloud->points.push_back(point); + FillPointsToPclMsg(cloud, dst_point, single_point_num); + if (!is_zero_packet) { + QueuePopUpdate(queue); + } else { + is_zero_packet = 0; } - - QueuePopUpdate(queue); - last_timestamp = timestamp; + cloud->width += single_point_num; ++published_packet; + last_timestamp = timestamp; } ros::Publisher *p_publisher = Lddc::GetCurrentPublisher(handle); @@ -335,72 +345,96 @@ uint32_t Lddc::PublishPointcloudData(LidarDataQueue *queue, uint32_t packet_num, cloud); } } - if (!lidar->data_is_pubulished) { lidar->data_is_pubulished = true; } - return published_packet; } +void Lddc::FillPointsToCustomMsg(livox_ros_driver::CustomMsg& livox_msg, \ + LivoxPointXyzrtl* src_point, uint32_t num, uint32_t offset_time, \ + uint32_t point_interval, uint32_t echo_num) { + LivoxPointXyzrtl* point_xyzrtl = (LivoxPointXyzrtl*)src_point; + for (uint32_t i = 0; i < num; i++) { + livox_ros_driver::CustomPoint point; + if (echo_num > 1) { /** dual return mode */ + point.offset_time = offset_time + (i / echo_num) * point_interval; + } else { + point.offset_time = offset_time + i * point_interval; + } + point.x = point_xyzrtl->x; + point.y = point_xyzrtl->y; + point.z = point_xyzrtl->z; + point.reflectivity = point_xyzrtl->reflectivity; + point.tag = point_xyzrtl->tag; + point.line = point_xyzrtl->line; + ++point_xyzrtl; + livox_msg.points.push_back(point); + } +} + uint32_t Lddc::PublishCustomPointcloud(LidarDataQueue *queue, uint32_t packet_num, uint8_t handle) { static uint32_t msg_seq = 0; uint64_t timestamp = 0; uint64_t last_timestamp = 0; - uint32_t published_packet = 0; - uint32_t packet_offset_time = 0; // ns - livox_ros_driver::CustomMsg livox_msg; + StoragePacket storage_packet; + LidarDevice *lidar = &lds_->lidars_[handle]; + if (GetPublishStartTime(lidar, queue, &last_timestamp, &storage_packet)) { + /* the remaning packets in queue maybe not enough after skip */ + return 0; + } - //livox_msg.header.frame_id = "livox_frame"; + livox_ros_driver::CustomMsg livox_msg; livox_msg.header.frame_id.assign(frame_id_); - livox_msg.header.seq = msg_seq; ++msg_seq; - // livox_msg.header.stamp = ros::Time::now(); livox_msg.timebase = 0; livox_msg.point_num = 0; livox_msg.lidar_id = handle; - LidarDevice *lidar = &lds_->lidars_[handle]; + uint8_t point_buf[2048]; uint8_t data_source = lds_->lidars_[handle].data_src; - StoragePacket storage_packet; + uint32_t line_num = GetLaserLineNumber(lidar->info.type); + uint32_t echo_num = GetEchoNumPerPoint(lidar->raw_data_type); + uint32_t point_interval = GetPointInterval(lidar->info.type); + uint32_t published_packet = 0; + uint32_t packet_offset_time = 0; /** uint:ns */ + uint32_t is_zero_packet = 0; while (published_packet < packet_num) { - QueueProPop(queue, &storage_packet); + QueuePrePop(queue, &storage_packet); LivoxEthPacket *raw_packet = reinterpret_cast(storage_packet.raw_data); - uint32_t point_interval = GetPointInterval(lidar->raw_data_type); - uint32_t dual_point = 0; - if ((raw_packet->data_type == kDualExtendCartesian) || - (raw_packet->data_type == kDualExtendSpherical)) { - dual_point = 1; - } - timestamp = GetStoragePacketTimestamp(&storage_packet, data_source); - if (((timestamp - last_timestamp) > kDeviceDisconnectThreshold) && - published_packet && lidar->data_is_pubulished) { - ROS_INFO("Lidar[%d] packet loss", handle); - break; + int64_t packet_gap = timestamp - last_timestamp; + if ((packet_gap > lidar->packet_interval_max) && + lidar->data_is_pubulished) { + // ROS_INFO("Lidar[%d] packet time interval is %ldns", handle, + // packet_gap); + if (kSourceLvxFile != data_source) { + timestamp = last_timestamp + lidar->packet_interval; + ZeroPointDataOfStoragePacket(&storage_packet); + is_zero_packet = 1; + } } + /** first packet */ if (!published_packet) { - livox_msg.timebase = timestamp; // to us - packet_offset_time = 0; // first packet - livox_msg.header.stamp = - ros::Time(timestamp / 1000000000.0); // to ros time stamp - // ROS_DEBUG("[%d]:%ld %d", handle, livox_msg.timebase, point_interval); + livox_msg.timebase = timestamp; + packet_offset_time = 0; + /** convert to ros time stamp */ + livox_msg.header.stamp = ros::Time(timestamp / 1000000000.0); } else { packet_offset_time = (uint32_t)(timestamp - livox_msg.timebase); } - livox_msg.point_num += storage_packet.point_num; + uint32_t single_point_num = storage_packet.point_num * echo_num; - uint8_t point_buf[2048]; if (kSourceLvxFile != data_source) { PointConvertHandler pf_point_convert = GetConvertHandler(lidar->raw_data_type); if (pf_point_convert) { - pf_point_convert(point_buf, raw_packet, - lidar->extrinsic_parameter); + pf_point_convert(point_buf, raw_packet, lidar->extrinsic_parameter, \ + line_num); } else { /* Skip the packet */ ROS_INFO("Lidar[%d] unkown packet type[%d]", handle, @@ -408,29 +442,20 @@ uint32_t Lddc::PublishCustomPointcloud(LidarDataQueue *queue, break; } } else { - LivoxPointToPxyzrtl(point_buf, raw_packet, - lidar->extrinsic_parameter); + LivoxPointToPxyzrtl(point_buf, raw_packet, lidar->extrinsic_parameter, \ + line_num); } - LivoxPointXyzrtl *dst_point = (LivoxPointXyzrtl *)point_buf; - for (uint32_t i = 0; i < storage_packet.point_num; i++) { - livox_ros_driver::CustomPoint point; - if (!dual_point) { /** dual return mode */ - point.offset_time = packet_offset_time + i * point_interval; - } else { - point.offset_time = packet_offset_time + (i / 2) * point_interval; - } - point.x = dst_point->x; - point.y = dst_point->y; - point.z = dst_point->z; - point.reflectivity = dst_point->reflectivity; - point.tag = dst_point->tag; - point.line = dst_point->line; - ++dst_point; - livox_msg.points.push_back(point); + FillPointsToCustomMsg(livox_msg, dst_point, single_point_num, \ + packet_offset_time, point_interval, echo_num); + + if (!is_zero_packet) { + QueuePopUpdate(queue); + } else { + is_zero_packet = 0; } - QueuePopUpdate(queue); + livox_msg.point_num += single_point_num; last_timestamp = timestamp; ++published_packet; } @@ -441,14 +466,13 @@ uint32_t Lddc::PublishCustomPointcloud(LidarDataQueue *queue, } else { if (bag_) { bag_->write(p_publisher->getTopic(), ros::Time(timestamp / 1000000000.0), - livox_msg); + livox_msg); } } if (!lidar->data_is_pubulished) { lidar->data_is_pubulished = true; } - return published_packet; } @@ -462,13 +486,13 @@ uint32_t Lddc::PublishImuData(LidarDataQueue *queue, uint32_t packet_num, uint8_t data_source = lds_->lidars_[handle].data_src; StoragePacket storage_packet; - QueueProPop(queue, &storage_packet); + QueuePrePop(queue, &storage_packet); LivoxEthPacket *raw_packet = reinterpret_cast(storage_packet.raw_data); timestamp = GetStoragePacketTimestamp(&storage_packet, data_source); if (timestamp >= 0) { imu_data.header.stamp = - ros::Time(timestamp / 1000000000.0); // to ros time stamp + ros::Time(timestamp / 1000000000.0); // to ros time stamp } uint8_t point_buf[2048]; @@ -494,7 +518,6 @@ uint32_t Lddc::PublishImuData(LidarDataQueue *queue, uint32_t packet_num, imu_data); } } - return published_packet; } @@ -509,14 +532,13 @@ int Lddc::RegisterLds(Lds *lds) { void Lddc::PollingLidarPointCloudData(uint8_t handle, LidarDevice *lidar) { LidarDataQueue *p_queue = &lidar->data; - if (p_queue == nullptr) { + if (p_queue->storage_packet == nullptr) { return; } while (!QueueIsEmpty(p_queue)) { uint32_t used_size = QueueUsedSize(p_queue); - uint32_t onetime_publish_packets = - GetPacketNumPerSec(lidar->raw_data_type) / publish_frq_; + uint32_t onetime_publish_packets = lidar->onetime_publish_packets; if (used_size < onetime_publish_packets) { break; } @@ -533,7 +555,7 @@ void Lddc::PollingLidarPointCloudData(uint8_t handle, LidarDevice *lidar) { void Lddc::PollingLidarImuData(uint8_t handle, LidarDevice *lidar) { LidarDataQueue *p_queue = &lidar->imu_data; - if (p_queue == nullptr) { + if (p_queue->storage_packet == nullptr) { return; } @@ -546,7 +568,7 @@ void Lddc::DistributeLidarData(void) { if (lds_ == nullptr) { return; } - + lds_->semaphore_.Wait(); for (uint32_t i = 0; i < lds_->lidar_count_; i++) { uint32_t lidar_id = i; LidarDevice *lidar = &lds_->lidars_[lidar_id]; @@ -555,7 +577,6 @@ void Lddc::DistributeLidarData(void) { (p_queue == nullptr)) { continue; } - PollingLidarPointCloudData(lidar_id, lidar); PollingLidarImuData(lidar_id, lidar); } @@ -603,9 +624,10 @@ ros::Publisher *Lddc::GetCurrentPublisher(uint8_t handle) { name_str, queue_size); } else if (kPclPxyziMsg == transfer_format_) { **pub = cur_node_->advertise(name_str, queue_size); - ROS_INFO("%s publish use pcl PointXYZI format, set ROS publisher queue " - "size %d", - name_str, queue_size); + ROS_INFO( + "%s publish use pcl PointXYZI format, set ROS publisher queue " + "size %d", + name_str, queue_size); } } @@ -654,9 +676,9 @@ void Lddc::CreateBagFile(const std::string &file_name) { void Lddc::PrepareExit(void) { if (bag_) { + ROS_INFO("Waiting to save the bag file!"); bag_->close(); - - ROS_INFO("Press [Ctrl+C] to exit!\n"); + ROS_INFO("Save the bag file successfully!"); bag_ = nullptr; } if (lds_) { @@ -665,4 +687,4 @@ void Lddc::PrepareExit(void) { } } -} // namespace livox_ros +} // namespace livox_ros diff --git a/livox_ros_driver/livox_ros_driver/lddc.h b/livox_ros_driver/livox_ros_driver/lddc.h index 8d71d18..8936147 100644 --- a/livox_ros_driver/livox_ros_driver/lddc.h +++ b/livox_ros_driver/livox_ros_driver/lddc.h @@ -29,9 +29,14 @@ #include #include +#include +#include +#include namespace livox_ros { +typedef pcl::PointCloud PointCloud; + /** Lidar data distribute control */ typedef enum { kPointCloud2Msg = 0, @@ -40,8 +45,8 @@ typedef enum { } TransferType; class Lddc { -public: - Lddc(int format, int multi_topic, int data_src, int output_type, double frq, \ + public: + Lddc(int format, int multi_topic, int data_src, int output_type, double frq, std::string &frame_id); ~Lddc(); @@ -59,9 +64,10 @@ class Lddc { Lds *lds_; -private: + private: int32_t GetPublishStartTime(LidarDevice *lidar, LidarDataQueue *queue, - uint64_t *start_time, StoragePacket *storage_packet); + uint64_t *start_time, + StoragePacket *storage_packet); uint32_t PublishPointcloud2(LidarDataQueue *queue, uint32_t packet_num, uint8_t handle); uint32_t PublishPointcloudData(LidarDataQueue *queue, uint32_t packet_num, @@ -75,7 +81,12 @@ class Lddc { ros::Publisher *GetCurrentImuPublisher(uint8_t handle); void PollingLidarPointCloudData(uint8_t handle, LidarDevice *lidar); void PollingLidarImuData(uint8_t handle, LidarDevice *lidar); - + void InitPointcloud2MsgHeader(sensor_msgs::PointCloud2& cloud); + void FillPointsToPclMsg(PointCloud::Ptr& pcl_msg, \ + LivoxPointXyzrtl* src_point, uint32_t num); + void FillPointsToCustomMsg(livox_ros_driver::CustomMsg& livox_msg, \ + LivoxPointXyzrtl* src_point, uint32_t num, uint32_t offset_time, \ + uint32_t point_interval, uint32_t echo_num); uint8_t transfer_format_; uint8_t use_multi_topic_; uint8_t data_src_; @@ -92,5 +103,5 @@ class Lddc { rosbag::Bag *bag_; }; -} // namespace livox_ros +} // namespace livox_ros #endif diff --git a/livox_ros_driver/livox_ros_driver/ldq.cpp b/livox_ros_driver/livox_ros_driver/ldq.cpp index 34e257d..6c96e92 100644 --- a/livox_ros_driver/livox_ros_driver/ldq.cpp +++ b/livox_ros_driver/livox_ros_driver/ldq.cpp @@ -31,7 +31,6 @@ namespace livox_ros { /* for pointcloud queue process */ int InitQueue(LidarDataQueue *queue, uint32_t queue_size) { - if (queue == nullptr) { return 1; } @@ -54,7 +53,6 @@ int InitQueue(LidarDataQueue *queue, uint32_t queue_size) { } int DeInitQueue(LidarDataQueue *queue) { - if (queue == nullptr) { return 1; } @@ -76,7 +74,7 @@ void ResetQueue(LidarDataQueue *queue) { queue->wr_idx = 0; } -void QueueProPop(LidarDataQueue *queue, StoragePacket *storage_packet) { +void QueuePrePop(LidarDataQueue *queue, StoragePacket *storage_packet) { uint32_t rd_idx = queue->rd_idx & queue->mask; memcpy(storage_packet, &(queue->storage_packet[rd_idx]), @@ -86,7 +84,7 @@ void QueueProPop(LidarDataQueue *queue, StoragePacket *storage_packet) { void QueuePopUpdate(LidarDataQueue *queue) { queue->rd_idx++; } uint32_t QueuePop(LidarDataQueue *queue, StoragePacket *storage_packet) { - QueueProPop(queue, storage_packet); + QueuePrePop(queue, storage_packet); QueuePopUpdate(queue); return 1; @@ -132,4 +130,4 @@ uint32_t QueuePushAny(LidarDataQueue *queue, uint8_t *data, uint32_t length, return 1; } -} // namespace livox_ros +} // namespace livox_ros diff --git a/livox_ros_driver/livox_ros_driver/ldq.h b/livox_ros_driver/livox_ros_driver/ldq.h index aa4cddf..1e741da 100644 --- a/livox_ros_driver/livox_ros_driver/ldq.h +++ b/livox_ros_driver/livox_ros_driver/ldq.h @@ -71,7 +71,7 @@ inline static uint32_t RoundupPowerOf2(uint32_t size) { int InitQueue(LidarDataQueue *queue, uint32_t queue_size); int DeInitQueue(LidarDataQueue *queue); void ResetQueue(LidarDataQueue *queue); -void QueueProPop(LidarDataQueue *queue, StoragePacket *storage_packet); +void QueuePrePop(LidarDataQueue *queue, StoragePacket *storage_packet); void QueuePopUpdate(LidarDataQueue *queue); uint32_t QueuePop(LidarDataQueue *queue, StoragePacket *storage_packet); uint32_t QueueUsedSize(LidarDataQueue *queue); @@ -82,5 +82,5 @@ uint32_t QueuePush(LidarDataQueue *queue, StoragePacket *storage_packet); uint32_t QueuePushAny(LidarDataQueue *queue, uint8_t *data, uint32_t length, uint64_t time_rcv, uint32_t point_num); -} // namespace livox_ros +} // namespace livox_ros #endif diff --git a/livox_ros_driver/livox_ros_driver/lds.cpp b/livox_ros_driver/livox_ros_driver/lds.cpp index 07c0685..9076bb6 100644 --- a/livox_ros_driver/livox_ros_driver/lds.cpp +++ b/livox_ros_driver/livox_ros_driver/lds.cpp @@ -24,16 +24,15 @@ #include "lds.h" -#include #include #include #include #include +#include namespace livox_ros { -/** Common function ------ - * ----------------------------------------------------------------------- */ +/** Common function --------------------------------------------------------- */ bool IsFilePathValid(const char *path_str) { int str_len = strlen(path_str); @@ -44,15 +43,14 @@ bool IsFilePathValid(const char *path_str) { } } -uint64_t GetStoragePacketTimestamp(StoragePacket *packet, uint8_t data_src_) { - +uint64_t GetStoragePacketTimestamp(StoragePacket *packet, uint8_t data_src) { LivoxEthPacket *raw_packet = reinterpret_cast(packet->raw_data); LdsStamp timestamp; memcpy(timestamp.stamp_bytes, raw_packet->timestamp, sizeof(timestamp)); if (raw_packet->timestamp_type == kTimestampTypePps) { - if (data_src_ != kSourceLvxFile) { + if (data_src != kSourceLvxFile) { return (timestamp.stamp + packet->time_rcv); } else { return timestamp.stamp; @@ -64,17 +62,17 @@ uint64_t GetStoragePacketTimestamp(StoragePacket *packet, uint8_t data_src_) { } else if (raw_packet->timestamp_type == kTimestampTypePpsGps) { struct tm time_utc; time_utc.tm_isdst = 0; - time_utc.tm_year = raw_packet->timestamp[0] + 100; // map 2000 to 1990 - time_utc.tm_mon = raw_packet->timestamp[1] - 1; // map 1~12 to 0~11 + time_utc.tm_year = raw_packet->timestamp[0] + 100; // map 2000 to 1990 + time_utc.tm_mon = raw_packet->timestamp[1] - 1; // map 1~12 to 0~11 time_utc.tm_mday = raw_packet->timestamp[2]; time_utc.tm_hour = raw_packet->timestamp[3]; time_utc.tm_min = 0; time_utc.tm_sec = 0; - //uint64_t time_epoch = mktime(&time_utc); - uint64_t time_epoch = timegm(&time_utc); // no timezone - time_epoch = time_epoch * 1000000 + timestamp.stamp_word.high; // to us - time_epoch = time_epoch * 1000; // to ns + // uint64_t time_epoch = mktime(&time_utc); + uint64_t time_epoch = timegm(&time_utc); // no timezone + time_epoch = time_epoch * 1000000 + timestamp.stamp_word.high; // to us + time_epoch = time_epoch * 1000; // to ns return time_epoch; } else { @@ -83,8 +81,10 @@ uint64_t GetStoragePacketTimestamp(StoragePacket *packet, uint8_t data_src_) { } } -uint32_t CalculatePacketQueueSize(uint32_t interval_ms, uint32_t data_type) { - uint32_t queue_size = (interval_ms * GetPacketNumPerSec(data_type)) / 1000; +uint32_t CalculatePacketQueueSize(uint32_t interval_ms, uint8_t product_type, + uint8_t data_type) { + uint32_t queue_size = + (interval_ms * GetPacketNumPerSec(product_type, data_type)) / 1000; if (queue_size < kMinEthPacketQueueSize) { queue_size = kMinEthPacketQueueSize; @@ -176,14 +176,15 @@ void PointExtrisincCompensation(PointXyz *dst_point, const PointXyz &src_point, /** Livox point procees for different raw data format * --------------------------------------------*/ uint8_t *LivoxPointToPxyzrtl(uint8_t *point_buf, LivoxEthPacket *eth_packet, - ExtrinsicParameter &extrinsic) { + ExtrinsicParameter &extrinsic, uint32_t line_num) { LivoxPointXyzrtl *dst_point = (LivoxPointXyzrtl *)point_buf; uint32_t points_per_packet = GetPointsPerPacket(eth_packet->data_type); LivoxPoint *raw_point = reinterpret_cast(eth_packet->data); while (points_per_packet) { RawPointConvert((LivoxPointXyzr *)dst_point, raw_point); - if (extrinsic.enable) { + if (extrinsic.enable && IsTripleFloatNoneZero(raw_point->x, + raw_point->y, raw_point->z)) { PointXyz src_point = *((PointXyz *)dst_point); PointExtrisincCompensation((PointXyz *)dst_point, src_point, extrinsic); } @@ -197,8 +198,8 @@ uint8_t *LivoxPointToPxyzrtl(uint8_t *point_buf, LivoxEthPacket *eth_packet, return (uint8_t *)dst_point; } -uint8_t *LivoxRawPointToPxyzrtl(uint8_t *point_buf, LivoxEthPacket *eth_packet, - ExtrinsicParameter &extrinsic) { +static uint8_t *LivoxRawPointToPxyzrtl(uint8_t *point_buf, LivoxEthPacket *eth_packet, + ExtrinsicParameter &extrinsic, uint32_t line_num) { LivoxPointXyzrtl *dst_point = (LivoxPointXyzrtl *)point_buf; uint32_t points_per_packet = GetPointsPerPacket(eth_packet->data_type); LivoxRawPoint *raw_point = @@ -206,7 +207,8 @@ uint8_t *LivoxRawPointToPxyzrtl(uint8_t *point_buf, LivoxEthPacket *eth_packet, while (points_per_packet) { RawPointConvert((LivoxPointXyzr *)dst_point, raw_point); - if (extrinsic.enable) { + if (extrinsic.enable && IsTripleIntNoneZero(raw_point->x, + raw_point->y, raw_point->z)) { PointXyz src_point = *((PointXyz *)dst_point); PointExtrisincCompensation((PointXyz *)dst_point, src_point, extrinsic); } @@ -220,9 +222,9 @@ uint8_t *LivoxRawPointToPxyzrtl(uint8_t *point_buf, LivoxEthPacket *eth_packet, return (uint8_t *)dst_point; } -uint8_t *LivoxSpherPointToPxyzrtl(uint8_t *point_buf, - LivoxEthPacket *eth_packet, - ExtrinsicParameter &extrinsic) { +static uint8_t *LivoxSpherPointToPxyzrtl(uint8_t *point_buf, \ + LivoxEthPacket *eth_packet, ExtrinsicParameter &extrinsic, \ + uint32_t line_num) { LivoxPointXyzrtl *dst_point = (LivoxPointXyzrtl *)point_buf; uint32_t points_per_packet = GetPointsPerPacket(eth_packet->data_type); LivoxSpherPoint *raw_point = @@ -230,7 +232,7 @@ uint8_t *LivoxSpherPointToPxyzrtl(uint8_t *point_buf, while (points_per_packet) { RawPointConvert((LivoxPointXyzr *)dst_point, raw_point); - if (extrinsic.enable) { + if (extrinsic.enable && raw_point->depth) { PointXyz src_point = *((PointXyz *)dst_point); PointExtrisincCompensation((PointXyz *)dst_point, src_point, extrinsic); } @@ -244,9 +246,9 @@ uint8_t *LivoxSpherPointToPxyzrtl(uint8_t *point_buf, return (uint8_t *)dst_point; } -uint8_t *LivoxExtendRawPointToPxyzrtl(uint8_t *point_buf, - LivoxEthPacket *eth_packet, - ExtrinsicParameter &extrinsic) { +static uint8_t *LivoxExtendRawPointToPxyzrtl(uint8_t *point_buf, \ + LivoxEthPacket *eth_packet, ExtrinsicParameter &extrinsic, \ + uint32_t line_num) { LivoxPointXyzrtl *dst_point = (LivoxPointXyzrtl *)point_buf; uint32_t points_per_packet = GetPointsPerPacket(eth_packet->data_type); LivoxExtendRawPoint *raw_point = @@ -255,13 +257,17 @@ uint8_t *LivoxExtendRawPointToPxyzrtl(uint8_t *point_buf, uint8_t line_id = 0; while (points_per_packet) { RawPointConvert((LivoxPointXyzr *)dst_point, (LivoxRawPoint *)raw_point); - if (extrinsic.enable) { + if (extrinsic.enable && IsTripleIntNoneZero(raw_point->x, + raw_point->y, raw_point->z)) { PointXyz src_point = *((PointXyz *)dst_point); PointExtrisincCompensation((PointXyz *)dst_point, src_point, extrinsic); } dst_point->tag = raw_point->tag; - dst_point->line = line_id; - dst_point->line = dst_point->line % 6; + if (line_num > 1) { + dst_point->line = line_id % line_num; + } else { + dst_point->line = 0; + } ++raw_point; ++dst_point; ++line_id; @@ -271,9 +277,9 @@ uint8_t *LivoxExtendRawPointToPxyzrtl(uint8_t *point_buf, return (uint8_t *)dst_point; } -uint8_t *LivoxExtendSpherPointToPxyzrtl(uint8_t *point_buf, - LivoxEthPacket *eth_packet, - ExtrinsicParameter &extrinsic) { +static uint8_t *LivoxExtendSpherPointToPxyzrtl(uint8_t *point_buf, \ + LivoxEthPacket *eth_packet, ExtrinsicParameter &extrinsic, \ + uint32_t line_num) { LivoxPointXyzrtl *dst_point = (LivoxPointXyzrtl *)point_buf; uint32_t points_per_packet = GetPointsPerPacket(eth_packet->data_type); LivoxExtendSpherPoint *raw_point = @@ -282,13 +288,16 @@ uint8_t *LivoxExtendSpherPointToPxyzrtl(uint8_t *point_buf, uint8_t line_id = 0; while (points_per_packet) { RawPointConvert((LivoxPointXyzr *)dst_point, (LivoxSpherPoint *)raw_point); - if (extrinsic.enable) { + if (extrinsic.enable && raw_point->depth) { PointXyz src_point = *((PointXyz *)dst_point); PointExtrisincCompensation((PointXyz *)dst_point, src_point, extrinsic); } dst_point->tag = raw_point->tag; - dst_point->line = line_id; - dst_point->line = dst_point->line % 6; + if (line_num > 1) { + dst_point->line = line_id % line_num; + } else { + dst_point->line = 0; + } ++raw_point; ++dst_point; ++line_id; @@ -298,25 +307,30 @@ uint8_t *LivoxExtendSpherPointToPxyzrtl(uint8_t *point_buf, return (uint8_t *)dst_point; } -uint8_t *LivoxDualExtendRawPointToPxyzrtl(uint8_t *point_buf, - LivoxEthPacket *eth_packet, - ExtrinsicParameter &extrinsic) { +static uint8_t *LivoxDualExtendRawPointToPxyzrtl(uint8_t *point_buf, \ + LivoxEthPacket *eth_packet, ExtrinsicParameter &extrinsic, \ + uint32_t line_num) { LivoxPointXyzrtl *dst_point = (LivoxPointXyzrtl *)point_buf; uint32_t points_per_packet = GetPointsPerPacket(eth_packet->data_type); LivoxExtendRawPoint *raw_point = reinterpret_cast(eth_packet->data); + /* LivoxDualExtendRawPoint = 2*LivoxExtendRawPoint */ + points_per_packet = points_per_packet * 2; uint8_t line_id = 0; while (points_per_packet) { RawPointConvert((LivoxPointXyzr *)dst_point, (LivoxRawPoint *)raw_point); - if (extrinsic.enable) { + if (extrinsic.enable && IsTripleIntNoneZero(raw_point->x, + raw_point->y, raw_point->z)) { PointXyz src_point = *((PointXyz *)dst_point); PointExtrisincCompensation((PointXyz *)dst_point, src_point, extrinsic); } dst_point->tag = raw_point->tag; - dst_point->line = - line_id / 2; /* LivoxDualExtendRawPoint = 2*LivoxExtendRawPoint */ - dst_point->line = dst_point->line % 6; + if (line_num > 1) { + dst_point->line = (line_id / 2) % line_num; + } else { + dst_point->line = 0; + } ++raw_point; ++dst_point; ++line_id; @@ -326,9 +340,9 @@ uint8_t *LivoxDualExtendRawPointToPxyzrtl(uint8_t *point_buf, return (uint8_t *)dst_point; } -uint8_t *LivoxDualExtendSpherPointToPxyzrtl(uint8_t *point_buf, - LivoxEthPacket *eth_packet, - ExtrinsicParameter &extrinsic) { +static uint8_t *LivoxDualExtendSpherPointToPxyzrtl(uint8_t *point_buf, \ + LivoxEthPacket *eth_packet, ExtrinsicParameter &extrinsic, \ + uint32_t line_num) { LivoxPointXyzrtl *dst_point = (LivoxPointXyzrtl *)point_buf; uint32_t points_per_packet = GetPointsPerPacket(eth_packet->data_type); LivoxDualExtendSpherPoint *raw_point = @@ -339,22 +353,119 @@ uint8_t *LivoxDualExtendSpherPointToPxyzrtl(uint8_t *point_buf, RawPointConvert((LivoxPointXyzr *)dst_point, (LivoxPointXyzr *)(dst_point + 1), (LivoxDualExtendSpherPoint *)raw_point); - if (extrinsic.enable) { + if (extrinsic.enable && raw_point->depth1) { + PointXyz src_point = *((PointXyz *)dst_point); + PointExtrisincCompensation((PointXyz *)dst_point, src_point, extrinsic); + } + dst_point->tag = raw_point->tag1; + if (line_num > 1) { + dst_point->line = line_id % line_num; + } else { + dst_point->line = 0; + } + ++dst_point; + + if (extrinsic.enable && raw_point->depth2) { + PointXyz src_point = *((PointXyz *)dst_point); + PointExtrisincCompensation((PointXyz *)dst_point, src_point, extrinsic); + } + dst_point->tag = raw_point->tag2; + if (line_num > 1) { + dst_point->line = line_id % line_num; + } else { + dst_point->line = 0; + } + ++dst_point; + + ++raw_point; /* only increase one */ + ++line_id; + --points_per_packet; + } + + return (uint8_t *)dst_point; +} + +static uint8_t *LivoxTripleExtendRawPointToPxyzrtl(uint8_t *point_buf, \ + LivoxEthPacket *eth_packet, ExtrinsicParameter &extrinsic, \ + uint32_t line_num) { + LivoxPointXyzrtl *dst_point = (LivoxPointXyzrtl *)point_buf; + uint32_t points_per_packet = GetPointsPerPacket(eth_packet->data_type); + LivoxExtendRawPoint *raw_point = + reinterpret_cast(eth_packet->data); + + /* LivoxTripleExtendRawPoint = 3*LivoxExtendRawPoint, echo_num */ + points_per_packet = points_per_packet * 3; + uint8_t line_id = 0; + while (points_per_packet) { + RawPointConvert((LivoxPointXyzr *)dst_point, (LivoxRawPoint *)raw_point); + if (extrinsic.enable && IsTripleIntNoneZero(raw_point->x, + raw_point->y, raw_point->z)) { + PointXyz src_point = *((PointXyz *)dst_point); + PointExtrisincCompensation((PointXyz *)dst_point, src_point, extrinsic); + } + dst_point->tag = raw_point->tag; + if (line_num > 1) { + dst_point->line = (line_id / 3) % line_num; + } else { + dst_point->line = 0; + } + ++raw_point; + ++dst_point; + ++line_id; + --points_per_packet; + } + + return (uint8_t *)dst_point; +} + +static uint8_t *LivoxTripleExtendSpherPointToPxyzrtl(uint8_t *point_buf, \ + LivoxEthPacket *eth_packet, ExtrinsicParameter &extrinsic, \ + uint32_t line_num) { + LivoxPointXyzrtl *dst_point = (LivoxPointXyzrtl *)point_buf; + uint32_t points_per_packet = GetPointsPerPacket(eth_packet->data_type); + LivoxTripleExtendSpherPoint *raw_point = + reinterpret_cast(eth_packet->data); + + uint8_t line_id = 0; + while (points_per_packet) { + RawPointConvert((LivoxPointXyzr *)dst_point, + (LivoxPointXyzr *)(dst_point + 1), + (LivoxPointXyzr *)(dst_point + 2), + (LivoxTripleExtendSpherPoint *)raw_point); + if (extrinsic.enable && raw_point->depth1) { PointXyz src_point = *((PointXyz *)dst_point); PointExtrisincCompensation((PointXyz *)dst_point, src_point, extrinsic); } dst_point->tag = raw_point->tag1; - dst_point->line = line_id; - dst_point->line = dst_point->line % 6; + if (line_num > 1) { + dst_point->line = line_id % line_num; + } else { + dst_point->line = 0; + } ++dst_point; - if (extrinsic.enable) { + if (extrinsic.enable && raw_point->depth2) { PointXyz src_point = *((PointXyz *)dst_point); PointExtrisincCompensation((PointXyz *)dst_point, src_point, extrinsic); } dst_point->tag = raw_point->tag2; - dst_point->line = line_id; - dst_point->line = dst_point->line % 6; + if (line_num > 1) { + dst_point->line = line_id % line_num; + } else { + dst_point->line = 0; + } + ++dst_point; + + if (extrinsic.enable && raw_point->depth3) { + PointXyz src_point = *((PointXyz *)dst_point); + PointExtrisincCompensation((PointXyz *)dst_point, src_point, extrinsic); + } + dst_point->tag = raw_point->tag3; + if (line_num > 1) { + dst_point->line = line_id % line_num; + } else { + dst_point->line = 0; + } ++dst_point; ++raw_point; /* only increase one */ @@ -377,7 +488,10 @@ const PointConvertHandler to_pxyzi_handler_table[kMaxPointDataType] = { LivoxExtendSpherPointToPxyzrtl, LivoxDualExtendRawPointToPxyzrtl, LivoxDualExtendSpherPointToPxyzrtl, - nullptr}; + nullptr, + LivoxTripleExtendRawPointToPxyzrtl, + LivoxTripleExtendSpherPointToPxyzrtl + }; PointConvertHandler GetConvertHandler(uint8_t data_type) { if (data_type < kMaxPointDataType) @@ -386,22 +500,11 @@ PointConvertHandler GetConvertHandler(uint8_t data_type) { return nullptr; } -uint8_t *FillZeroPointXyzrtl(uint8_t *point_buf, uint32_t num) { - LivoxPointXyzrtl *dst_point = (LivoxPointXyzrtl *)point_buf; - uint32_t points_per_packet = num; - - while (points_per_packet) { - dst_point->x = 0; - dst_point->y = 0; - dst_point->z = 0; - dst_point->reflectivity = 0; - dst_point->tag = 0; - dst_point->line = 0; - ++dst_point; - --points_per_packet; - } - - return (uint8_t *)dst_point; +void ZeroPointDataOfStoragePacket(StoragePacket* storage_packet) { + LivoxEthPacket *raw_packet = + reinterpret_cast(storage_packet->raw_data); + uint32_t point_length = GetPointLen(raw_packet->data_type); + memset(raw_packet->data, 0, point_length * storage_packet->point_num); } #if 0 @@ -415,14 +518,11 @@ static void PointCloudConvert(LivoxPoint *p_dpoint, LivoxRawPoint *p_raw_point) #endif -/* Member function ------ - * ----------------------------------------------------------------------- */ - -Lds::Lds(uint32_t buffer_time_ms, uint8_t data_src) - : buffer_time_ms_(buffer_time_ms), data_src_(data_src) { - lidar_count_ = kMaxSourceLidar; - request_exit_ = false; - ResetLds(data_src_); +/* Member function --------------------------------------------------------- */ +Lds::Lds(uint32_t buffer_time_ms, uint8_t data_src) : \ + lidar_count_(kMaxSourceLidar), semaphore_(0), \ + buffer_time_ms_(buffer_time_ms), data_src_(data_src), request_exit_(false) { + ResetLds(data_src_); }; Lds::~Lds() { @@ -455,6 +555,31 @@ void Lds::ResetLds(uint8_t data_src) { } } +void Lds::RequestExit() { + request_exit_ = true; +} + +bool Lds::IsAllQueueEmpty() { + for (int i = 0; i < lidar_count_; i++) { + if (!QueueIsEmpty(&lidars_[i].data)) { + return false; + } + } + + return true; +} + +bool Lds::IsAllQueueReadStop() { + for (int i = 0; i < lidar_count_; i++) { + uint32_t data_size = QueueUsedSize(&lidars_[i].data); + if (data_size && (data_size > lidars_[i].onetime_publish_packets)) { + return false; + } + } + + return true; +} + uint8_t Lds::GetDeviceType(uint8_t handle) { if (handle < kMaxSourceLidar) { return lidars_[handle].info.type; @@ -463,6 +588,92 @@ uint8_t Lds::GetDeviceType(uint8_t handle) { } } +void Lds::UpdateLidarInfoByEthPacket(LidarDevice *p_lidar, \ + LivoxEthPacket* eth_packet) { + if (p_lidar->raw_data_type != eth_packet->data_type) { + p_lidar->raw_data_type = eth_packet->data_type; + p_lidar->packet_interval = GetPacketInterval(p_lidar->info.type, \ + eth_packet->data_type); + p_lidar->packet_interval_max = p_lidar->packet_interval * 1.8f; + p_lidar->onetime_publish_packets = \ + GetPacketNumPerSec(p_lidar->info.type, \ + p_lidar->raw_data_type) * buffer_time_ms_ / 1000; + printf("DataType[%d] PacketInterval[%d] PublishPackets[%d]\n", \ + p_lidar->raw_data_type, p_lidar->packet_interval, \ + p_lidar->onetime_publish_packets); + } +} + +void Lds::StorageRawPacket(uint8_t handle, LivoxEthPacket* eth_packet) { + LidarDevice *p_lidar = &lidars_[handle]; + LidarPacketStatistic *packet_statistic = &p_lidar->statistic_info; + LdsStamp cur_timestamp; + memcpy(cur_timestamp.stamp_bytes, eth_packet->timestamp, + sizeof(cur_timestamp)); + + if (kImu != eth_packet->data_type) { + UpdateLidarInfoByEthPacket(p_lidar, eth_packet); + if (eth_packet->timestamp_type == kTimestampTypePps) { + /** Whether a new sync frame */ + if ((cur_timestamp.stamp < packet_statistic->last_timestamp) && + (cur_timestamp.stamp < kPacketTimeGap)) { + auto cur_time = std::chrono::high_resolution_clock::now(); + int64_t sync_time = cur_time.time_since_epoch().count(); + /** used receive time as timebase */ + packet_statistic->timebase = sync_time; + } + } + packet_statistic->last_timestamp = cur_timestamp.stamp; + + LidarDataQueue *p_queue = &p_lidar->data; + if (nullptr == p_queue->storage_packet) { + uint32_t queue_size = CalculatePacketQueueSize( + buffer_time_ms_, p_lidar->info.type, eth_packet->data_type); + queue_size = queue_size * 8; /* 8 multiple the min size */ + InitQueue(p_queue, queue_size); + printf("Lidar%02d[%s] queue size : %d %d\n", p_lidar->handle, + p_lidar->info.broadcast_code, queue_size, p_queue->size); + } + if (!QueueIsFull(p_queue)) { + QueuePushAny(p_queue, (uint8_t *)eth_packet, \ + GetEthPacketLen(eth_packet->data_type), \ + packet_statistic->timebase, \ + GetPointsPerPacket(eth_packet->data_type)); + if (QueueUsedSize(p_queue) > p_lidar->onetime_publish_packets) { + if (semaphore_.GetCount() <= 0) { + semaphore_.Signal(); + } + } + } + } else { + if (eth_packet->timestamp_type == kTimestampTypePps) { + /** Whether a new sync frame */ + if ((cur_timestamp.stamp < packet_statistic->last_imu_timestamp) && + (cur_timestamp.stamp < kPacketTimeGap)) { + auto cur_time = std::chrono::high_resolution_clock::now(); + int64_t sync_time = cur_time.time_since_epoch().count(); + /** used receive time as timebase */ + packet_statistic->imu_timebase = sync_time; + } + } + packet_statistic->last_imu_timestamp = cur_timestamp.stamp; + + LidarDataQueue *p_queue = &p_lidar->imu_data; + if (nullptr == p_queue->storage_packet) { + uint32_t queue_size = 256; /* fixed imu data queue size */ + InitQueue(p_queue, queue_size); + printf("Lidar%02d[%s] imu queue size : %d %d\n", p_lidar->handle, + p_lidar->info.broadcast_code, queue_size, p_queue->size); + } + if (!QueueIsFull(p_queue)) { + QueuePushAny(p_queue, (uint8_t *)eth_packet, \ + GetEthPacketLen(eth_packet->data_type),\ + packet_statistic->imu_timebase, \ + GetPointsPerPacket(eth_packet->data_type)); + } + } +} + void Lds::PrepareExit(void) {} -} // namespace livox_ros +} // namespace livox_ros diff --git a/livox_ros_driver/livox_ros_driver/lds.h b/livox_ros_driver/livox_ros_driver/lds.h index 8363468..0bc0243 100644 --- a/livox_ros_driver/livox_ros_driver/lds.h +++ b/livox_ros_driver/livox_ros_driver/lds.h @@ -33,6 +33,8 @@ #include #include #include +#include +#include #include "ldq.h" @@ -55,10 +57,10 @@ const uint32_t KCartesianPointSize = 13; const uint32_t KSphericalPointSzie = 9; const int64_t kPacketTimeGap = 1000000; /**< 1ms = 1000000ns */ -const int64_t kMaxPacketTimeGap = - 1700000; /**< the threshold of packet continuous */ -const int64_t kDeviceDisconnectThreshold = - 1000000000; /**< the threshold of device disconect */ +/**< the threshold of packet continuous */ +const int64_t kMaxPacketTimeGap = 1700000; +/**< the threshold of device disconect */ +const int64_t kDeviceDisconnectThreshold = 1000000000; const int64_t kNsPerSecond = 1000000000; /**< 1s = 1000000000ns */ const int kPathStrMinSize = 4; /**< Must more than 4 char */ @@ -98,9 +100,9 @@ typedef enum { kConfigFan = 1 << 0, kConfigReturnMode = 1 << 1, kConfigCoordinate = 1 << 2, - kConfigImuRate = 1 << 3, + kConfigImuRate = 1 << 3, kConfigGetExtrinsicParameter = 1 << 4, - kConfigSetHighSensitivity = 1 << 5, + kConfigSetHighSensitivity = 1 << 5, kConfigUndef } LidarConfigCodeBit; @@ -167,15 +169,17 @@ typedef struct { /** Lidar data source info abstract */ typedef struct { - uint8_t handle; /**< Lidar access handle. */ - uint8_t data_src; /**< From raw lidar or livox file. */ - uint8_t raw_data_type; /**< The data type in eth packaet */ - bool data_is_pubulished; /**< Indicate the data of lidar whether is - pubulished. */ - volatile uint32_t packet_interval;/**< The time interval between packets - of current lidar, unit:ns */ + uint8_t handle; /**< Lidar access handle. */ + uint8_t data_src; /**< From raw lidar or livox file. */ + uint8_t raw_data_type; /**< The data type in eth packaet */ + bool data_is_pubulished; /**< Indicate the data of lidar whether is + pubulished. */ + volatile uint32_t packet_interval; /**< The time interval between packets + of current lidar, unit:ns */ volatile uint32_t packet_interval_max; /**< If more than it, - have packet loss */ + have packet loss */ + /**< packet num that onetime published */ + volatile uint32_t onetime_publish_packets; volatile LidarConnectState connect_state; DeviceInfo info; LidarPacketStatistic statistic_info; @@ -187,12 +191,17 @@ typedef struct { } LidarDevice; typedef struct { - uint32_t points_per_packet; - uint32_t points_per_second; - uint32_t point_interval; /**< unit:ns */ - uint32_t packet_interval; /**< unit:ns */ - uint32_t packet_length; -} PacketInfoPair; + uint32_t points_per_packet; /**< number of points every packet */ + uint32_t packet_length; /**< length of raw ethenet packet unit:bytes */ + uint32_t raw_point_length; /**< length of point uint:bytes */ + uint32_t echo_num; /**< echo number of current data */ +} DataTypePointInfoPair; + +typedef struct { + uint32_t points_per_second; /**< number of points per second */ + uint32_t point_interval; /**< unit:ns */ + uint32_t line_num; /**< laser line number */ +} ProductTypePointInfoPair; #pragma pack(1) @@ -220,52 +229,90 @@ typedef struct { #pragma pack() -typedef uint8_t *(*PointConvertHandler)(uint8_t *point_buf, - LivoxEthPacket *eth_packet, - ExtrinsicParameter &extrinsic); - -const PacketInfoPair packet_info_pair_table[kMaxPointDataType] = { - {100, 100000, 10000, 1000000, 1318}, {100, 100000, 10000, 1000000, 918}, - {96, 240000, 4167, 400000, 1362}, {96, 240000, 4167, 400000, 978}, - {96, 480000, 4167, 400000, 1362}, {48, 480000, 4167, 400000, 978}, - {1, 200, 10000000, 10000000, 42}}; +typedef uint8_t *(*PointConvertHandler)(uint8_t *point_buf, \ + LivoxEthPacket *eth_packet, ExtrinsicParameter &extrinsic, \ + uint32_t line_num); + +const DataTypePointInfoPair data_type_info_pair_table[kMaxPointDataType] = { + {100, 1318, sizeof(LivoxRawPoint), 1}, + {100, 918, 9, 1}, + {96, 1362, 14, 1}, + {96, 978, 9, 1}, + {48, 1362, sizeof(LivoxDualExtendRawPoint), 2}, + {48, 786, sizeof(LivoxDualExtendSpherPoint), 2}, + {1, 42, sizeof(LivoxImuPoint), 1}, + {30, 1278, sizeof(LivoxTripleExtendRawPoint), 3}, + {30, 678, sizeof(LivoxTripleExtendSpherPoint), 3}}; + +const uint32_t kMaxProductType = 9; +const uint32_t kDeviceTypeLidarMid70 = 6; +const ProductTypePointInfoPair product_type_info_pair_table[kMaxProductType] = { + {100000, 10000, 1}, + {100000, 10000, 1}, + {240000, 4167 , 6}, /**< tele */ + {240000, 4167 , 6}, + {100000, 10000, 1}, + {100000, 10000, 1}, + {100000, 10000, 1}, /**< mid70 */ + {240000, 4167, 6}, + {240000, 4167, 6}, +}; /** * Global function for general use. */ bool IsFilePathValid(const char *path_str); -uint64_t GetStoragePacketTimestamp(StoragePacket *packet, uint8_t data_src_); -uint32_t CalculatePacketQueueSize(uint32_t interval_ms, uint32_t data_type); +uint64_t GetStoragePacketTimestamp(StoragePacket *packet, uint8_t data_src); +uint32_t CalculatePacketQueueSize(uint32_t interval_ms, uint8_t product_type, + uint8_t data_type); void ParseCommandlineInputBdCode(const char *cammandline_str, std::vector &bd_code_list); PointConvertHandler GetConvertHandler(uint8_t data_type); uint8_t *LivoxPointToPxyzrtl(uint8_t *point_buf, LivoxEthPacket *eth_packet, - ExtrinsicParameter &extrinsic); -uint8_t *FillZeroPointXyzrtl(uint8_t *point_buf, uint32_t num); + ExtrinsicParameter &extrinsic, uint32_t line_num); +void ZeroPointDataOfStoragePacket(StoragePacket* storage_packet); uint8_t *LivoxImuDataProcess(uint8_t *point_buf, LivoxEthPacket *eth_packet); void EulerAnglesToRotationMatrix(EulerAngle euler, RotationMatrix matrix); void PointExtrisincCompensation(PointXyz *dst_point, ExtrinsicParameter &extrinsic); -inline uint32_t GetPointInterval(uint32_t data_type) { - return packet_info_pair_table[data_type].point_interval; +inline uint32_t GetPointInterval(uint32_t product_type) { + return product_type_info_pair_table[product_type].point_interval; } -inline uint32_t GetPacketNumPerSec(uint32_t data_type) { - return packet_info_pair_table[data_type].points_per_second / - packet_info_pair_table[data_type].points_per_packet; +// inline uint32_t GetPacketNumPerSec(uint32_t data_type) { +// return packet_info_pair_table[data_type].points_per_second / +// packet_info_pair_table[data_type].points_per_packet; +//} + +inline uint32_t GetPacketNumPerSec(uint32_t product_type, uint32_t data_type) { + return product_type_info_pair_table[product_type].points_per_second / + data_type_info_pair_table[data_type].points_per_packet; } -inline uint32_t GetPointsPerPacket(uint32_t data_type) { - return packet_info_pair_table[data_type].points_per_packet; +inline uint32_t GetPacketInterval(uint32_t product_type, uint32_t data_type) { + return product_type_info_pair_table[product_type].point_interval * + data_type_info_pair_table[data_type].points_per_packet; +} + +inline uint32_t GetLaserLineNumber(uint32_t product_type) { + return product_type_info_pair_table[product_type].line_num; } -inline uint32_t GetPacketInterval(uint32_t data_type) { - return packet_info_pair_table[data_type].packet_interval; +inline uint32_t GetPointsPerPacket(uint32_t data_type) { + return data_type_info_pair_table[data_type].points_per_packet; } inline uint32_t GetEthPacketLen(uint32_t data_type) { - return packet_info_pair_table[data_type].packet_length; + return data_type_info_pair_table[data_type].packet_length; +} + +inline uint32_t GetPointLen(uint32_t data_type) { + return data_type_info_pair_table[data_type].raw_point_length; +} + +inline uint32_t GetEchoNumPerPoint(uint32_t data_type) { + return data_type_info_pair_table[data_type].echo_num; } inline void RawPointConvert(LivoxPointXyzr *dst_point, LivoxPoint *raw_point) { @@ -306,39 +353,104 @@ inline void RawPointConvert(LivoxPointXyzr *dst_point1, dst_point1->z = radius1 * cos(theta); dst_point1->reflectivity = (float)raw_point->reflectivity1; - (dst_point2 + 1)->x = radius2 * sin(theta) * cos(phi); - (dst_point2 + 1)->y = radius2 * sin(theta) * sin(phi); - (dst_point2 + 1)->z = radius2 * cos(theta); - (dst_point2 + 1)->reflectivity = (float)raw_point->reflectivity2; + dst_point2->x = radius2 * sin(theta) * cos(phi); + dst_point2->y = radius2 * sin(theta) * sin(phi); + dst_point2->z = radius2 * cos(theta); + dst_point2->reflectivity = (float)raw_point->reflectivity2; +} + +inline void RawPointConvert(LivoxPointXyzr *dst_point1, + LivoxPointXyzr *dst_point2, + LivoxPointXyzr *dst_point3, + LivoxTripleExtendSpherPoint *raw_point) { + double radius1 = raw_point->depth1 / 1000.0; + double radius2 = raw_point->depth2 / 1000.0; + double radius3 = raw_point->depth3 / 1000.0; + double theta = raw_point->theta / 100.0 / 180 * PI; + double phi = raw_point->phi / 100.0 / 180 * PI; + dst_point1->x = radius1 * sin(theta) * cos(phi); + dst_point1->y = radius1 * sin(theta) * sin(phi); + dst_point1->z = radius1 * cos(theta); + dst_point1->reflectivity = (float)raw_point->reflectivity1; + + dst_point2->x = radius2 * sin(theta) * cos(phi); + dst_point2->y = radius2 * sin(theta) * sin(phi); + dst_point2->z = radius2 * cos(theta); + dst_point2->reflectivity = (float)raw_point->reflectivity2; + + dst_point3->x = radius3 * sin(theta) * cos(phi); + dst_point3->y = radius3 * sin(theta) * sin(phi); + dst_point3->z = radius3 * cos(theta); + dst_point3->reflectivity = (float)raw_point->reflectivity3; +} + +inline bool IsTripleIntNoneZero(int32_t x, int32_t y, int32_t z) { + return (x | y | z); +} + +inline bool IsTripleFloatNoneZero(float x, float y, float z) { + return ((x != 0.0f) || (y != 0.0f) || (z != 0.0f)); } +class Semaphore { + public: + explicit Semaphore(int count = 0) : count_(count) { + } + + void Signal() { + std::unique_lock lock(mutex_); + ++count_; + cv_.notify_one(); + } + + void Wait() { + std::unique_lock lock(mutex_); + cv_.wait(lock, [=] { return count_ > 0; }); + --count_; + } + + int GetCount() { + return count_; + } + + private: + std::mutex mutex_; + std::condition_variable cv_; + volatile int count_; +}; + /** * Lidar data source abstract. */ class Lds { -public: + public: Lds(uint32_t buffer_time_ms, uint8_t data_src); virtual ~Lds(); + void StorageRawPacket(uint8_t handle, LivoxEthPacket* eth_packet); uint8_t GetDeviceType(uint8_t handle); static void ResetLidar(LidarDevice *lidar, uint8_t data_src); static void SetLidarDataSrc(LidarDevice *lidar, uint8_t data_src); void ResetLds(uint8_t data_src); - void RequestExit() { request_exit_ = true; } + void RequestExit(); + bool IsAllQueueEmpty(); + bool IsAllQueueReadStop(); void CleanRequestExit() { request_exit_ = false; } bool IsRequestExit() { return request_exit_; } virtual void PrepareExit(void); - + void UpdateLidarInfoByEthPacket(LidarDevice *p_lidar, \ + LivoxEthPacket* eth_packet); uint8_t lidar_count_; /**< Lidar access handle. */ LidarDevice lidars_[kMaxSourceLidar]; /**< The index is the handle */ + Semaphore semaphore_; -protected: + protected: uint32_t buffer_time_ms_; /**< Buffer time before data in queue is read */ uint8_t data_src_; -private: + private: volatile bool request_exit_; }; -} // namespace livox_ros +} // namespace livox_ros #endif diff --git a/livox_ros_driver/livox_ros_driver/lds_hub.cpp b/livox_ros_driver/livox_ros_driver/lds_hub.cpp index 3a8dea1..f43b5f7 100644 --- a/livox_ros_driver/livox_ros_driver/lds_hub.cpp +++ b/livox_ros_driver/livox_ros_driver/lds_hub.cpp @@ -24,9 +24,9 @@ #include "lds_hub.h" -#include #include #include +#include #include #include "rapidjson/document.h" @@ -35,18 +35,14 @@ namespace livox_ros { -/** Const varible - * ------------------------------------------------------------------------------- - */ +/** Const varible ------------------------------------------------------------*/ /** For callback use only */ static LdsHub *g_lds_hub = nullptr; -/** Global function for common use - * ---------------------------------------------------------------*/ +/** Global function for common use -------------------------------------------*/ -/** Lds hub function - * -----------------------------------------------------------------------------*/ +/** Lds hub function ---------------------------------------------------------*/ LdsHub::LdsHub(uint32_t interval_ms) : Lds(interval_ms, kSourceRawHub) { auto_connect_mode_ = true; whitelist_count_ = 0; @@ -67,7 +63,6 @@ void LdsHub::ResetLdsHub(void) { int LdsHub::InitLdsHub(std::vector &broadcast_code_strs, const char *user_config_path) { - if (is_initialized_) { printf("LiDAR data source is already inited!\n"); return -1; @@ -104,8 +99,9 @@ int LdsHub::InitLdsHub(std::vector &broadcast_code_strs, } } else { EnableAutoConnectMode(); - printf("No broadcast code was added to whitelist, swith to automatic " - "connection mode!\n"); + printf( + "No broadcast code was added to whitelist, swith to automatic " + "connection mode!\n"); } /** Start livox sdk to receive lidar data */ @@ -126,7 +122,6 @@ int LdsHub::InitLdsHub(std::vector &broadcast_code_strs, } int LdsHub::DeInitLdsHub(void) { - if (!is_initialized_) { printf("LiDAR data source is not exit"); return -1; @@ -149,81 +144,14 @@ void LdsHub::OnHubDataCb(uint8_t hub_handle, LivoxEthPacket *data, if (!data || !data_num) { return; } + /** Caculate which lidar the eth packet data belong to */ uint8_t handle = HubGetLidarHandle(eth_packet->slot, eth_packet->id); if (handle >= kMaxLidarCount) { return; } - LidarDevice *p_lidar = &lds_hub->lidars_[handle]; - LidarPacketStatistic *packet_statistic = &p_lidar->statistic_info; - LdsStamp cur_timestamp; - memcpy(cur_timestamp.stamp_bytes, eth_packet->timestamp, - sizeof(cur_timestamp)); - - if (kImu != eth_packet->data_type) { - if (p_lidar->raw_data_type != eth_packet->data_type) { - p_lidar->raw_data_type = eth_packet->data_type; - p_lidar->packet_interval = GetPacketInterval(eth_packet->data_type); - p_lidar->packet_interval_max = p_lidar->packet_interval * 1.8f; - - } - - if (eth_packet->timestamp_type == kTimestampTypePps) { - /** Whether a new sync frame */ - if ((cur_timestamp.stamp < packet_statistic->last_timestamp) && - (cur_timestamp.stamp < kPacketTimeGap)) { - auto cur_time = std::chrono::high_resolution_clock::now(); - int64_t sync_time = cur_time.time_since_epoch().count(); - /** used receive time as timebase */ - packet_statistic->timebase = sync_time; - } - } - packet_statistic->last_timestamp = cur_timestamp.stamp; - - LidarDataQueue *p_queue = &p_lidar->data; - if (nullptr == p_queue->storage_packet) { - uint32_t queue_size = CalculatePacketQueueSize(lds_hub->buffer_time_ms_, - eth_packet->data_type); - queue_size = queue_size * 16; /* 16 multiple the min size */ - InitQueue(p_queue, queue_size); - printf("Lidar%02d[%s] queue size : %d %d\n", p_lidar->handle, - p_lidar->info.broadcast_code, queue_size, p_queue->size); - } - if (!QueueIsFull(p_queue)) { - QueuePushAny(p_queue, (uint8_t *)eth_packet, - GetEthPacketLen(eth_packet->data_type), - packet_statistic->timebase, - GetPointsPerPacket(eth_packet->data_type)); - } - } else { - if (eth_packet->timestamp_type == kTimestampTypePps) { - /** Whether a new sync frame */ - if ((cur_timestamp.stamp < packet_statistic->last_imu_timestamp) && - (cur_timestamp.stamp < kPacketTimeGap)) { - auto cur_time = std::chrono::high_resolution_clock::now(); - int64_t sync_time = cur_time.time_since_epoch().count(); - /** used receive time as timebase */ - packet_statistic->imu_timebase = sync_time; - } - } - packet_statistic->last_imu_timestamp = cur_timestamp.stamp; - - LidarDataQueue *p_queue = &p_lidar->imu_data; - if (nullptr == p_queue->storage_packet) { - uint32_t queue_size = 256; - InitQueue(p_queue, queue_size); - printf("Lidar%02d[%s] imu queue size : %d %d\n", p_lidar->handle, - p_lidar->info.broadcast_code, queue_size, p_queue->size); - } - - if (!QueueIsFull(p_queue)) { - QueuePushAny(p_queue, (uint8_t *)eth_packet, - GetEthPacketLen(eth_packet->data_type), - packet_statistic->imu_timebase, - GetPointsPerPacket(eth_packet->data_type)); - } - } + lds_hub->StorageRawPacket(handle, eth_packet); } void LdsHub::OnDeviceBroadcast(const BroadcastDeviceInfo *info) { @@ -300,7 +228,8 @@ void LdsHub::OnDeviceChange(const DeviceInfo *info, DeviceEvent type) { printf("Hub[%s] connect on\n", p_hub->info.broadcast_code); } } else if (type == kEventDisconnect) { - p_hub->connect_state = kConnectStateOff; + g_lds_hub->ResetLds(0); + g_lds_hub->ResetLidar(p_hub, 0); printf("Hub[%s] disconnect!\n", info->broadcast_code); } else if (type == kEventStateChange) { p_hub->info = *info; @@ -526,6 +455,7 @@ void LdsHub::ConfigImuPushFrequency(LdsHub *lds_hub) { LidarDevice *p_lidar = &(lds_hub->lidars_[i]); if ((p_lidar->info.type != kDeviceTypeLidarMid40) && + (p_lidar->info.type != kDeviceTypeLidarMid70) && (p_lidar->connect_state == kConnectStateSampling)) { UserRawConfig config; if (lds_hub->GetRawConfig(p_lidar->info.broadcast_code, config)) { @@ -779,4 +709,4 @@ int LdsHub::GetRawConfig(const char *broadcast_code, UserRawConfig &config) { return -1; } -} // namespace livox_ros +} // namespace livox_ros diff --git a/livox_ros_driver/livox_ros_driver/lds_hub.h b/livox_ros_driver/livox_ros_driver/lds_hub.h index bcc339b..71b0ccc 100644 --- a/livox_ros_driver/livox_ros_driver/lds_hub.h +++ b/livox_ros_driver/livox_ros_driver/lds_hub.h @@ -39,7 +39,7 @@ namespace livox_ros { * LiDAR data source, data from hub. */ class LdsHub : public Lds { -public: + public: static LdsHub *GetInstance(uint32_t interval_ms) { static LdsHub lds_hub(interval_ms); return &lds_hub; @@ -49,7 +49,7 @@ class LdsHub : public Lds { const char *user_config_path); int DeInitLdsHub(void); -private: + private: LdsHub(uint32_t interval_ms); LdsHub(const LdsHub &) = delete; ~LdsHub(); @@ -69,16 +69,14 @@ class LdsHub : public Lds { void *client_data); static void ControlFanCb(livox_status status, uint8_t handle, uint8_t response, void *clent_data); - static void - HubSetPointCloudReturnModeCb(livox_status status, uint8_t handle, - HubSetPointCloudReturnModeResponse *response, - void *clent_data); + static void HubSetPointCloudReturnModeCb( + livox_status status, uint8_t handle, + HubSetPointCloudReturnModeResponse *response, void *clent_data); static void SetCoordinateCb(livox_status status, uint8_t handle, uint8_t response, void *clent_data); - static void - HubSetImuRatePushFrequencyCb(livox_status status, uint8_t handle, - HubSetImuPushFrequencyResponse *response, - void *clent_data); + static void HubSetImuRatePushFrequencyCb( + livox_status status, uint8_t handle, + HubSetImuPushFrequencyResponse *response, void *clent_data); static void HubErrorStatusCb(livox_status status, uint8_t handle, ErrorMessage *message); static void ConfigPointCloudReturnMode(LdsHub *lds_hub); @@ -118,5 +116,5 @@ class LdsHub : public Lds { UserRawConfig hub_raw_config_; }; -} // namespace livox_ros +} // namespace livox_ros #endif diff --git a/livox_ros_driver/livox_ros_driver/lds_lidar.cpp b/livox_ros_driver/livox_ros_driver/lds_lidar.cpp index e76117b..09c6362 100644 --- a/livox_ros_driver/livox_ros_driver/lds_lidar.cpp +++ b/livox_ros_driver/livox_ros_driver/lds_lidar.cpp @@ -27,8 +27,8 @@ #include #include #include -#include #include +#include #include "rapidjson/document.h" #include "rapidjson/filereadstream.h" @@ -38,17 +38,13 @@ using namespace std; namespace livox_ros { -/** Const varible - * ------------------------------------------------------------------------------- - */ +/** Const varible ------------------------------------------------------------*/ /** For callback use only */ LdsLidar *g_lds_ldiar = nullptr; -/** Global function for common use - * ---------------------------------------------------------------*/ +/** Global function for common use -------------------------------------------*/ -/** Lds lidar function - * ---------------------------------------------------------------------------*/ +/** Lds lidar function -------------------------------------------------------*/ LdsLidar::LdsLidar(uint32_t interval_ms) : Lds(interval_ms, kSourceRawLidar) { auto_connect_mode_ = true; is_initialized_ = false; @@ -101,8 +97,9 @@ int LdsLidar::InitLdsLidar(std::vector &broadcast_code_strs, } } else { EnableAutoConnectMode(); - printf("No broadcast code was added to whitelist, swith to automatic " - "connection mode!\n"); + printf( + "No broadcast code was added to whitelist, swith to automatic " + "connection mode!\n"); } if (enable_timesync_) { @@ -138,7 +135,6 @@ int LdsLidar::InitLdsLidar(std::vector &broadcast_code_strs, } int LdsLidar::DeInitLdsLidar(void) { - if (!is_initialized_) { printf("LiDAR data source is not exit"); return -1; @@ -156,8 +152,7 @@ int LdsLidar::DeInitLdsLidar(void) { void LdsLidar::PrepareExit(void) { DeInitLdsLidar(); } -/** Static function in LdsLidar for callback or event process - * ------------------------------------*/ +/** Static function in LdsLidar for callback or event process ----------------*/ /** Receiving point cloud data from Livox LiDAR. */ void LdsLidar::OnLidarDataCb(uint8_t handle, LivoxEthPacket *data, @@ -171,76 +166,7 @@ void LdsLidar::OnLidarDataCb(uint8_t handle, LivoxEthPacket *data, return; } - LidarDevice *p_lidar = &lds_lidar->lidars_[handle]; - LidarPacketStatistic *packet_statistic = &p_lidar->statistic_info; - LdsStamp cur_timestamp; - memcpy(cur_timestamp.stamp_bytes, eth_packet->timestamp, - sizeof(cur_timestamp)); - - if (kImu != eth_packet->data_type) { - if (p_lidar->raw_data_type != eth_packet->data_type) { - p_lidar->raw_data_type = eth_packet->data_type; - p_lidar->packet_interval = GetPacketInterval(eth_packet->data_type); - p_lidar->packet_interval_max = p_lidar->packet_interval * 1.8f; - } - - if (eth_packet->timestamp_type == kTimestampTypePps) { - if ((cur_timestamp.stamp < packet_statistic->last_timestamp) && - (cur_timestamp.stamp < kPacketTimeGap)) { // whether a new sync frame - - auto cur_time = std::chrono::high_resolution_clock::now(); - int64_t sync_time = cur_time.time_since_epoch().count(); - - packet_statistic->timebase = sync_time; // used receive time as timebase - } - } - packet_statistic->last_timestamp = cur_timestamp.stamp; - - LidarDataQueue *p_queue = &p_lidar->data; - if (nullptr == p_queue->storage_packet) { - uint32_t queue_size = CalculatePacketQueueSize(lds_lidar->buffer_time_ms_, - eth_packet->data_type); - queue_size = queue_size * 16; /* 16 multiple the min size */ - InitQueue(p_queue, queue_size); - printf("Lidar%02d[%s] queue size : %d %d\n", p_lidar->handle, - p_lidar->info.broadcast_code, queue_size, p_queue->size); - } - - if (!QueueIsFull(p_queue)) { - QueuePushAny(p_queue, (uint8_t *)eth_packet, - GetEthPacketLen(eth_packet->data_type), - packet_statistic->timebase, - GetPointsPerPacket(eth_packet->data_type)); - } - } else { - if (eth_packet->timestamp_type == kTimestampTypePps) { - if ((cur_timestamp.stamp < packet_statistic->last_imu_timestamp) && - (cur_timestamp.stamp < kPacketTimeGap)) { // whether a new sync frame - - auto cur_time = std::chrono::high_resolution_clock::now(); - int64_t sync_time = cur_time.time_since_epoch().count(); - - packet_statistic->imu_timebase = - sync_time; // used receive time as timebase - } - } - packet_statistic->last_imu_timestamp = cur_timestamp.stamp; - - LidarDataQueue *p_queue = &p_lidar->imu_data; - if (nullptr == p_queue->storage_packet) { - uint32_t queue_size = 256; - InitQueue(p_queue, queue_size); - printf("Lidar%02d[%s] imu queue size : %d %d\n", p_lidar->handle, - p_lidar->info.broadcast_code, queue_size, p_queue->size); - } - - if (!QueueIsFull(p_queue)) { - QueuePushAny(p_queue, (uint8_t *)eth_packet, - GetEthPacketLen(eth_packet->data_type), - packet_statistic->timebase, - GetPointsPerPacket(eth_packet->data_type)); - } - } + lds_lidar->StorageRawPacket(handle, eth_packet); } void LdsLidar::OnDeviceBroadcast(const BroadcastDeviceInfo *info) { @@ -292,8 +218,7 @@ void LdsLidar::OnDeviceBroadcast(const BroadcastDeviceInfo *info) { p_lidar->config.imu_rate = config.imu_rate; p_lidar->config.extrinsic_parameter_source = config.extrinsic_parameter_source; - p_lidar->config.enable_high_sensitivity = - config.enable_high_sensitivity; + p_lidar->config.enable_high_sensitivity = config.enable_high_sensitivity; } else { printf("Add lidar to connect is failed : %d %d \n", result, handle); } @@ -335,7 +260,7 @@ void LdsLidar::OnDeviceChange(const DeviceInfo *info, DeviceEvent type) { if (p_lidar->info.state == kLidarStateNormal) { /** Ensure the thread safety for set_bits and connect_state */ lock_guard lock(g_lds_ldiar->config_mutex_); - + if (p_lidar->config.coordinate != 0) { SetSphericalCoordinate(handle, SetCoordinateCb, g_lds_ldiar); } else { @@ -350,7 +275,8 @@ void LdsLidar::OnDeviceChange(const DeviceInfo *info, DeviceEvent type) { p_lidar->config.set_bits |= kConfigReturnMode; } - if (kDeviceTypeLidarMid40 != info->type) { + if ((kDeviceTypeLidarMid70 != info->type) && + (kDeviceTypeLidarMid40 != info->type)) { LidarSetImuPushFrequency(handle, (ImuFreq)(p_lidar->config.imu_rate), SetImuRatePushFrequencyCb, g_lds_ldiar); p_lidar->config.set_bits |= kConfigImuRate; @@ -365,8 +291,7 @@ void LdsLidar::OnDeviceChange(const DeviceInfo *info, DeviceEvent type) { if (kDeviceTypeLidarTele == info->type) { if (p_lidar->config.enable_high_sensitivity) { - LidarEnableHighSensitivity(handle, SetHighSensitivityCb, - g_lds_ldiar); + LidarEnableHighSensitivity(handle, SetHighSensitivityCb, g_lds_ldiar); printf("Enable high sensitivity\n"); } else { LidarDisableHighSensitivity(handle, SetHighSensitivityCb, @@ -534,7 +459,7 @@ void LdsLidar::GetLidarExtrinsicParameterCb( if (!p_lidar->config.set_bits) { LidarStartSampling(handle, StartSampleCb, lds_lidar); p_lidar->connect_state = kConnectStateSampling; - } + } } else { printf("Lidar[%d] get ExtrinsicParameter fail!\n", handle); } @@ -544,7 +469,8 @@ void LdsLidar::GetLidarExtrinsicParameterCb( } void LdsLidar::SetHighSensitivityCb(livox_status status, uint8_t handle, - DeviceParameterResponse *response, void *clent_data) { + DeviceParameterResponse *response, + void *clent_data) { LdsLidar *lds_lidar = static_cast(clent_data); if (handle >= kMaxLidarCount) { @@ -563,11 +489,9 @@ void LdsLidar::SetHighSensitivityCb(livox_status status, uint8_t handle, }; } else { if (p_lidar->config.enable_high_sensitivity) { - LidarEnableHighSensitivity(handle, SetHighSensitivityCb, - g_lds_ldiar); + LidarEnableHighSensitivity(handle, SetHighSensitivityCb, g_lds_ldiar); } else { - LidarDisableHighSensitivity(handle, SetHighSensitivityCb, - g_lds_ldiar); + LidarDisableHighSensitivity(handle, SetHighSensitivityCb, g_lds_ldiar); } printf("Set high sensitivity fail, try again!\n"); } @@ -668,8 +592,7 @@ int LdsLidar::ParseTimesyncConfig(rapidjson::Document &doc) { break; const rapidjson::Value &object = doc["timesync_config"]; - if (!object.IsObject()) - break; + if (!object.IsObject()) break; if (!object.HasMember("enable_timesync") || !object["enable_timesync"].IsBool()) @@ -854,4 +777,4 @@ int LdsLidar::GetRawConfig(const char *broadcast_code, UserRawConfig &config) { return -1; } -} // namespace livox_ros +} // namespace livox_ros diff --git a/livox_ros_driver/livox_ros_driver/lds_lidar.h b/livox_ros_driver/livox_ros_driver/lds_lidar.h index 8f37857..edd2e33 100644 --- a/livox_ros_driver/livox_ros_driver/lds_lidar.h +++ b/livox_ros_driver/livox_ros_driver/lds_lidar.h @@ -28,8 +28,8 @@ #define LIVOX_ROS_DRIVER_LDS_LIDAR_H_ #include -#include #include +#include #include "lds.h" #include "livox_sdk.h" @@ -42,7 +42,7 @@ namespace livox_ros { * LiDAR data source, data from dependent lidar. */ class LdsLidar : public Lds { -public: + public: static LdsLidar *GetInstance(uint32_t interval_ms) { static LdsLidar lds_lidar(interval_ms); return &lds_lidar; @@ -52,7 +52,7 @@ class LdsLidar : public Lds { const char *user_config_path); int DeInitLdsLidar(void); -private: + private: LdsLidar(uint32_t interval_ms); LdsLidar(const LdsLidar &) = delete; ~LdsLidar(); @@ -84,12 +84,12 @@ class LdsLidar : public Lds { uint8_t response, void *client_data); static void ReceiveSyncTimeCallback(const char *rmc, uint32_t rmc_length, void *client_data); - static void - GetLidarExtrinsicParameterCb(livox_status status, uint8_t handle, - LidarGetExtrinsicParameterResponse *response, - void *clent_data); + static void GetLidarExtrinsicParameterCb( + livox_status status, uint8_t handle, + LidarGetExtrinsicParameterResponse *response, void *clent_data); static void SetHighSensitivityCb(livox_status status, uint8_t handle, - DeviceParameterResponse *response, void *clent_data); + DeviceParameterResponse *response, + void *clent_data); void ResetLdsLidar(void); int AddBroadcastCodeToWhitelist(const char *broadcast_code); @@ -116,5 +116,5 @@ class LdsLidar : public Lds { std::mutex config_mutex_; }; -} // namespace livox_ros +} // namespace livox_ros #endif diff --git a/livox_ros_driver/livox_ros_driver/lds_lvx.cpp b/livox_ros_driver/livox_ros_driver/lds_lvx.cpp index 902435e..e484469 100644 --- a/livox_ros_driver/livox_ros_driver/lds_lvx.cpp +++ b/livox_ros_driver/livox_ros_driver/lds_lvx.cpp @@ -24,23 +24,21 @@ #include "lds_lvx.h" -#include -#include #include +#include #include +#include +#include #include #include "lvx_file.h" namespace livox_ros { -/** Const varible - * -------------------------------------------------------------------------------- - */ +/** Const varible ------------------------------------------------------------*/ const uint32_t kMaxPacketsNumOfFrame = 8192; -/** For device connect use - * ---------------------------------------------------------------------- */ +/** For device connect use ---------------------------------------------------*/ LdsLvx::LdsLvx(uint32_t interval_ms) : Lds(interval_ms, kSourceLvxFile) { start_read_lvx_ = false; is_initialized_ = false; @@ -62,7 +60,7 @@ LdsLvx::~LdsLvx() { void LdsLvx::PrepareExit(void) { lvx_file_->CloseLvxFile(); - printf("Lvx to rosbag convert complete and exit!\n"); + printf("Convert complete, Press [Ctrl+C] to exit!\n"); } int LdsLvx::InitLdsLvx(const char *lvx_path) { @@ -83,31 +81,37 @@ int LdsLvx::InitLdsLvx(const char *lvx_path) { ResetLds(kSourceLvxFile); } - lidar_count_ = lvx_file_->GetDeviceCount(); - if (!lidar_count_ || (lidar_count_ >= kMaxSourceLidar)) { + uint32_t valid_lidar_count_ = lvx_file_->GetDeviceCount(); + if (!valid_lidar_count_ || (valid_lidar_count_ >= kMaxSourceLidar)) { lvx_file_->CloseLvxFile(); - printf("Lidar count error in %s : %d\n", lvx_path, lidar_count_); + printf("Lidar count error in %s : %d\n", lvx_path, valid_lidar_count_); return -1; } - printf("LvxFile[%s] have %d lidars\n", lvx_path, lidar_count_); + printf("LvxFile[%s] have %d lidars\n", lvx_path, valid_lidar_count_); - for (int i = 0; i < lidar_count_; i++) { + for (uint32_t i = 0; i < valid_lidar_count_; i++) { LvxFileDeviceInfo lvx_dev_info; lvx_file_->GetDeviceInfo(i, &lvx_dev_info); - lidars_[i].handle = i; - lidars_[i].connect_state = kConnectStateSampling; - lidars_[i].info.handle = i; - lidars_[i].info.type = lvx_dev_info.device_type; - memcpy(lidars_[i].info.broadcast_code, lvx_dev_info.lidar_broadcast_code, - sizeof(lidars_[i].info.broadcast_code)); + uint8_t handle = lvx_dev_info.device_index; + if (handle >= kMaxSourceLidar) { + printf("Invalid hanle from lvx file!\n"); + continue; + } + lidars_[handle].handle = handle; + lidars_[handle].connect_state = kConnectStateSampling; + lidars_[handle].info.handle = handle; + lidars_[handle].info.type = lvx_dev_info.device_type; + memcpy(lidars_[handle].info.broadcast_code, \ + lvx_dev_info.lidar_broadcast_code, \ + sizeof(lidars_[handle].info.broadcast_code)); if (lvx_file_->GetFileVersion() == kLvxFileV1) { - lidars_[i].data_src = kSourceRawLidar; + lidars_[handle].data_src = kSourceRawLidar; } else { - lidars_[i].data_src = kSourceLvxFile; + lidars_[handle].data_src = kSourceLvxFile; } - ExtrinsicParameter *p_extrinsic = &lidars_[i].extrinsic_parameter; + ExtrinsicParameter *p_extrinsic = &lidars_[handle].extrinsic_parameter; p_extrinsic->euler[0] = lvx_dev_info.roll * PI / 180.0; p_extrinsic->euler[1] = lvx_dev_info.pitch * PI / 180.0; p_extrinsic->euler[2] = lvx_dev_info.yaw * PI / 180.0; @@ -118,9 +122,9 @@ int LdsLvx::InitLdsLvx(const char *lvx_path) { p_extrinsic->enable = lvx_dev_info.extrinsic_enable; uint32_t queue_size = kMaxEthPacketQueueSize * 16; - InitQueue(&lidars_[i].data, queue_size); + InitQueue(&lidars_[handle].data, queue_size); queue_size = kMaxEthPacketQueueSize; - InitQueue(&lidars_[i].imu_data, queue_size); + InitQueue(&lidars_[handle].imu_data, queue_size); } t_read_lvx_ = @@ -134,8 +138,7 @@ int LdsLvx::InitLdsLvx(const char *lvx_path) { /** Global function in LdsLvx for callback */ void LdsLvx::ReadLvxFile() { - while (!start_read_lvx_) - ; + while (!start_read_lvx_); printf("Start to read lvx file.\n"); int file_state = kLvxFileOk; @@ -164,32 +167,19 @@ void LdsLvx::ReadLvxFile() { data_type = eth_packet->data_type; /** Packet length + device index */ - data_offset += (GetEthPacketLen(data_type) + 1); - if (data_type != kImu) { - LidarDevice *p_lidar = &lidars_[handle]; - LidarDataQueue *p_queue = &lidars_[handle].data; - if (p_lidar->raw_data_type != eth_packet->data_type) { - p_lidar->raw_data_type = eth_packet->data_type; - p_lidar->packet_interval = GetPacketInterval(eth_packet->data_type); - p_lidar->packet_interval_max = p_lidar->packet_interval * 1.8f; - } - if ((p_queue != nullptr) && (handle < lidar_count_)) { - while (QueueIsFull(p_queue)) { - std::this_thread::sleep_for(std::chrono::milliseconds(1)); - } - QueuePushAny(p_queue, (uint8_t *)eth_packet, - GetEthPacketLen(data_type), 0, - GetPointsPerPacket(data_type)); + data_offset += (GetEthPacketLen(data_type) + 1); + StorageRawPacket(handle, eth_packet); + + LidarDataQueue *p_queue = &lidars_[handle].data; + if (p_queue != nullptr) { + while (QueueIsFull(p_queue)) { + std::this_thread::sleep_for(std::chrono::milliseconds(1)); } - } else { - LidarDataQueue *p_queue = &lidars_[handle].imu_data; - if ((p_queue != nullptr) && (handle < lidar_count_)) { - while (QueueIsFull(p_queue)) { - std::this_thread::sleep_for(std::chrono::milliseconds(1)); - } - QueuePushAny(p_queue, (uint8_t *)eth_packet, - GetEthPacketLen(data_type), 0, - GetPointsPerPacket(data_type)); + } + p_queue = &lidars_[handle].imu_data; + if (p_queue != nullptr) { + while (QueueIsFull(p_queue)) { + std::this_thread::sleep_for(std::chrono::milliseconds(1)); } } } @@ -207,10 +197,13 @@ void LdsLvx::ReadLvxFile() { printf("Read progress : %d \n", progress); } } - - int32_t wait_cnt = 10; + printf("Wait for file conversion to complete!\n"); + int32_t wait_cnt = 5; while (!IsAllQueueEmpty()) { - std::this_thread::sleep_for(std::chrono::milliseconds(50)); + std::this_thread::sleep_for(std::chrono::milliseconds(40)); + if (semaphore_.GetCount() <= 0) { + semaphore_.Signal(); + } if (IsAllQueueReadStop()) { --wait_cnt; if (wait_cnt <= 0) { @@ -218,31 +211,12 @@ void LdsLvx::ReadLvxFile() { } } } - RequestExit(); -} - -bool LdsLvx::IsAllQueueEmpty() { - for (int i = 0; i < lidar_count_; i++) { - LidarDevice *p_lidar = &lidars_[i]; - if (!QueueIsEmpty(&p_lidar->data)) { - return false; - } - } - return true; -} - -bool LdsLvx::IsAllQueueReadStop() { - static uint32_t remain_size[kMaxSourceLidar]; - for (int i = 0; i < lidar_count_; i++) { - LidarDevice *p_lidar = &lidars_[i]; - if (remain_size[i] != QueueIsEmpty(&p_lidar->data)) { - remain_size[i] = QueueIsEmpty(&p_lidar->data); - return false; - } + RequestExit(); + while(semaphore_.GetCount() > 0) { + std::this_thread::sleep_for(std::chrono::milliseconds(10)); } - - return true; + semaphore_.Signal(); } -} // namespace livox_ros +} // namespace livox_ros diff --git a/livox_ros_driver/livox_ros_driver/lds_lvx.h b/livox_ros_driver/livox_ros_driver/lds_lvx.h index f9cdc4c..eb5ba41 100644 --- a/livox_ros_driver/livox_ros_driver/lds_lvx.h +++ b/livox_ros_driver/livox_ros_driver/lds_lvx.h @@ -39,7 +39,7 @@ namespace livox_ros { * Lidar data source abstract. */ class LdsLvx : public Lds { -public: + public: static LdsLvx *GetInstance(uint32_t interval_ms) { static LdsLvx lds_lvx(interval_ms); return &lds_lvx; @@ -49,7 +49,7 @@ class LdsLvx : public Lds { int DeInitLdsLvx(void); void PrepareExit(void); -private: + private: LdsLvx(uint32_t interval_ms); LdsLvx(const LdsLvx &) = delete; ~LdsLvx(); @@ -60,8 +60,6 @@ class LdsLvx : public Lds { bool IsStarted() { return start_read_lvx_; } void ReadLvxFile(); - bool IsAllQueueEmpty(); - bool IsAllQueueReadStop(); volatile bool is_initialized_; OutPacketBuffer packets_of_frame_; @@ -70,5 +68,5 @@ class LdsLvx : public Lds { volatile bool start_read_lvx_; }; -} // namespace livox_ros +} // namespace livox_ros #endif diff --git a/livox_ros_driver/livox_ros_driver/livox_ros_driver.cpp b/livox_ros_driver/livox_ros_driver/livox_ros_driver.cpp index 795bcfa..1dd7a2d 100644 --- a/livox_ros_driver/livox_ros_driver/livox_ros_driver.cpp +++ b/livox_ros_driver/livox_ros_driver/livox_ros_driver.cpp @@ -27,19 +27,18 @@ #include #include +#include #include "lddc.h" #include "lds_hub.h" #include "lds_lidar.h" #include "lds_lvx.h" #include "livox_sdk.h" -#include using namespace livox_ros; const int32_t kSdkVersionMajorLimit = 2; int main(int argc, char **argv) { - ROS_INFO("Livox Ros Driver Version: %s", LIVOX_ROS_DRIVER_VERSION_STRING); /** Ros related */ @@ -59,7 +58,7 @@ int main(int argc, char **argv) { return 0; } - /** Init defualt system parameter */ + /** Init default system parameter */ int xfer_format = kPointCloud2Msg; int multi_topic = 0; int data_src = kSourceRawLidar; @@ -82,7 +81,7 @@ int main(int argc, char **argv) { } /** Lidar data distribute control and lidar data source set */ - Lddc *lddc = new Lddc(xfer_format, multi_topic, data_src, output_type, \ + Lddc *lddc = new Lddc(xfer_format, multi_topic, data_src, output_type, publish_freq, frame_id); lddc->SetRosNode(&livox_node); @@ -159,14 +158,8 @@ int main(int argc, char **argv) { } ros::Time::init(); - double poll_freq = publish_freq * 4; - if (data_src == kSourceLvxFile) { - poll_freq = 2000; - } - ros::Rate r(poll_freq); while (ros::ok()) { lddc->DistributeLidarData(); - r.sleep(); } return 0; diff --git a/livox_ros_driver/livox_ros_driver/lvx_file.cpp b/livox_ros_driver/livox_ros_driver/lvx_file.cpp index 4448abd..2a681a0 100644 --- a/livox_ros_driver/livox_ros_driver/lvx_file.cpp +++ b/livox_ros_driver/livox_ros_driver/lvx_file.cpp @@ -23,9 +23,9 @@ // #include "lvx_file.h" -#include #include #include +#include #include "lds.h" #include "rapidxml/rapidxml.hpp" @@ -40,8 +40,14 @@ const char *kLvxHeaderSigStr = "livox_tech"; const uint32_t kLvxHeaderMagicCode = 0xac0ea767; LvxFileHandle::LvxFileHandle() - : file_ver_(kLvxFileV1), device_count_(0), cur_frame_index_(0), - cur_offset_(0), data_start_offset_(0), size_(0), mode_(0), state_(0) { + : file_ver_(kLvxFileV1), + device_count_(0), + cur_frame_index_(0), + cur_offset_(0), + data_start_offset_(0), + size_(0), + mode_(0), + state_(0) { memset((void *)&public_header_, 0, sizeof(public_header_)); memset((void *)&private_header_, 0, sizeof(private_header_)); memset((void *)&private_header_v0_, 0, sizeof(private_header_v0_)); @@ -151,7 +157,6 @@ bool LvxFileHandle::PrepareDataRead() { } int LvxFileHandle::Open(const char *filename, std::ios_base::openmode mode) { - if ((mode & std::ios::in) == std::ios::in) { state_ = kLvxFileOk; lvx_file_.open(filename, mode | std::ios_base::binary | std::ios_base::ate); @@ -298,8 +303,7 @@ void LvxFileHandle::SaveFrameToLvxFile( } void LvxFileHandle::CloseLvxFile() { - if (lvx_file_ && lvx_file_.is_open()) - lvx_file_.close(); + if (lvx_file_ && lvx_file_.is_open()) lvx_file_.close(); } void LvxFileHandle::BasePointsHandle(LivoxEthPacket *data, @@ -416,4 +420,4 @@ void ParseExtrinsicXml(DeviceItem &item, LvxFileDeviceInfo &info) { } } -} // namespace livox_ros +} // namespace livox_ros diff --git a/livox_ros_driver/livox_ros_driver/lvx_file.h b/livox_ros_driver/livox_ros_driver/lvx_file.h index 0c75d7f..3d0135b 100644 --- a/livox_ros_driver/livox_ros_driver/lvx_file.h +++ b/livox_ros_driver/livox_ros_driver/lvx_file.h @@ -24,13 +24,13 @@ #ifndef LIVOX_FILE_H_ #define LIVOX_FILE_H_ -#include "livox_sdk.h" #include #include #include #include #include #include +#include "livox_sdk.h" namespace livox_ros { @@ -121,9 +121,7 @@ typedef struct { LvxFilePacket *packet; } LvxFileFrame; -typedef struct { - uint8_t device_count; -} LvxFilePrivateHeaderV0; +typedef struct { uint8_t device_count; } LvxFilePrivateHeaderV0; typedef struct { uint8_t lidar_broadcast_code[16]; @@ -172,7 +170,7 @@ typedef struct { #pragma pack() class LvxFileHandle { -public: + public: LvxFileHandle(); ~LvxFileHandle() = default; @@ -196,7 +194,7 @@ class LvxFileHandle { int GetLvxFileReadProgress(); int GetFileVersion() { return file_ver_; } -private: + private: std::fstream lvx_file_; std::vector device_info_list_; uint8_t file_ver_; @@ -232,5 +230,5 @@ class LvxFileHandle { } }; -} // namespace livox_ros +} // namespace livox_ros #endif diff --git a/livox_ros_driver/timesync/timesync.cpp b/livox_ros_driver/timesync/timesync.cpp index eb038ab..015015e 100644 --- a/livox_ros_driver/timesync/timesync.cpp +++ b/livox_ros_driver/timesync/timesync.cpp @@ -24,17 +24,19 @@ #include "timesync.h" -#include -#include #include #include +#include +#include #include namespace livox_ros { using namespace std; TimeSync::TimeSync() - : exit_poll_state_(false), start_poll_state_(false), exit_poll_data_(false), + : exit_poll_state_(false), + start_poll_state_(false), + exit_poll_data_(false), start_poll_data_(false) { fsm_state_ = kOpenDev; uart_ = nullptr; @@ -78,10 +80,8 @@ int32_t TimeSync::InitTimeSync(const TimeSyncConfig &config) { int32_t TimeSync::DeInitTimeSync() { StopTimesync(); - if (uart_) - delete uart_; - if (comm_) - delete comm_; + if (uart_) delete uart_; + if (comm_) delete comm_; fn_cb_ = nullptr; client_data_ = nullptr; @@ -197,4 +197,4 @@ void TimeSync::FsmCheckDevState() { } } -} // namespace livox_ros +} // namespace livox_ros diff --git a/livox_ros_driver/timesync/timesync.h b/livox_ros_driver/timesync/timesync.h index b1bc133..71a1d1d 100644 --- a/livox_ros_driver/timesync/timesync.h +++ b/livox_ros_driver/timesync/timesync.h @@ -25,10 +25,10 @@ #ifndef TIMESYNC_TIMESYNC_H_ #define TIMESYNC_TIMESYNC_H_ +#include #include "comm_device.h" #include "comm_protocol.h" #include "user_uart.h" -#include namespace livox_ros { @@ -43,7 +43,7 @@ typedef struct { } TimeSyncConfig; class TimeSync { -public: + public: static TimeSync *GetInstance() { static TimeSync time_sync; @@ -67,7 +67,7 @@ class TimeSync { } } -private: + private: TimeSync(); ~TimeSync(); TimeSync(const TimeSync &) = delete; @@ -101,5 +101,5 @@ class TimeSync { void FsmCheckDevState(); }; -} // namespace livox_ros +} // namespace livox_ros #endif diff --git a/livox_ros_driver/timesync/user_uart/user_uart.cpp b/livox_ros_driver/timesync/user_uart/user_uart.cpp index e1d095d..9fe86b3 100644 --- a/livox_ros_driver/timesync/user_uart/user_uart.cpp +++ b/livox_ros_driver/timesync/user_uart/user_uart.cpp @@ -51,7 +51,7 @@ UserUart::~UserUart() { } int UserUart::Open(const char *filename) { - fd_ = open(filename, O_RDWR | O_NOCTTY); //| O_NDELAY + fd_ = open(filename, O_RDWR | O_NOCTTY); //| O_NDELAY if (fd_ < 0) { printf("Open %s fail!\n", filename); return -1; @@ -72,7 +72,6 @@ int UserUart::Open(const char *filename) { } int UserUart::Close() { - is_open_ = false; if (fd_ > 0) { /** first we flush the port */ @@ -121,38 +120,38 @@ int UserUart::Setup(uint8_t baudrate_index, uint8_t parity) { options.c_cflag |= baudrate; switch (parity) { - case P_8N1: - /** No parity (8N1) */ - options.c_cflag &= ~PARENB; - options.c_cflag &= ~CSTOPB; - options.c_cflag &= ~CSIZE; - options.c_cflag |= CS8; - break; - case P_7E1: - /** Even parity (7E1) */ - options.c_cflag |= PARENB; - options.c_cflag &= ~PARODD; - options.c_cflag &= ~CSTOPB; - options.c_cflag &= ~CSIZE; - options.c_cflag |= CS7; - break; - case P_7O1: - /** Odd parity (7O1) */ - options.c_cflag |= PARENB; - options.c_cflag |= PARODD; - options.c_cflag &= ~CSTOPB; - options.c_cflag &= ~CSIZE; - options.c_cflag |= CS7; - break; - case P_7S1: - /** Space parity is setup the same as no parity (7S1) */ - options.c_cflag &= ~PARENB; - options.c_cflag &= ~CSTOPB; - options.c_cflag &= ~CSIZE; - options.c_cflag |= CS8; - break; - default: - return -1; + case P_8N1: + /** No parity (8N1) */ + options.c_cflag &= ~PARENB; + options.c_cflag &= ~CSTOPB; + options.c_cflag &= ~CSIZE; + options.c_cflag |= CS8; + break; + case P_7E1: + /** Even parity (7E1) */ + options.c_cflag |= PARENB; + options.c_cflag &= ~PARODD; + options.c_cflag &= ~CSTOPB; + options.c_cflag &= ~CSIZE; + options.c_cflag |= CS7; + break; + case P_7O1: + /** Odd parity (7O1) */ + options.c_cflag |= PARENB; + options.c_cflag |= PARODD; + options.c_cflag &= ~CSTOPB; + options.c_cflag &= ~CSIZE; + options.c_cflag |= CS7; + break; + case P_7S1: + /** Space parity is setup the same as no parity (7S1) */ + options.c_cflag &= ~PARENB; + options.c_cflag &= ~CSTOPB; + options.c_cflag &= ~CSIZE; + options.c_cflag |= CS8; + break; + default: + return -1; } /** now we setup the values in port's termios */ @@ -192,4 +191,4 @@ ssize_t UserUart::Read(char *buffer, size_t size) { } } -} // namespace livox_ros +} // namespace livox_ros diff --git a/livox_ros_driver/timesync/user_uart/user_uart.h b/livox_ros_driver/timesync/user_uart/user_uart.h index 0cea554..2e1c392 100644 --- a/livox_ros_driver/timesync/user_uart/user_uart.h +++ b/livox_ros_driver/timesync/user_uart/user_uart.h @@ -66,8 +66,7 @@ enum BaudRate { }; class UserUart { - -public: + public: UserUart(uint8_t baudrate_index, uint8_t parity); ~UserUart(); @@ -78,7 +77,7 @@ class UserUart { int Open(const char *filename); bool IsOpen() { return is_open_; }; -private: + private: int fd_; volatile bool is_open_; @@ -86,6 +85,6 @@ class UserUart { uint8_t parity_; }; -} // namespace livox_ros +} // namespace livox_ros #endif