Beispiel #1
0
  void XmlWriter::WriteCdata(const Cdata& rCdata)
  {
    WriteIndent();
    std::string sString(rCdata.GetValue());
    std::string::size_type nPos = 0;
    while ((nPos = sString.find("]]>", nPos)) != std::string::npos)
    {
      sString.replace(nPos, 3, "]]]]><![CDATA[>", 15);
      nPos += 15;
    }

    m_rStream << "<![CDATA[" << sString << "]]>";
  }
Beispiel #2
0
////////////////////////////////////////////////////////////////////////////////
// BeginElement
//
bool XmlWriter::BeginElement( const char *psElementName ) {
    if (CloseCurrentElement()
        && WriteIndent()
        && WriteText( "<", 1 )
        && WriteName( psElementName ))
    {
        mnState = kStateElement;
        mbSimpleElement = true;
        mnIndentLevel++;
        return true;
    }
    return false;
}
void StdCompilerINIWrite::PutName(bool fSection)
{
	if (fSection && Buf.getLength())
		Buf.Append("\r\n");
	WriteIndent(fSection);
	// Put name
	if (fSection)
		Buf.AppendFormat("[%s]\r\n", pNaming->Name.getData());
	else
		Buf.AppendFormat("%s=", pNaming->Name.getData());
	// Set flag
	fPutName = false;
}
Beispiel #4
0
//----------------------------------------------------------------------------------
// Name: StartCDATA
// Desc: Starts a CDATA block.
//----------------------------------------------------------------------------------
BOOL XMLWriter::StartCDATA()
{
    BOOL bResult = TRUE;
    if( !m_bOpenTagFinished )
    {
        if( !EndOpenTag() ) 
            return FALSE;
        if( !WriteNewline() )
            return FALSE;
    }
    bResult &= WriteIndent();
    bResult &= OutputStringFast( "<![CDATA[", 9 );
    return bResult;
}
Beispiel #5
0
void VDJSONWriter::Close() {
	uint8 code = mStack.back();
	mStack.pop_back();

	if (!mbFirstItem) {
		WriteLine();
		WriteIndent();
	}

	Write(mbArrayMode ? L"]" : L"}", 1);

	mbArrayMode = (code & 1) != 0;
	mbFirstItem = (code & 2) != 0;
}
Beispiel #6
0
void 
myParser::charData(const XML_Char *s, int len)
{
  const int leadingSpace = skipWhiteSpace(s);
  if (len==0 || len==leadingSpace)
  	return;  // called with whitespace between elements
  	
  WriteIndent();

/* write out the user data bracketed by ()*/
  putchar('(');
  fwrite(s, len, 1, stdout);
  puts(")");
}
Beispiel #7
0
//===========================================================================
//
// Parameter:               -
// Returns:                 -
// Changes Globals:     -
//===========================================================================
bool WriteWeightConfig(char *filename, weightconfig_t * config)
{
	int             i;
	FILE           *fp;
	weight_t       *ifw;

	fp = fopen(filename, "wb");
	if(!fp)
	{
		return false;
	}

	for(i = 0; i < config->numweights; i++)
	{
		ifw = &config->weights[i];
		if(fprintf(fp, "\nweight \"%s\"\n", ifw->name) < 0)
		{
			return false;
		}
		if(fprintf(fp, "{\n") < 0)
		{
			return false;
		}
		if(ifw->firstseperator->index > 0)
		{
			if(!WriteFuzzySeperators_r(fp, ifw->firstseperator, 1))
			{
				return false;
			}
		}						//end if
		else
		{
			if(!WriteIndent(fp, 1))
			{
				return false;
			}
			if(!WriteFuzzyWeight(fp, ifw->firstseperator))
			{
				return false;
			}
		}						//end else
		if(fprintf(fp, "} //end weight\n") < 0)
		{
			return false;
		}
	}							//end for
	fclose(fp);
	return true;
}								//end of the function WriteWeightConfig
	//write the value for the element
	int HtlXDLWriter::WriteValue(HtlElement * ptrElement, std::string & strOutput, bool blnWithFormatting)
	{
		std::string strTemp, strDecodedValue;
		strTemp = ptrElement->Get_strValue();
		bool blnIsAllWhiteSpace = IsAllWhiteSpace(strTemp);
		if( (blnIsAllWhiteSpace == false) && (strTemp.size() > 0) )
		{
			//write a carriage return if necessary for formatting
			if(blnWithFormatting){strOutput += '\n';};
			//write the open tag indent
			if(blnWithFormatting){WriteIndent(strOutput,ptrElement->Get_intLevel());};
			strOutput +=  ptrElement->Get_strValue();
		};
		return 1;
	};
