void BottomlineWindow::HandleInputMethodEvent(BMessage* event, EventList& newEvents) { CALLED(); PostMessage(event, fTextView); const char* string; bool confirmed; int32 opcode; if (event->FindInt32("be:opcode", &opcode) != B_OK || opcode != B_INPUT_METHOD_CHANGED || event->FindBool("be:confirmed", &confirmed) != B_OK || !confirmed || event->FindString("be:string", &string) != B_OK) return; SERIAL_PRINT(("IME : %i, %s\n", opcode, string)); SERIAL_PRINT(("IME : confirmed\n")); int32 length = strlen(string); int32 offset = 0; int32 nextOffset = 0; while (offset < length) { // this is supposed to go to the next UTF-8 character for (++nextOffset; (string[nextOffset] & 0xC0) == 0x80; ++nextOffset) ; BMessage *newEvent = new BMessage(B_KEY_DOWN); if (newEvent != NULL) { newEvent->AddInt32("key", 0); newEvent->AddInt64("when", system_time()); BString bytes(string + offset, nextOffset - offset); newEvent->AddString("bytes", bytes); newEvent->AddInt32("raw_char", 0xa); newEvents.AddItem(newEvent); } offset = nextOffset; } }
Connection::Connection(CryptoIdentity& ci, Path path, ConnectionPool& cp, ConnectionHandler& ch) : Forwarding(randint64()) , _ci(&ci) , _cp(cp) , _ch(ch) , _naclsession( std::get<1>(path.at(path.size()-1))->enc_key() ) , _their_id( std::get<1>(path.at(path.size()-1))->id() ) , _route_id( bytes( id() ) ) , _authenticated(false) , _request_packet(new std::string) , _packet_queue(new std::vector<std::string>) , _nonces(nullptr) { _request_packet->push_back('\1'); std::string nonce = _route_id + randomstring(8); _request_packet->append(nonce); nonce.resize(crypto_box_NONCEBYTES,'\0'); RoutingRequest rq; rq.set_enc_algo(enumval(PkencAlgo::CURVE25519XSALSA20POLY1305)); rq.set_sender_pubkey(_naclsession.our_pk()); Hop hop; { hop.set_type(Hop::UP); hop.set_nonce_algo(Hop::XTEA32); rq.set_details(_naclsession.encrypt(hop.SerializeAsString(), nonce)); } hop.Clear(); hop.set_type(Hop::SIMPLE); hop.set_next(_their_id); for (signed int i=path.size()-2; i>=0; --i) { auto dev = std::get<1>(path[i]); hop.set_details(rq.details()); rq.set_details( crypto_box( hop.SerializeAsString(), nonce, dev->enc_key(), _naclsession.our_sk()) ); hop.set_next(dev->id()); } rq.AppendToString(_request_packet.get()); }
void BitSourceTest::testSource() { byte rawBytes[] = {(byte) 1, (byte) 2, (byte) 3, (byte) 4, (byte) 5}; ArrayRef<byte> bytes(rawBytes, 5); BitSource source(bytes); CPPUNIT_ASSERT_EQUAL(40, source.available()); CPPUNIT_ASSERT_EQUAL(0, source.readBits(1)); CPPUNIT_ASSERT_EQUAL(39, source.available()); CPPUNIT_ASSERT_EQUAL(0, source.readBits(6)); CPPUNIT_ASSERT_EQUAL(33, source.available()); CPPUNIT_ASSERT_EQUAL(1, source.readBits(1)); CPPUNIT_ASSERT_EQUAL(32, source.available()); CPPUNIT_ASSERT_EQUAL(2, source.readBits(8)); CPPUNIT_ASSERT_EQUAL(24, source.available()); CPPUNIT_ASSERT_EQUAL(12, source.readBits(10)); CPPUNIT_ASSERT_EQUAL(14, source.available()); CPPUNIT_ASSERT_EQUAL(16, source.readBits(8)); CPPUNIT_ASSERT_EQUAL(6, source.available()); CPPUNIT_ASSERT_EQUAL(5, source.readBits(6)); CPPUNIT_ASSERT_EQUAL(0, source.available()); }
// // Free a block of memory. // void Heap::free(void* ptr) { Print tracef(this->output()); if (this->tracing) { tracef("Heap[%p]::free(%p)\n", this, ptr); } Alignment* optr = static_cast<Alignment*>(ptr); if (0 != optr) { size_t osize = *(--optr); size_t nsize = bytes(words(osize)); this->current -= nsize; delete [] optr; ++this->frees; } else { ++this->nulls; } }
std::string HDSeed::Bip32Root(const std::string& fingerprint) const { // TODO: make fingerprint non-const std::string input(fingerprint); std::uint32_t notUsed = 0; auto seed = Seed(input, notUsed); if (!seed) { return ""; } auto start = static_cast<const unsigned char*>(seed->getMemory()); const auto end = start + seed->getMemorySize(); std::vector<unsigned char> bytes(start, end); std::ostringstream stream; stream << std::hex << std::setfill('0'); for (int byte : bytes) { stream << std::setw(2) << byte; } return stream.str(); }
/*! Returns the binary representation of this QUuid. The byte array is in big endian format, and formatted according to RFC 4122, section 4.1.2 - "Layout and byte order". The order is as follows: \table \header \li Field # \li Source \row \li 1 \li data1 \row \li 2 \li data2 \row \li 3 \li data3 \row \li 4 \li data4[0] .. data4[7] \endtable \since 4.8 */ QByteArray QUuid::toRfc4122() const { // we know how many bytes a UUID has, I hope :) QByteArray bytes(16, Qt::Uninitialized); uchar *data = reinterpret_cast<uchar*>(bytes.data()); qToBigEndian(data1, data); data += sizeof(quint32); qToBigEndian(data2, data); data += sizeof(quint16); qToBigEndian(data3, data); data += sizeof(quint16); for (int i = 0; i < 8; ++i) { *(data) = data4[i]; data++; } return bytes; }
Bytes PyValue::asBytes() { if (m_symbolGroup) return Bytes(); ULONG64 address = 0; if (FAILED(m_symbolGroup->GetSymbolOffset(m_index, &address))) return Bytes(); ULONG size; if (FAILED(m_symbolGroup->GetSymbolSize(m_index, &size))) return Bytes(); Bytes bytes(size); unsigned long received; auto data = ExtensionCommandContext::instance()->dataSpaces(); if (FAILED(data->ReadVirtual(address, bytes.data(), size, &received))) return Bytes(); bytes.resize(received); return bytes; }
MethodLivenessResult MethodLiveness::BasicBlock::get_liveness_at(ciMethod* method, int bci) { MethodLivenessResult answer(NEW_RESOURCE_ARRAY(size_t, _analyzer->bit_map_size_words()), _analyzer->bit_map_size_bits()); answer.set_is_valid(); #ifndef ASSERT if (bci == start_bci()) { answer.set_from(_entry); return answer; } #endif #ifdef ASSERT ResourceMark rm; BitMap g(_gen.size()); g.set_from(_gen); BitMap k(_kill.size()); k.set_from(_kill); #endif if (_last_bci != bci || trueInDebug) { ciBytecodeStream bytes(method); bytes.reset_to_bci(bci); bytes.set_max_bci(limit_bci()); compute_gen_kill_range(&bytes); assert(_last_bci != bci || (g.is_same(_gen) && k.is_same(_kill)), "cached computation is incorrect"); _last_bci = bci; } answer.clear(); answer.set_union(_normal_exit); answer.set_difference(_kill); answer.set_union(_gen); answer.set_union(_exception_exit); #ifdef ASSERT if (bci == start_bci()) { assert(answer.is_same(_entry), "optimized answer must be accurate"); } #endif return answer; }
I rand_int(size_t max_bits = ::test_max_bits) { std::vector<uint8_t> bytes((max_bits+7)/8); assert(!bytes.empty()); static uint32_t rand_state = 0x123456; auto R = [&]() { rand_state = rand_state * 1664525 + 1013904223; return static_cast<uint8_t>(uint64_t(rand_state)*255/(UINT64_C(1)<<32)); }; for (auto& b : bytes) { b = R(); } if (max_bits % 8) { const auto first_max = (1<<max_bits%8)-1; std::cout << "first_max = " << first_max << std::endl; while (bytes[0] > first_max) bytes[0] = R(); } return funtls::be_uint_from_bytes<I>(bytes); }
void labPort::sendMsg( const char* msg, int numChars, bool inTime ) { if( _closing ) { return; } QByteArray bytes( msg, numChars ); _msgToSend.push_back( bytes ); if( !_sendTimer.isActive() ) { timeToSendMsg(); _sendTimer.start( _writingPauseMs ); } if( inTime ) { _inTimeValueCounter++; } }
/******************************************************************************* ** ** Function: nativeLlcpSocket_doReceive ** ** Description: Receive data from peer. ** e: JVM environment. ** o: Java object. ** origBuffer: Buffer to put received data. ** ** Returns: Number of bytes received. ** *******************************************************************************/ static jint nativeLlcpSocket_doReceive(JNIEnv *e, jobject o, jbyteArray origBuffer) { ALOGD_IF ((appl_trace_level>=BT_TRACE_LEVEL_DEBUG), "%s: enter", __FUNCTION__); ScopedByteArrayRW bytes(e, origBuffer); PeerToPeer::tJNI_HANDLE jniHandle = (PeerToPeer::tJNI_HANDLE) nfc_jni_get_nfc_socket_handle(e, o); uint16_t actualLen = 0; bool stat = PeerToPeer::getInstance().receive(jniHandle, reinterpret_cast<UINT8*>(&bytes[0]), bytes.size(), actualLen); jint retval = 0; if (stat && (actualLen>0)) { retval = actualLen; } else retval = -1; ALOGD_IF ((appl_trace_level>=BT_TRACE_LEVEL_DEBUG), "%s: exit; actual len=%d", __FUNCTION__, retval); return retval; }
void SerialModule::serialDataReceived(const var & data) { inActivityTrigger->trigger(); switch (port->mode) { case SerialDevice::LINES: processDataLine(data.toString()); break; case SerialDevice::DATA255: case SerialDevice::RAW: case SerialDevice::COBS: Array<uint8> bytes((const uint8_t *)data.getBinaryData()->getData(), (int)data.getBinaryData()->getSize()); processDataBytes(bytes); break; } }
STD1::uint32_t ControlButton::write( std::FILE *out ) const { STD1::uint32_t bytes( sizeof( STD1::uint16_t ) * 2 ); STD1::uint16_t type( 1 ); if( std::fwrite( &type, sizeof( STD1::uint16_t), 1, out) != 1 ) throw FatalError( ERR_WRITE ); if( std::fwrite( &res, sizeof( STD1::uint16_t), 1, out) != 1 ) throw FatalError( ERR_WRITE ); std::string buffer; wtomb_string( txt, buffer ); std::size_t length( buffer.size() ); if( length > 255 ) { buffer.erase( 255 ); length = 255; } if( std::fputc( static_cast< STD1::uint8_t >( length ), out) == EOF || std::fwrite( buffer.data(), sizeof( char ), length, out ) != length ) throw FatalError( ERR_WRITE ); bytes += length + 1; return bytes; }
/* * reverse -- display input in reverse order by line. * * There are six separate cases for this -- regular and non-regular * files by bytes, lines or the whole file. * * BYTES display N bytes * REG reverse scan and display the lines * NOREG cyclically read characters into a wrap-around buffer * * LINES display N lines * REG reverse scan and display the lines * NOREG cyclically read lines into a wrap-around array of buffers * * FILE display the entire file * REG reverse scan and display the lines * NOREG cyclically read input into a linked list of buffers */ void reverse(FILE *fp, enum STYLE style, off_t off, struct stat *sbp) { if (style != REVERSE && off == 0) return; if (!S_ISREG(sbp->st_mode) || r_reg(fp, style, off, sbp) != 0) switch(style) { case FBYTES: case RBYTES: (void)bytes(fp, off); break; case FLINES: case RLINES: (void)lines(fp, off); break; case REVERSE: r_buf(fp); break; } }
static std::string& GetStringFromValue(KValueRef value) { static std::string data; if (value->IsString()) { data = value->ToString(); } else { AutoPtr<Bytes> bytes(value->ToObject().cast<Bytes>()); if (!bytes.isNull()) { data = std::string(bytes->Pointer(), bytes->Length()); } else { data = ""; } } return data; }
PassRefPtr<SharedBitmap> SharedBitmap::clipBitmap(const IntRect& rect, bool useAlpha) { int oldWidth = width(); int oldHeight = height(); int copyWidth = std::min<int>(rect.width(), oldWidth - rect.x()); int copyHeight = std::min<int>(rect.height(), oldHeight - rect.y()); if (!copyWidth || !copyHeight) return 0; RefPtr<SharedBitmap> newBmp = create(IntSize(copyWidth, copyHeight), useAlpha && is32bit() ? BitmapInfo::BitCount32 : BitmapInfo::BitCount16, false); if (!newBmp || !newBmp->bytes()) return 0; DCHolder dcNew(newBmp.get()); StretchDIBits(dcNew.get(), 0, 0, copyWidth, copyHeight, rect.x(), rect.y(), copyWidth, copyHeight, bytes(), &bitmapInfo(), DIB_RGB_COLORS, SRCCOPY); return newBmp; }
/* * the main method * receives a Flow message and prints out its associated information * If the message belongs to another class, an exception is thrown. */ virtual void _receive_msg(std::shared_ptr<const Msg>&& m, int /* index */) { if ( m->type() == MSG_ID(Flow) ) { auto flow = static_cast<const Flow *>(m.get()); std::stringstream ss; const FlowKey& fk = flow->key(); int duration = flow->end_time() - flow->start_time(); ss<<"Flow of "<< flow->packets() << " packets and "<<flow->bytes()<<" bytes begin at "<<flow->start_time()<<" end at "<<flow->end_time()<< "duration (ms.) "<<duration <<std::endl; ss<<"SRC IP "<<ip_to_string(fk.src_ip4)<<" SRC port "<<fk.src_port<<std::endl; ss<<"DST IP "<<ip_to_string(fk.dst_ip4)<<" DST port "<<fk.dst_port<<std::endl; ss<<"protocol "<<fk.proto<<std::endl; blocklog(ss.str(),log_info); } else { throw std::runtime_error("Flowprinter: wrong message type"); } }
/// Parses a string into a bytes quantity. /// /// \param in_str The user-provided string to be converted. /// /// \return The converted bytes quantity. /// /// \throw std::runtime_error If the input string is empty or invalid. units::bytes units::bytes::parse(const std::string& in_str) { if (in_str.empty()) throw std::runtime_error("Bytes quantity cannot be empty"); uint64_t multiplier; std::string str = in_str; { const char unit = str[str.length() - 1]; switch (unit) { case 'T': case 't': multiplier = TB; break; case 'G': case 'g': multiplier = GB; break; case 'M': case 'm': multiplier = MB; break; case 'K': case 'k': multiplier = KB; break; default: multiplier = 1; } if (multiplier != 1) str.erase(str.length() - 1); } if (str.empty()) throw std::runtime_error("Bytes quantity cannot be empty"); if (str[0] == '.' || str[str.length() - 1] == '.') { // The standard parser for float values accepts things like ".3" and // "3.", which means that we would interpret ".3K" and "3.K" as valid // quantities. I think this is ugly and should not be allowed, so // special-case this condition and just error out. throw std::runtime_error(F("Invalid bytes quantity '%s'") % in_str); } double count; try { count = text::to_type< double >(str); } catch (const text::value_error& e) { throw std::runtime_error(F("Invalid bytes quantity '%s'") % in_str); } return bytes(uint64_t(count * multiplier)); }
void reserve() { BOOST_ASSERT( ptr_ == 0 ); if( !count_ ) { return; } if( is_mapped() ) { boost::filesystem::path tmp( boost::filesystem::temp_directory_path() ); filename_ = tmp.string() + "/mm_XXXXXX"; char name[256]; strcpy( name, filename_.c_str() ); fd_ = mkstemp( name ); filename_ = std::string( name ); if( fd_ == -1 ) { std::cerr << "Unable to create map file: " << filename_ << std::endl; return; } off_t file_size( bytes() ); ftruncate( fd_, file_size ); void* mem = mmap( 0, file_size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_NORESERVE, fd_, 0 ); BOOST_ASSERT( mem != MAP_FAILED ); ptr_ = static_cast<num_type*>( mem ); } else { ptr_ = new num_type[count_]; } }
/* decoded base64 stream to put on mysql row , file or network streams */ RichDoc OpenRichDoc( const QString datastream_base64 ) { RichDoc li; QByteArray xcode(""); xcode.append(datastream_base64); quint32 magic, version; QByteArray bytes(QByteArray::fromBase64(xcode)); /* decoded base64 string to QByteArray */ QBuffer buffer(&bytes); if (!buffer.open(QIODevice::ReadOnly)) { return li; } QDataStream ds(&buffer); /* place header */ ds.setVersion(QDataStream::Qt_4_2); ds >> magic; if ( (quint32)RichDoc::MAGICNUMBER != magic ) { qWarning() << "######## RichDoc::MAGICNUMBER not ok " << magic; buffer.close(); return li; } ds >> version; if ( (quint32)RichDoc::VERSION != version ) { qWarning() << "######## RichDoc::VERSION not ok " << version; buffer.close(); return li; } QString s; QByteArray h; ds >> h; ds >> s; li.style = s; li.html = h; SPics appoint; while (!ds.atEnd()) { ds >> appoint; li.resource.insert(appoint.name,appoint); } buffer.close(); return li; }
static QString decodeNameRecord(FT_SfntName name) { QString string; QByteArray encoding; if (name.platform_id == TT_PLATFORM_APPLE_UNICODE) { encoding = "UTF-16BE"; } else if (name.platform_id == TT_PLATFORM_MICROSOFT) { switch (name.encoding_id) { case TT_MS_ID_SYMBOL_CS: case TT_MS_ID_UNICODE_CS: case TT_MS_ID_UCS_4: encoding = "UTF-16BE"; break; case TT_MS_ID_SJIS: encoding = "Shift-JIS"; break; case TT_MS_ID_GB2312: encoding = "GB18030-0"; break; case TT_MS_ID_BIG_5: encoding = "Big5"; break; default: break; } } if (!encoding.isEmpty()) { QTextCodec* codec = QTextCodec::codecForName(encoding); QByteArray bytes((const char*) name.string, name.string_len); string = codec->toUnicode(bytes); } return string; }
/* It is a simpler form of Tiff IFD, so we add them as TiffEntries */ void RawParser::ParseFuji(uint32 offset, TiffIFD *target_ifd) { try { ByteStreamSwap bytes(mInput->getData(offset), mInput->getSize()-offset); uint32 entries = bytes.getUInt(); if (entries > 255) ThrowTPE("ParseFuji: Too many entries"); for (uint32 i = 0; i < entries; i++) { ushort16 tag = bytes.getShort(); ushort16 length = bytes.getShort(); TiffEntry *t; // Set types of known tags switch (tag) { case 0x100: case 0x121: case 0x2ff0: t = new TiffEntryBE((TiffTag)tag, TIFF_SHORT, length/2, bytes.getData()); break; case 0xc000: // This entry seem to have swapped endianness: t = new TiffEntry((TiffTag)tag, TIFF_LONG, length/4, bytes.getData()); break; default: t = new TiffEntry((TiffTag)tag, TIFF_UNDEFINED, length, bytes.getData()); } target_ifd->mEntry[t->tag] = t; bytes.skipBytes(length); } } catch (IOException e) { ThrowTPE("ParseFuji: IO error occurred during parsing. Skipping the rest"); } }
static JSBool Print(JSContext *cx, uintN argc, jsval *vp) { uintN i, n; JSString *str; jsval *argv = JS_ARGV(cx, vp); for (i = n = 0; i < argc; i++) { str = JS_ValueToString(cx, argv[i]); if (!str) return false; JSAutoByteString bytes(cx, str); if (!bytes) return false; fprintf(gOutFile, "%s%s", i ? " " : "", bytes.ptr()); } n++; if (n) fputc('\n', gOutFile); JS_SET_RVAL(cx, vp, JSVAL_VOID); return true; }
void CloudStream::onRequestFinished() { m_reply->deleteLater(); int code = m_reply->attribute( QNetworkRequest::HttpStatusCodeAttribute ).toInt(); tDebug() << "######### CloudStream : HTTP reply : #########"; tDebug( LOGINFO ) << "#### Cloudstream : HttpStatusCode : " << code; tDebug( LOGINFO ) << "#### Cloudstream : URL : " << m_reply->url(); QByteArray data = m_reply->readAll(); if ( code != 206 ) { m_num_requests_in_error++; tDebug( LOGINFO ) << "#### Cloudstream : Error " << code << " retrieving url to tag for " << m_filename; tDebug() << "#### CloudStream : body response : " << data; if ( refreshStreamUrl() ) { readBlock (m_currentBlocklength); return; } else { //return TagLib::ByteVector(); precache(); return ; } } TagLib::ByteVector bytes( data.data(), data.size() ); m_cursor += data.size(); FillCache( m_currentStart, bytes ); precache(); }
std::string LoadFragmentShader( const std::string filename ) { std::ifstream fin( filename, std::ios_base::binary | std::ios_base::in ); assert( fin.good() ); int magic; fin.read( reinterpret_cast<char*>( &magic ), sizeof( magic ) ); assert( magic == joefx_magic ); int version; fin.read( reinterpret_cast<char*>( &version ), sizeof( version ) ); assert( version == joefx_version ); int vert_length; fin.read( reinterpret_cast<char*>( &vert_length ), sizeof( vert_length ) ); std::vector<char> bytes( vert_length ); fin.read( &bytes[0], vert_length ); std::string ret( &bytes[0], vert_length ); return ret; }
QString ControlPeer::sendRawMessage(const QString & msg, int timeout) { if (mode() != ModeClient) { p->error = NotInClientModeError; return QString(); } QString controlSocketPath = Guzum::Config::controlSocketPath(); QLocalSocket socket; bool res = false; socket.connectToServer(controlSocketPath); res = socket.waitForConnected(timeout); if (!res) { p->error = ReadFailedError; return QString(); } QByteArray bytes(msg.toUtf8()); QByteArray responseBytes; QDataStream ds(&socket); ds.writeBytes(bytes.constData(), bytes.size()); res = socket.waitForBytesWritten(timeout); if (res) { res &= socket.waitForReadyRead(timeout); // wait for ack if (res) { responseBytes = socket.read(qstrlen(ACK)); res &= (responseBytes == ACK); } } if (!res) { p->error = ReadFailedError; return QString(); } p->error = NoError; return QString::fromUtf8(responseBytes.constData()); }
const KoColorProfile *KisCanvasResourceProvider::getScreenProfile(int screen) { #ifdef Q_WS_X11 Atom type; int format; unsigned long nitems; unsigned long bytes_after; quint8 * str; static Atom icc_atom = XInternAtom(QX11Info::display(), "_ICC_PROFILE", True); if (XGetWindowProperty(QX11Info::display(), QX11Info::appRootWindow(screen), icc_atom, 0, INT_MAX, False, XA_CARDINAL, &type, &format, &nitems, &bytes_after, (unsigned char **) &str) == Success ) { QByteArray bytes(nitems, '\0'); bytes = QByteArray::fromRawData((char*)str, (quint32)nitems); return KoColorSpaceRegistry::instance()->createColorProfile(RGBAColorModelID.id(), Integer8BitsColorDepthID.id(), bytes); return 0; } else { return 0; } #else return 0; #endif }
void data_store_multi_images::get_file_sizes() { std::vector<int> global_indices(m_my_datastore_indices.size()*m_num_img_srcs); std::vector<int> bytes(m_my_datastore_indices.size()*m_num_img_srcs); std::unordered_map<std::string, size_t> names; size_t jj = 0; size_t j = 0; double tm = get_time(); for (auto base_index : m_my_datastore_indices) { ++j; if (j % 100 == 0 and m_master) { double e = get_time() - tm; double time_per_file = e / j; int remaining_files = (m_my_datastore_indices.size()-j)*m_num_img_srcs; double estimated_remaining_time = time_per_file * remaining_files; std::cerr << "P_0: got size for " << j*m_num_img_srcs << " of " << m_data_filepaths.size() << " files; elapsed time: " << get_time() - tm << "s est. remaining time: " << estimated_remaining_time << "s\n"; } const std::vector<std::string> sample(get_sample(base_index)); for (size_t k=0; k<sample.size(); k++) { size_t index = base_index*m_num_img_srcs + k; size_t file_len = 0; if (names.find(sample[k]) != names.end()) { file_len = names[sample[k]]; } else { file_len = get_file_size(m_dir, sample[k]); names[sample[k]] = file_len; } global_indices[jj] = index; bytes[jj] = file_len; ++jj; } } exchange_file_sizes(global_indices, bytes); }
CString TextCodecUTF8::encodeCommon(const CharType* characters, size_t length) { // The maximum number of UTF-8 bytes needed per UTF-16 code unit is 3. // BMP characters take only one UTF-16 code unit and can take up to 3 bytes (3x). // Non-BMP characters take two UTF-16 code units and can take up to 4 bytes (2x). if (length > numeric_limits<size_t>::max() / 3) CRASH(); Vector<uint8_t> bytes(length * 3); size_t i = 0; size_t bytesWritten = 0; while (i < length) { UChar32 character; U16_NEXT(characters, i, length, character); // U16_NEXT will simply emit a surrogate code point if an unmatched surrogate // is encountered; we must convert it to a U+FFFD (REPLACEMENT CHARACTER) here. if (0xD800 <= character && character <= 0xDFFF) character = replacementCharacter; U8_APPEND_UNSAFE(bytes.data(), bytesWritten, character); } return CString(reinterpret_cast<char*>(bytes.data()), bytesWritten); }
uint32_t ReadPixel(SharedSurface* src) { GLContext* gl = src->mGL; uint32_t pixel; ScopedReadbackFB a(src); { ScopedPackAlignment autoAlign(gl, 4); UniquePtr<uint8_t[]> bytes(new uint8_t[4]); gl->raw_fReadPixels(0, 0, 1, 1, LOCAL_GL_RGBA, LOCAL_GL_UNSIGNED_BYTE, bytes.get()); memcpy(&pixel, bytes.get(), 4); } return pixel; }