module StringTest;

import tango.io.device.FileConduit;
import tango.io.Stdout;
import tango.time.StopWatch;
import Util = tango.text.Util;

void main() {

   StopWatch overallWatch;
   overallWatch.start();
   
   StopWatch loadWatch;
   loadWatch.start();

   auto file = new FileConduit("shakespeare.txt");
   char[] text = new char[file.length];
   file.input.read(text);

   Stdout.formatln("time to load file: {0:f6} seconds", loadWatch.stop());

   runCharIterateTest(text);
   runWordFindTest(text);
   runWordReplaceTest(text);
   char[][] splitWords = runWordSplitTest(text);
   runConcatenateTest(splitWords);

   Stdout.formatln("overall test duration: {0:f6} seconds", overallWatch.stop());
}

private static void runCharIterateTest(char[] text) {
   StopWatch watch;
   watch.start();
   int spaceCount = 0;
   foreach (dchar c; text) {
     if (c == ' ') spaceCount++;
   }
   Stdout.formatln("iterated through {0} characters, and found {1} spaces in {2:f6} seconds", text.length, spaceCount, watch.stop());
}

private static void runWordFindTest(char[] text) {
   StopWatch watch;
   watch.start();
   int wordInstanceCount = -1;
   int position = 0;
   do {
      wordInstanceCount++;
      position = Util.locatePattern(text, "the", position + 1);
   } while (position < text.length);
   Stdout.formatln("String.indexOf(): found {0} instances of 'the' in {1:f6} seconds", wordInstanceCount, watch.stop());
}

private static void runWordReplaceTest(char[] text) {
   int oldLength = text.length;
   StopWatch watch;
   watch.start();
   char[] replaced = Util.substitute(text, "the", "XXXX");
   int newLength = replaced.length;
   int replacementCount = newLength - oldLength;
   Stdout.formatln("replaced {0} instances of 'the' with 'XXXX' in {1:f6} seconds", replacementCount, watch.stop());
}

private static char[][] runWordSplitTest(char[] text) {
   StopWatch watch;
   watch.start();
   char[][] splitWords = Util.split(text, " ");
   Stdout.formatln("split text into {0} words in {1:f6} seconds", splitWords.length, watch.stop());
   return splitWords;
}

private static void runConcatenateTest(char[][] splitWords) {
   StopWatch watch;
   watch.start();
   char[] buffer;
   foreach (char[] word; splitWords) {
      buffer ~= word;
      buffer ~= " ";
   }
   Stdout.formatln("concatenated {0} words (with {1} chars) in {2:f6} seconds", splitWords.length, buffer.length, watch.stop());
}