Beispiel #9
0
////////////////////////////////////////////////////////////////////////////////
// BeginElement
//
bool XmlWriter::BeginProcessingInstruction( const char *psInstructionName )
{
   if (CloseCurrentElement()
       && WriteIndent()
       && WriteText( "<?", 2 )
       && WriteText( psInstructionName, kSizeTypeNull ))
   {
      mbSimpleElement = false;
      mnState = kStateProcessingInstruction;

      return true;
   }

   return false;
}
Beispiel #10
0
//----------------------------------------------------------------------------------
// Name: StartComment
// Desc: Writes the beginning of an XML comment tag.
//----------------------------------------------------------------------------------
BOOL XMLWriter::StartComment( BOOL bInline )
{
    if( !m_bOpenTagFinished )
    {
        if( !EndOpenTag() ) 
            return FALSE;
        if( !bInline && !WriteNewline() )
            return FALSE;
    }
    BOOL result = TRUE;
    if( !bInline )
        result &= WriteIndent();
    result &= OutputStringFast( "<!-- ", 5 );
    m_bOpenTagFinished = TRUE;
    m_bWriteCloseTagIndent = FALSE;
    m_bInlineComment = bInline;
    return result;
}
Beispiel #11
0
//----------------------------------------------------------------------------------
// Name: StartElement
// Desc: Writes the beginning of an XML open tag.
//----------------------------------------------------------------------------------
BOOL XMLWriter::StartElement( const CHAR* strName )
{
    if( !m_bOpenTagFinished )
    {
        if( !EndOpenTag() ) 
            return FALSE;
        if( !WriteNewline() )
            return FALSE;
    }
    BOOL result = TRUE;
    result &= WriteIndent();
    PushName( strName );
    result &= OutputStringFast( "<", 1 );
    result &= OutputString( strName );
    m_bOpenTagFinished = FALSE;
    m_bWriteCloseTagIndent = FALSE;
    return result;
}
/**
 * Open new structure (one level deeper than the current one) 'name = {<LF>'.
 */
void DumpTarget::BeginStruct(size_t type_id, const char *name, const void *ptr)
{
    /* make composite name */
    CStrA cur_name = GetCurrentStructName().Transfer();
    if (cur_name.Size() > 0) {
        /* add name delimiter (we use structured names) */
        cur_name.AppendStr(".");
    }
    cur_name.AppendStr(name);

    /* put the name onto stack (as current struct name) */
    m_cur_struct.push(cur_name);

    /* put it also to the map of known structures */
    m_known_names.insert(KNOWN_NAMES::value_type(KnownStructKey(type_id, ptr), cur_name));

    WriteIndent();
    m_out.AddFormat("%s = {\n", name);
    m_indent++;
}
Beispiel #13
0
//----------------------------------------------------------------------------------
// Name: EndElement
// Desc: Writes an element close tag corresponding with the most recent open tag.
//----------------------------------------------------------------------------------
BOOL XMLWriter::EndElement()
{
    const CHAR* strName = PopName();
    if( strName == nullptr )
        return FALSE;
    BOOL result = TRUE;
    if( !m_bOpenTagFinished )
    {
        m_bOpenTagFinished = TRUE;
        result &= OutputStringFast( " />", 3 );
        result &= WriteNewline();
        m_bWriteCloseTagIndent = TRUE;
        return result;
    }
    if( m_bWriteCloseTagIndent )
        result &= WriteIndent();
    result &= OutputStringFast( "</", 2 );
    result &= OutputString( strName );
    result &= OutputStringFast( ">", 1 );
    result &= WriteNewline();
    m_bWriteCloseTagIndent = TRUE;
    return result;
}
//===========================================================================
//
// Parameter:				-
// Returns:					-
// Changes Globals:		-
//===========================================================================
qboolean WriteFuzzySeperators_r(FILE *fp, fuzzyseperator_t *fs, int indent)
{
	if (!WriteIndent(fp, indent)) return qfalse;
	if (fprintf(fp, "switch(%d)\n", fs->index) < 0) return qfalse;
	if (!WriteIndent(fp, indent)) return qfalse;
	if (fprintf(fp, "{\n") < 0) return qfalse;
	indent++;
	do
	{
		if (!WriteIndent(fp, indent)) return qfalse;
		if (fs->next)
		{
			if (fprintf(fp, "case %d:", fs->value) < 0) return qfalse;
		} //end if
		else
		{
			if (fprintf(fp, "default:") < 0) return qfalse;
		} //end else
		if (fs->child)
		{
			if (fprintf(fp, "\n") < 0) return qfalse;
			if (!WriteIndent(fp, indent)) return qfalse;
			if (fprintf(fp, "{\n") < 0) return qfalse;
			if (!WriteFuzzySeperators_r(fp, fs->child, indent + 1)) return qfalse;
			if (!WriteIndent(fp, indent)) return qfalse;
			if (fs->next)
			{
				if (fprintf(fp, "} //end case\n") < 0) return qfalse;
			} //end if
			else
			{
				if (fprintf(fp, "} //end default\n") < 0) return qfalse;
			} //end else
		} //end if
		else
		{
			if (!WriteFuzzyWeight(fp, fs)) return qfalse;
		} //end else
		fs = fs->next;
	} while(fs);
	indent--;
	if (!WriteIndent(fp, indent)) return qfalse;
	if (fprintf(fp, "} //end switch\n") < 0) return qfalse;
	return qtrue;
} //end of the function WriteItemFuzzyWeights_r
Beispiel #15
0
void JSONValue::ToString(String& dest, int spacing, int indent) const
{
    switch (type)
    {
    case JSON_BOOL:
        dest += data.boolValue;
        return;
        
    case JSON_NUMBER:
        dest += String(data.numberValue);
        return;
        
    case JSON_STRING:
        WriteJSONString(dest, *(reinterpret_cast<const String*>(&data)));
        return;
        
    case JSON_ARRAY:
        {
            const JSONArray& array = GetArray();
            dest += '[';
            
            if (array.Size())
            {
                indent += spacing;
                for (JSONArray::ConstIterator it = array.Begin(); it < array.End(); ++it)
                {
                    if (it != array.Begin())
                        dest += ',';
                    dest += '\n';
                    WriteIndent(dest, indent);
                    it->ToString(dest, spacing, indent);
                }
                indent -= spacing;
                dest += '\n';
                WriteIndent(dest, indent);
            }
            
            dest += ']';
        }
        break;
        
    case JSON_OBJECT:
        {
            const JSONObject& object = GetObject();
            dest += '{';
            
            if (object.Size())
            {
                indent += spacing;
                for (JSONObject::ConstIterator it = object.Begin(); it != object.End(); ++it)
                {
                    if (it != object.Begin())
                        dest += ',';
                    dest += '\n';
                    WriteIndent(dest, indent);
                    WriteJSONString(dest, it->first_);
                    dest += ": ";
                    it->second_.ToString(dest, spacing, indent);
                }
                indent -= spacing;
                dest += '\n';
                WriteIndent(dest, indent);
            }
            
            dest += '}';
        }
        break;
        
    default:
        dest += "null";
    }
}
/** Write name & TileIndex to the output. */
void DumpTarget::WriteTile(const char *name, TileIndex tile)
{
    WriteIndent();
    m_out.AddFormat("%s = %s\n", name, TileStr(tile).Data());
}
Beispiel #17
0
Datei: Dsl.cpp Projekt: CQiao/DSL
 void WriteString(FILE* fp, const char* str, int indent)
 {
   const char* escapeChars = " \t\r\n{}()[],;~`!%^&*-+=|:<>?/#\\";
   WriteIndent(fp, indent);
   fprintf(fp, "\"%s\"", str);
 }
