using System.Text; namespace HeuristicLab.Problems.ProgramSynthesis.Push.Stack { using System.Collections; using System.Collections.Generic; using HeuristicLab.Problems.ProgramSynthesis.Push.Constants; using HeuristicLab.Problems.ProgramSynthesis.Push.Extensions; /// /// Optimized for string concatenation to reduce memory effort /// public class PrintStack : IPrintStack { private int lineCount = 0; private int length = 0; private IReadOnlyList lines; private readonly StringBuilder stringBuilder = new StringBuilder(); public PrintStack() { IsCurrentLineEmpty = true; } public bool IsCurrentLineEmpty { get; private set; } IEnumerator IEnumerable.GetEnumerator() { return Lines.GetEnumerator(); } public void Add(string item) { Push(item); } public IReadOnlyList Lines { get { if (lines != null && stringBuilder.Length == length) return lines; length = stringBuilder.Length; lines = stringBuilder.ToString().Split(PushEnvironment.NewLine); return lines; } } void IPushStack.Clear() { lineCount = 0; length = 0; lines = null; IsCurrentLineEmpty = true; stringBuilder.Clear(); } public void NewLine() { stringBuilder.Append(PushEnvironment.NewLine); IsCurrentLineEmpty = true; lineCount++; } public void Push(T item) { if (IsEmpty) lineCount = 1; var str = item.ToString(); stringBuilder.Append(str); IsCurrentLineEmpty = IsCurrentLineEmpty && string.IsNullOrEmpty(str); } public void Push(float item) { if (IsEmpty) lineCount = 1; stringBuilder.Concat(item); IsCurrentLineEmpty = false; } public void Push(double item) { if (IsEmpty) lineCount = 1; stringBuilder.Concat(item); IsCurrentLineEmpty = false; } public void Push(long item) { if (IsEmpty) lineCount = 1; stringBuilder.Concat(item); IsCurrentLineEmpty = false; } public void Push(int item) { if (IsEmpty) lineCount = 1; stringBuilder.Concat(item); IsCurrentLineEmpty = false; } public void Push(char item) { if (IsEmpty) lineCount = 1; stringBuilder.Append(item); IsCurrentLineEmpty = false; } public void Push(bool item) { if (IsEmpty) lineCount = 1; stringBuilder.Append(item); IsCurrentLineEmpty = false; } public void Push(string item) { if (IsEmpty) lineCount = 1; stringBuilder.Append(item); IsCurrentLineEmpty = IsCurrentLineEmpty && string.IsNullOrEmpty(item); } public void Push(IReadOnlyList items, int startIndex) { for (var i = startIndex; i < items.Count; i++) stringBuilder.Append(items[i]); IsCurrentLineEmpty = false; } public void Push(IReadOnlyList items) { Push(items, 0); } public void Push(IEnumerable items) { foreach (var item in items) stringBuilder.Append(item); IsCurrentLineEmpty = false; } public IEnumerable AsStrings() { return Lines; } public IEnumerable AsObjects() { return Lines; } int IPushStack.Count { get { return lineCount; } } public bool IsEmpty { get { return stringBuilder.Length == 0; } } public bool IsEnabled { get; set; } public bool IsReadOnly { get { return false; } } public override string ToString() { return stringBuilder.ToString(); } } }