BitSharper.Script.Parse C# (CSharp) Method

Parse() private method

To run a script, first we parse it which breaks it up into chunks representing pushes of data or logical opcodes. Then we can run the parsed chunks.
The reason for this split, instead of just interpreting directly, is to make it easier to reach into a programs structure and pull out bits of data without having to run it. This is necessary to render the to/from addresses of transactions in a user interface. The official client does something similar.
private Parse ( byte programBytes, int offset, int length ) : void
programBytes byte
offset int
length int
return void
        private void Parse(byte[] programBytes, int offset, int length)
        {
            // TODO: this is inefficient
            _programCopy = new byte[length];
            Array.Copy(programBytes, offset, _programCopy, 0, length);

            _program = _programCopy;
            offset = 0;
            _chunks = new List<byte[]>(10); // Arbitrary choice of initial size.
            _cursor = offset;
            while (_cursor < offset + length)
            {
                var opcode = (int) ReadByte();
                if (opcode >= 0xF0)
                {
                    // Not a single byte opcode.
                    opcode = (opcode << 8) | ReadByte();
                }

                if (opcode > 0 && opcode < OpPushData1)
                {
                    // Read some bytes of data, where how many is the opcode value itself.
                    _chunks.Add(GetData(opcode)); // opcode == len here.
                }
                else if (opcode == OpPushData1)
                {
                    var len = ReadByte();
                    _chunks.Add(GetData(len));
                }
                else if (opcode == OpPushData2)
                {
                    // Read a short, then read that many bytes of data.
                    var len = ReadByte() | (ReadByte() << 8);
                    _chunks.Add(GetData(len));
                }
                else if (opcode == OpPushData4)
                {
                    // Read a uint32, then read that many bytes of data.
                    _log.Error("PUSHDATA4: Unimplemented");
                }
                else
                {
                    _chunks.Add(new[] {(byte) opcode});
                }
            }
        }