OSDN Git Service

Revert "セマフォーだとデッドロックを起こすことがあるのでリーダーライターロッカーに変更した"
[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             try{
188                 if (length > 0)
189                     this.buf.RemoveRange(index, length);
190                 this.buf.InsertRange(index, chars, count);
191             }
192             finally
193             {
194                 this.UnLock();
195             }
196
197             this.Update(this, new DocumentUpdateEventArgs(UpdateType.Replace, index, length, count));
198         }
199
200         internal async Task LoadAsync(TextReader fs, CancellationTokenSource tokenSource = null)
201         {
202             char[] str = new char[1024 * 256];
203             int readCount;
204             do
205             {
206                 int index = this.Length;
207                 if (index < 0)
208                     index = 0;
209
210                 readCount = await fs.ReadAsync(str, 0, str.Length).ConfigureAwait(false);
211
212                 //内部形式に変換する
213                 var internal_str = from s in str where s != '\r' && s != '\0' select s;
214
215                 await this.LockAsync().ConfigureAwait(false);
216                 //str.lengthは事前に確保しておくために使用するので影響はない
217                 this.buf.InsertRange(index, internal_str, str.Length);
218
219                 this.UnLock();
220
221                 if (tokenSource != null)
222                     tokenSource.Token.ThrowIfCancellationRequested();
223 #if TEST_ASYNC
224                 System.Diagnostics.Debug.WriteLine("waiting now");
225                 await Task.Delay(100).ConfigureAwait(false);
226 #endif
227                 Array.Clear(str, 0, str.Length);
228             } while (readCount > 0);
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                 try
246                 {
247                     //空行は削除する必要はない
248                     if (lineHeadIndex < this.buf.Count)
249                         this.buf.RemoveRange(lineHeadIndex, lineLength);
250                     this.buf.InsertRange(lineHeadIndex, output, output.Length);
251                 }
252                 finally
253                 {
254                     this.UnLock();
255                 }
256
257                 this.Update(this, new DocumentUpdateEventArgs(UpdateType.Replace, lineHeadIndex, lineLength, output.Length, i));
258             }
259         }
260
261         internal void ReplaceAll(LineToIndexTable layoutlines,string target, string pattern, bool ci = false)
262         {
263             TextSearch ts = new TextSearch(target, ci);
264             char[] pattern_chars = pattern.ToCharArray();
265             for(int i = 0; i < layoutlines.Count; i++)
266             {
267                 int lineHeadIndex = layoutlines.GetIndexFromLineNumber(i), lineLength = layoutlines.GetLengthFromLineNumber(i);
268                 int left = lineHeadIndex, right = lineHeadIndex;
269                 int newLineLength = lineLength;
270                 while ((right = ts.IndexOf(this.buf, left, lineHeadIndex + newLineLength)) != -1)
271                 {
272                     this.Lock();
273                     try
274                     {
275                         this.buf.RemoveRange(right, target.Length);
276                         this.buf.InsertRange(right, pattern_chars, pattern.Length);
277                     }
278                     finally
279                     {
280                         this.UnLock();
281
282                     }
283                     left = right + pattern.Length;
284                     newLineLength += pattern.Length - target.Length;
285                 }
286
287
288                 this.Update(this, new DocumentUpdateEventArgs(UpdateType.Replace, lineHeadIndex, lineLength, newLineLength, i));
289             }
290         }
291
292         internal int IndexOf(string target, int start,bool ci = false)
293         {
294             this.Lock();
295
296             TextSearch ts = new TextSearch(target,ci);
297             int patternIndex = ts.IndexOf(this.buf, start,this.buf.Count);
298
299             this.UnLock();
300
301             return patternIndex;
302         }
303
304         /// <summary>
305         /// 文字列を削除する
306         /// </summary>
307         internal void Clear()
308         {
309             this.buf.Clear();
310             this.Update(this, new DocumentUpdateEventArgs(UpdateType.Clear, 0, this.buf.Count,0));
311         }
312
313         internal IEnumerable<char> GetEnumerator(int start, int length)
314         {
315             for (int i = start; i < start + length; i++)
316                 yield return this.buf[i];
317         }
318
319         #region IEnumerable<char> メンバー
320
321         public IEnumerator<char> GetEnumerator()
322         {
323             for (int i = 0; i < this.Length; i++)
324                 yield return this.buf[i];
325         }
326
327         #endregion
328
329         #region IEnumerable メンバー
330
331         System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
332         {
333             for (int i = 0; i < this.Length; i++)
334                 yield return this[i];
335         }
336
337         #endregion
338     }
339
340     sealed class TextSearch
341     {
342         char[] pattern;
343         int patternLength;
344         Dictionary<char, int> qsTable = new Dictionary<char, int>();
345         bool caseInsenstive;
346         public TextSearch(string pattern,bool ci = false)
347         {
348             this.patternLength = pattern.Length;
349             this.caseInsenstive = ci;
350             if (ci)
351             {
352                 this.CreateQSTable(pattern.ToLower());
353                 this.CreateQSTable(pattern.ToUpper());
354                 this.pattern = new char[pattern.Length];
355                 for (int i = 0; i < pattern.Length; i++)
356                     this.pattern[i] = CharTool.ToUpperFastIf(pattern[i]);
357             }
358             else
359             {
360                 this.CreateQSTable(pattern);
361                 this.pattern = pattern.ToCharArray();
362             }
363         }
364         void CreateQSTable(string pattern)
365         {
366             int len = pattern.Length;
367             for (int i = 0; i < len; i++)
368             {
369                 if (!this.qsTable.ContainsKey(pattern[i]))
370                     this.qsTable.Add(pattern[i], len - i);
371                 else
372                     this.qsTable[pattern[i]] = len - i;
373             }
374         }
375         public int IndexOf(GapBuffer<char> buf, int start,int end)
376         {
377             //QuickSearch法
378             int buflen = buf.Count - 1;
379             int plen = this.patternLength;
380             int i = start;
381             int search_end = end - plen;
382             //最適化のためわざとコピペした
383             if (this.caseInsenstive)
384             {
385                 while (i <= search_end)
386                 {
387                     int j = 0;
388                     while (j < plen)
389                     {
390                         if (CharTool.ToUpperFastIf(buf[i + j]) != this.pattern[j])
391                             break;
392                         j++;
393                     }
394                     if (j == plen)
395                     {
396                         return i;
397                     }
398                     else
399                     {
400                         int k = i + plen;
401                         if (k <= buflen)        //buffer以降にアクセスする可能性がある
402                         {
403                             int moveDelta;
404                             if (this.qsTable.TryGetValue(buf[k], out moveDelta))
405                                 i += moveDelta;
406                             else
407                                 i += plen;
408                         }
409                         else
410                         {
411                             break;
412                         }
413                     }
414                 }
415
416             }
417             else
418             {
419                 while (i <= search_end)
420                 {
421                     int j = 0;
422                     while (j < plen)
423                     {
424                         if (buf[i + j] != this.pattern[j])
425                             break;
426                         j++;
427                     }
428                     if (j == plen)
429                     {
430                         return i;
431                     }
432                     else
433                     {
434                         int k = i + plen;
435                         if (k <= buflen)        //buffer以降にアクセスする可能性がある
436                         {
437                             int moveDelta;
438                             if (this.qsTable.TryGetValue(buf[k], out moveDelta))
439                                 i += moveDelta;
440                             else
441                                 i += plen;
442                         }
443                         else
444                         {
445                             break;
446                         }
447                     }
448                 }
449             }
450             return -1;
451         }
452     }
453     static class CharTool
454     {
455         /// <summary>
456         /// Converts characters to lowercase.
457         /// </summary>
458         const string _lookupStringL =
459         "---------------------------------!-#$%&-()*+,-./0123456789:;<=>?@abcdefghijklmnopqrstuvwxyz[-]^_`abcdefghijklmnopqrstuvwxyz{|}~-";
460
461         /// <summary>
462         /// Converts characters to uppercase.
463         /// </summary>
464         const string _lookupStringU =
465         "---------------------------------!-#$%&-()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[-]^_`ABCDEFGHIJKLMNOPQRSTUVWXYZ{|}~-";
466
467         /// <summary>
468         /// Get lowercase version of this ASCII character.
469         /// </summary>
470         public static char ToLower(char c)
471         {
472             return _lookupStringL[c];
473         }
474
475         /// <summary>
476         /// Get uppercase version of this ASCII character.
477         /// </summary>
478         public static char ToUpper(char c)
479         {
480             return _lookupStringU[c];
481         }
482
483         /// <summary>
484         /// Translate uppercase ASCII characters to lowercase.
485         /// </summary>
486         public static char ToLowerFastIf(char c)
487         {
488             if (c >= 'A' && c <= 'Z')
489             {
490                 return (char)(c + 32);
491             }
492             else
493             {
494                 return c;
495             }
496         }
497
498         /// <summary>
499         /// Translate lowercase ASCII characters to uppercase.
500         /// </summary>
501         public static char ToUpperFastIf(char c)
502         {
503             if (c >= 'a' && c <= 'z')
504             {
505                 return (char)(c - 32);
506             }
507             else
508             {
509                 return c;
510             }
511         }
512     }
513 }