public static GameMemory OpenFile(string filename) { byte[] file = ReadFile(filename); int length = file.Length; if(length < headerSize) { throw new ArgumentException($"{filename} is not a valid story file"); } ImmutableByteWrapper wrapper = new ImmutableByteWrapper(file); byte high = wrapper.ReadAddress(Bits.AddressOfHighByte(baseOffset)); byte low = wrapper.ReadAddress(Bits.AddressOfLowByte(baseOffset)); int dynamicSegmentLength = (256 * high) + low; if(dynamicSegmentLength > length) { throw new ArgumentException($"{filename} is not a valid story file"); } byte[] dynamicPart = new byte[dynamicSegmentLength]; Array.Copy(file, dynamicPart, dynamicSegmentLength); byte[] staticPart = new byte[length - dynamicSegmentLength]; Array.Copy(file, dynamicSegmentLength, staticPart, 0, length - dynamicSegmentLength); return new GameMemory(staticPart, new ImmutableByteWrapper(dynamicPart)); }
private static string ReadAsUtf8String(ImmutableByteWrapper bulkEdits) { byte[] asRead = new byte[bulkEdits.Length]; for (int i = 0; i < bulkEdits.Length; i++) { asRead[i] = bulkEdits.ReadAddress(new ByteAddress(i)); } return Encoding.UTF8.GetString(asRead); }
private static void TestMemoryBase() { byte[] bytes = Encoding.UTF8.GetBytes("Hello World"); ImmutableByteWrapper initialState = new ImmutableByteWrapper(bytes); ByteAddress address1 = new ByteAddress(1); ImmutableByteWrapper edited = initialState.WriteToAddress(address1, 0x00); //owerwrite "world" byte[] newBytes = Encoding.UTF8.GetBytes("woid!"); IEnumerable<int> sixThruTen = Enumerable.Range(6, 5); var multiEdits = sixThruTen.Select(val => { var address = new ByteAddress(val); var toWrite = newBytes[val - 6]; return new Tuple<ByteAddress, byte>(address, toWrite); }); ImmutableByteWrapper bulkEdits = initialState.WriteMultipleAddress(multiEdits); var toPrint = ReadAsUtf8String(bulkEdits); var oldToPrint = ReadAsUtf8String(initialState); Console.WriteLine($"Initial state has {oldToPrint} and bulk edited has {toPrint}"); int length = initialState.Length; Console.WriteLine(edited.ReadAddress(address1)); Console.WriteLine(initialState.ReadAddress(address1)); }