void TLSClient_Impl::application_data(DataBuffer record_plaintext) { if (conversation_state != cl_tls_state_connected) throw Exception("Unexpected application data record received"); int pos = recv_out_data.get_size(); recv_out_data.set_size(pos + record_plaintext.get_size()); memcpy(recv_out_data.get_data() + pos, record_plaintext.get_data(), record_plaintext.get_size()); }
DataBuffer * NetworkFunctions::createUpdateObjectBuffer(unsigned long netID) { GameObject * tempObject = gameObjects->getValue(netID); if (tempObject == NULL) return NULL; DataBuffer * tempBuffer = tempObject->serialize(); int functionIndex = EVENT_UPDATE_GAME_OBJECT; tempBuffer->copy(0, &functionIndex, 4); tempBuffer->copy(4, &netID, 4); return tempBuffer; }
int SSClient::SendMsg( Packet & packet ) { DataBuffer * buff = packet.GetBuffer(); int iRet = SockSend( buff->GetReadPtr(), buff->GetDataSize()); if(iRet < 0) return -1; return 0; }
void append(DataBuffer<sz>& dst, SegmentedSectionPtr ptr, SectionSegmentPool& pool) { Uint32 len = ptr.sz; while(len > SectionSegment::DataLength) { dst.append(ptr.p->theData, SectionSegment::DataLength); ptr.p = pool.getPtr(ptr.p->m_nextSegment); len -= SectionSegment::DataLength; } dst.append(ptr.p->theData, len); }
DataBuffer* GfxFeatureMapReplyPacket::getGfxFeatureMapData() { bool zipped = false; DataBuffer* maybeZippedBuf = getGfxFeatureMapData( zipped ); if ( zipped ) { // Zipped, means that we should unzip it. // Check unzipped length. int unzippedLength = GunzipUtil::origLength( maybeZippedBuf->getBufferAddress(), maybeZippedBuf->getBufferSize() ); // Unzip. DataBuffer* unzippedBuf = new DataBuffer( unzippedLength ); int retVal = GunzipUtil::gunzip( unzippedBuf->getBufferAddress(), unzippedBuf->getBufferSize(), maybeZippedBuf->getBufferAddress(), maybeZippedBuf->getBufferSize() ); delete maybeZippedBuf; if ( retVal < 0 ) { delete unzippedBuf; return NULL; } // Better read past the bytes just to make sure.. unzippedBuf->readPastBytes( unzippedLength ); return unzippedBuf; } else { // Was already unzipped. return maybeZippedBuf; } }
DataBuffer ZLibCompression::compress(const DataBuffer &data, bool raw, int compression_level, CompressionMode mode) { const int window_bits = 15; DataBuffer zbuffer(1024*1024); IODevice_Memory output; int strategy = MZ_DEFAULT_STRATEGY; switch (mode) { case default_strategy: strategy = MZ_DEFAULT_STRATEGY; break; case filtered: strategy = MZ_FILTERED; break; case huffman_only: strategy = MZ_HUFFMAN_ONLY; break; case rle: strategy = MZ_RLE; break; case fixed: strategy = MZ_FIXED; break; } mz_stream zs = { nullptr }; int result = mz_deflateInit2(&zs, compression_level, MZ_DEFLATED, raw ? -window_bits : window_bits, 8, strategy); // Undocumented: if wbits is negative, zlib skips header check if (result != MZ_OK) throw Exception("Zlib deflateInit failed"); try { zs.next_in = (unsigned char *) data.get_data(); zs.avail_in = data.get_size(); while (true) { zs.next_out = (unsigned char *) zbuffer.get_data(); zs.avail_out = zbuffer.get_size(); int result = mz_deflate(&zs, MZ_FINISH); if (result == MZ_NEED_DICT) throw Exception("Zlib deflate wants a dictionary!"); if (result == MZ_DATA_ERROR) throw Exception("Zip data stream is corrupted"); if (result == MZ_STREAM_ERROR) throw Exception("Zip stream structure was inconsistent!"); if (result == MZ_MEM_ERROR) throw Exception("Zlib did not have enough memory to compress file!"); if (result == MZ_BUF_ERROR) throw Exception("Not enough data in buffer when Z_FINISH was used"); if (result != MZ_OK && result != MZ_STREAM_END) throw Exception("Zlib deflate failed while compressing zip file!"); int zsize = zbuffer.get_size() - zs.avail_out; if (zsize == 0) break; output.write(zbuffer.get_data(), zsize); if (result == MZ_STREAM_END) break; } mz_deflateEnd(&zs); } catch (...) { mz_deflateEnd(&zs); throw; } return output.get_data(); }
void TestApp::test_aes192() { Console::write_line(" Header: aes192_encrypt.h and aes192_decrypt.h"); Console::write_line(" Class: AES192_Encrypt and AES192_Decrypt"); // Test data from http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf // and http://csrc.nist.gov/groups/ST/toolkit/documents/Examples/AES_CBC.pdf test_aes192_helper( "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b", // KEY "000102030405060708090A0B0C0D0E0F", // IV "6bc1bee22e409f96e93d7e117393172a" // PLAINTEXT "ae2d8a571e03ac9c9eb76fac45af8e51" "30c81c46a35ce411e5fbc1191a0a52ef" "f69f2445df4f9b17ad2b417be66c3710", "4f021db243bc633d7178183a9fa071e8" // CIPHERTEXT "b4d9ada9ad7dedf4e5e738763f69145a" "571b242012fb7ae07fa9baac3df102e0" "08b0e27988598881d920a9e64f5615cd" ); const int test_data_length = 192; unsigned char test_data[test_data_length]; std::vector<unsigned char> key; std::vector<unsigned char> iv; convert_ascii("8E73B0F7DA0E6452C810F32B809079E562F8EAD2522C6B7B", key); convert_ascii("000102030405060708090A0B0C0D0E0F", iv); for (int cnt=0; cnt<test_data_length; cnt++) { test_data[cnt] = (unsigned char) cnt; AES192_Encrypt aes192_encrypt; aes192_encrypt.set_iv(&iv[0]); aes192_encrypt.set_key(&key[0]); aes192_encrypt.add(test_data, cnt+1); aes192_encrypt.calculate(); AES192_Decrypt aes192_decrypt; aes192_decrypt.set_iv(&iv[0]); aes192_decrypt.set_key(&key[0]); DataBuffer buffer = aes192_encrypt.get_data(); aes192_decrypt.add(buffer.get_data(), buffer.get_size()); bool result = aes192_decrypt.calculate(); if (!result) fail(); DataBuffer buffer2 = aes192_decrypt.get_data(); if (buffer2.get_size() != cnt+1) fail(); unsigned char *data_ptr2 = (unsigned char *) buffer2.get_data(); if (memcmp(data_ptr2, test_data, cnt+1)) fail(); } }
void TestApp::test_aes128() { Console::write_line(" Header: aes128_encrypt.h and aes128_decrypt.h"); Console::write_line(" Class: AES128_Encrypt and AES128_Decrypt"); // Test data from http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf // and http://csrc.nist.gov/groups/ST/toolkit/documents/Examples/AES_CBC.pdf test_aes128_helper( "2b7e151628aed2a6abf7158809cf4f3c", // KEY "000102030405060708090A0B0C0D0E0F", // IV "6bc1bee22e409f96e93d7e117393172a" // PLAINTEXT "ae2d8a571e03ac9c9eb76fac45af8e51" "30c81c46a35ce411e5fbc1191a0a52ef" "f69f2445df4f9b17ad2b417be66c3710", "7649abac8119b246cee98e9b12e9197d" // CIPHERTEXT "5086cb9b507219ee95db113a917678b2" "73bed6b8e3c1743b7116e69e22229516" "3ff1caa1681fac09120eca307586e1a7" ); const int test_data_length = 128; unsigned char test_data[test_data_length]; std::vector<unsigned char> key; std::vector<unsigned char> iv; convert_ascii("2B7E151628AED2A6ABF7158809CF4F3C", key); convert_ascii("000102030405060708090A0B0C0D0E0F", iv); for (int cnt=0; cnt<test_data_length; cnt++) { test_data[cnt] = (unsigned char) cnt; AES128_Encrypt aes128_encrypt; aes128_encrypt.set_iv(&iv[0]); aes128_encrypt.set_key(&key[0]); aes128_encrypt.add(test_data, cnt+1); aes128_encrypt.calculate(); AES128_Decrypt aes128_decrypt; aes128_decrypt.set_iv(&iv[0]); aes128_decrypt.set_key(&key[0]); DataBuffer buffer = aes128_encrypt.get_data(); aes128_decrypt.add(buffer.get_data(), buffer.get_size()); bool result = aes128_decrypt.calculate(); if (!result) fail(); DataBuffer buffer2 = aes128_decrypt.get_data(); if (buffer2.get_size() != cnt+1) fail(); unsigned char *data_ptr2 = (unsigned char *) buffer2.get_data(); if (memcmp(data_ptr2, test_data, cnt+1)) fail(); } }
bool POIInfo::load( const MC2String& filename, uint32 offset ) { DataBuffer fileBuff; fileBuff.memMapFile( filename.c_str() ); DataBuffer offsetBuff( fileBuff.getBufferAddress() + offset, fileBuff.getBufferSize() - offset ); load( offsetBuff ); return true; }
// // Basic integrity test. // void integrity() { ClientSession ss(CssmAllocator::standard(), CssmAllocator::standard()); printf("* Generating random sample: "); DataBuffer<11> sample; ss.generateRandom(sample); for (uint32 n = 0; n < sample.length(); n++) printf("%.2x", ((unsigned char *)sample)[n]); printf("\n"); }
// -------------------------------------------------------------------------------------- // // Gets next hot heap (*pHotHeap, of index *pHotHeapIndex) from the heaps directory. // Returns S_OK and fills *pHotHeap and *pHotHeapIndex with the next code:HotHeap information. // Returns S_FALSE, if the last hot heap was already returned. Clears *pHotHeap and *pHotHeapIndex in this // case. // Returns error code if the format is invalid. Clears *pHotHeap and *pHotHeapIndex in this case. // __checkReturn HRESULT HotHeapsDirectoryIterator::GetNext( HotHeap *pHotHeap, HeapIndex *pHotHeapIndex) { HRESULT hr; DataBuffer hotHeapHeaderData; DataBuffer hotHeapData; struct HotHeapsDirectoryEntry *pEntry; if (!m_RemainingHeapsDirectoryData.GetData<struct HotHeapsDirectoryEntry>( &pEntry)) { hr = S_FALSE; goto ErrExit; } if (!HeapIndex::IsValid(pEntry->m_nHeapIndex)) { Debug_ReportError("Invalid hot heaps directory format - invalid heap index."); IfFailGo(METADATA_E_INVALID_FORMAT); } pHotHeapIndex->Set(pEntry->m_nHeapIndex); hotHeapHeaderData = m_HotHeapsData; if (!hotHeapHeaderData.SkipToExactSize(pEntry->m_nHeapHeaderStart_NegativeOffset)) { Debug_ReportError("Invalid hot heaps directory format - heap header offset reaches in front of of hot heaps data."); IfFailGo(METADATA_E_INVALID_FORMAT); } struct HotHeapHeader *pHeader; if (!hotHeapHeaderData.PeekData<struct HotHeapHeader>(&pHeader)) { Debug_ReportError("Invalid hot heaps directory format - heap header reaches behind hot heaps data."); IfFailGo(METADATA_E_INVALID_FORMAT); } hotHeapData = m_HotHeapsData; if (!hotHeapData.TruncateBySize(pEntry->m_nHeapHeaderStart_NegativeOffset)) { Debug_ReportInternalError("There's a bug because previous call to SkipToExactSize succeeded."); IfFailGo(METADATA_E_INVALID_FORMAT); } IfFailGo(pHotHeap->Initialize(pHeader, hotHeapData)); _ASSERTE(hr == S_OK); return hr; ErrExit: pHotHeap->Clear(); pHotHeapIndex->SetInvalid(); return hr; } // HotHeapsDirectoryIterator::GetNext
void saveBuffer( const DataBuffer& buff, int fd ) throw (MC2String) { int retVal = write( fd, buff.getBufferAddress(), buff.getCurrentOffset() ); if ( retVal == -1 ) { throw MC2String("[DBU]: Could not write: ") + strerror(errno); } else if ( uint32(retVal) != buff.getCurrentOffset() ) { throw MC2String("[DBU]: Could not write buffer. Short byte count"); } }
bool StreamSoundSource::fillBufferAndQueue(uint buffer) { if(m_waitingFile) return false; // fill buffer static DataBuffer<char> bufferData(2*STREAM_FRAGMENT_SIZE); ALenum format = m_soundFile->getSampleFormat(); int maxRead = STREAM_FRAGMENT_SIZE; if(m_downMix != NoDownMix) maxRead *= 2; int bytesRead = 0; do { bytesRead += m_soundFile->read(&bufferData[bytesRead], maxRead - bytesRead); // end of sound file if(bytesRead < maxRead) { if(m_looping) m_soundFile->reset(); else { m_eof = true; break; } } } while(bytesRead < maxRead); if(bytesRead > 0) { if(m_downMix != NoDownMix) { if(format == AL_FORMAT_STEREO16) { assert(bytesRead % 2 == 0); bytesRead /= 2; uint16_t *data = (uint16_t*)bufferData.data(); for(int i=0;i<bytesRead/2;i++) data[i] = data[2*i + (m_downMix == DownMixLeft ? 0 : 1)]; format = AL_FORMAT_MONO16; } } alBufferData(buffer, format, &bufferData[0], bytesRead, m_soundFile->getRate()); ALenum err = alGetError(); if(err != AL_NO_ERROR) g_logger.error(stdext::format("unable to refill audio buffer for '%s': %s", m_soundFile->getName(), alGetString(err))); alSourceQueueBuffers(m_sourceId, 1, &buffer); err = alGetError(); if(err != AL_NO_ERROR) g_logger.error(stdext::format("unable to queue audio buffer for '%s': %s", m_soundFile->getName(), alGetString(err))); } // return false if there aren't more buffers to fill return (bytesRead >= STREAM_FRAGMENT_SIZE && !m_eof); }
bool ReadSingleSensor::Response::match(DataBuffer& data) { const uint16 TOTAL_BYTES = 5; //if there aren't enough bytes in the buffer to match the response if(data.bytesRemaining() < TOTAL_BYTES) { //not a good response m_success = false; return false; } //create a save point with the data ReadBufferSavePoint savePoint(&data); //verify the command id if(data.read_uint8() != 0x03) { //not a good response m_success = false; return false; } uint16 sensorVal = data.read_uint16(); ChecksumBuilder checksum; checksum.append_uint16(sensorVal); //value of the requested channel //verify the checksum (only a checksum on the actual data value) if(checksum.simpleChecksum() != data.read_uint16()) { //not a good response m_success = false; return false; } //if we made it this far, the bytes match the expected response m_success = true; m_sensorValue = sensorVal; //commit the current read position savePoint.commit(); //we have fully matched the response m_fullyMatched = true; //notify that the response was matched m_matchCondition.notify(); return true; }
void Texture::create(char *name, char *filename, unsigned char relativePath, unsigned int flags, unsigned char filter, float anisotropicFilter) { strcpy(this->name, name); DataBuffer *dataBuffer = new DataBuffer(); dataBuffer->read(filename, relativePath); if (dataBuffer->getSize()) { load(dataBuffer); generateId(flags, filter, anisotropicFilter); freePixel(); delete dataBuffer; } }
void PredicateIndex::serialize(DataBuffer &buffer) const { _features_store.serialize(buffer); buffer.writeInt16(_arity); buffer.writeInt32(_zero_constraint_docs.size()); for (auto it = _zero_constraint_docs.begin(); it.valid(); ++it) { buffer.writeInt32(it.getKey()); } IntervalSerializer<Interval> interval_serializer(_interval_store); _interval_index.serialize(buffer, interval_serializer); IntervalSerializer<IntervalWithBounds> bounds_serializer(_interval_store); _bounds_index.serialize(buffer, bounds_serializer); }
DataBuffer IconSet_Impl::create_ico_helper(const std::vector<PixelBuffer> &images, int type, const std::vector<Point> &hotspots) { DataBuffer buf; buf.set_capacity(32*1024); MemoryDevice device(buf); IconHeader header; memset(&header, 0, sizeof(IconHeader)); header.idType = type; header.idCount = images.size(); device.write(&header, sizeof(IconHeader)); std::vector<PixelBuffer> bmp_images; for (auto & image : images) bmp_images.push_back(create_bitmap_data(image)); int image_offset = size_header + size_direntry*bmp_images.size(); for (size_t i = 0; i < bmp_images.size(); i++) { IconDirectoryEntry entry; memset(&entry, 0, sizeof(IconDirectoryEntry)); entry.bWidth = bmp_images[i].get_width(); entry.bHeight = bmp_images[i].get_height(); entry.bColorCount = 0; entry.wPlanes = 1; entry.wBitCount = 32; entry.dwBytesInRes = size_bitmap_info + bmp_images[i].get_pitch() * bmp_images[i].get_height(); entry.dwImageOffset = image_offset; if (type == 2) { entry.XHotspot = hotspots[i].x; entry.YHotspot = hotspots[i].y; } device.write(&entry, size_direntry); image_offset += entry.dwBytesInRes; } for (auto & bmp_image : bmp_images) { IconBitmapInfoHeader bmp_header; memset(&bmp_header, 0, sizeof(IconBitmapInfoHeader)); bmp_header.biSize = size_bitmap_info; bmp_header.biWidth = bmp_image.get_width(); bmp_header.biHeight = bmp_image.get_height() * 2; // why on earth do I have to multiply this by two?? bmp_header.biPlanes = 1; bmp_header.biBitCount = 32; bmp_header.biCompression = bi_rgb; device.write(&bmp_header, size_bitmap_info); device.write(bmp_image.get_data(), bmp_image.get_pitch() * bmp_image.get_height()); } return device.get_data(); }
void Message::setData(DataBuffer db) { //kill the previous buffer buffer.clear(); buffer.resize(db.size()); //copy the data buffer buffer.write(db.data(), db.size()); msgHasReadLength = true; msgLength = buffer.size(); }
bool NavMapHandler::handleVectorMap( UserItem* userItem, NavRequestPacket* req, NavReplyPacket* reply ) { bool ok = true; // The params const NParamBlock& params = req->getParamBlock(); NParamBlock& rparams = reply->getParamBlock(); uint32 startTime = TimeUtility::getCurrentTime(); MC2String reqStr; // Start parameter printing mc2log << info << "handleVectorMap:"; if ( params.getParam( 2400 ) ) { reqStr = params.getParam( 2400 )->getString( m_thread->clientUsesLatin1()); mc2log << " " << reqStr; } mc2log << endl; rparams.addParam( NParam( 2500, reqStr, m_thread->clientUsesLatin1() ) ); DataBuffer* data = m_thread->getTileMap( reqStr.c_str() ); if ( data != NULL ) { NParam& pdata = rparams.addParam( NParam( 2501 ) ); pdata.addByteArray( data->getBufferAddress(), data->getCurrentOffset() ); mc2log << info << "handleVectorMap: Reply " << data->getCurrentOffset() << " bytes" << endl; } else { // Error mc2log << warn << "handleVectorMap: NULL TileMap answer: "; if ( TimeUtility::getCurrentTime() - startTime > 3000 ) { reply->setStatusCode( NavReplyPacket::NAV_STATUS_REQUEST_TIMEOUT ); mc2log << "Timeout"; } else { reply->setStatusCode( NavReplyPacket::NAV_STATUS_NOT_OK ); mc2log << "Error"; } mc2log << endl; } delete data; return ok; }
DataBuffer CursorProvider_Win32::create_ico_helper(const std::vector<PixelBuffer> &images, const std::vector<Rect> &rects, WORD type, const std::vector<Point> &hotspots) { DataBuffer buf; buf.set_capacity(32 * 1024); MemoryDevice device(buf); ICONHEADER header; memset(&header, 0, sizeof(ICONHEADER)); header.idType = type; header.idCount = images.size(); device.write(&header, sizeof(ICONHEADER)); std::vector<PixelBuffer> bmp_images; for (size_t i = 0; i < images.size(); i++) bmp_images.push_back(Win32Window::create_bitmap_data(images[i], rects[i])); for (size_t i = 0; i < bmp_images.size(); i++) { IconDirectoryEntry entry; memset(&entry, 0, sizeof(IconDirectoryEntry)); entry.bWidth = bmp_images[i].get_width(); entry.bHeight = bmp_images[i].get_height(); entry.bColorCount = 0; entry.wPlanes = 1; entry.wBitCount = 32; entry.dwBytesInRes = sizeof(BITMAPINFOHEADER) + bmp_images[i].get_pitch() * bmp_images[i].get_height(); entry.dwImageOffset = size_header + size_direntry*bmp_images.size(); if (type == 2) { entry.XHotspot = hotspots[i].x; entry.YHotspot = hotspots[i].y; } device.write(&entry, sizeof(IconDirectoryEntry)); } for (size_t i = 0; i < bmp_images.size(); i++) { BITMAPINFOHEADER bmp_header; memset(&bmp_header, 0, sizeof(BITMAPINFOHEADER)); bmp_header.biSize = sizeof(BITMAPINFOHEADER); bmp_header.biWidth = bmp_images[i].get_width(); bmp_header.biHeight = bmp_images[i].get_height() * 2; // why on earth do I have to multiply this by two?? bmp_header.biPlanes = 1; bmp_header.biBitCount = 32; bmp_header.biCompression = BI_RGB; bmp_header.biSizeImage = bmp_images[i].get_pitch() * bmp_images[i].get_height(); device.write(&bmp_header, sizeof(BITMAPINFOHEADER)); device.write(bmp_images[i].get_data(), bmp_images[i].get_pitch() * bmp_images[i].get_height()); } return device.get_data(); }
void Slider::timerTick(){ if(renderer){ DataBuffer<float> *b = renderer->getBuffer()->getFloatBuffer(); Datum<float> *d = b->read(0); if(d && d->isRecent()){ if(d->t > out->timeSent){ // printf("New data : %f. Outvar set to %f\n",d->d,out->val); machine.get().onNewData(this,d->d); } } } }
void MsgClient::HandleInnerData( socket_t *sock, const char *data, int len ) { User user = _online_user.GetUserBySocket( sock ) ; if ( user._user_id.empty() ) { OUT_ERROR( sock->_szIp, sock->_port, "CAIS" , "find fd %d user failed, data %s", sock->_fd, data ) ; return ; } user._last_active_time = time(NULL) ; _online_user.SetUser( user._user_id, user ) ; string line( data, len ) ; vector<string> vec ; if ( ! splitvector( line, vec, " " , 6 ) ){ OUT_ERROR( sock->_szIp, sock->_port, user._user_name.c_str() , "fd %d data error: %s", sock->_fd, data ) ; return ; } DataBuffer buf ; string head = vec[0] ; string seqid = vec[1] ; string macid = vec[2] ; string code = vec[3] ; // 通信码,对于点名数据的区分 string cmd = vec[4] ; string val = vec[5] ; if ( head == "CAITS" ) { if( cmd == "U_REPT" ){ // 上报类消息处理 _convert->convert_urept( macid , val , buf , ( code == "201") ) ; } else if( cmd == "D_CTLM" ) { // ToDo: 控制类消息处理 } else if( cmd == "D_SNDM" ) { // ToDo : 消息发送的处理 } else { OUT_WARNING( sock->_szIp, sock->_port, user._user_name.c_str() , "except message:%s", (const char*)data ) ; } } else { // 处理通应应答消息 _convert->convert_comm( seqid, macid, val, buf ) ; } if( buf.getLength() > 0 ) { // 添加用户会话中 _session.AddSession( macid, user._user_id ) ; // 发送指定的地区用户 _pEnv->GetPasClient()->HandleData( buf.getBuffer(), buf.getLength() ) ; } }
int SFProtobufProtocol::tryDeframeIncomingPacket(DataBuffer& Buffer, BasePacket*& pPacket, int& packetId, unsigned int& nExtractedBytes) { if(Buffer.GetDataSize() < 8) return SFProtocol::eIncompletePacket; char* pBuffer = Buffer.GetBuffer(); unsigned int sStart = 0; unsigned int packetLen = 0; packetId = 0; unsigned int sEnd = 0; for (int i=0; i<2; i++) { *((BYTE*)(&sStart)+i)=pBuffer[i]; *((BYTE*)(&packetLen)+i)=pBuffer[i+2]; *((BYTE*)(&packetId) + i) = pBuffer[i + 4]; } if (sStart!=SignatureStart) return SFProtocol::eCorruptPacket; if (packetLen > Buffer.GetDataSize()) return SFProtocol::eIncompletePacket; for (int i=0; i<2; i++) *((BYTE*)(&sEnd)+i)=pBuffer[packetLen-2+i]; if(sEnd!=SignatureEnd) return SFProtocol::eCorruptPacket; char* pData = pBuffer + 6; unsigned int dataSize = packetLen - 8; nExtractedBytes = packetLen; pPacket = CreateIncomingPacketFromPacketId(packetId); if(pPacket==NULL) return SFProtocol::eUndefinedFailure; if(!pPacket->Decode(pData, dataSize)) { disposeIncomingPacket(pPacket); return SFProtocol::eDecodingFailure; } return SFProtocol::Success; }
// 序列化接口 void OracleSqlObj::Seralize( DataBuffer &buf ) { int nsize = _kv.size(); // 写入字段个数 buf.writeInt16( nsize ); // 写入插入的字段 if ( nsize > 0 ) { CKVMap::iterator it; for ( it = _kv.begin(); it != _kv.end() ; ++ it ) { buf.writeInt16( it->first.length() ); buf.writeBlock( it->first.c_str(), it->first.length() ); _SqlVal &v = it->second; buf.writeInt8( v._type ); switch( v._type ) { case TYPE_INT: buf.writeInt32( v._nval ); break ; case TYPE_LONGLONG: buf.writeInt64(v._llval); break; case TYPE_STRING: case TYPE_VAR: buf.writeInt16( v._sval.length() ); buf.writeBlock( v._sval.c_str(), v._sval.length() ); break ; default: break ; } } } }
size_t GenericHeader::Tag::read(DataBuffer &buf) { char *pos = buf.getData(); vespalib::string name(pos); buf.moveDataToDead(name.size() + 1); uint8_t type = buf.readInt8(); switch (type) { case TYPE_FLOAT: _fVal = buf.readDouble(); break; case TYPE_INTEGER: _iVal = buf.readInt64(); break; case TYPE_STRING: _sVal = vespalib::string(buf.getData()); buf.moveDataToDead(_sVal.size() + 1); break; default: throw IllegalHeaderException("Can not deserialize empty tag."); } _name = name; // assign here for exception safety _type = (Type)type; return buf.getData() - pos; }
void POIInfo::load( DataBuffer& buff ) { mc2dbg8 << "[POIInfo] loading." << endl; buff.alignToLong(); m_staticID = buff.readNextLong(); m_dynamicInfo = buff.readNextLong(); uint32 nbrPOIInfos = buff.readNextLong(); mc2dbg8 << "static id: " << m_staticID << endl; mc2dbg8 << "dynamicInfo: " << m_dynamicInfo << endl; mc2dbg8 << "[POIInfo] #" << nbrPOIInfos << " poi infos." << endl; STLUtility::deleteValues( m_poiInfos ); m_poiInfos.resize( nbrPOIInfos ); // read infos for ( uint32 i = 0; i < m_poiInfos.size(); ++i ) { buff.alignToLong(); uint32 type = buff.readNextLong(); LangTypes::language_t lang = static_cast<LangTypes::language_t>( buff.readNextLong() ); MC2String str = buff.readNextString(); m_poiInfos[ i ] = new POIInfoData( type, lang, str ); } }
/*发送透明传输数据*/ bool CVechileMgr::SendTransparentMsg(_stVechile *p , int ncount,unsigned short wType) { if( ncount <= 0 ) { return false ; } DataBuffer transport_buf; TransHeader header; int nLen = _logistics->BuildTransportData(wType,transport_buf); OUT_HEX(NULL, 0, "Transport", transport_buf.getBuffer(),transport_buf.getLength()); BuildHeader(header.header, 0x900,nLen, p); DataBuffer sendbuf; sendbuf.writeBlock(&header, sizeof(header)); sendbuf.writeBlock(transport_buf.getBuffer(), transport_buf.getLength()); unsigned short mlen = (sendbuf.getLength()-sizeof(GBheader)) & 0x03FF ; sendbuf.fillInt16( mlen, 3 ) ; GBFooter footer ; sendbuf.writeBlock(&footer, sizeof(footer) ) ; if ( ! Send5BData( p->fd_, sendbuf.getBuffer(), sendbuf.getLength() ) ) { p->car_state_ = OFF_LINE ; return false ; } p->lgs_time_ = share::Util::currentTimeUsec() ; return true ; }
bool DataBuffer::Test( ) { bool ok = true; cout << "Testing DataBuffer" << endl; DataBuffer buff; TESTCHECK( buff.Data() == 0, true, &ok ); TESTCHECK( buff.Size(), 0, &ok ); char sIn[ 10 ] = "123456789"; Foo fIn = { 127, 2.5f }; cout << "Add( char *, 10 )" << endl; buff.Add( sIn, 10 ); TESTCHECK( *buff.Data(), '1', &ok ); TESTCHECK( buff.Size(), 10, &ok ); cout << "Add( Foo )" << endl; buff.Add( fIn ); cout << "Read( 10 )" << endl; const char * sOut = buff.Read( 10 ); TESTCHECK( (string( sIn ) == string( sOut )), true, &ok ); cout << "Read< Foo >()" << endl; const Foo * pFoo = buff.Read< Foo >( ); TESTCHECK( pFoo->i, 127, &ok ); TESTCHECK( pFoo->f, 2.5f, &ok ); if ( ok ) cout << "DataBuffer PASSED." << endl << endl; else cout << "DataBuffer FAILED." << endl << endl; return ok; }
bool ShortPing::Response::match(DataBuffer& data) { const uint16 TOTAL_BYTES = 1; //if there aren't enough bytes in the buffer to match the response if(data.bytesRemaining() < TOTAL_BYTES) { //not a good response m_success = false; return false; } //create a save point with the data ReadBufferSavePoint savePoint(&data); uint8 resultByte = data.read_uint8(); //single byte 0x21 is a fail response if(resultByte == 0x21) { //legitimate fail response m_success = false; } //single byte 0x02 is a success response else if(resultByte == WirelessProtocol::cmdId_shortPing) { //success response m_success = true; } else { //non-matching response m_success = false; return false; } //if we made it this far, the bytes match the expected response (success or fail) //commit the current read position savePoint.commit(); //we have fully matched the response m_fullyMatched = true; //notify that the response was matched m_matchCondition.notify(); return true; }
// -------------------------------------------------------------------------------------- // // Initializes hot heap from its header and data. // Provides limited debug-only validation of the structure. // __checkReturn HRESULT HotHeap::Initialize( struct HotHeapHeader *pHotHeapHeader, DataBuffer hotHeapData) { _ASSERTE(hotHeapData.GetDataPointerBehind() == reinterpret_cast<BYTE *>(pHotHeapHeader)); UINT32 nMaximumNegativeOffset = hotHeapData.GetSize(); if (pHotHeapHeader->m_nIndexTableStart_NegativeOffset > nMaximumNegativeOffset) { m_pHotHeapHeader = NULL; Debug_ReportError("Invalid hot heap header format - invalid index table offset."); return METADATA_E_INVALID_FORMAT; } if ((pHotHeapHeader->m_nIndexTableStart_NegativeOffset % 4) != 0) { m_pHotHeapHeader = NULL; Debug_ReportError("Invalid hot heap header format - index table offset is not aligned."); return METADATA_E_INVALID_FORMAT; } if (pHotHeapHeader->m_nValueOffsetTableStart_NegativeOffset > nMaximumNegativeOffset) { m_pHotHeapHeader = NULL; Debug_ReportError("Invalid hot heap header format - invalid value offset table offset."); return METADATA_E_INVALID_FORMAT; } if ((pHotHeapHeader->m_nValueOffsetTableStart_NegativeOffset % 4) != 0) { m_pHotHeapHeader = NULL; Debug_ReportError("Invalid hot heap header format - value offset table offset is not aligned."); return METADATA_E_INVALID_FORMAT; } // Index table has to be behind value offset table if (pHotHeapHeader->m_nValueOffsetTableStart_NegativeOffset < pHotHeapHeader->m_nIndexTableStart_NegativeOffset) { m_pHotHeapHeader = NULL; Debug_ReportError("Invalid hot heap header format - value offset table doesn't start before index table."); return METADATA_E_INVALID_FORMAT; } if (pHotHeapHeader->m_nValueHeapStart_NegativeOffset > nMaximumNegativeOffset) { m_pHotHeapHeader = NULL; Debug_ReportError("Invalid hot heap header format - invalid value heap offset."); return METADATA_E_INVALID_FORMAT; } m_pHotHeapHeader = pHotHeapHeader; return S_OK; } // HotHeap::Initialize