001 /*
002 * Sonar, open source software quality management tool.
003 * Copyright (C) 2008-2012 SonarSource
004 * mailto:contact AT sonarsource DOT com
005 *
006 * Sonar is free software; you can redistribute it and/or
007 * modify it under the terms of the GNU Lesser General Public
008 * License as published by the Free Software Foundation; either
009 * version 3 of the License, or (at your option) any later version.
010 *
011 * Sonar is distributed in the hope that it will be useful,
012 * but WITHOUT ANY WARRANTY; without even the implied warranty of
013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
014 * Lesser General Public License for more details.
015 *
016 * You should have received a copy of the GNU Lesser General Public
017 * License along with Sonar; if not, write to the Free Software
018 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
019 */
020 package org.sonar.plugins.core.timemachine.tracking;
021
022 import com.google.common.collect.Lists;
023
024 import java.util.List;
025
026 /**
027 * Text is a {@link Sequence} of lines.
028 */
029 public class StringText implements Sequence {
030
031 final String content;
032
033 /**
034 * Map of line number to starting position within {@link #content}.
035 */
036 final List<Integer> lines;
037
038 public StringText(String str) {
039 this.content = str;
040 this.lines = lineMap(content, 0, content.length());
041 }
042
043 public int length() {
044 return lines.size() - 2;
045 }
046
047 private static List<Integer> lineMap(String buf, int ptr, int end) {
048 List<Integer> lines = Lists.newArrayList();
049 lines.add(Integer.MIN_VALUE);
050 for (; ptr < end; ptr = nextLF(buf, ptr)) {
051 lines.add(ptr);
052 }
053 lines.add(end);
054 return lines;
055 }
056
057 private static int nextLF(String b, int ptr) {
058 return next(b, ptr, '\n');
059 }
060
061 private static int next(final String b, int ptr, final char chrA) {
062 final int sz = b.length();
063 while (ptr < sz) {
064 if (b.charAt(ptr++) == chrA) {
065 return ptr;
066 }
067 }
068 return ptr;
069 }
070
071 }