Skip to content

Commit

Permalink
Merge pull request #636 from marek-safar/api
Browse files Browse the repository at this point in the history
Add index based method to ILProcessor
  • Loading branch information
jbevain authored Dec 16, 2019
2 parents 9602632 + ab9bd42 commit daadf76
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
27 changes: 27 additions & 0 deletions Mono.Cecil.Cil/ILProcessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,16 @@ public void InsertAfter (Instruction target, Instruction instruction)
instructions.Insert (index + 1, instruction);
}

public void InsertAfter (int index, Instruction instruction)
{
if (index < 0 || index >= instructions.Count)
throw new ArgumentOutOfRangeException ("index");
if (instruction == null)
throw new ArgumentNullException ("instruction");

instructions.Insert (index + 1, instruction);
}

public void Append (Instruction instruction)
{
if (instruction == null)
Expand All @@ -248,6 +258,15 @@ public void Replace (Instruction target, Instruction instruction)
Remove (target);
}

public void Replace (int index, Instruction instruction)
{
if (instruction == null)
throw new ArgumentNullException ("instruction");

InsertAfter (index, instruction);
RemoveAt (index);
}

public void Remove (Instruction instruction)
{
if (instruction == null)
Expand All @@ -256,5 +275,13 @@ public void Remove (Instruction instruction)
if (!instructions.Remove (instruction))
throw new ArgumentOutOfRangeException ("instruction");
}

public void RemoveAt (int index)
{
if (index < 0 || index >= instructions.Count)
throw new ArgumentOutOfRangeException ("index");

instructions.RemoveAt (index);
}
}
}
24 changes: 24 additions & 0 deletions Test/Mono.Cecil.Tests/ILProcessorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,30 @@ public void InsertAfter ()
AssertOpCodeSequence (new [] { OpCodes.Ldloc_0, OpCodes.Ldloc_1, OpCodes.Ldloc_2, OpCodes.Ldloc_3 }, method);
}

[Test]
public void InsertAfterUsingIndex ()
{
var method = CreateTestMethod (OpCodes.Ldloc_0, OpCodes.Ldloc_2, OpCodes.Ldloc_3);
var il = method.GetILProcessor ();

il.InsertAfter (
0,
il.Create (OpCodes.Ldloc_1));

AssertOpCodeSequence (new [] { OpCodes.Ldloc_0, OpCodes.Ldloc_1, OpCodes.Ldloc_2, OpCodes.Ldloc_3 }, method);
}

[Test]
public void ReplaceUsingIndex ()
{
var method = CreateTestMethod (OpCodes.Ldloc_0, OpCodes.Ldloc_2, OpCodes.Ldloc_3);
var il = method.GetILProcessor ();

il.Replace (1, il.Create (OpCodes.Nop));

AssertOpCodeSequence (new [] { OpCodes.Ldloc_0, OpCodes.Nop, OpCodes.Ldloc_3 }, method);
}

static void AssertOpCodeSequence (OpCode [] expected, MethodBody body)
{
var opcodes = body.Instructions.Select (i => i.OpCode).ToArray ();
Expand Down

0 comments on commit daadf76

Please sign in to comment.