Beispiel #18
0
 void XmlWriter::WriteComment(const Comment& rComment)
 {
   WriteIndent();
   m_rStream << "<!--" << EscapeString(rComment.GetValue()) << "-->";
 }
Beispiel #19
0
/*
=======================================================================================================================================
WriteStructWithIndent
=======================================================================================================================================
*/
int WriteStructWithIndent(FILE *fp, structdef_t *def, char *structure, int indent) {
	int i, num;
	void *p;
	fielddef_t *fd;

	if (!WriteIndent(fp, indent)) {
		return qfalse;
	}

	if (fprintf(fp, "{\r\n") < 0) {
		return qfalse;
	}

	indent++;

	for (i = 0; def->fields[i].name; i++) {
		fd = &def->fields[i];

		if (!WriteIndent(fp, indent)) {
			return qfalse;
		}

		if (fprintf(fp, "%s\t", fd->name) < 0) {
			return qfalse;
		}

		p = (void *)(structure + fd->offset);

		if (fd->type & FT_ARRAY) {
			num = fd->maxarray;

			if (fprintf(fp, "{") < 0) {
				return qfalse;
			}
		} else {
			num = 1;
		}

		while (num-- > 0) {
			switch (fd->type & FT_TYPE) {
				case FT_CHAR:
				{
					if (fprintf(fp, "%d", *(char *)p) < 0) {
						return qfalse;
					}

					p = (char *)p + sizeof(char);
					break;
				}
				case FT_INT:
				{
					if (fprintf(fp, "%d", *(int *)p) < 0) {
						return qfalse;
					}

					p = (char *)p + sizeof(int);
					break;
				}
				case FT_FLOAT:
				{
					if (!WriteFloat(fp, *(float *)p)) {
						return qfalse;
					}

					p = (char *)p + sizeof(float);
					break;
				}
				case FT_STRING:
				{
					if (fprintf(fp, "\"%s\"", (char *)p) < 0) {
						return qfalse;
					}

					p = (char *)p + MAX_STRINGFIELD;
					break;
				}
				case FT_STRUCT:
				{
					if (!WriteStructWithIndent(fp, fd->substruct, structure, indent)) {
						return qfalse;
					}

					p = (char *)p + fd->substruct->size;
					break;
				}
			}

			if (fd->type & FT_ARRAY) {
				if (num > 0) {
					if (fprintf(fp, ",") < 0) {
						return qfalse;
					}
				} else {
					if (fprintf(fp, "}") < 0) {
						return qfalse;
					}
				}
			}
		}

		if (fprintf(fp, "\r\n") < 0) {
			return qfalse;
		}
	}

	indent--;

	if (!WriteIndent(fp, indent)) {
		return qfalse;
	}

	if (fprintf(fp, "}\r\n") < 0) {
		return qfalse;
	}

	return qtrue;
}
Beispiel #20
0
Datei: Dsl.cpp Projekt: CQiao/DSL
 void WriteId(FILE* fp, const char* str, int indent)
 {
   WriteIndent(fp, indent);
   fprintf(fp, "%s", str);
 }
