singrdk/base/Applications/WebServer/ByteString.sg

144 lines
3.4 KiB
Plaintext

//------------------------------------------------------------------------------
// <copyright company='Microsoft Corporation'>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Information Contained Herein is Proprietary and Confidential.
// </copyright>
//------------------------------------------------------------------------------
namespace Microsoft.Singularity.WebServer
{
using System;
using System.Collections;
using System.Text;
internal sealed class ByteString
{
private byte[] bytes;
private int offset;
private int length;
public ByteString(byte[] bytes, int offset, int length)
{
this.bytes = bytes;
this.offset = offset;
this.length = length;
}
public byte[] Bytes
{
get {
return bytes;
}
}
public bool IsEmpty
{
get {
return (bytes == null || length == 0);
}
}
public int Length
{
get {
return length;
}
}
public int Offset
{
get {
return offset;
}
}
public byte this[int index]
{
get {
return bytes[offset+index];
}
}
public String GetString()
{
return GetString(Encoding.UTF8);
}
public String GetString(Encoding enc)
{
if (IsEmpty) {
return String.Empty;
}
return enc.GetString(bytes, offset, length);
}
public byte[] GetBytes()
{
byte[] newBytes = new byte[length];
if (length > 0) {
Buffer.BlockCopy(bytes, offset, newBytes, 0, length);
}
return newBytes;
}
public int IndexOf(char ch)
{
return IndexOf(ch, 0);
}
public int IndexOf(char ch, int offset)
{
for (int i = offset; i < length; i++) {
if (this[i] == (byte)ch) {
return i;
}
}
return -1;
}
public ByteString Substring(int offset)
{
return Substring(offset, length-offset);
}
public ByteString Substring(int offset, int len)
{
return new ByteString(bytes, this.offset+offset, len);
}
public ByteString[] Split(char sep)
{
ArrayList list = new ArrayList();
int pos = 0;
while (pos < length) {
int i = IndexOf(sep, pos);
if (i < 0) {
break;
}
list.Add(Substring(pos, i-pos));
pos = i+1;
while (this[pos] == (byte)sep && pos < length) {
pos++;
}
}
if (pos < length) {
list.Add(Substring(pos));
}
int n = list.Count;
ByteString[] result = new ByteString[n];
for (int i = 0; i < n; i++) {
result[i] = (ByteString)list[i];
}
return result;
}
}
}