OSDN Git Service

最終行が空行だと全置換えに失敗するバグを修正した
[fooeditengine/FooEditEngine.git] / Core / StringBuffer.cs
1 /*
2  * Copyright (C) 2013 FooProject
3  * * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by
4  * the Free Software Foundation; either version 3 of the License, or (at your option) any later version.
5
6  * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of 
7  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
8
9 You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
10  */
11 //#define TEST_ASYNC
12 using System;
13 using System.IO;
14 using System.Collections.Generic;
15 using System.Globalization;
16 using System.Linq;
17 using System.Text;
18 using System.Text.RegularExpressions;
19 using System.Threading;
20 using System.Threading.Tasks;
21 using Slusser.Collections.Generic;
22
23 namespace FooEditEngine
24 {
25     /// <summary>
26     /// ランダムアクセス可能な列挙子を提供するインターフェイス
27     /// </summary>
28     /// <typeparam name="T"></typeparam>
29     public interface IRandomEnumrator<T>
30     {
31         /// <summary>
32         /// インデクサーを表す
33         /// </summary>
34         /// <param name="index">インデックス</param>
35         /// <returns>Tを返す</returns>
36         T this[int index]{get;}
37     }
38
39     sealed class StringBuffer : IEnumerable<char>, IRandomEnumrator<char>
40     {
41         GapBuffer<char> buf = new GapBuffer<char>();
42         const int MaxSemaphoreCount = 1;
43         SemaphoreSlim Semaphore = new SemaphoreSlim(MaxSemaphoreCount);
44
45         public StringBuffer()
46         {
47             this.Update = (s, e) => { };
48         }
49
50         /// <summary>
51         /// ロック中なら真を返し、そうでないなら偽を返す
52         /// </summary>
53         public bool IsLocked
54         {
55             get
56             {
57                 return this.Semaphore.CurrentCount == 0;
58             }
59         }
60
61         /// <summary>
62         /// ロックを解除します
63         /// </summary>
64         public void UnLock()
65         {
66             this.Semaphore.Release();
67         }
68
69         /// <summary>
70         /// ロックします
71         /// </summary>
72         public void Lock()
73         {
74             this.Semaphore.Wait();
75         }
76
77         /// <summary>
78         /// ロックします
79         /// </summary>
80         /// <returns>Taskオブジェクト</returns>
81         public Task LockAsync()
82         {
83             return this.Semaphore.WaitAsync();
84         }
85
86         public StringBuffer(StringBuffer buffer)
87             : this()
88         {
89             buf.AddRange(buffer.buf, buffer.Length);
90         }
91
92
93         public char this[int index]
94         {
95             get
96             {
97                 char c = buf[index];
98                 return c;
99             }
100         }
101
102         public string ToString(int index, int length)
103         {
104             this.Lock();
105
106             StringBuilder temp = new StringBuilder();
107             temp.Clear();
108             for (int i = index; i < index + length; i++)
109                 temp.Append(buf[i]);
110
111             this.UnLock();
112
113             return temp.ToString();
114         }
115
116         public IEnumerable<string> GetLines(int startIndex, int endIndex, int maxCharCount = -1)
117         {
118             foreach (Tuple<int, int> range in this.ForEachLines(startIndex, endIndex, maxCharCount))
119             {
120                 StringBuilder temp = new StringBuilder();
121                 temp.Clear();
122                 int lineEndIndex = range.Item1;
123                 if (range.Item2 > 0)
124                     lineEndIndex += range.Item2 - 1;
125                 for (int i = range.Item1; i <= lineEndIndex; i++)
126                     temp.Append(buf[i]);
127                 yield return temp.ToString();
128             }
129         }
130
131         public IEnumerable<Tuple<int,int>> ForEachLines(int startIndex, int endIndex, int maxCharCount = -1)
132         {
133             int currentLineHeadIndex = startIndex;
134             int currentLineLength = 0;
135             
136             for (int i = startIndex; i <= endIndex; i++)
137             {
138                 currentLineLength++;
139                 char c = this.buf[i];
140                 if (c == Document.NewLine ||
141                     (maxCharCount != -1 && currentLineLength >= maxCharCount))
142                 {
143                     UnicodeCategory uc = CharUnicodeInfo.GetUnicodeCategory(c);
144                     if (uc != UnicodeCategory.NonSpacingMark &&
145                     uc != UnicodeCategory.SpacingCombiningMark &&
146                     uc != UnicodeCategory.EnclosingMark &&
147                     uc != UnicodeCategory.Surrogate)
148                     {
149                         yield return new Tuple<int,int>(currentLineHeadIndex, currentLineLength);
150                         currentLineHeadIndex += currentLineLength;
151                         currentLineLength = 0;
152                     }
153                 }
154             }
155             if (currentLineLength > 0)
156                 yield return new Tuple<int, int>(currentLineHeadIndex, currentLineLength);
157         }
158         
159         public int Length
160         {
161             get { return this.buf.Count; }
162         }
163
164         internal DocumentUpdateEventHandler Update;
165
166         internal void Replace(StringBuffer buf)
167         {
168             this.Replace(buf.buf);
169         }
170
171         internal void Replace(GapBuffer<char> buf)
172         {
173             this.Lock();
174
175             this.Clear();
176             this.buf = buf;
177
178             this.UnLock();
179
180             this.Update(this, new DocumentUpdateEventArgs(UpdateType.Replace, 0, 0, buf.Count));
181         }
182
183         internal void Replace(int index, int length, IEnumerable<char> chars,int count)
184         {
185             this.Lock();
186
187             if (length > 0)
188                 this.buf.RemoveRange(index, length);
189             this.buf.InsertRange(index, chars,count);
190
191             this.UnLock();
192
193             this.Update(this, new DocumentUpdateEventArgs(UpdateType.Replace, index, length, count));
194         }
195
196         internal async Task LoadAsync(TextReader fs, CancellationTokenSource tokenSource = null)
197         {
198             char[] str = new char[1024 * 256];
199             int readCount;
200             do
201             {
202                 int index = this.Length;
203                 if (index < 0)
204                     index = 0;
205
206                 readCount = await fs.ReadAsync(str, 0, str.Length).ConfigureAwait(false);
207
208                 //内部形式に変換する
209                 var internal_str = from s in str where s != '\r' && s != '\0' select s;
210
211                 await this.LockAsync().ConfigureAwait(false);
212
213                 //str.lengthは事前に確保しておくために使用するので影響はない
214                 this.buf.InsertRange(index, internal_str, str.Length);
215
216                 this.UnLock();
217
218                 if (tokenSource != null)
219                     tokenSource.Token.ThrowIfCancellationRequested();
220 #if TEST_ASYNC
221                 System.Diagnostics.Debug.WriteLine("waiting now");
222                 await Task.Delay(100).ConfigureAwait(false);
223 #endif
224                 Array.Clear(str, 0, str.Length);
225             } while (readCount > 0);
226
227             this.Update(this, new DocumentUpdateEventArgs(UpdateType.Clear, -1, -1, -1));
228             this.Update(this, new DocumentUpdateEventArgs(UpdateType.Replace, 0, 0, buf.Count));
229         }
230
231         internal void ReplaceRegexAll(LineToIndexTable layoutlines, Regex regex, string pattern, bool groupReplace)
232         {
233             for (int i = 0; i < layoutlines.Count; i++)
234             {
235                 int lineHeadIndex = layoutlines.GetIndexFromLineNumber(i), lineLength = layoutlines.GetLengthFromLineNumber(i);
236                 int left = lineHeadIndex, right = lineHeadIndex;
237                 string output = regex.Replace(layoutlines[i], (m) => {
238                     if (groupReplace)
239                         return m.Result(pattern);
240                     else
241                         return pattern;
242                 });
243
244                 this.Lock();
245                 //空行は削除する必要はない
246                 if(lineHeadIndex < this.buf.Count )
247                     this.buf.RemoveRange(lineHeadIndex, lineLength);
248                 this.buf.InsertRange(lineHeadIndex, output, output.Length);
249
250                 this.UnLock();
251
252                 this.Update(this, new DocumentUpdateEventArgs(UpdateType.Replace, lineHeadIndex, lineLength, output.Length, i));
253             }
254         }
255
256         internal void ReplaceAll(LineToIndexTable layoutlines,string target, string pattern, bool ci = false)
257         {
258             TextSearch ts = new TextSearch(target, ci);
259             char[] pattern_chars = pattern.ToCharArray();
260             for(int i = 0; i < layoutlines.Count; i++)
261             {
262                 int lineHeadIndex = layoutlines.GetIndexFromLineNumber(i), lineLength = layoutlines.GetLengthFromLineNumber(i);
263                 int left = lineHeadIndex, right = lineHeadIndex;
264                 int newLineLength = lineLength;
265                 while ((right = ts.IndexOf(this.buf, left, lineHeadIndex + newLineLength)) != -1)
266                 {
267                     this.Lock();
268
269                     this.buf.RemoveRange(right, target.Length);
270                     this.buf.InsertRange(right, pattern_chars, pattern.Length);
271
272                     this.UnLock();
273                     left = right + pattern.Length;
274                     newLineLength += pattern.Length - target.Length;
275                 }
276
277
278                 this.Update(this, new DocumentUpdateEventArgs(UpdateType.Replace, lineHeadIndex, lineLength, newLineLength, i));
279             }
280         }
281
282         internal int IndexOf(string target, int start,bool ci = false)
283         {
284             this.Lock();
285
286             TextSearch ts = new TextSearch(target,ci);
287             int patternIndex = ts.IndexOf(this.buf, start,this.buf.Count);
288
289             this.UnLock();
290
291             return patternIndex;
292         }
293
294         /// <summary>
295         /// 文字列を削除する
296         /// </summary>
297         internal void Clear()
298         {
299             this.buf.Clear();
300             this.Update(this, new DocumentUpdateEventArgs(UpdateType.Clear, 0, this.buf.Count,0));
301         }
302
303         internal IEnumerable<char> GetEnumerator(int start, int length)
304         {
305             for (int i = start; i < start + length; i++)
306                 yield return this.buf[i];
307         }
308
309         #region IEnumerable<char> メンバー
310
311         public IEnumerator<char> GetEnumerator()
312         {
313             for (int i = 0; i < this.Length; i++)
314                 yield return this.buf[i];
315         }
316
317         #endregion
318
319         #region IEnumerable メンバー
320
321         System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
322         {
323             for (int i = 0; i < this.Length; i++)
324                 yield return this[i];
325         }
326
327         #endregion
328     }
329
330     sealed class TextSearch
331     {
332         char[] pattern;
333         int patternLength;
334         Dictionary<char, int> qsTable = new Dictionary<char, int>();
335         bool caseInsenstive;
336         public TextSearch(string pattern,bool ci = false)
337         {
338             this.patternLength = pattern.Length;
339             this.caseInsenstive = ci;
340             if (ci)
341             {
342                 this.CreateQSTable(pattern.ToLower());
343                 this.CreateQSTable(pattern.ToUpper());
344                 this.pattern = new char[pattern.Length];
345                 for (int i = 0; i < pattern.Length; i++)
346                     this.pattern[i] = CharTool.ToUpperFastIf(pattern[i]);
347             }
348             else
349             {
350                 this.CreateQSTable(pattern);
351                 this.pattern = pattern.ToCharArray();
352             }
353         }
354         void CreateQSTable(string pattern)
355         {
356             int len = pattern.Length;
357             for (int i = 0; i < len; i++)
358             {
359                 if (!this.qsTable.ContainsKey(pattern[i]))
360                     this.qsTable.Add(pattern[i], len - i);
361                 else
362                     this.qsTable[pattern[i]] = len - i;
363             }
364         }
365         public int IndexOf(GapBuffer<char> buf, int start,int end)
366         {
367             //QuickSearch法
368             int buflen = buf.Count - 1;
369             int plen = this.patternLength;
370             int i = start;
371             int search_end = end - plen;
372             //最適化のためわざとコピペした
373             if (this.caseInsenstive)
374             {
375                 while (i <= search_end)
376                 {
377                     int j = 0;
378                     while (j < plen)
379                     {
380                         if (CharTool.ToUpperFastIf(buf[i + j]) != this.pattern[j])
381                             break;
382                         j++;
383                     }
384                     if (j == plen)
385                     {
386                         return i;
387                     }
388                     else
389                     {
390                         int k = i + plen;
391                         if (k <= buflen)        //buffer以降にアクセスする可能性がある
392                         {
393                             int moveDelta;
394                             if (this.qsTable.TryGetValue(buf[k], out moveDelta))
395                                 i += moveDelta;
396                             else
397                                 i += plen;
398                         }
399                         else
400                         {
401                             break;
402                         }
403                     }
404                 }
405
406             }
407             else
408             {
409                 while (i <= search_end)
410                 {
411                     int j = 0;
412                     while (j < plen)
413                     {
414                         if (buf[i + j] != this.pattern[j])
415                             break;
416                         j++;
417                     }
418                     if (j == plen)
419                     {
420                         return i;
421                     }
422                     else
423                     {
424                         int k = i + plen;
425                         if (k <= buflen)        //buffer以降にアクセスする可能性がある
426                         {
427                             int moveDelta;
428                             if (this.qsTable.TryGetValue(buf[k], out moveDelta))
429                                 i += moveDelta;
430                             else
431                                 i += plen;
432                         }
433                         else
434                         {
435                             break;
436                         }
437                     }
438                 }
439             }
440             return -1;
441         }
442     }
443     static class CharTool
444     {
445         /// <summary>
446         /// Converts characters to lowercase.
447         /// </summary>
448         const string _lookupStringL =
449         "---------------------------------!-#$%&-()*+,-./0123456789:;<=>?@abcdefghijklmnopqrstuvwxyz[-]^_`abcdefghijklmnopqrstuvwxyz{|}~-";
450
451         /// <summary>
452         /// Converts characters to uppercase.
453         /// </summary>
454         const string _lookupStringU =
455         "---------------------------------!-#$%&-()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[-]^_`ABCDEFGHIJKLMNOPQRSTUVWXYZ{|}~-";
456
457         /// <summary>
458         /// Get lowercase version of this ASCII character.
459         /// </summary>
460         public static char ToLower(char c)
461         {
462             return _lookupStringL[c];
463         }
464
465         /// <summary>
466         /// Get uppercase version of this ASCII character.
467         /// </summary>
468         public static char ToUpper(char c)
469         {
470             return _lookupStringU[c];
471         }
472
473         /// <summary>
474         /// Translate uppercase ASCII characters to lowercase.
475         /// </summary>
476         public static char ToLowerFastIf(char c)
477         {
478             if (c >= 'A' && c <= 'Z')
479             {
480                 return (char)(c + 32);
481             }
482             else
483             {
484                 return c;
485             }
486         }
487
488         /// <summary>
489         /// Translate lowercase ASCII characters to uppercase.
490         /// </summary>
491         public static char ToUpperFastIf(char c)
492         {
493             if (c >= 'a' && c <= 'z')
494             {
495                 return (char)(c - 32);
496             }
497             else
498             {
499                 return c;
500             }
501         }
502     }
503 }