Apache.NMS.Util.EndianBinaryWriter.WriteString16 C# (CSharp) Method

WriteString16() public method

Method WriteString16, writes a string to the output using the Java standard modified UTF-8 encoding with an unsigned short value written first to indicate the length of the encoded data, the short is read as an unsigned value so the max amount of data this method can write is 65535 encoded bytes. Unlike the WriteString32 method this method does not encode the length value to -1 if the string is null, this is to match the behaviour of the Java DataOuputStream class's writeUTF method. Because modified UTF-8 encding can result in a number of bytes greater that the size of the String this method must first check that the encoding proces will not result in a value that cannot be written becuase it is greater than the max value of an unsigned short.
public WriteString16 ( String text ) : void
text String A string
return void
        public void WriteString16(String text)
        {
            if(text != null)
            {
                if(text.Length > ushort.MaxValue)
                {
                    throw new IOException(
                        String.Format(
                            "Cannot marshall string longer than: {0} characters, supplied string was: " +
                            "{1} characters", ushort.MaxValue, text.Length));
                }

                char[] charr = text.ToCharArray();
                uint utfLength = CountUtf8Bytes(charr);

                if(utfLength > ushort.MaxValue)
                {
                    throw new IOException(
                        String.Format(
                            "Cannot marshall an encoded string longer than: {0} bytes, supplied" +
                            "string requires: {1} characters to encode", ushort.MaxValue, utfLength));
                }

                byte[] bytearr = new byte[utfLength];
                encodeUTF8toBuffer(charr, bytearr);

                Write((ushort) utfLength);
                Write(bytearr);
            }
        }

Usage Example

		public void testWriteString16_nullstring()
		{
			// test that a null string writes no output.
			MemoryStream stream = new MemoryStream();
			EndianBinaryWriter writer = new EndianBinaryWriter(stream);
			writer.WriteString16(null);
			Assert.AreEqual(0, stream.Length);
		}
All Usage Examples Of Apache.NMS.Util.EndianBinaryWriter::WriteString16