/// <summary> /// Maps a position in the source space to the corresponding position in the target space. /// </summary> public int GetTargetPosition(int sourcePosition, PositionBias bias = PositionBias.Right) { int targetPosition = sourcePosition; foreach (var edit in _edits) { targetPosition = Translate( targetPosition, edit.Start, edit.DeleteLength, edit.InsertLength, bias); } return(targetPosition); }
/// <summary> /// Reverse maps a position from the target space to the correpsonding position in the source space. /// </summary> public int GetSourcePosition(int targetPosition, PositionBias bias = PositionBias.Right) { int sourcePosition = targetPosition; for (int i = _edits.Count - 1; i >= 0; i--) { var edit = _edits[i]; // since we are doing the reverse operation // deletes are inserts and inserts are deletes sourcePosition = Translate( position: sourcePosition, start: edit.Start, deleteLength: edit.InsertLength, insertLength: edit.DeleteLength, bias: bias); } return(sourcePosition); }
/// <summary> /// Translate a position across an edit /// </summary> private static int Translate(int position, int start, int deleteLength, int insertLength, PositionBias bias) { if (deleteLength > 0 && position > start) { if (position > start + deleteLength) { // after deleted range, adjust downward position -= deleteLength; } else { // inside deleted range, adjust to start position = start; } } if (insertLength > 0) { // if after the insert position, adjust upward // or at the insert position and bias is toward right, also adjust upward if (position > start || (bias == PositionBias.Right && position == start)) { position += insertLength; } } return(position); }
/// <summary> /// Gets the position in the original text corresponding to the position in the current text. /// If current position corresponds to a region of the text that was inserted, it will return the position /// at the start of where change occurred. /// </summary> public int GetOriginalPosition(int currentPosition, PositionBias bias = PositionBias.Right) { return(this._map.GetSourcePosition(currentPosition, bias)); }
/// <summary> /// Gets the position in the current text corresponding to the position in the original text. /// If original position corresponds to a region of text that was removed or replaced, it will return the position /// at the start of where the change occurred. /// </summary> public int GetCurrentPosition(int originalPosition, PositionBias bias = PositionBias.Right) { return(this._map.GetTargetPosition(originalPosition, bias)); }