static void TestPackedUInt(skiatest::Reporter* reporter) { // we know that packeduint tries to write 1, 2 or 4 bytes for the length, // so we test values around each of those transitions (and a few others) const size_t sizes[] = { 0, 1, 2, 0xFC, 0xFD, 0xFE, 0xFF, 0x100, 0x101, 32767, 32768, 32769, 0xFFFD, 0xFFFE, 0xFFFF, 0x10000, 0x10001, 0xFFFFFD, 0xFFFFFE, 0xFFFFFF, 0x1000000, 0x1000001, 0x7FFFFFFE, 0x7FFFFFFF, 0x80000000, 0x80000001, 0xFFFFFFFE, 0xFFFFFFFF }; size_t i; char buffer[sizeof(sizes) * 4]; SkMemoryWStream wstream(buffer, sizeof(buffer)); for (i = 0; i < SK_ARRAY_COUNT(sizes); ++i) { bool success = wstream.writePackedUInt(sizes[i]); REPORTER_ASSERT(reporter, success); } wstream.flush(); SkMemoryStream rstream(buffer, sizeof(buffer)); for (i = 0; i < SK_ARRAY_COUNT(sizes); ++i) { size_t n = rstream.readPackedUInt(); if (sizes[i] != n) { ERRORF(reporter, "sizes:%x != n:%x\n", i, sizes[i], n); } } }
// Test that image encoding failures do not break picture serialization/deserialization. DEF_TEST(Image_Serialize_Encoding_Failure, reporter) { SkAutoTUnref<SkSurface> surface(SkSurface::NewRasterN32Premul(100, 100)); surface->getCanvas()->clear(SK_ColorGREEN); SkAutoTUnref<SkImage> image(surface->newImageSnapshot()); REPORTER_ASSERT(reporter, image); SkPictureRecorder recorder; SkCanvas* canvas = recorder.beginRecording(100, 100); canvas->drawImage(image, 0, 0); SkAutoTUnref<SkPicture> picture(recorder.endRecording()); REPORTER_ASSERT(reporter, picture); REPORTER_ASSERT(reporter, picture->approximateOpCount() > 0); MockSerializer emptySerializer([]() -> SkData* { return SkData::NewEmpty(); }); MockSerializer nullSerializer([]() -> SkData* { return nullptr; }); MockSerializer* serializers[] = { &emptySerializer, &nullSerializer }; for (size_t i = 0; i < SK_ARRAY_COUNT(serializers); ++i) { SkDynamicMemoryWStream wstream; REPORTER_ASSERT(reporter, !serializers[i]->didEncode()); picture->serialize(&wstream, serializers[i]); REPORTER_ASSERT(reporter, serializers[i]->didEncode()); SkAutoTDelete<SkStream> rstream(wstream.detachAsStream()); SkAutoTUnref<SkPicture> deserialized(SkPicture::CreateFromStream(rstream)); REPORTER_ASSERT(reporter, deserialized); REPORTER_ASSERT(reporter, deserialized->approximateOpCount() > 0); } }
static void TestPackedUInt(skiatest::Reporter* reporter) { // we know that packeduint tries to write 1, 2 or 4 bytes for the length, // so we test values around each of those transitions (and a few others) const size_t sizes[] = { 0, 1, 2, 0xFC, 0xFD, 0xFE, 0xFF, 0x100, 0x101, 32767, 32768, 32769, 0xFFFD, 0xFFFE, 0xFFFF, 0x10000, 0x10001, 0xFFFFFD, 0xFFFFFE, 0xFFFFFF, 0x1000000, 0x1000001, 0x7FFFFFFE, 0x7FFFFFFF, 0x80000000, 0x80000001, 0xFFFFFFFE, 0xFFFFFFFF }; size_t i; SkDynamicMemoryWStream wstream; for (i = 0; i < SK_ARRAY_COUNT(sizes); ++i) { bool success = wstream.writePackedUInt(sizes[i]); REPORTER_ASSERT(reporter, success); } std::unique_ptr<SkStreamAsset> rstream(wstream.detachAsStream()); for (i = 0; i < SK_ARRAY_COUNT(sizes); ++i) { size_t n; if (!rstream->readPackedUInt(&n)) { ERRORF(reporter, "[%d] sizes:%x could not be read\n", i, sizes[i]); } if (sizes[i] != n) { ERRORF(reporter, "[%d] sizes:%x != n:%x\n", i, sizes[i], n); } } }
/** * Returns the output from call to transform. */ QString SSMLConvert::getOutput() { /// Read back the data that was written to /tmp/fileName.output. QFile readfile(m_outFilename); if(!readfile.open(QIODevice::ReadOnly)) { /// uhh yeah... Issues writing to the SSML file. kDebug() << "SSMLConvert::slotProcessExited: Could not read file " << m_outFilename; return QString(); } QTextStream rstream(&readfile); QString convertedData = rstream.readAll(); readfile.close(); // kDebug() << "SSMLConvert::slotProcessExited: Read SSML file at " + m_inFilename + " and created " + m_outFilename + " based on the stylesheet at " << m_xsltFilename; // Clean up. QFile::remove(m_inFilename); m_inFilename.clear(); QFile::remove(m_outFilename); m_outFilename.clear(); // Ready for another transform. m_state = tsIdle; return convertedData; }
T produce_next_value() { guarantee(!memory_queue.empty()); write_message_t wm(std::move(memory_queue.front())); memory_queue.pop_front(); memory_queue_free_space += wm.size(); items_in_queue--; if (memory_queue.empty()) { available_control.set_available(false); } if (notify_when_room_in_memory_queue != nullptr) { notify_when_room_in_memory_queue->pulse_if_not_already_pulsed(); } // TODO: This does some unnecessary copying. vector_stream_t stream; stream.reserve(wm.size()); int res = send_write_message(&stream, &wm); guarantee(res == 0); std::vector<char> data; stream.swap(&data); vector_read_stream_t rstream(std::move(data)); T value; archive_result_t dres = deserialize<cluster_version_t::LATEST_OVERALL>(&rstream, &value); guarantee_deserialization(dres, "disk backed queue wrapper"); return value; }
// ============================================================================ // RCwrtRegistryClientSession::getAttributeL() // Returns the attribute value for the widget // // ============================================================================ EXPORT_C QVariant RWACRegistryClientSession::getAttributeL( const QString& appId, const QString& attribute, const QVariant& defaultValue ) { const TInt maxSize = 5120; CBufFlat* sendBuf = CBufFlat::NewL( maxSize ); CleanupStack::PushL( sendBuf ); RBufWriteStream stream( *sendBuf ); CleanupClosePushL( stream ); SerializeStringL( stream, appId ); SerializeStringL( stream, attribute ); SerializeStringL( stream, defaultValue.toString() ); CleanupStack::PopAndDestroy( &stream ); CBufFlat* recvBuf = CBufFlat::NewL( maxSize ); CleanupStack::PushL( recvBuf ); recvBuf->ExpandL( 0, maxSize ); TPtr8 sendArg( sendBuf->Ptr(0) ); TPtr8 recvArg( recvBuf->Ptr(0) ); User::LeaveIfError( SendReceive( EOpCodeGetWebAttribute, TIpcArgs( &sendArg, &recvArg ) ) ); // deserialize RDesReadStream rstream( recvArg ); CleanupClosePushL( rstream ); QString attrValue = DeserializeStringL( rstream ); CleanupStack::PopAndDestroy( 3, sendBuf ); // rstream, recvBuf, sendBuf return ( QVariant( attrValue ) ); }
std::ostream& GCType::print(std::ostream& stream) const { llvm::raw_os_ostream rstream(stream); GCTypePrintVisitor visitor(rstream); visitor.print(this); return stream; }
/** destroys the block_store ** n.b. everyone must have their hands off the block_store before you destroy it */ ~block_store() { moost::container::resource_stack< std::fstream >::scoped_resource rstream(m_rstreams); rstream->seekp(0); rstream->write(reinterpret_cast<const char *>(&m_allocated), sizeof(size_t)); rstream->seekp(getpos(m_allocated)); size_t free_list_size = m_free_list.size(); rstream->write(reinterpret_cast<const char *>(&free_list_size), sizeof(size_t)); if (free_list_size > 0) rstream->write(reinterpret_cast<const char *>(&m_free_list[0]), free_list_size * sizeof(size_t)); rstream->rdbuf()->pubsync(); }
DEF_TEST(Picture_preserveCullRect, r) { SkPictureRecorder recorder; SkCanvas* c = recorder.beginRecording(SkRect::MakeLTRB(1, 2, 3, 4)); c->clear(SK_ColorCYAN); sk_sp<SkPicture> picture(recorder.finishRecordingAsPicture()); SkDynamicMemoryWStream wstream; picture->serialize(&wstream); SkAutoTDelete<SkStream> rstream(wstream.detachAsStream()); sk_sp<SkPicture> deserializedPicture(SkPicture::MakeFromStream(rstream)); REPORTER_ASSERT(r, deserializedPicture != nullptr); REPORTER_ASSERT(r, deserializedPicture->cullRect().left() == 1); REPORTER_ASSERT(r, deserializedPicture->cullRect().top() == 2); REPORTER_ASSERT(r, deserializedPicture->cullRect().right() == 3); REPORTER_ASSERT(r, deserializedPicture->cullRect().bottom() == 4); }
// Process output when xsltproc exits. void XmlTransformerProc::processOutput() { QFile::remove(m_inFilename); int exitStatus = 11; if (m_xsltProc->normalExit()) exitStatus = m_xsltProc->exitStatus(); else kdDebug() << "XmlTransformerProc::processOutput: xsltproc was killed." << endl; delete m_xsltProc; m_xsltProc = 0; if (exitStatus != 0) { kdDebug() << "XmlTransformerProc::processOutput: xsltproc abnormal exit. Status = " << exitStatus << endl; m_state = fsFinished; QFile::remove(m_outFilename); emit filteringFinished(); return; } /// Read back the data that was written to /tmp/fileName.output. QFile readfile(m_outFilename); if(!readfile.open(IO_ReadOnly)) { /// uhh yeah... Issues writing to the output file. kdDebug() << "XmlTransformerProc::processOutput: Could not read file " << m_outFilename << endl; m_state = fsFinished; emit filteringFinished(); } QTextStream rstream(&readfile); m_text = rstream.read(); readfile.close(); kdDebug() << "XmlTransformerProc::processOutput: Read file at " + m_inFilename + " and created " + m_outFilename + " based on the stylesheet at " << m_xsltFilePath << endl; // Clean up. QFile::remove(m_outFilename); m_state = fsFinished; m_wasModified = true; emit filteringFinished(); }
void SkTypeface::serialize(SkWStream* wstream) const { bool isLocal = false; SkFontDescriptor desc(this->style()); this->onGetFontDescriptor(&desc, &isLocal); desc.serialize(wstream); if (isLocal) { int ttcIndex; // TODO: write this to the stream? SkAutoTUnref<SkStream> rstream(this->openStream(&ttcIndex)); if (rstream.get()) { size_t length = rstream->getLength(); wstream->writePackedUInt(length); wstream->writeStream(rstream, length); } else { wstream->writePackedUInt(0); } } else { wstream->writePackedUInt(0); } }
static sk_sp<SkPicture> copy_picture_via_serialization(SkPicture* src) { SkDynamicMemoryWStream wstream; src->serialize(&wstream); std::unique_ptr<SkStreamAsset> rstream(wstream.detachAsStream()); return SkPicture::MakeFromStream(rstream.get()); }
// --------------------------------------------------------- // CT_LbsClientPosTp261::StartL // // (other items were commented in a header). // --------------------------------------------------------- // void CT_LbsClientPosTp261::StartL() { _LIT(KService1, "Service1"); _LIT(KService2, "Service2"); _LIT(KService3, "Service3"); _LIT(KContact1, "Contact1"); _LIT(KContact2, "Contact2"); _LIT(KContact3, "Contact3"); CRequestor* serviceId1 = CRequestor::NewL(CRequestor::ERequestorService, CRequestor::EFormatApplication, KService1); CRequestor* serviceId2 = CRequestor::NewL(CRequestor::ERequestorService, CRequestor::EFormatApplication, KService2); CRequestor* serviceId3 = CRequestor::NewL(CRequestor::ERequestorService, CRequestor::EFormatApplication, KService3); CRequestor* contactId1 = CRequestor::NewL(CRequestor::ERequestorContact, CRequestor::EFormatTelephone, KContact1); CRequestor* contactId2 = CRequestor::NewL(CRequestor::ERequestorContact, CRequestor::EFormatUrl, KContact2); CRequestor* contactId3 = CRequestor::NewL(CRequestor::ERequestorContact, CRequestor::EFormatMail, KContact3); RRequestorStack stack = RRequestorStack(); CleanupStack::PushL(TCleanupItem(CleanOp ,&stack)); CleanupStack::PushL(serviceId1); CleanupStack::PushL(serviceId2); CleanupStack::PushL(serviceId3); CleanupStack::PushL(contactId1); CleanupStack::PushL(contactId2); CleanupStack::PushL(contactId3); ConnectL(); OpenPositioner(); stack.Append(serviceId1); stack.Append(contactId1); stack.Append(contactId2); stack.Append(serviceId2); stack.Append(contactId3); stack.Append(serviceId3); CleanupStack::Pop(contactId3); CleanupStack::Pop(contactId2); CleanupStack::Pop(contactId1); CleanupStack::Pop(serviceId3); CleanupStack::Pop(serviceId2); CleanupStack::Pop(serviceId1); TInt err = iPositioner.SetRequestor(stack); if (err != KErrNone) { _LIT(KErrorAndLeave, "Problems setting requestorstack"); LogErrorAndLeaveL(KErrorAndLeave); } const TInt KPosBufFlatExpandSize = 100; //ExternalizeL CBufFlat* bufFlat = CBufFlat::NewL(KPosBufFlatExpandSize); CleanupStack::PushL(bufFlat); RBufWriteStream stream(*bufFlat); CleanupClosePushL(stream); stack.ExternalizeL(stream); TPtr8 dataPtr((TUint8*)NULL, 0); dataPtr.Set(bufFlat->Ptr(0)); CleanupStack::PopAndDestroy(&stream); HBufC8* tempBuf = HBufC8::NewLC(bufFlat->Size()); TPtr8 ptr = tempBuf->Des(); ptr = dataPtr; //Internalize bufFlat->InsertL(0, ptr); RBufReadStream rstream(*bufFlat); CleanupClosePushL(rstream); RRequestorStack stack2 = RRequestorStack(); CleanupStack::PushL(TCleanupItem(CleanOp ,&stack2)); stack2.InternalizeL(rstream); // Verify the requestor stack VerifyRequestorStackL(stack2); _LIT(KResult, "The RequestorStack is correct after Externalize/Internalize"); INFO_PRINTF1(KResult); CleanupStack::PopAndDestroy(1); // CleanupOp stack2 CleanupStack::PopAndDestroy(&rstream); CleanupStack::PopAndDestroy(tempBuf); CleanupStack::PopAndDestroy(bufFlat); CleanupStack::PopAndDestroy(1); // CleanupOp stack1 ClosePositioner(); Disconnect(); }
// -------------------------------------------------------------------------- // // Function // Name: HTTPRequest::Receive(IOStreamGetLine &, int) // Purpose: Read the request from an IOStreamGetLine (and // attached stream). // Returns false if there was no valid request, // probably due to a kept-alive connection closing. // Created: 26/3/04 // // -------------------------------------------------------------------------- bool HTTPRequest::Receive(IOStreamGetLine &rGetLine, int Timeout) { // Check caller's logic if(mMethod != Method_UNINITIALISED) { THROW_EXCEPTION(HTTPException, RequestAlreadyBeenRead); } // Read the first line, which is of a different format to the rest of the lines std::string requestLine; if(!rGetLine.GetLine(requestLine, false /* no preprocessing */, Timeout)) { // Didn't get the request line, probably end of connection which had been kept alive return false; } BOX_TRACE("Request line: " << requestLine); // Check the method size_t p = 0; // current position in string p = requestLine.find(' '); // end of first word if(p == std::string::npos) { // No terminating space, looks bad p = requestLine.size(); } else { mHttpVerb = requestLine.substr(0, p); if (mHttpVerb == "GET") { mMethod = Method_GET; } else if (mHttpVerb == "HEAD") { mMethod = Method_HEAD; } else if (mHttpVerb == "POST") { mMethod = Method_POST; } else if (mHttpVerb == "PUT") { mMethod = Method_PUT; } else { mMethod = Method_UNKNOWN; } } // Skip spaces to find URI const char *requestLinePtr = requestLine.c_str(); while(requestLinePtr[p] != '\0' && requestLinePtr[p] == ' ') { ++p; } // Check there's a URI following... if(requestLinePtr[p] == '\0') { // Didn't get the request line, probably end of connection which had been kept alive return false; } // Read the URI, unescaping any %XX hex codes while(requestLinePtr[p] != ' ' && requestLinePtr[p] != '\0') { // End of URI, on to query string? if(requestLinePtr[p] == '?') { // Put the rest into the query string, without escaping anything ++p; while(requestLinePtr[p] != ' ' && requestLinePtr[p] != '\0') { mQueryString += requestLinePtr[p]; ++p; } break; } // Needs unescaping? else if(requestLinePtr[p] == '+') { mRequestURI += ' '; } else if(requestLinePtr[p] == '%') { // Be tolerant about this... bad things are silently accepted, // rather than throwing an error. char code[4] = {0,0,0,0}; code[0] = requestLinePtr[++p]; if(code[0] != '\0') { code[1] = requestLinePtr[++p]; } // Convert into a char code long c = ::strtol(code, NULL, 16); // Accept it? if(c > 0 && c <= 255) { mRequestURI += (char)c; } } else { // Simple copy of character mRequestURI += requestLinePtr[p]; } ++p; } // End of URL? if(requestLinePtr[p] == '\0') { // Assume HTTP 0.9 mHTTPVersion = HTTPVersion_0_9; } else { // Skip any more spaces while(requestLinePtr[p] != '\0' && requestLinePtr[p] == ' ') { ++p; } // Check to see if there's the right string next... if(::strncmp(requestLinePtr + p, "HTTP/", 5) == 0) { // Find the version numbers int major, minor; if(::sscanf(requestLinePtr + p + 5, "%d.%d", &major, &minor) != 2) { THROW_EXCEPTION_MESSAGE(HTTPException, BadRequest, "Unable to parse HTTP version number: " << requestLinePtr); } // Store version mHTTPVersion = (major * HTTPVersion__MajorMultiplier) + minor; } else { // Not good -- wrong string found THROW_EXCEPTION_MESSAGE(HTTPException, BadRequest, "Unable to parse HTTP request line: " << requestLinePtr); } } BOX_TRACE("HTTPRequest: method=" << mMethod << ", uri=" << mRequestURI << ", version=" << mHTTPVersion); // If HTTP 1.1 or greater, assume keep-alive if(mHTTPVersion >= HTTPVersion_1_1) { mClientKeepAliveRequested = true; } // Decode query string? if((mMethod == Method_GET || mMethod == Method_HEAD) && !mQueryString.empty()) { HTTPQueryDecoder decoder(mQuery); decoder.DecodeChunk(mQueryString.c_str(), mQueryString.size()); decoder.Finish(); } // Now parse the headers ParseHeaders(rGetLine, Timeout); std::string expected; if(GetHeader("Expect", &expected)) { if(expected == "100-continue") { mExpectContinue = true; } } // Parse form data? if(mMethod == Method_POST && mContentLength >= 0) { // Too long? Don't allow people to be nasty by sending lots of data if(mContentLength > MAX_CONTENT_SIZE) { THROW_EXCEPTION(HTTPException, POSTContentTooLong); } // Some data in the request to follow, parsing it bit by bit HTTPQueryDecoder decoder(mQuery); // Don't forget any data left in the GetLine object int fromBuffer = rGetLine.GetSizeOfBufferedData(); if(fromBuffer > mContentLength) fromBuffer = mContentLength; if(fromBuffer > 0) { BOX_TRACE("Decoding " << fromBuffer << " bytes of " "data from getline buffer"); decoder.DecodeChunk((const char *)rGetLine.GetBufferedData(), fromBuffer); // And tell the getline object to ignore the data we just used rGetLine.IgnoreBufferedData(fromBuffer); } // Then read any more data, as required int bytesToGo = mContentLength - fromBuffer; while(bytesToGo > 0) { char buf[4096]; int toRead = sizeof(buf); if(toRead > bytesToGo) toRead = bytesToGo; IOStream &rstream(rGetLine.GetUnderlyingStream()); int r = rstream.Read(buf, toRead, Timeout); if(r == 0) { // Timeout, just error THROW_EXCEPTION_MESSAGE(HTTPException, RequestReadFailed, "Failed to read complete request with the timeout"); } decoder.DecodeChunk(buf, r); bytesToGo -= r; } // Finish off decoder.Finish(); } else if (mContentLength > 0) { IOStream::pos_type bytesToCopy = rGetLine.GetSizeOfBufferedData(); if (bytesToCopy > mContentLength) { bytesToCopy = mContentLength; } Write(rGetLine.GetBufferedData(), bytesToCopy); SetForReading(); mpStreamToReadFrom = &(rGetLine.GetUnderlyingStream()); } return true; }
static sk_sp<SkPicture> copy_picture_via_serialization(SkPicture* src) { SkDynamicMemoryWStream wstream; src->serialize(&wstream); SkAutoTDelete<SkStreamAsset> rstream(wstream.detachAsStream()); return SkPicture::MakeFromStream(rstream); }