TEST(StringBuffer, Push) { StringBuffer buffer; buffer.Push(5); EXPECT_EQ(5u, buffer.GetSize()); // Causes sudden expansion to make the stack's capacity equal to size buffer.Push(65536u); EXPECT_EQ(5u + 65536u, buffer.GetSize()); }
bool run_test(uint32_t* hash_out) { StringBuffer buffer; Writer<StringBuffer> writer(buffer); write_object(writer, root_object); *hash_out = hash_str(*hash_out, buffer.GetString(), buffer.GetSize()); return true; }
std::string jsonToString(const Value& elem) { StringBuffer buffer; Writer<StringBuffer> writer(buffer); elem.Accept(writer); return std::string(buffer.GetString(), buffer.GetSize()); }
int main(int argc, char **argv) { Document d; d.SetObject(); Value vElem; vElem.SetArray(); Document::AllocatorType & allocator = d.GetAllocator(); for(int i = 0; i < 10; ++i) { Value tmp;///(i); tmp.SetInt(i); // vElem.PushBack<int>(i, d.GetAllocator); vElem.PushBack(tmp, allocator); } d.AddMember("Data", vElem, allocator); StringBuffer buffer; Writer<StringBuffer> writer(buffer); d.Accept(writer); string json(buffer.GetString(), buffer.GetSize()); cout << json << endl; // Document::AllocatorType& a = d.GetAllocator(); // cout << d["test"].IsNull() << endl;// = 1; // Value v1("foo"); // Value v2(v1, a); }
TEST(StringBuffer, Put) { StringBuffer buffer; buffer.Put('A'); EXPECT_EQ(1u, buffer.GetSize()); EXPECT_STREQ("A", buffer.GetString()); }
TEST(StringBuffer, MoveAssignment) { StringBuffer x; x.Put('A'); x.Put('B'); x.Put('C'); x.Put('D'); EXPECT_EQ(4u, x.GetSize()); EXPECT_STREQ("ABCD", x.GetString()); StringBuffer y; // y = x; // does not compile (!is_copy_assignable) y = std::move(x); EXPECT_EQ(0u, x.GetSize()); EXPECT_EQ(4u, y.GetSize()); EXPECT_STREQ("ABCD", y.GetString()); }
TEST(Writer, Compact) { StringStream s("{ \"hello\" : \"world\", \"t\" : true , \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3] } "); StringBuffer buffer; Writer<StringBuffer> writer(buffer); Reader reader; reader.Parse<0>(s, writer); EXPECT_STREQ("{\"hello\":\"world\",\"t\":true,\"f\":false,\"n\":null,\"i\":123,\"pi\":3.1416,\"a\":[1,2,3]}", buffer.GetString()); EXPECT_EQ(77u, buffer.GetSize()); }
string doc2str(Document &doc) { StringBuffer buffer; Writer<StringBuffer> writer(buffer); doc.Accept(writer); string str(buffer.GetString(), buffer.GetSize()); return str; }
std::string jsonToPrettyString(const Value& elem) { StringBuffer buffer; PrettyWriter<StringBuffer> writer(buffer); writer.SetIndent(' ', 2); writer.SetFormatOptions(PrettyFormatOptions::kFormatSingleLineArray); elem.Accept(writer); return std::string(buffer.GetString(), buffer.GetSize()); }
TEST(StringBuffer, Clear) { StringBuffer buffer; buffer.Put('A'); buffer.Put('B'); buffer.Put('C'); buffer.Clear(); EXPECT_EQ(0u, buffer.GetSize()); EXPECT_STREQ("", buffer.GetString()); }
bool JSONFile::Save(Serializer& dest, const String& indendation) const { StringBuffer buffer; PrettyWriter<StringBuffer> writer(buffer, &(document_->GetAllocator())); writer.SetIndent(!indendation.Empty() ? indendation.Front() : '\0', indendation.Length()); document_->Accept(writer); unsigned size = (unsigned)buffer.GetSize(); return dest.Write(buffer.GetString(), size) == size; }
TEST(StringBuffer, Pop) { StringBuffer buffer; buffer.Put('A'); buffer.Put('B'); buffer.Put('C'); buffer.Put('D'); buffer.Put('E'); buffer.Pop(3); EXPECT_EQ(2u, buffer.GetSize()); EXPECT_STREQ("AB", buffer.GetString()); }
int Dynamo::Json2str(const rapidjson::Value &json, std::string& str) { StringBuffer buffer; Writer<StringBuffer> writer(buffer); if (false == json.Accept(writer)) { snprintf(lastErr, sizeof(lastErr), "Value::Accept failed"); return -1; } str.append(buffer.GetString(), buffer.GetSize()); return 0; }
bool packet::accept(string& payload_ptr, vector<shared_ptr<const string> >&buffers) { char frame_char = _frame+'0'; payload_ptr.append(&frame_char,1); if (_frame!=frame_message) { return false; } bool hasMessage = false; Document doc; if (_message) { accept_message(*_message, doc, doc, buffers); hasMessage = true; } bool hasBinary = buffers.size()>0; _type = _type&(~type_undetermined); if(_type == type_event) { _type = hasBinary?type_binary_event:type_event; } else if(_type == type_ack) { _type = hasBinary? type_binary_ack : type_ack; } ostringstream ss; ss.precision(8); ss<<_type; if (hasBinary) { ss<<buffers.size()<<"-"; } if(_nsp.size()>0 && _nsp!="/") { ss<<_nsp; if (hasMessage || _pack_id>=0) { ss<<","; } } if(_pack_id>=0) { ss<<_pack_id; } payload_ptr.append(ss.str()); if (hasMessage) { StringBuffer buffer; Writer<StringBuffer> writer(buffer); doc.Accept(writer); payload_ptr.append(buffer.GetString(),buffer.GetSize()); } return hasBinary; }
TEST(StringBuffer, MoveConstructor) { StringBuffer x; x.Put('A'); x.Put('B'); x.Put('C'); x.Put('D'); EXPECT_EQ(4u, x.GetSize()); EXPECT_STREQ("ABCD", x.GetString()); // StringBuffer y(x); // does not compile (!is_copy_constructible) StringBuffer y(std::move(x)); EXPECT_EQ(0u, x.GetSize()); EXPECT_EQ(4u, y.GetSize()); EXPECT_STREQ("ABCD", y.GetString()); // StringBuffer z = y; // does not compile (!is_copy_assignable) StringBuffer z = std::move(y); EXPECT_EQ(0u, y.GetSize()); EXPECT_EQ(4u, z.GetSize()); EXPECT_STREQ("ABCD", z.GetString()); }
static int json_encode(lua_State* L) { try { Encoder encode(L, 2); StringBuffer s; encode.encode(L, &s, 1); lua_pushlstring(L, s.GetString(), s.GetSize()); return 1; } catch (...) { luaL_error(L, "error while encoding"); } return 0; }
void create_json_response_sds(write_batch* batch) { StringBuffer s; Writer<StringBuffer> writer(s); writer.StartObject(); writer.Key("message"); writer.String("Hello, World!"); writer.EndObject(); sds response_buffer = sdsnew("HTTP/1.1 200 OK\r\n"); response_buffer = sdscat(response_buffer, "Server: octane\r\n"); response_buffer = sdscat(response_buffer, "Content-Type: application/json\r\n"); response_buffer = sdscatprintf(response_buffer, "Content-Length: %d\r\n", s.GetSize()); response_buffer = sdscatprintf(response_buffer, "Date: %s\r\n", current_time); response_buffer = sdscat(response_buffer, s.GetString()); batch->buffers[batch->number_of_used_buffers].base = response_buffer; batch->buffers[batch->number_of_used_buffers].len = sdslen(response_buffer); batch->number_of_used_buffers++; }
TEST(Document, ParseStream_EncodedInputStream) { // UTF8 -> UTF16 FILE* fp = OpenEncodedFile("utf8.json"); char buffer[256]; FileReadStream bis(fp, buffer, sizeof(buffer)); EncodedInputStream<UTF8<>, FileReadStream> eis(bis); GenericDocument<UTF16<> > d; d.ParseStream<0, UTF8<> >(eis); EXPECT_FALSE(d.HasParseError()); fclose(fp); wchar_t expected[] = L"I can eat glass and it doesn't hurt me."; GenericValue<UTF16<> >& v = d[L"en"]; EXPECT_TRUE(v.IsString()); EXPECT_EQ(sizeof(expected) / sizeof(wchar_t) - 1, v.GetStringLength()); EXPECT_EQ(0, StrCmp(expected, v.GetString())); // UTF16 -> UTF8 in memory StringBuffer bos; typedef EncodedOutputStream<UTF8<>, StringBuffer> OutputStream; OutputStream eos(bos, false); // Not writing BOM { Writer<OutputStream, UTF16<>, UTF8<> > writer(eos); d.Accept(writer); } // Condense the original file and compare. fp = OpenEncodedFile("utf8.json"); FileReadStream is(fp, buffer, sizeof(buffer)); Reader reader; StringBuffer bos2; Writer<StringBuffer> writer2(bos2); reader.Parse(is, writer2); fclose(fp); EXPECT_EQ(bos.GetSize(), bos2.GetSize()); EXPECT_EQ(0, memcmp(bos.GetString(), bos2.GetString(), bos2.GetSize())); }
TEST(Document, ParseStream_AutoUTFInputStream) { // Any -> UTF8 FILE* fp = OpenEncodedFile("utf32be.json"); char buffer[256]; FileReadStream bis(fp, buffer, sizeof(buffer)); AutoUTFInputStream<unsigned, FileReadStream> eis(bis); Document d; d.ParseStream<0, AutoUTF<unsigned> >(eis); EXPECT_FALSE(d.HasParseError()); fclose(fp); char expected[] = "I can eat glass and it doesn't hurt me."; Value& v = d["en"]; EXPECT_TRUE(v.IsString()); EXPECT_EQ(sizeof(expected) - 1, v.GetStringLength()); EXPECT_EQ(0, StrCmp(expected, v.GetString())); // UTF8 -> UTF8 in memory StringBuffer bos; Writer<StringBuffer> writer(bos); d.Accept(writer); { // Condense the original file and compare. FILE *fp = OpenEncodedFile("utf8.json"); FileReadStream is(fp, buffer, sizeof(buffer)); Reader reader; StringBuffer bos2; Writer<StringBuffer> writer(bos2); reader.Parse(is, writer); fclose(fp); EXPECT_EQ(bos.GetSize(), bos2.GetSize()); EXPECT_EQ(0, memcmp(bos.GetString(), bos2.GetString(), bos2.GetSize())); } }
int MessageBusFactory::CreateRouterMessage(MessageBus* messageBus, void** messageBuffer , bool useCompression) { StringBuffer sbMessageBus; Writer<StringBuffer> writerBus(sbMessageBus); messageBus->Serialize(writerBus); void *serializedMessage = (void*) sbMessageBus.GetString(); int serializedMessageLen = sbMessageBus.GetSize(); Bytef *zBuffer = NULL; if(useCompression) { z_stream defstream; defstream.zalloc = Z_NULL; defstream.zfree = Z_NULL; defstream.opaque = Z_NULL; defstream.avail_in = sbMessageBus.GetSize(); defstream.next_in = (Bytef *)sbMessageBus.GetString(); int zBufLen = (int) ceil(1.001 * sbMessageBus.GetSize()) + 12 + 6; zBuffer = (Bytef *)malloc( zBufLen ); defstream.avail_out = zBufLen; defstream.next_out = zBuffer; deflateInit2( &defstream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, (15+16), 8, Z_DEFAULT_STRATEGY); int status; while( ( status = deflate( &defstream, Z_FINISH ) ) == Z_OK ); deflateEnd(&defstream); serializedMessage = zBuffer; serializedMessageLen = defstream.total_out; } int bufferLen = 15 + messageBus->Header.BodyType.size() + 4 + serializedMessageLen + 4; CallerContext c1; if(!messageBus->Header.CallStack.empty()) { c1 = messageBus->Header.CallStack.top(); bufferLen += c1.Id.Id.size() + 4 + c1.Id.Type.size(); } void* bufferRet = malloc(bufferLen); char* pos = (char*)bufferRet; memset(bufferRet, 0, bufferLen); memcpy(pos, &(messageBus->Header.Type), sizeof(char)); pos += 1; memcpy(pos, &(messageBus->Header.Priority), sizeof(char)); pos += 2; //Reservado int64_t ticks = HermEsb::Utils::Time::TimeExtensions::ticks_from_mindate(messageBus->Header.CreatedAt); memcpy(pos, &ticks, sizeof(int64_t)); pos +=sizeof(int64_t); int bodytypeLen = messageBus->Header.BodyType.size(); memcpy(pos, &bodytypeLen, sizeof(int)); pos += sizeof(int); memcpy(pos, messageBus->Header.BodyType.c_str(), bodytypeLen); pos += bodytypeLen; int bodysize = serializedMessageLen; memcpy(pos, &bodysize, sizeof(int)); pos += sizeof(int); memcpy(pos, serializedMessage, bodysize); if(!c1.Id.Id.empty()) { pos += bodysize; int idLen = c1.Id.Id.size(); memcpy(pos, &idLen, sizeof(int)); pos += sizeof(int); memcpy(pos, c1.Id.Id.c_str(), c1.Id.Id.size()); pos += c1.Id.Id.size(); int typeLen = c1.Id.Type.size(); memcpy(pos, &typeLen, sizeof(int)); pos += sizeof(int); memcpy(pos, c1.Id.Type.c_str(), c1.Id.Type.size()); } if(zBuffer!=NULL) free(zBuffer); *messageBuffer = bufferRet; return bufferLen; }
void StringBuffer::operator = (const StringBuffer& src) { Clear(); AppendString(src.ToCStr(), src.GetSize()); }
String::String(const StringBuffer& src) { pData = AllocDataCopy1(src.GetSize(), 0, src.ToCStr(), src.GetSize()); }
StringBuffer::StringBuffer(const StringBuffer& src) : pData(NULL), Size(0), BufferSize(src.GetGrowSize()), GrowSize(OVR_SBUFF_DEFAULT_GROW_SIZE), LengthIsSize(false) { AppendString(src.ToCStr(), src.GetSize()); LengthIsSize = src.LengthIsSize; }
void String::operator = (const StringBuffer& src) { DataDesc* polddata = GetData(); SetData(AllocDataCopy1(src.GetSize(), 0, src.ToCStr(), src.GetSize())); polddata->Release(); }
void Converter::Save(const std::wstring & taniFileName) { auto ddsFileName = GenTempFileName(); StringBuffer sb; { // width group std::unordered_map<uint32_t, std::vector<size_t>> frameGroups; { size_t id = 0; for (auto&& frame : _shp.GetFrames()) frameGroups[frame.CroppedWidth].emplace_back(id++); } uint32_t width = 0; { for (auto&& group : frameGroups) width += group.first; } width = FitTo4(width); uint32_t height = 0; { for (auto&& group : frameGroups) { uint32_t groupHeight = 0; for (auto&& frame : group.second) groupHeight += _shp.GetFrames()[frame].CroppedHeight; height = std::max(height, groupHeight); } } height = FitTo4(height); ComPtr<IWICBitmap> targetBitmap; ThrowIfFailed(_wicFactory->CreateBitmap(width, height, GUID_WICPixelFormat32bppBGRA, WICBitmapCacheOnDemand, &targetBitmap)); MemoryPoolAllocator<> allocator; auto jFrames = Value(Type::kArrayType).GetArray(); WICRect rect{ 0, 0, width, height }; { ComPtr<IWICBitmapLock> locker; ThrowIfFailed(targetBitmap->Lock(&rect, WICBitmapLockWrite, &locker)); UINT cbBufferSize = 0; UINT cbStride = 0; BYTE *pv = NULL; ThrowIfFailed(locker->GetDataPointer(&cbBufferSize, &pv)); ThrowIfFailed(locker->GetStride(&cbStride)); uint32_t x = 0; for (auto&& group : frameGroups) { uint32_t y = 0; for (auto&& frameId : group.second) { auto&& frame = _shp.GetFrames()[frameId]; DrawFrame(reinterpret_cast<uint32_t*>(pv), x, y, cbStride / 4, _palette, frame); Value jFrame(Type::kObjectType); { Value jCoord(kObjectType); jCoord.AddMember("x", x, allocator); jCoord.AddMember("y", y, allocator); jFrame.AddMember("coord", jCoord, allocator); } { Value jOffset(kObjectType); jOffset.AddMember("x", frame.OffsetX, allocator); jOffset.AddMember("y", frame.OffsetY, allocator); jFrame.AddMember("offset", jOffset, allocator); } { Value jSize(kObjectType); jSize.AddMember("width", frame.CroppedWidth, allocator); jSize.AddMember("height", frame.CroppedHeight, allocator); jFrame.AddMember("size", jSize, allocator); } { auto color = frame.RadarColor; jFrame.AddMember("radarColor", uint32_t((color.a << 24) | (color.r << 16) | (color.g << 8) | color.b), allocator); } jFrames.PushBack(jFrame, allocator); y += frame.CroppedHeight; } x += group.first; } } Document doc(Type::kObjectType); { Value jSize(Type::kObjectType); jSize.AddMember("width", _shp.GetFrameWidth(), allocator); jSize.AddMember("height", _shp.GetFrameHeight(), allocator); doc.AddMember("size", jSize, allocator); } doc.AddMember("frames", jFrames, allocator); PrettyWriter<StringBuffer> writer(sb); doc.Accept(writer); ComPtr<IWICDdsEncoder> ddsEncoder; ComPtr<IWICBitmapEncoder> bitmapEncoder; ThrowIfFailed(_wicFactory->CreateEncoder(GUID_ContainerFormatDds, NULL, &bitmapEncoder)); ThrowIfFailed(bitmapEncoder.As(&ddsEncoder)); ComPtr<IWICStream> outputStream; ThrowIfFailed(_wicFactory->CreateStream(&outputStream)); ThrowIfFailed(outputStream->InitializeFromFilename(ddsFileName.c_str(), GENERIC_WRITE)); ThrowIfFailed(bitmapEncoder->Initialize(outputStream.Get(), WICBitmapEncoderNoCache)); WICDdsParameters parameters{}; parameters.Width = width; parameters.Height = height; parameters.ArraySize = 1; parameters.AlphaMode = WICDdsAlphaModeStraight; parameters.Dimension = WICDdsTexture2D; parameters.DxgiFormat = DXGI_FORMAT_BC2_UNORM; parameters.MipLevels = 1; parameters.Depth = 1; ThrowIfFailed(ddsEncoder->SetParameters(¶meters)); ComPtr<IWICBitmapFrameEncode> frameEncoder; ThrowIfFailed(bitmapEncoder->CreateNewFrame(&frameEncoder, nullptr)); ThrowIfFailed(frameEncoder->Initialize(nullptr)); ThrowIfFailed(frameEncoder->WriteSource(targetBitmap.Get(), nullptr)); ThrowIfFailed(frameEncoder->Commit()); ThrowIfFailed(bitmapEncoder->Commit()); } zipFile_raii zipFile(zipOpen(ws2s(taniFileName, CP_UTF8).c_str(), APPEND_STATUS_CREATE)); { zip_fileinfo zi{}; ThrowIfNot(zipOpenNewFileInZip(zipFile.get(), "ani.dds", &zi, nullptr, 0, nullptr, 0, nullptr, Z_DEFLATED, 3) == ZIP_OK, L"Error in create new archive."); FILE* fin; _wfopen_s(&fin, ddsFileName.c_str(), L"rb"); int err = ZIP_OK; int size_read; byte buf[40960]; do { size_read = (int)fread(buf, 1, sizeof(buf), fin); if ((size_read < sizeof(buf)) && (feof(fin) == 0)) { err = ZIP_ERRNO; } if (size_read > 0) { err = zipWriteInFileInZip(zipFile.get(), buf, size_read); } } while ((err == ZIP_OK) && (size_read > 0)); fclose(fin); ThrowIfNot(zipCloseFileInZip(zipFile.get()) == ZIP_OK, L"Error in close ani.dds archive."); } { zip_fileinfo zi{}; ThrowIfNot(zipOpenNewFileInZip(zipFile.get(), "ani.json", &zi, nullptr, 0, nullptr, 0, nullptr, Z_DEFLATED, 3) == ZIP_OK, L"Error in create new archive."); ThrowIfNot(zipWriteInFileInZip(zipFile.get(), sb.GetString(), sb.GetSize()) == ZIP_OK, L"Error in write ani.json archive."); ThrowIfNot(zipCloseFileInZip(zipFile.get()) == ZIP_OK, L"Error in close ani.json archive."); } }
BOOST_FIXTURE_TEST_CASE(subscribe, NotifFixture) { struct stat buffer; WAIT_FOR(stat(SOCK_NAME.c_str(), &buffer) == 0, 500); LOG(INFO) << "Connecting"; stream_protocol::socket s(io); s.connect(stream_protocol::endpoint(SOCK_NAME)); StringBuffer r; Writer<StringBuffer> writer(r); writer.StartObject(); writer.Key("method"); writer.String("subscribe"); writer.Key("params"); writer.StartObject(); writer.Key("type"); writer.StartArray(); writer.String("virtual-ip"); writer.EndArray(); writer.EndObject(); writer.Key("id"); writer.String("1"); writer.EndObject(); std::string t("test"); uint32_t size = htonl(r.GetSize()); ba::write(s, ba::buffer(&size, 4)); ba::write(s, ba::buffer(r.GetString(), r.GetSize())); Document rdoc; readMessage(s, rdoc); //StringBuffer output; //{ // PrettyWriter<StringBuffer> owriter(output); // rdoc.Accept(owriter); // LOG(INFO) << std::endl << output.GetString(); //} { boost::unordered_set<std::string> uuids; uuids.insert("4412dcd2-0cd0-4741-99d1-d8b3946e1fa9"); uuids.insert("1cc9483a-8d7a-48d5-9c23-862401691e01"); notif.dispatchVirtualIp(uuids, opflex::modb::MAC("11:22:33:44:55:66"), "1.2.3.4"); } Document notif; readMessage(s, notif); BOOST_REQUIRE(notif.HasMember("method")); BOOST_REQUIRE(notif["method"].IsString()); BOOST_CHECK_EQUAL("virtual-ip", std::string(notif["method"].GetString())); BOOST_REQUIRE(notif.HasMember("params")); BOOST_REQUIRE(notif["params"].IsObject()); const rapidjson::Value& p = notif["params"]; BOOST_REQUIRE(p.HasMember("mac")); BOOST_REQUIRE(p["mac"].IsString()); BOOST_CHECK_EQUAL("11:22:33:44:55:66", std::string(p["mac"].GetString())); BOOST_REQUIRE(p.HasMember("ip")); BOOST_REQUIRE(p["ip"].IsString()); BOOST_CHECK_EQUAL("1.2.3.4", std::string(p["ip"].GetString())); BOOST_REQUIRE(p.HasMember("uuid")); BOOST_REQUIRE(p["uuid"].IsArray()); std::set<std::string> us; const rapidjson::Value& uuids = p["uuid"]; rapidjson::Value::ConstValueIterator it; for (it = uuids.Begin(); it != uuids.End(); ++it) { BOOST_REQUIRE(it->IsString()); us.insert(it->GetString()); } BOOST_CHECK_EQUAL(2, us.size()); BOOST_CHECK(us.find("4412dcd2-0cd0-4741-99d1-d8b3946e1fa9") != us.end()); BOOST_CHECK(us.find("1cc9483a-8d7a-48d5-9c23-862401691e01") != us.end()); //output.Clear(); //{ // PrettyWriter<StringBuffer> owriter(output); // notif.Accept(owriter); // LOG(INFO) << std::endl << output.GetString(); //} }
virtual ReturnValue evaluate() { char valueBuffer[MAX_JSON_DOCUMENT_LENGTH]; char parseBuffer[MAX_JSON_STRING_LENGTH]; MemoryPoolAllocator<> valueAllocator(valueBuffer, sizeof(valueBuffer)); MemoryPoolAllocator<> parseAllocator(parseBuffer, sizeof(parseBuffer)); // input: JSON document, JSON pointer DocumentNZ document(&valueAllocator, sizeof(parseBuffer), &parseAllocator); Pointer pointer; // JSON input document in argument[0] StringArg *arg0; arg0 = stringArg(0); char *input = arg0->data; int inputLen = arg0->length; if (inputLen > MAX_JSON_DOCUMENT_LENGTH) { throwUdxException("JSON input too long"); } logMsg(LOG_DEBUG, "INPUT: %.*s\n", inputLen, input); // parse JSON input ParseResult ok = document.Parse(input); if (!ok) { char msg[1024]; sprintf(msg, "JSON parse error (offset %u): %s\n", ok.Offset(), GetParseError_En(ok.Code())); throwUdxException(msg); } // JSON input pointer in argument[1] StringArg *arg1; arg1 = stringArg(1); char *ptr = arg1->data; int ptrLen = arg1->length; logMsg(LOG_DEBUG, "POINTER: %.*s\n", ptrLen, ptr); pointer = Pointer(ptr); if (!pointer.IsValid()) { char msg[1024]; sprintf(msg, "JSON pointer error (offset %u): %d\n", pointer.GetParseErrorOffset(), pointer.GetParseErrorCode()); throwUdxException(msg); } // retrieve value Value* result = pointer.Get(document); if (!result || result->IsNull()) { logMsg(LOG_DEBUG, "RESULT: NULL\n"); NZ_UDX_RETURN_NULL(); } // handle results if (result->IsBool()) { if (STRING_TYPE(returnType())) { StringReturn* ret = stringReturnInfo(); const char* retval = result->GetBool() ? "true" : "false"; ret->size = strlen(retval); memcpy(ret->data, retval, ret->size); NZ_UDX_RETURN_STRING(ret); } logMsg(LOG_DEBUG, "RESULT: %s\n", result->GetBool() ? "true" : "false"); NZ_UDX_RETURN_BOOL(result->GetBool()); } if (result->IsInt()) { // check for Int first to do the 'smallest' ones early if (STRING_TYPE(returnType())) { StringReturn* ret = stringReturnInfo(); sprintf(ret->data, "%ld", result->GetInt()); ret->size = strlen(ret->data); NZ_UDX_RETURN_STRING(ret); } logMsg(LOG_DEBUG, "RESULT: %ld\n", result->GetInt()); NZ_UDX_RETURN_INT32(result->GetInt()); } if (result->IsInt64()) { // then for Int64 to handle left over big ints if (STRING_TYPE(returnType())) { StringReturn* ret = stringReturnInfo(); sprintf(ret->data, "%lld", result->GetInt64()); ret->size = strlen(ret->data); NZ_UDX_RETURN_STRING(ret); } logMsg(LOG_DEBUG, "RESULT: %lld\n", result->GetInt64()); NZ_UDX_RETURN_INT64(result->GetInt64()); } if (result->IsDouble()) { if (STRING_TYPE(returnType())) { StringReturn* ret = stringReturnInfo(); sprintf(ret->data, "%g", result->GetDouble()); ret->size = strlen(ret->data); NZ_UDX_RETURN_STRING(ret); } logMsg(LOG_DEBUG, "RESULT: %g\n", result->GetDouble()); NZ_UDX_RETURN_DOUBLE(result->GetDouble()); } if (result->IsString()) { // output: JSON string value at pointer StringReturn* ret = stringReturnInfo(); logMsg(LOG_DEBUG, "RESULT: %.*s\n", result->GetStringLength(), result->GetString()); ret->size = result->GetStringLength(); memcpy(ret->data, result->GetString(), ret->size); NZ_UDX_RETURN_STRING(ret); } if (result->IsObject() || result->IsArray()) { // output: JSON object stringified if (!STRING_TYPE(returnType())) { throwUdxException("return type is not a string type"); } StringBuffer sb; Writer<StringBuffer> writer(sb); if(!Stringify(&writer, result)) { throwUdxException("can not stringify result"); } StringReturn* ret = stringReturnInfo(); logMsg(LOG_DEBUG, "RESULT: %.*s\n", sb.GetSize(), sb.GetString()); memcpy(ret->data, sb.GetString(), sb.GetSize()); NZ_UDX_RETURN_STRING(ret); } // give up throwUdxException("unknown how to handle data result"); }
TEST(StringBuffer, InitialSize) { StringBuffer buffer; EXPECT_EQ(0u, buffer.GetSize()); EXPECT_STREQ("", buffer.GetString()); }