Beispiel #21
0
/*!
 The two functions write the indentation as \e spaces in the JSON output
 text. When called with a int parameter, the function
 writes the specified number of spaces.
 If no parameter is given, the function computes the number of spaces
 using the following formula:
 If the wxJSONWRITER_TAB_INDENT flag is used in the writer's cnstructor,
 the function calls WriteTabIndent().

 The function also checks that wxJSONWRITER_STYLED is set and the
 wxJSONWRITER_NO_INDENTATION is not set.
*/
int
wxJSONWriter::WriteIndent( wxOutputStream& os )
{
    int lastChar = WriteIndent( os, m_level );
    return lastChar;
}
Beispiel #22
0
/*!
 The function writes the string \c str to the output object that
 was specified in the wxJSONWriter::Write() function.
 The function may split strings in two or more lines if the
 string contains LF characters if the \c m_style data member contains
 the wxJSONWRITER_SPLIT_STRING flag.

 The function does not actually write the string: for every character
 in the provided string the function calls WriteChar() which does
 the actual character output.

 The function returns ZERO on success or -1 in case of errors.
*/
int
wxJSONWriter::WriteStringValue( wxOutputStream& os, const wxString& str )
{
    // JSON values of type STRING are written by converting the whole string
    // to UTF-8 and then copying the UTF-8 buffer to the 'os' stream
    // one byte at a time and processing them
    os.PutC( '\"' );        // open quotes

    // the buffer that has to be written is either UTF-8 or ANSI c_str() depending
    // on the 'm_noUtf8' flag
    char* writeBuff = 0;
    wxCharBuffer utf8CB = str.ToUTF8();        // the UTF-8 buffer
#if !defined( wxJSON_USE_UNICODE )
    wxCharBuffer ansiCB( str.c_str());        // the ANSI buffer
    if ( m_noUtf8 )    {
        writeBuff = ansiCB.data();
    }
    else    {
        writeBuff = utf8CB.data();
    }
#else
        writeBuff = utf8CB.data();
#endif

    // NOTE: in ANSI builds UTF-8 conversion may fail (see samples/test5.cpp,
    // test 7.3) although I do not know why
    if ( writeBuff == 0 )    {
        const char* err = "<wxJSONWriter::WriteStringValue(): error converting the string to a UTF8 buffer>";
        os.Write( err, strlen( err ));
        return 0;
    }
    size_t len = strlen( writeBuff );
    int lastChar = 0;

    // store the column at which the string starts
    // splitting strings only happen if the string starts within
    // column wxJSONWRITER_LAST_COL (default 50)
    // see 'include/wx/json_defs.h' for the defines
    int tempCol = m_colNo;

    // now write the UTF8 buffer processing the bytes
    size_t i;
    for ( i = 0; i < len; i++ ) {
        bool shouldEscape = false;
        unsigned char ch = *writeBuff;
        ++writeBuff;        // point to the next byte

        // the escaped character
        char escCh = 0;

        // for every character we have to check if it is a character that
        // needs to be escaped: note that characters that should be escaped
        // may be not if some writer's flags are specified
        switch ( ch )  {
        case '\"' :     // quotes
            shouldEscape = true;
            escCh = '\"';
            break;
        case '\\' :     // reverse solidus
            shouldEscape = true;
            escCh = '\\';
            break;
        case '/'  :     // solidus
            shouldEscape = true;
            escCh = '/';
            break;
        case '\b' :     // backspace
            shouldEscape = true;
            escCh = 'b';
            break;
        case '\f' :     // formfeed
            shouldEscape = true;
            escCh = 'f';
            break;
        case '\n' :     // newline
            shouldEscape = true;
            escCh = 'n';
            break;
        case '\r' :     // carriage-return
            shouldEscape = true;
            escCh = 'r';
            break;
        case '\t' :      // horizontal tab
            shouldEscape = true;
            escCh = 't';
            break;
        default :
            shouldEscape = false;
            break;
        }        // end switch


        // if the character is a control character that is not identified by a
        // lowercase letter, we should escape it
        if ( !shouldEscape && ch < 32 )  {
            char b[8];
            snprintf( b, 8, "\\u%04X", (int) ch );
            os.Write( b, 6 );
            if ( os.GetLastError() != wxSTREAM_NO_ERROR )    {
                return -1;
            }
        }

        // the char is not a control character
        else {
            // some characters that should be escaped are not escaped
            // if the writer was constructed with some flags
            if ( shouldEscape && !( m_style & wxJSONWRITER_ESCAPE_SOLIDUS) )  {
                if ( ch == '/' )  {
                    shouldEscape = false;
                }
            }
            if ( shouldEscape && (m_style & wxJSONWRITER_MULTILINE_STRING))  {
                if ( ch == '\n' || ch == '\t' )  {
                    shouldEscape = false;
                }
            }


            // now write the character prepended by ESC if it should be escaped
            if ( shouldEscape )  {
                os.PutC( '\\' );
                os.PutC( escCh );
                if ( os.GetLastError() != wxSTREAM_NO_ERROR )    {
                    return -1;
                }
            }
            else {
                //  a normal char or a UTF-8 units: write the character
                os.PutC( ch );
                if ( os.GetLastError() != wxSTREAM_NO_ERROR )    {
                    return -1;
                }
            }
        }

        // check if SPLIT_STRING flag is set and if the string has to
        // be splitted
        if ( (m_style & wxJSONWRITER_STYLED) && (m_style & wxJSONWRITER_SPLIT_STRING))   {
            // split the string if the character written is LF
            if ( ch == '\n' ) {
                // close quotes and CR
                os.Write( "\"\n", 2 );
                lastChar = WriteIndent( os, m_level + 2 );     // write indentation
                os.PutC( '\"' );               // reopen quotes
                if ( lastChar < 0 )  {
                    return lastChar;
                }
            }
            // split the string only if there is at least wxJSONWRITER_MIN_LENGTH
            // character to write and the character written is a punctuation or space
            // BUG: the following does not work because the columns are not counted
            else if ( (m_colNo >= wxJSONWRITER_SPLIT_COL)
                     && (tempCol <= wxJSONWRITER_LAST_COL )) {
                if ( IsSpace( ch ) || IsPunctuation( ch ))  {
                    if ( len - i > wxJSONWRITER_MIN_LENGTH )  {
                        // close quotes and CR
                        os.Write( "\"\n", 2 );
                        lastChar = WriteIndent( os, m_level + 2 );     // write indentation
                        os.PutC( '\"' );           // reopen quotes
                        if ( lastChar < 0 )  {
                            return lastChar;
                        }
                    }
                }
            }
        }
    }            // end for
    os.PutC( '\"' );    // close quotes
    return 0;
}
Beispiel #23
0
/*!
 This is a recursive function that gets the type of the \c value object and
 calls several protected functions depending on the type:

 \li \c WriteNullvalue for type NULL
 \li \c WriteStringValue() for STRING and CSTRING types
 \li \c WriteIntValue for INT types
 \li \c WriteUIntValue for UINT types
 \li \c WriteBoolValue for BOOL types
 \li \c WriteDoubleValue for DOUBLE types
 \li \c WriteMemoryBuff for MEMORYBUFF types

 If the value is an array or key/value map (types ARRAY and OBJECT), the function
 iterates through all JSON value object in the array/map and calls itself for every
 item in the container.
*/
int
wxJSONWriter::DoWrite( wxOutputStream& os, const wxJSONValue& value, const wxString* key, bool comma )
{
    // note that this function is recursive

    // some variables that cannot be allocated in the switch statement
    const wxJSONInternalMap* map = 0;
    int size;
    m_colNo = 1; m_lineNo = 1;
    // determine the comment position; it is one of:
    //
    //  wxJSONVALUE_COMMENT_BEFORE
    //  wxJSONVALUE_COMMENT_AFTER
    //  wxJSONVALUE_COMMENT_INLINE
    //
    // or -1 if comments have not to be written
    int commentPos = -1;
    if ( value.GetCommentCount() > 0 && (m_style & wxJSONWRITER_WRITE_COMMENTS))  {
        commentPos = value.GetCommentPos();
        if ( ( m_style & wxJSONWRITER_COMMENTS_BEFORE) != 0 ) {
            commentPos = wxJSONVALUE_COMMENT_BEFORE;
        }
        else if ( (m_style & wxJSONWRITER_COMMENTS_AFTER) != 0 ) {
            commentPos = wxJSONVALUE_COMMENT_AFTER;
        }
    }

    int lastChar = 0;  // check if WriteComment() writes the last LF char

    // first write the comment if it is BEFORE
    if ( commentPos == wxJSONVALUE_COMMENT_BEFORE )   {
        lastChar = WriteComment( os, value, true );
        if ( lastChar < 0 )   {
            return lastChar;
        }
        else if ( lastChar != '\n' )  {
            WriteSeparator( os );
        }
    }

    lastChar = WriteIndent( os );
    if ( lastChar < 0 )   {
        return lastChar;
    }

    // now write the key if it is not NULL
    if ( key )   {
        lastChar = WriteKey( os, *key );
    }
    if ( lastChar < 0 )   {
        return lastChar;
    }

    // now write the value
    wxJSONInternalMap::const_iterator it;    // declare the map object
    long int count = 0;

    wxJSONType t = value.GetType();
    switch ( t )  {
    case wxJSONTYPE_INVALID :
        WriteInvalid( os );
        wxFAIL_MSG( _T("wxJSONWriter::WriteEmpty() cannot be called (not a valid JSON text"));
        break;

    case wxJSONTYPE_INT :
    case wxJSONTYPE_SHORT :
    case wxJSONTYPE_LONG :
    case wxJSONTYPE_INT64 :
        lastChar = WriteIntValue( os, value );
        break;

    case wxJSONTYPE_UINT :
    case wxJSONTYPE_USHORT :
    case wxJSONTYPE_ULONG :
    case wxJSONTYPE_UINT64 :
        lastChar = WriteUIntValue( os, value );
        break;

    case wxJSONTYPE_NULL :
        lastChar = WriteNullValue( os );
        break;
    case wxJSONTYPE_BOOL :
        lastChar = WriteBoolValue( os, value );
        break;

    case wxJSONTYPE_DOUBLE :
        lastChar = WriteDoubleValue( os, value );
        break;

    case wxJSONTYPE_STRING :
    case wxJSONTYPE_CSTRING :
        lastChar = WriteStringValue( os, value.AsString());
        break;

    case wxJSONTYPE_MEMORYBUFF :
        lastChar = WriteMemoryBuff( os, value.AsMemoryBuff());
        break;

    case wxJSONTYPE_ARRAY :
        ++m_level;
        os.PutC( '[' );
        // the inline comment for objects and arrays are printed in the open char
        if ( commentPos == wxJSONVALUE_COMMENT_INLINE )   {
            commentPos = -1;  // we have already written the comment
            lastChar = WriteComment( os, value, false );
            if ( lastChar < 0 )   {
                return lastChar;
            }
            if ( lastChar != '\n' )   {
                lastChar = WriteSeparator( os );
            }
        }
        else   {    // comment is not to be printed inline, so write a LF
            lastChar = WriteSeparator( os );
            if ( lastChar < 0 )   {
                return lastChar;
            }
        }

        // now iterate through all sub-items and call DoWrite() recursively
        size = value.Size();
        for ( int i = 0; i < size; i++ )  {
            bool comma = false;
            if ( i < size - 1 )  {
                comma = true;
            }
            wxJSONValue v = value.ItemAt( i );
            lastChar = DoWrite( os, v, 0, comma );
            if ( lastChar < 0 )  {
                return lastChar;
            }

        }
        --m_level;
        lastChar = WriteIndent( os );
        if ( lastChar < 0 )   {
            return lastChar;
        }
        os.PutC( ']' );
        break;

    case wxJSONTYPE_OBJECT :
        ++m_level;

        os.PutC( '{' );
        // the inline comment for objects and arrays are printed in the open char
        if ( commentPos == wxJSONVALUE_COMMENT_INLINE )   {
            commentPos = -1;  // we have already written the comment
            lastChar = WriteComment( os, value, false );
            if ( lastChar < 0 )   {
                return lastChar;
            }
            if ( lastChar != '\n' )   {
                WriteSeparator( os );
            }
        }
        else   {
            lastChar = WriteSeparator( os );
        }

        map = value.AsMap();
        size = value.Size();
        count = 0;
        for ( it = map->begin(); it != map->end(); ++it )  {
            // get the key and the value
            wxString key = it->first;
            const wxJSONValue& v = it->second;
            bool comma = false;
            if ( count < size - 1 )  {
                comma = true;
            }
            lastChar = DoWrite( os, v, &key, comma );
            if ( lastChar < 0 )  {
                return lastChar;
            }
            count++;
        }
        --m_level;
        lastChar = WriteIndent( os );
        if ( lastChar < 0 )   {
            return lastChar;
        }
        os.PutC( '}' );
        break;

    default :
        // a not yet defined wxJSONType: we FAIL
        wxFAIL_MSG( _T("wxJSONWriter::DoWrite() undefined wxJSONType type"));
        break;
    }

    // writes the comma character before the inline comment
    if ( comma )  {
        os.PutC( ',' );
    }

    if ( commentPos == wxJSONVALUE_COMMENT_INLINE )   {
        lastChar = WriteComment( os, value, false );
        if ( lastChar < 0 )   {
            return lastChar;
        }
    }
    else if ( commentPos == wxJSONVALUE_COMMENT_AFTER )   {
        WriteSeparator( os );
        lastChar = WriteComment( os, value, true );
        if ( lastChar < 0 )   {
            return lastChar;
        }
    }
    if ( lastChar != '\n' )  {
        lastChar = WriteSeparator( os );
    }
    return lastChar;
}
Beispiel #24
0
/*!
 The type wxJSONTYPE_MEMORYBUFF is a \b wxJSON extension that is not correctly read by
 other JSON implementations.
 By default, the function writes such a type as an array of INTs as follows:
 \code
   [ 0,32,45,255,6,...]
 \endcode
 If the writer object was constructed using the \c wxJSONWRITER_MEMORYBUFF flag, then
 the output is much more compact and recognized by the \b wxJSON reader as a memory buffer
 type:
 \code
   '00203FFF06..'
 \endcode

*/
int
wxJSONWriter::WriteMemoryBuff( wxOutputStream& os, const wxMemoryBuffer& buff )
{
#define MAX_BYTES_PER_ROW	20
    char str[16];

    // if STYLED and SPLIT_STRING flags are set, the function writes 20 bytes on every row
    // the following is the counter of bytes written.
    // the string is splitted only for the special meory buffer type, not for array of INTs
    int bytesWritten = 0;
    bool splitString = false;
    if ( (m_style & wxJSONWRITER_STYLED) && 
               (m_style & wxJSONWRITER_SPLIT_STRING))   {
        splitString = true;
    }

    size_t buffLen = buff.GetDataLen();
    unsigned char* ptr = (unsigned char*) buff.GetData();
    wxASSERT( ptr );
    char openChar = '\'';
    char closeChar = '\'';
    bool asArray = false;

    if ( (m_style & wxJSONWRITER_MEMORYBUFF ) == 0 )  {
        // if the special flag is not specified, write as an array of INTs
        openChar = '[';
        closeChar = ']';
        asArray = true;
    }
    // write the open character
    os.PutC( openChar );

    for ( size_t i = 0; i < buffLen; i++ )  {
        unsigned char c = *ptr;
        ++ptr;

        if ( asArray )  {
            snprintf( str, 14, "%d", c );
            size_t len = strlen( str );
            wxASSERT( len <= 3 );
            wxASSERT( len >= 1 );
            str[len] = ',';
            // do not write the comma char for the last element
            if ( i < buffLen - 1 )    {
                ++len;
            }
            os.Write( str, len );
            if ( os.GetLastError() != wxSTREAM_NO_ERROR )    {
                return -1;
            }
        }
        else {
            // now convert the byte in two hex digits
            char c1 = c / 16;
            char c2 = c % 16;
            c1 += '0';
            c2 += '0';
            if ( c1 > '9' )  {
                c1 += 7;
            }
            if ( c2 > '9' )  {
                c2 += 7;
            }
            os.PutC( c1 );
            os.PutC( c2 );
            if ( os.GetLastError() != wxSTREAM_NO_ERROR )    {
                return -1;
            }
            if ( splitString )  {
                ++bytesWritten;
            }

            if (( bytesWritten >= MAX_BYTES_PER_ROW ) && ((buffLen - i ) >= 5 ))   {
                // split the string if we wrote 20 bytes, but only is we have to
                // write at least 5 bytes
                os.Write( "\'\n", 2 );
                int lastChar = WriteIndent( os, m_level + 2 );     // write indentation
                os.PutC( '\'' );               // reopen quotes
                if ( lastChar < 0 )  {
                    return lastChar;
                }
                bytesWritten = 0;
            }
        }
    }

    // write the close character
    os.PutC( closeChar );
    return closeChar;
}
Beispiel #25
0
static JSBool
JO(JSContext *cx, jsval *vp, StringifyContext *scx)
{
    JSObject *obj = JSVAL_TO_OBJECT(*vp);

    if (!scx->cb.append('{'))
        return JS_FALSE;

    jsval vec[3] = {JSVAL_NULL, JSVAL_NULL, JSVAL_NULL};
    JSAutoTempValueRooter tvr(cx, 3, vec);
    jsval& key = vec[0];
    jsval& outputValue = vec[1];

    JSObject *iterObj = NULL;
    jsval *keySource = vp;
    bool usingWhitelist = false;

    // if the replacer is an array, we use the keys from it
    if (scx->replacer && JS_IsArrayObject(cx, scx->replacer)) {
        usingWhitelist = true;
        vec[2] = OBJECT_TO_JSVAL(scx->replacer);
        keySource = &vec[2];
    }

    if (!js_ValueToIterator(cx, JSITER_ENUMERATE, keySource))
        return JS_FALSE;
    iterObj = JSVAL_TO_OBJECT(*keySource);

    JSBool memberWritten = JS_FALSE;

    bool ok = false;
    while (true) {
        outputValue = JSVAL_VOID;
        if (!js_CallIteratorNext(cx, iterObj, &key))
            goto error_break;
        if (key == JSVAL_HOLE)
            break;

        jsuint index = 0;
        if (usingWhitelist) {
            // skip non-index properties
            if (!js_IdIsIndex(key, &index))
                continue;

            jsval newKey;
            if (!scx->replacer->getProperty(cx, key, &newKey))
                goto error_break;
            key = newKey;
        }

        JSString *ks;
        if (JSVAL_IS_STRING(key)) {
            ks = JSVAL_TO_STRING(key);
        } else {
            ks = js_ValueToString(cx, key);
            if (!ks)
                goto error_break;
        }
        JSAutoTempValueRooter keyStringRoot(cx, ks);

        // Don't include prototype properties, since this operation is
        // supposed to be implemented as if by ES3.1 Object.keys()
        jsid id;
        jsval v = JS_FALSE;
        if (!js_ValueToStringId(cx, STRING_TO_JSVAL(ks), &id) ||
            !js_HasOwnProperty(cx, obj->map->ops->lookupProperty, obj, id, &v)) {
            goto error_break;
        }

        if (v != JSVAL_TRUE)
            continue;

        if (!JS_GetPropertyById(cx, obj, id, &outputValue))
            goto error_break;

        if (JSVAL_IS_OBJECT(outputValue) && !js_TryJSON(cx, &outputValue))
            goto error_break;

        // call this here, so we don't write out keys if the replacer function
        // wants to elide the value.
        if (!CallReplacerFunction(cx, id, obj, scx, &outputValue))
            goto error_break;

        JSType type = JS_TypeOfValue(cx, outputValue);

        // elide undefined values and functions and XML
        if (outputValue == JSVAL_VOID || type == JSTYPE_FUNCTION || type == JSTYPE_XML)
            continue;

        // output a comma unless this is the first member to write
        if (memberWritten && !scx->cb.append(','))
            goto error_break;
        memberWritten = JS_TRUE;

        if (!WriteIndent(cx, scx, scx->depth))
            goto error_break;

        // Be careful below, this string is weakly rooted
        JSString *s = js_ValueToString(cx, key);
        if (!s)
            goto error_break;

        const jschar *chars;
        size_t length;
        s->getCharsAndLength(chars, length);
        if (!write_string(cx, scx->cb, chars, length) ||
            !scx->cb.append(':') ||
            !Str(cx, id, obj, scx, &outputValue, false)) {
            goto error_break;
        }
    }
    ok = true;

  error_break:
    if (iterObj) {
        // Always close the iterator, but make sure not to stomp on OK
        JS_ASSERT(OBJECT_TO_JSVAL(iterObj) == *keySource);
        ok &= js_CloseIterator(cx, *keySource);
    }

    if (!ok)
        return JS_FALSE;

    if (memberWritten && !WriteIndent(cx, scx, scx->depth - 1))
        return JS_FALSE;

    return scx->cb.append('}');
}
Beispiel #26
0
void
XMLNode::Serialise(const Data &data, BufferedOutputStream &os, int format)
{
  bool has_children = false;

  // If the element has no name then assume this is the head node.
  if (!data.name.empty()) {
    // "<elementname "
    const unsigned cb = format == -1 ? 0 : format;

    WriteIndent(os, cb);
    os.Write('<');
    if (data.is_declaration)
      os.Write('?');
    os.Write(data.name.c_str());

    // Enumerate attributes and add them to the string
    for (auto i = data.attributes.begin(), end = data.attributes.end();
         i != end; ++i) {
      const Data::Attribute *pAttr = &*i;
      os.Write(' ');
      os.Write(pAttr->name.c_str());
      os.Write('=');
      os.Write('"');
      WriteXMLString(os, pAttr->value);
      os.Write('"');
      pAttr++;
    }

    has_children = data.HasChildren();
    if (data.is_declaration) {
      os.Write('?');
      os.Write('>');
      if (format != -1)
        os.Write('\n');
    } else
    // If there are child nodes we need to terminate the start tag
    if (has_children) {
      os.Write('>');
      if (format != -1)
        os.Write('\n');
    }
  }

  // Calculate the child format for when we recurse.  This is used to
  // determine the number of spaces used for prefixes.
  int child_format = -1;
  if (format != -1) {
    if (!data.name.empty())
      child_format = format + 1;
    else
      child_format = format;
  }

  /* write the child elements */
  for (auto i = data.begin(), end = data.end(); i != end; ++i)
    Serialise(*i->d, os, child_format);

  /* write the text */
  if (!data.text.empty()) {
    if (format != -1) {
      WriteIndent(os, format + 1);
      WriteXMLString(os, data.text);
      os.Write('\n');
    } else {
      WriteXMLString(os, data.text);
    }
  }

  if (!data.name.empty() && !data.is_declaration) {
    // If we have child entries we need to use long XML notation for
    // closing the element - "<elementname>blah blah blah</elementname>"
    if (has_children) {
      // "</elementname>\0"
      if (format != -1)
        WriteIndent(os, format);

      os.Write("</");
      os.Write(data.name.c_str());

      os.Write('>');
    } else {
      // If there are no children we can use shorthand XML notation -
      // "<elementname/>"
      // "/>\0"
      os.Write("/>");
    }

    if (format != -1)
      os.Write('\n');
  }
}
/** Write 'name = value' with indent and new-line. */
void DumpTarget::WriteValue(const char *name, const char *value_str)
{
    WriteIndent();
    m_out.AddFormat("%s = %s\n", name, value_str);
}