本文整理汇总了C++中StringStream::str方法的典型用法代码示例。如果您正苦于以下问题:C++ StringStream::str方法的具体用法?C++ StringStream::str怎么用?C++ StringStream::str使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类StringStream
的用法示例。
在下文中一共展示了StringStream::str方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: desugar
void desugar(AST *&ast_, unsigned obj_level)
{
if (auto *ast = dynamic_cast<Apply*>(ast_)) {
desugar(ast->target, obj_level);
for (Apply::Arg &arg : ast->args)
desugar(arg.expr, obj_level);
} else if (auto *ast = dynamic_cast<ApplyBrace*>(ast_)) {
desugar(ast->left, obj_level);
desugar(ast->right, obj_level);
ast_ = alloc->make<Binary>(ast->location, ast->openFodder,
ast->left, EF, BOP_PLUS, ast->right);
} else if (auto *ast = dynamic_cast<Array*>(ast_)) {
for (auto &el : ast->elements)
desugar(el.expr, obj_level);
} else if (auto *ast = dynamic_cast<ArrayComprehension*>(ast_)) {
for (ComprehensionSpec &spec : ast->specs)
desugar(spec.expr, obj_level);
desugar(ast->body, obj_level + 1);
int n = ast->specs.size();
AST *zero = make<LiteralNumber>(E, EF, "0.0");
AST *one = make<LiteralNumber>(E, EF, "1.0");
auto *_r = id(U"$r");
auto *_l = id(U"$l");
std::vector<const Identifier*> _i(n);
for (int i = 0; i < n ; ++i) {
StringStream ss;
ss << U"$i_" << i;
_i[i] = id(ss.str());
}
std::vector<const Identifier*> _aux(n);
for (int i = 0; i < n ; ++i) {
StringStream ss;
ss << U"$aux_" << i;
_aux[i] = id(ss.str());
}
// Build it from the inside out. We keep wrapping 'in' with more ASTs.
assert(ast->specs[0].kind == ComprehensionSpec::FOR);
int last_for = n - 1;
while (ast->specs[last_for].kind != ComprehensionSpec::FOR)
last_for--;
// $aux_{last_for}($i_{last_for} + 1, $r + [body])
AST *in = make<Apply>(
ast->body->location,
EF,
var(_aux[last_for]),
EF,
Apply::Args {
{ make<Binary>(E, EF, var(_i[last_for]), EF, BOP_PLUS, one), EF},
{ make<Binary>(E, EF, var(_r), EF, BOP_PLUS, singleton(ast->body)), EF}
},
false, // trailingComma
EF,
EF,
true // tailstrict
);
for (int i = n - 1; i >= 0 ; --i) {
const ComprehensionSpec &spec = ast->specs[i];
AST *out;
if (i > 0) {
int prev_for = i - 1;
while (ast->specs[prev_for].kind != ComprehensionSpec::FOR)
prev_for--;
// aux_{prev_for}($i_{prev_for} + 1, $r)
out = make<Apply>( // False branch.
E,
EF,
var(_aux[prev_for]),
EF,
Apply::Args {
{ make<Binary>(E, EF, var(_i[prev_for]), EF, BOP_PLUS, one), EF, },
{ var(_r), EF, }
},
false, // trailingComma
EF,
EF,
true // tailstrict
);
} else {
out = var(_r);
}
switch (spec.kind) {
case ComprehensionSpec::IF: {
/*
if [[[...cond...]]] then
[[[...in...]]]
else
[[[...out...]]]
*/
in = make<Conditional>(
ast->location,
EF,
spec.expr,
EF,
//.........这里部分代码省略.........
示例2: initialise
void GLFrameBufferObject::initialise()
{
// Release depth and stencil, if they were bound
mManager->releaseRenderBuffer(mDepth);
mManager->releaseRenderBuffer(mStencil);
mManager->releaseRenderBuffer(mMultisampleColourBuffer);
// First buffer must be bound
if(!mColour[0].buffer)
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"Attachment 0 must have surface attached",
"GLFrameBufferObject::initialise");
}
// If we're doing multisampling, then we need another FBO which contains a
// renderbuffer which is set up to multisample, and we'll blit it to the final
// FBO afterwards to perform the multisample resolve. In that case, the
// mMultisampleFB is bound during rendering and is the one with a depth/stencil
// Store basic stats
uint32 width = mColour[0].buffer->getWidth();
uint32 height = mColour[0].buffer->getHeight();
GLuint format = mColour[0].buffer->getGLFormat();
ushort maxSupportedMRTs = Root::getSingleton().getRenderSystem()->getCapabilities()->getNumMultiRenderTargets();
// Bind simple buffer to add colour attachments
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, mFB);
// Bind all attachment points to frame buffer
for(unsigned int x=0; x<maxSupportedMRTs; ++x)
{
if(mColour[x].buffer)
{
if(mColour[x].buffer->getWidth() != width || mColour[x].buffer->getHeight() != height)
{
StringStream ss;
ss << "Attachment " << x << " has incompatible size ";
ss << mColour[x].buffer->getWidth() << "x" << mColour[x].buffer->getHeight();
ss << ". It must be of the same as the size of surface 0, ";
ss << width << "x" << height;
ss << ".";
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, ss.str(), "GLFrameBufferObject::initialise");
}
if(mColour[x].buffer->getGLFormat() != format)
{
StringStream ss;
ss << "Attachment " << x << " has incompatible format.";
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, ss.str(), "GLFrameBufferObject::initialise");
}
mColour[x].buffer->bindToFramebuffer(GL_COLOR_ATTACHMENT0_EXT+x, mColour[x].zoffset);
}
else
{
// Detach
glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT+x,
GL_RENDERBUFFER_EXT, 0);
}
}
// Now deal with depth / stencil
if (mMultisampleFB)
{
// Bind multisample buffer
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, mMultisampleFB);
// Create AA render buffer (colour)
// note, this can be shared too because we blit it to the final FBO
// right after the render is finished
mMultisampleColourBuffer = mManager->requestRenderBuffer(format, width, height, mNumSamples);
// Attach it, because we won't be attaching below and non-multisample has
// actually been attached to other FBO
mMultisampleColourBuffer.buffer->bindToFramebuffer(GL_COLOR_ATTACHMENT0_EXT,
mMultisampleColourBuffer.zoffset);
// depth & stencil will be dealt with below
}
// Depth buffer is not handled here anymore.
// See GLFrameBufferObject::attachDepthBuffer() & RenderSystem::setDepthBufferFor()
// Do glDrawBuffer calls
GLenum bufs[OGRE_MAX_MULTIPLE_RENDER_TARGETS];
GLsizei n=0;
for(unsigned int x=0; x<OGRE_MAX_MULTIPLE_RENDER_TARGETS; ++x)
{
// Fill attached colour buffers
if(mColour[x].buffer)
{
bufs[x] = GL_COLOR_ATTACHMENT0_EXT + x;
// Keep highest used buffer + 1
n = x+1;
}
else
{
bufs[x] = GL_NONE;
}
}
if(glDrawBuffers)
//.........这里部分代码省略.........
示例3: initialise
void GLESFrameBufferObject::initialise()
{
// Release depth and stencil, if they were bound
mManager->releaseRenderBuffer(mDepth);
mManager->releaseRenderBuffer(mStencil);
mManager->releaseRenderBuffer(mMultisampleColourBuffer);
/// First buffer must be bound
if(!mColour[0].buffer)
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"Attachment 0 must have surface attached",
"GLESFrameBufferObject::initialise");
}
// If we're doing multisampling, then we need another FBO which contains a
// renderbuffer which is set up to multisample, and we'll blit it to the final
// FBO afterwards to perform the multisample resolve. In that case, the
// mMultisampleFB is bound during rendering and is the one with a depth/stencil
/// Store basic stats
size_t width = mColour[0].buffer->getWidth();
size_t height = mColour[0].buffer->getHeight();
GLuint format = mColour[0].buffer->getGLFormat();
PixelFormat ogreFormat = mColour[0].buffer->getFormat();
// Bind simple buffer to add colour attachments
glBindFramebufferOES(GL_FRAMEBUFFER_OES, mFB);
GL_CHECK_ERROR;
/// Bind all attachment points to frame buffer
for(size_t x=0; x<OGRE_MAX_MULTIPLE_RENDER_TARGETS; ++x)
{
if(mColour[x].buffer)
{
if(mColour[x].buffer->getWidth() != width || mColour[x].buffer->getHeight() != height)
{
StringStream ss;
ss << "Attachment " << x << " has incompatible size ";
ss << mColour[x].buffer->getWidth() << "x" << mColour[x].buffer->getHeight();
ss << ". It must be of the same as the size of surface 0, ";
ss << width << "x" << height;
ss << ".";
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, ss.str(), "GLESFrameBufferObject::initialise");
}
if(mColour[x].buffer->getGLFormat() != format)
{
StringStream ss;
ss << "Attachment " << x << " has incompatible format.";
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, ss.str(), "GLESFrameBufferObject::initialise");
}
mColour[x].buffer->bindToFramebuffer(GL_COLOR_ATTACHMENT0_OES+x, mColour[x].zoffset);
}
else
{
// Detach
glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES+x,
GL_RENDERBUFFER_OES, 0);
GL_CHECK_ERROR;
}
}
// Now deal with depth / stencil
if (mMultisampleFB)
{
// Bind multisample buffer
glBindFramebufferOES(GL_FRAMEBUFFER_OES, mMultisampleFB);
GL_CHECK_ERROR;
// Create AA render buffer (colour)
// note, this can be shared too because we blit it to the final FBO
// right after the render is finished
mMultisampleColourBuffer = mManager->requestRenderBuffer(format, width, height, mNumSamples);
// Attach it, because we won't be attaching below and non-multisample has
// actually been attached to other FBO
mMultisampleColourBuffer.buffer->bindToFramebuffer(GL_COLOR_ATTACHMENT0_OES,
mMultisampleColourBuffer.zoffset);
// depth & stencil will be dealt with below
}
/// Find suitable depth and stencil format that is compatible with colour format
GLenum depthFormat, stencilFormat;
mManager->getBestDepthStencil(ogreFormat, &depthFormat, &stencilFormat);
/// Request surfaces
mDepth = mManager->requestRenderBuffer(depthFormat, width, height, mNumSamples);
if (depthFormat == GL_DEPTH24_STENCIL8_OES)
{
// bind same buffer to depth and stencil attachments
mManager->requestRenderBuffer(mDepth);
mStencil = mDepth;
}
else
{
// separate stencil
mStencil = mManager->requestRenderBuffer(stencilFormat, width, height, mNumSamples);
}
/// Attach/detach surfaces
//.........这里部分代码省略.........
示例4: assert
void GLES2FrameBufferObject::initialise()
{
GLES2RenderSystem* rs = getGLES2RenderSystem();
assert(mContext == rs->_getCurrentContext());
// Release depth and stencil, if they were bound
mManager->releaseRenderBuffer(mDepth);
mManager->releaseRenderBuffer(mStencil);
mManager->releaseRenderBuffer(mMultisampleColourBuffer);
// First buffer must be bound
if(!mColour[0].buffer)
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"Attachment 0 must have surface attached",
"GLES2FrameBufferObject::initialise");
}
// If we're doing multisampling, then we need another FBO which contains a
// renderbuffer which is set up to multisample, and we'll blit it to the final
// FBO afterwards to perform the multisample resolve. In that case, the
// mMultisampleFB is bound during rendering and is the one with a depth/stencil
// Store basic stats
uint32 width = mColour[0].buffer->getWidth();
uint32 height = mColour[0].buffer->getHeight();
GLuint format = mColour[0].buffer->getGLFormat();
ushort maxSupportedMRTs = rs->getCapabilities()->getNumMultiRenderTargets();
// Bind simple buffer to add colour attachments
OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, mFB));
bool isDepth = PixelUtil::isDepth(getFormat());
// Bind all attachment points to frame buffer
for(unsigned int x = 0; x < maxSupportedMRTs; ++x)
{
if(mColour[x].buffer)
{
if(mColour[x].buffer->getWidth() != width || mColour[x].buffer->getHeight() != height)
{
StringStream ss;
ss << "Attachment " << x << " has incompatible size ";
ss << mColour[x].buffer->getWidth() << "x" << mColour[x].buffer->getHeight();
ss << ". It must be of the same as the size of surface 0, ";
ss << width << "x" << height;
ss << ".";
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, ss.str(), "GLES2FrameBufferObject::initialise");
}
if(mColour[x].buffer->getGLFormat() != format)
{
StringStream ss;
ss << "Attachment " << x << " has incompatible format.";
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, ss.str(), "GLES2FrameBufferObject::initialise");
}
mColour[x].buffer->bindToFramebuffer(
isDepth ? GL_DEPTH_ATTACHMENT : (GL_COLOR_ATTACHMENT0 + x), mColour[x].zoffset);
}
else
{
// Detach
OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer(GL_FRAMEBUFFER, static_cast<GLenum>(GL_COLOR_ATTACHMENT0+x), GL_RENDERBUFFER, 0));
}
}
// Now deal with depth / stencil
if (mMultisampleFB)
{
// Bind multisample buffer
OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, mMultisampleFB));
// Create AA render buffer (colour)
// note, this can be shared too because we blit it to the final FBO
// right after the render is finished
mMultisampleColourBuffer = mManager->requestRenderBuffer(format, width, height, mNumSamples);
// Attach it, because we won't be attaching below and non-multisample has
// actually been attached to other FBO
mMultisampleColourBuffer.buffer->bindToFramebuffer(GL_COLOR_ATTACHMENT0,
mMultisampleColourBuffer.zoffset);
// depth & stencil will be dealt with below
}
// Depth buffer is not handled here anymore.
// See GLES2FrameBufferObject::attachDepthBuffer() & RenderSystem::setDepthBufferFor()
if(rs->hasMinGLVersion(3, 0) && OGRE_PLATFORM != OGRE_PLATFORM_EMSCRIPTEN) // ED on Emscripten
{
GLenum bufs[OGRE_MAX_MULTIPLE_RENDER_TARGETS];
GLsizei n=0;
for(unsigned int x=0; x<maxSupportedMRTs; ++x)
{
// Fill attached colour buffers
if(mColour[x].buffer)
{
bufs[x] = isDepth ? GL_DEPTH_ATTACHMENT : (GL_COLOR_ATTACHMENT0 + x);
// Keep highest used buffer + 1
n = x+1;
}
else
//.........这里部分代码省略.........
示例5: discPath
string DrawContext::discPath(u16 radius)
{
StringStream ss;
ss << "disc-"<<radius;
return ss.str();
}
示例6: ParseRule
CSSRule* CSSStream::ParseRule(CSSStyleSheet* parentStyleSheet, CSSRule* parentRule, ICSSRuleListener* pListener)
{
// stream->SkipSpaces();
getnextc();
if (m_c == L'/')
{
getnextc();
//if (c == L'*')
EatChar(L'*');
{
CSSCommentRule* p = new CSSCommentRule;
//p->AddRef();
p->m_textOffset[0] = stream.m_ipos-2;
p->m_textOffset[1] = stream.m_ipos-2;
p->m_textOffset[2] = stream.m_ipos;
p->m_parentStyleSheet = parentStyleSheet;
p->m_parentRule = parentRule;
StringStream cssText;
cssText << L"/*";
while (!stream.eof())
{
if (stream.m_c == L'*')
{
stream.getnextc();
if (stream.m_c == L'/')
{
stream.getnextc();
break;
}
}
cssText << (WCHAR)stream.m_c;
}
p->m_textOffset[3] = stream.m_ipos;
stream.EatChar(L'*');
stream.EatChar(L'/');
p->m_textOffset[4] = stream.m_ipos;
p->m_textOffset[5] = stream.m_ipos;
cssText << L"*/";
p->m_cssText = cssText->str();
*pVal = p;
}
}
else if (m_c == L'@') // at-rule
{
ASSERT(0);
#if 0
String id = stream.GetID();
StringStream strbuilder;
strbuilder << L"@";
strbuilder << id;
int curly = 0;
while (!stream.eof())
{
strbuilder << (WCHAR)m_c;
if (stream.m_c == L'{')
{
curly++;
}
else if (stream.m_c == L'}')
{
curly--;
if (curly == 0)
break;
}
else if (stream.m_c == L';')
{
if (curly == 0)
{
break;
}
}
}
// Read spaces
while (!stream.eof())
{
if (!isspace(stream.m_c))
{
break;
}
strbuilder << (WCHAR)stream.m_c;
stream.getnextc();
//.........这里部分代码省略.........
示例7: if
/** Detect which internal formats are allowed as RTT
Also detect what combinations of stencil and depth are allowed with this internal
format.
*/
void GLES2FBOManager::detectFBOFormats()
{
#if OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN
memset(mProps, 0, sizeof(mProps));
// TODO: Fix that probing all formats slows down startup not just on the web also on Android / iOS
mProps[PF_A8B8G8R8].valid = true;
FormatProperties::Mode mode = {1, 0};
mProps[PF_A8B8G8R8].modes.push_back(mode);
LogManager::getSingleton().logMessage("[GLES2] : detectFBOFormats is disabled on this platform (due performance reasons)");
#else
// Try all formats, and report which ones work as target
GLES2RenderSystem* rs = getGLES2RenderSystem();
GLuint fb = 0, tid = 0;
bool hasGLES3 = rs->hasMinGLVersion(3, 0);
const size_t depthCount = hasGLES3 ? DEPTHFORMAT_COUNT : DEPTHFORMAT_COUNT - 1; // 32_8 is not available on GLES2
const size_t stencilStep = hasGLES3 ? 3 : 1; // 1 and 4 bit not available on GLES3
for(size_t x = 0; x < PF_COUNT; ++x)
{
mProps[x].valid = false;
// Fetch GL format token
GLint internalFormat = GLES2PixelUtil::getGLInternalFormat((PixelFormat)x);
GLenum fmt = GLES2PixelUtil::getGLOriginFormat((PixelFormat)x);
GLenum type = GLES2PixelUtil::getGLOriginDataType((PixelFormat)x);
// Note: letting PF_UNKNOWN pass here is for pure depth/ stencil formats
// however there are reports that this crashes some unspecified android devices
if((internalFormat == GL_NONE || fmt == GL_NONE || type == GL_NONE) && (x != 0))
continue;
// not color-renderable in GLES
if(fmt == GL_BGRA_EXT)
continue;
// No test for compressed formats
if(PixelUtil::isCompressed((PixelFormat)x))
continue;
// Create and attach framebuffer
_createTempFramebuffer((PixelFormat)x, internalFormat, fmt, type, fb, tid);
// Ignore status in case of fmt==GL_NONE, because no implementation will accept
// a buffer without *any* attachment. Buffers with only stencil and depth attachment
// might still be supported, so we must continue probing.
if(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE)
{
mProps[x].valid = true;
StringStream str;
str << "FBO " << PixelUtil::getFormatName((PixelFormat)x)
<< " depth/stencil support: ";
// For each depth/stencil formats
for (size_t depth = 0; depth < depthCount; ++depth)
{
if (depthFormats[depth] != GL_DEPTH24_STENCIL8 && depthFormats[depth] != GL_DEPTH32F_STENCIL8)
{
// General depth/stencil combination
for (size_t stencil = 0; stencil < STENCILFORMAT_COUNT; stencil += stencilStep)
{
// StringStream l;
// l << "Trying " << PixelUtil::getFormatName((PixelFormat)x)
// << " D" << depthBits[depth]
// << "S" << stencilBits[stencil];
// LogManager::getSingleton().logMessage(l.str());
if (_tryFormat(depthFormats[depth], stencilFormats[stencil]))
{
// Add mode to allowed modes
str << "D" << depthBits[depth] << "S" << stencilBits[stencil] << " ";
FormatProperties::Mode mode;
mode.depth = depth;
mode.stencil = stencil;
mProps[x].modes.push_back(mode);
}
else
{
// There is a small edge case that FBO is trashed during the test
// on some drivers resulting in undefined behavior
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glDeleteFramebuffers(1, &fb);
_createTempFramebuffer((PixelFormat)x, internalFormat, fmt, type, fb, tid);
}
}
}
else if(hasGLES3 || rs->checkExtension("GL_OES_packed_depth_stencil") )
{
// Packed depth/stencil format
if (_tryPackedFormat(depthFormats[depth]))
{
// Add mode to allowed modes
//.........这里部分代码省略.........
示例8:
Pair::~Pair()
{
StringStream ss;
ss << "~Pair():[key=" << mKey << ",value=" << mValue << ']';
LogManager::getSingleton().logMessage( ss.str() );
}
示例9: encodingTest
/// Builds an index with payloads in the given Directory and performs different
/// tests to verify the payload encoding
static void encodingTest(const DirectoryPtr& dir) {
PayloadAnalyzerPtr analyzer = newLucene<PayloadAnalyzer>();
IndexWriterPtr writer = newLucene<IndexWriter>(dir, analyzer, true, IndexWriter::MaxFieldLengthLIMITED);
// should be in sync with value in TermInfosWriter
int32_t skipInterval = 16;
int32_t numTerms = 5;
String fieldName = L"f1";
int32_t numDocs = skipInterval + 1;
// create content for the test documents with just a few terms
Collection<TermPtr> terms = generateTerms(fieldName, numTerms);
StringStream sb;
for (Collection<TermPtr>::iterator term = terms.begin(); term != terms.end(); ++term) {
sb << (*term)->text() << L" ";
}
String content = sb.str();
int32_t payloadDataLength = numTerms * numDocs * 2 + numTerms * numDocs * (numDocs - 1) / 2;
ByteArray payloadData = generateRandomData(payloadDataLength);
DocumentPtr d = newLucene<Document>();
d->add(newLucene<Field>(fieldName, content, Field::STORE_NO, Field::INDEX_ANALYZED));
// add the same document multiple times to have the same payload lengths for all
// occurrences within two consecutive skip intervals
int32_t offset = 0;
for (int32_t i = 0; i < 2 * numDocs; ++i) {
analyzer->setPayloadData(fieldName, payloadData, offset, 1);
offset += numTerms;
writer->addDocument(d);
}
// make sure we create more than one segment to test merging
writer->commit();
for (int32_t i = 0; i < numDocs; ++i) {
analyzer->setPayloadData(fieldName, payloadData, offset, i);
offset += i * numTerms;
writer->addDocument(d);
}
writer->optimize();
// flush
writer->close();
// Verify the index
IndexReaderPtr reader = IndexReader::open(dir, true);
ByteArray verifyPayloadData(ByteArray::newInstance(payloadDataLength));
offset = 0;
Collection<TermPositionsPtr> tps = Collection<TermPositionsPtr>::newInstance(numTerms);
for (int32_t i = 0; i < numTerms; ++i) {
tps[i] = reader->termPositions(terms[i]);
}
while (tps[0]->next()) {
for (int32_t i = 1; i < numTerms; ++i) {
tps[i]->next();
}
int32_t freq = tps[0]->freq();
for (int32_t i = 0; i < freq; ++i) {
for (int32_t j = 0; j < numTerms; ++j) {
tps[j]->nextPosition();
tps[j]->getPayload(verifyPayloadData, offset);
offset += tps[j]->getPayloadLength();
}
}
}
for (int32_t i = 0; i < numTerms; ++i) {
tps[i]->close();
}
EXPECT_TRUE(payloadData.equals(verifyPayloadData));
// test lazy skipping
TermPositionsPtr tp = reader->termPositions(terms[0]);
tp->next();
tp->nextPosition();
// now we don't read this payload
tp->nextPosition();
EXPECT_EQ(1, tp->getPayloadLength());
ByteArray payload = tp->getPayload(ByteArray(), 0);
EXPECT_EQ(payload[0], payloadData[numTerms]);
tp->nextPosition();
// we don't read this payload and skip to a different document
tp->skipTo(5);
tp->nextPosition();
EXPECT_EQ(1, tp->getPayloadLength());
payload = tp->getPayload(ByteArray(), 0);
EXPECT_EQ(payload[0], payloadData[5 * numTerms]);
// Test different lengths at skip points
tp->seek(terms[1]);
//.........这里部分代码省略.........
示例10: buildMessage
String ParserStatus::buildMessage(const size_t line, const size_t column, const String& str) const {
StringStream msg;
msg << str << " (line " << line << ", column " << column << ")";
return msg.str();
}
示例11: displayRecognitionError
void displayRecognitionError (pANTLR3_BASE_RECOGNIZER recognizer, pANTLR3_UINT8 * tokenNames)
{
// Adopted code from https://github.com/antlr/antlr3/blob/master/runtime/C/src/antlr3baserecognizer.c
pANTLR3_EXCEPTION ex;
pANTLR3_COMMON_TOKEN theToken;
pANTLR3_BASE_TREE theBaseTree;
pANTLR3_COMMON_TREE theCommonTree;
// Retrieve some info for easy reading.
ex = recognizer->state->exception;
String fileName;
// See if there is a 'filename' we can use
if (ex->streamName != NULL)
{
pANTLR3_STRING ftext;
ftext = ex->streamName->to8(ex->streamName);
fileName.assign((const char*)ftext->chars);
}
int line = recognizer->state->exception->line;
StringStream ss;
ss << (const char*) (recognizer->state->exception->message);
// How we determine the next piece is dependent on which thing raised the
// error.
pANTLR3_STRING ttext;
switch (recognizer->type)
{
case ANTLR3_TYPE_PARSER:
{
// Prepare the knowledge we know we have
theToken = (pANTLR3_COMMON_TOKEN)(recognizer->state->exception->token);
ttext = theToken->toString(theToken);
ss << ", at offset " << recognizer->state->exception->charPositionInLine;
if (theToken != NULL)
{
if (theToken->type == ANTLR3_TOKEN_EOF)
ss << ", at <EOF>";
else
// Guard against null text in a token
ss << "\n near " << (ttext == NULL ? "<no text for the token>" : (const char*)ttext->chars) << "\n ";
}
}
break;
case ANTLR3_TYPE_TREE_PARSER:
theBaseTree = (pANTLR3_BASE_TREE)(recognizer->state->exception->token);
ttext = theBaseTree->toStringTree(theBaseTree);
if (theBaseTree != NULL)
{
theCommonTree = (pANTLR3_COMMON_TREE) theBaseTree->super;
if (theCommonTree != NULL)
{
theToken = (pANTLR3_COMMON_TOKEN) theBaseTree->getToken(theBaseTree);
}
ss << ", at offset " << theBaseTree->getCharPositionInLine(theBaseTree);
ss << ", near " << (const char*)ttext->chars;
}
break;
default:
std::cerr << "Base recognizer function displayRecognitionError called by unknown parser type - provide override for this function\n";
return;
break;
}
// Although this function should generally be provided by the implementation, this one
// should be as helpful as possible for grammar developers and serve as an example
// of what you can do with each exception type. In general, when you make up your
// 'real' handler, you should debug the routine with all possible errors you expect
// which will then let you be as specific as possible about all circumstances.
//
// Note that in the general case, errors thrown by tree parsers indicate a problem
// with the output of the parser or with the tree grammar itself. The job of the parser
// is to produce a perfect (in traversal terms) syntactically correct tree, so errors
// at that stage should really be semantic errors that your own code determines and handles
// in whatever way is appropriate.
switch (ex->type)
{
case ANTLR3_UNWANTED_TOKEN_EXCEPTION:
// Indicates that the recognizer was fed a token which seesm to be
// spurious input. We can detect this when the token that follows
// this unwanted token would normally be part of the syntactically
// correct stream. Then we can see that the token we are looking at
// is just something that should not be there and throw this exception.
if (tokenNames == NULL)
ss << " : Extraneous input...";
else
{
if (ex->expecting == ANTLR3_TOKEN_EOF)
ss << " : Extraneous input - expected <EOF>\n";
else
ss << " : Extraneous input - expected " << tokenNames[ex->expecting] << " ...\n";
}
break;
case ANTLR3_MISSING_TOKEN_EXCEPTION:
// Indicates that the recognizer detected that the token we just
// hit would be valid syntactically if preceeded by a particular
// token. Perhaps a missing ';' at line end or a missing ',' in an
//.........这里部分代码省略.........
示例12: ConstructFromXML
void Entresol::ConstructFromXML(const String& EngineDataPath, const Mezzanine::ArchiveType ArchType, const String& InitializerFile)
{
//Add default manager factories
AddAllEngineDefaultManagerFactories();
//Set some sane Defaults for some values.
this->ManualLoopBreak = false;
// Create Ogre.
SetupOgre();
// Load the necessary plugins.
SubSystemParticleFXPlugin = new Ogre::ParticleFXPlugin();
Ogre::Root::getSingleton().installPlugin(SubSystemParticleFXPlugin);
// Set up the data we'll be populating.
XML::Attribute CurrAttrib;
String GUIInit, ResourceInit, PluginsInit, LogFileName;
String PluginExtension, PluginPath;
// Create or set the resource manager.
/// @todo This currently forces our default resource manager to be constructed, which isn't in line with our factory/initiailzation design.
/// This should be addressed somehow.
if(ResourceManager::SingletonValid())
{ AddManager(ResourceManager::GetSingletonPtr()); }
else
{ AddManager(new ResourceManager(EngineDataPath, ArchType)); }
// Open and load the initializer doc.
ResourceManager* ResourceMan = GetResourceManager();
/// @todo Replace this stack allocated stream for one initialized from the Resource Manager, after the system is ready.
Resource::FileStream InitStream(InitializerFile,EngineDataPath);
XML::Document InitDoc;
XML::ParseResult DocResult = InitDoc.Load(InitStream);
if( DocResult.Status != XML::StatusOk )
{
StringStream ExceptionStream;
ExceptionStream << "Failed to parse XML file \"" << InitializerFile << "\".";
MEZZ_EXCEPTION(Exception::SYNTAX_ERROR_EXCEPTION_XML,ExceptionStream.str());
}
XML::Node InitRoot = InitDoc.GetChild("InitializerRoot");
if( InitRoot.Empty() )
{
StringStream ExceptionStream;
ExceptionStream << "Failed to find expected Root node in \"" << InitializerFile << "\".";
MEZZ_EXCEPTION(Exception::SYNTAX_ERROR_EXCEPTION_XML,ExceptionStream.str());
}
// Get the world settings and set them.
XML::Node WorldSettings = InitRoot.GetChild("WorldSettings");
for( XML::NodeIterator SetIt = WorldSettings.begin() ; SetIt != WorldSettings.end() ; ++SetIt )
{
String SecName = (*SetIt).Name();
if( "FrameSettings" == SecName )
{
CurrAttrib = (*SetIt).GetAttribute("TargetFrameRate");
if(CurrAttrib.Empty())
{
CurrAttrib = (*SetIt).GetAttribute("TargetFrameTime");
if(!CurrAttrib.Empty())
SetTargetFrameTimeMicroseconds(CurrAttrib.AsWhole());
}else{
this->SetTargetFrameRate(CurrAttrib.AsWhole());
}
}
else
{
MEZZ_EXCEPTION(Exception::SYNTAX_ERROR_EXCEPTION_XML,String("Unknown WorldSetting ")+SecName);
}
}
SetupLogging(LogFileName);
// Get the other initializer files we'll be using, since we'll need the plugins initializer.
XML::Node InitFiles = InitRoot.GetChild("OtherInitializers");
for( XML::NodeIterator InitIt = InitFiles.begin() ; InitIt != InitFiles.end() ; ++InitIt )
{
String InitFileName = (*InitIt).Name();
if( "PluginInit" == InitFileName )
{
CurrAttrib = (*InitIt).GetAttribute("FileName");
if(!CurrAttrib.Empty())
PluginsInit = CurrAttrib.AsString();
}
else if( "ResourceInit" == InitFileName )
{
CurrAttrib = (*InitIt).GetAttribute("FileName");
if(!CurrAttrib.Empty())
ResourceInit = CurrAttrib.AsString();
}
else if( "GUIInit" == InitFileName )
{
CurrAttrib = (*InitIt).GetAttribute("FileName");
if(!CurrAttrib.Empty())
GUIInit = CurrAttrib.AsString();
}
}
// Load additional resource groups
/*if(!ResourceInit.empty())
//.........这里部分代码省略.........
示例13: run
static int run(int argc, const Char* const* argv){
ScopedMessage message;
try{
bool show_usage = false;
bool quiet = false;
const Char* source_file_arg = NULL;
for (int i = 1; i < argc; ++i) {
String arg = argv[i];
if (arg[0] == '-') {
if (arg == _("--help") || arg == _("-h"))
show_usage = true;
else if (arg == _("--quiet") || arg == _("-q"))
quiet = true;
} else {
// multiple file arguments is erroneous
if (source_file_arg != NULL)
show_usage = true;
source_file_arg = argv[i];
}
}
if(show_usage || source_file_arg == NULL){
message<<_("Usage: ")<<fs::system_complete(argv[0]).leaf()<<_(" [--quiet] <filename>")<<endl<<endl;
return 1;
}
const Path source_file = fs::system_complete(source_file_arg);
Path target_dir = fs::system_complete(argv[0]).branch_path();
if(!fs::exists(source_file)){
message<<source_file<<endl<<_("File not found.")<<endl;
return 1;
}
ArchiveType content = read_archive_content_sd7(source_file);
if(content == R_OTHER){
content = read_archive_content_sdz(source_file);
}
if(content == R_OTHER){
message<<_("'")<<source_file.leaf()<<_("' is not a valid map/mod ")
_("it may be corrupted, try to redownload it.")<<endl;
return 1;
}
//for(Path test_path = source_file; test_path.has_root_directory(); ){
// if(fs::equivalent(test_path, target_dir)){
// message<<_("'")<<source_file.leaf()<<_("' already exists in the Spring directory.")<<endl;
// return 1;
// }
// test_path = test_path.branch_path();
//}
if(content == R_MAP){
//message<<"isMap: "<<filename<<endl;
target_dir /= _("maps");
}else if(content == R_MOD){
//message<<"isMod: "<<filename<<endl;
target_dir /= _("mods");
}else{
assert(false);
}
if(!fs::exists(target_dir)){
message<<_("The target directory '")<<target_dir<<_("' doesn't exist.")<<endl;
return 1;
}
// stash existing files away
if (fs::exists(target_dir / source_file.leaf())) {
int i = 0;
Path target_test;
do {
String stashed = (source_file.leaf() + _(".old"));
if (i > 0) {
StringStream tmp;
tmp << i;
stashed += _(".")+tmp.str();
}
target_test = target_dir / stashed;
++i;
} while (fs::exists(target_test));
fs::rename(target_dir / source_file.leaf(), target_test);
message << "File with same name found. It has been moved to " << endl
<< target_test << endl << endl;
}
target_dir /= source_file.leaf();
fs::rename(source_file, target_dir);
if (!quiet) {
message<<_("The ")<<(content == R_MAP? _("map '") : _("mod '"))<<source_file.leaf()
<<_("' has been saved succesfully to '")<<target_dir.branch_path()<<_("'.")<<endl
<<_("Use the reload mods/maps button in the lobby to make Spring find it.")<<endl;
}
//.........这里部分代码省略.........
示例14: desugar
void desugar(AST *&ast_)
{
if (auto *ast = dynamic_cast<Apply*>(ast_)) {
desugar(ast->target);
for (AST *&arg : ast->arguments)
desugar(arg);
} else if (auto *ast = dynamic_cast<Array*>(ast_)) {
for (AST *&el : ast->elements)
desugar(el);
} else if (auto *ast = dynamic_cast<ArrayComprehension*>(ast_)) {
for (ComprehensionSpec &spec : ast->specs)
desugar(spec.expr);
desugar(ast->body);
int n = ast->specs.size();
AST *zero = make<LiteralNumber>(E, 0.0);
AST *one = make<LiteralNumber>(E, 1.0);
auto *_r = id(U"$r");
auto *_l = id(U"$l");
std::vector<const Identifier*> _i(n);
for (int i = 0; i < n ; ++i) {
StringStream ss;
ss << U"$i_" << i;
_i[i] = id(ss.str());
}
std::vector<const Identifier*> _aux(n);
for (int i = 0; i < n ; ++i) {
StringStream ss;
ss << U"$aux_" << i;
_aux[i] = id(ss.str());
}
// Build it from the inside out. We keep wrapping 'in' with more ASTs.
assert(ast->specs[0].kind == ComprehensionSpec::FOR);
int last_for = n - 1;
while (ast->specs[last_for].kind != ComprehensionSpec::FOR)
last_for--;
// $aux_{last_for}($i_{last_for} + 1, $r + [body])
AST *in = make<Apply>(
ast->body->location,
var(_aux[last_for]),
std::vector<AST*> {
make<Binary>(E, var(_i[last_for]), BOP_PLUS, one),
make<Binary>(E, var(_r), BOP_PLUS, singleton(ast->body))
},
true // tailstrict
);
for (int i = n - 1; i >= 0 ; --i) {
const ComprehensionSpec &spec = ast->specs[i];
AST *out;
if (i > 0) {
int prev_for = i - 1;
while (ast->specs[prev_for].kind != ComprehensionSpec::FOR)
prev_for--;
// aux_{prev_for}($i_{prev_for} + 1, $r)
out = make<Apply>( // False branch.
E,
var(_aux[prev_for]),
std::vector<AST*> {
make<Binary>(E, var(_i[prev_for]), BOP_PLUS, one), var(_r)},
true // tailstrict
);
} else {
out = var(_r);
}
switch (spec.kind) {
case ComprehensionSpec::IF: {
/*
if [[[...cond...]]] then
[[[...in...]]]
else
[[[...out...]]]
*/
in = make<Conditional>(
ast->location,
spec.expr,
in, // True branch.
out); // False branch.
} break;
case ComprehensionSpec::FOR: {
/*
local $l = [[[...array...]]];
local aux_{i}(i_{i}, r) =
if i_{i} >= std.length(l) then
[[[...out...]]]
else
local [[[...var...]]] = l[i_{i}];
[[[...in...]]]
aux_{i}(0, r) tailstrict;
*/
in = make<Local>(
ast->location,
Local::Binds {
{_l, spec.expr},
{_aux[i], make<Function>(
//.........这里部分代码省略.........
示例15: ReadAt
unsigned Stream::ReadAt(void *buffer, uint64_t pos, size_t len, size_t *pread)
{
/** @todo Isn't thread-safe like the other ReadAt's. Add a mutex. */
LOG(HTTP) << "hs" << this << ".ReadAt(" << pos << ",+" << len << ") lastpos=" << m_last_pos << "\n";
if (!m_need_fetch && pos != m_last_pos)
{
m_socket.Close();
m_socket.Open();
m_need_fetch = true;
Seek(pos);
}
if (m_len && pos == m_len)
{
*pread = 0;
return 0;
}
if (m_need_fetch)
{
m_socket.SetNonBlocking(false);
LOG(HTTP) << "hs" << this << ": synchronous connect\n";
unsigned int rc = m_socket.Connect(m_ipe);
if (rc != 0)
{
LOG(HTTP) << "hs" << this << " can't connect: " << rc << "\n";
return rc;
}
std::string headers = "GET";
headers += " " + m_path + " HTTP/1.1\r\n";
headers += "Host: " + m_host + "\r\n";
if (pos)
{
if (m_len)
{
headers += util::Printf() << "Range: bytes=" << pos << "-"
<< (m_len-1) << "\r\n";
}
else
{
/* This is a bit nasty. Some "traditional" Receiver
* servers (in particular, Jupiter) don't like
* one-ended ranges. All such servers are on the
* "traditional" Receiver port of 12078; all such
* servers don't deal with >4GB files anyway. They do,
* however, deal with clipping large ranges to the
* actual size.
*/
if (m_ipe.port == 12078)
{
headers += util::Printf() << "Range: bytes="
<< pos << "-4294967295\r\n";
}
else
{
headers += util::Printf() << "Range: bytes="
<< pos << "-\r\n";
}
}
}
headers += "User-Agent: " PACKAGE_NAME "/" PACKAGE_VERSION "\r\n";
headers += "\r\n";
rc = m_socket.WriteAll(headers.c_str(), headers.length());
if (rc != 0)
{
TRACE << "Can't even write headers: " << rc << "\n";
return rc;
}
LOG(HTTP) << "hs" << this << " sent headers:\n" << headers;
rc = m_socket.SetNonBlocking(true);
if (rc != 0)
{
TRACE << "Can't set non-blocking: " << rc << "\n";
return rc;
}
util::GreedyLineReader lr(&m_socket);
http::Parser hp(&lr);
bool is_error = false;
for (;;)
{
unsigned int httpcode;
rc = hp.GetResponseLine(&httpcode, NULL);
//.........这里部分代码省略.........