tlang-interperter-cs/tlanglib/TArray.cs

70 lines
2.0 KiB
C#

using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json.Linq;
namespace tlang
{
public class TArray : TObject
{
public override JToken AsToken()
{
var ls = new JArray();
foreach(var item in Items)
{
ls.Add(item.AsToken());
}
return ls;
}
public byte[] ToBytes()
{
byte[] data = new byte[Items.Count];
SetBytes(data,0,data.Length);
return data;
}
public void SetBytes(byte[] data,int offset,int count)
{
count = Math.Min(data.Length - offset,count);
for(int i = 0;i<count;i++)
{
var item = Items[i+offset];
var c = item as TChar;
var n = item as TNumber;
if(c != null) data[i] = (byte)c.Value;
if(n != null) data[i] = (byte)n.Value;
}
}
public static TArray FromBytes(byte[] data,int offset,int count)
{
var array = TObject.Array(count);
for(int i = 0;i<count;i++)
{
array.Items[i+offset] = TObject.Number(data[i]);
}
return array;
}
public override bool AsBoolean => Items.Count > 0;
public TArray(int sz=0)
{
Items =new List<TObject>();
for(int i = 0;i<sz;i++)
{
Items.Add(TObject.Uninit);
}
}
public override string ToString()
{
StringBuilder b = new StringBuilder();
b.AppendLine("Array Items:");
foreach(var item in Items)
{
b.AppendLine(item.ToString());
}
return b.ToString();
}
public List<TObject> Items {get;set;}
}
}