-
Notifications
You must be signed in to change notification settings - Fork 329
Expand file tree
/
Copy pathFile.cs
More file actions
1843 lines (1627 loc) · 57.8 KB
/
File.cs
File metadata and controls
1843 lines (1627 loc) · 57.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// File.cs: Provides a basic framework for reading from and writing to
// a file, as well as accessing basic tagging and media properties.
//
// Author:
// Brian Nickel (brian.nickel@gmail.com)
// Aaron Bockover (abockover@novell.com)
//
// Original Source:
// tfile.cpp from TagLib
//
// Copyright (C) 2005, 2007 Brian Nickel
// Copyright (C) 2006 Novell, Inc.
// Copyright (C) 2002,2003 Scott Wheeler (Original Implementation)
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License version
// 2.1 as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
// USA
//
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Runtime.Serialization;
namespace TagLib
{
/// <summary>
/// Specifies the options to use when reading the media.
/// </summary>
[Flags]
public enum ReadStyle
{
/// <summary>
/// The media properties will not be read.
/// </summary>
None = 0,
// Fast = 1,
/// <summary>
/// The media properties will be read with average accuracy.
/// </summary>
Average = 2,
/// <summary>
/// Use the <see cref="PictureLazy"/> class in the
/// the property <see cref="Tag.Pictures"/>.
/// This will avoid loading picture content when reading the Tag.
/// Picture will be read lazily, when the picture content is
/// accessed.
/// </summary>
PictureLazy = 4
}
/// <summary>
/// This abstract class provides a basic framework for reading from
/// and writing to a file, as well as accessing basic tagging and
/// media properties.
/// </summary>
/// <remarks>
/// <para>This class is agnostic to all specific media types. Its
/// child classes, on the other hand, support the the intricacies of
/// different media and tagging formats. For example, <see
/// cref="Mpeg4.File" /> supports the MPEG-4 specificication and
/// Apple's tagging format.</para>
/// <para>Each file type can be created using its format specific
/// constructors, ie. <see cref="Mpeg4.File(string)" />, but the
/// preferred method is to use <see
/// cref="Create(string,string,ReadStyle)" /> or one of its
/// variants, as it automatically detects the appropriate class from
/// the file extension or provided mime-type.</para>
/// </remarks>
public abstract class File : IDisposable
{
#region Enums
/// <summary>
/// Specifies the type of file access operations currently
/// permitted on an instance of <see cref="File" />.
/// </summary>
public enum AccessMode
{
/// <summary>
/// Read operations can be performed.
/// </summary>
Read,
/// <summary>
/// Read and write operations can be performed.
/// </summary>
Write,
/// <summary>
/// The file is closed for both read and write
/// operations.
/// </summary>
Closed
}
#endregion
#region Delegates
/// <summary>
/// This delegate is used for intervening in <see
/// cref="Create(string)" /> by resolving the file type
/// before any standard resolution operations.
/// </summary>
/// <param name="abstraction">
/// A <see cref="IFileAbstraction" /> object representing the
/// file to be read.
/// </param>
/// <param name="mimetype">
/// A <see cref="string" /> object containing the mime-type
/// of the file.
/// </param>
/// <param name="style">
/// A <see cref="ReadStyle" /> value specifying how to read
/// media properties from the file.
/// </param>
/// <returns>
/// A new instance of <see cref="File" /> or <see
/// langword="null" /> if the resolver could not match it.
/// </returns>
/// <remarks>
/// <para>A <see cref="FileTypeResolver" /> is one way of
/// altering the behavior of <see cref="Create(string)" />
/// .</para>
/// <para>When <see cref="Create(string)" /> is called, the
/// registered resolvers are invoked in the reverse order in
/// which they were registered. The resolver may then perform
/// any operations necessary, including other type-finding
/// methods.</para>
/// <para>If the resolver returns a new <see cref="File" />,
/// it will instantly be returned, by <see
/// cref="Create(string)" />. If it returns <see
/// langword="null" />, <see cref="Create(string)" /> will
/// continue to process. If the resolver throws an exception
/// it will be uncaught.</para>
/// <para>To register a resolver, use <see
/// cref="AddFileTypeResolver" />.</para>
/// </remarks>
public delegate File FileTypeResolver (IFileAbstraction abstraction, string mimetype, ReadStyle style);
#endregion
#region Private Properties
/// <summary>
/// Contains the current stream used in reading/writing.
/// </summary>
Stream file_stream;
/// <summary>
/// Contains the internal file abstraction.
/// </summary>
protected IFileAbstraction file_abstraction;
/// <summary>
/// Contains buffer size to use when reading.
/// </summary>
static readonly int buffer_size = 1024;
/// <summary>
/// Contains the file type resolvers to use in <see
/// cref="Create(string)" />.
/// </summary>
static readonly List<FileTypeResolver> file_type_resolvers = new List<FileTypeResolver> ();
/// <summary>
/// The reasons (if any) why this file is marked as corrupt.
/// </summary>
List<string> corruption_reasons;
/// <summary>
/// Specifies whether the file should be readable by other
/// threads while being written to by the thread that opened it.
/// </summary>
public bool read_share_when_writing;
#endregion
#region Public Static Properties
/// <summary>
/// The buffer size to use when reading large blocks of data
/// in the <see cref="File" /> class.
/// </summary>
/// <value>
/// A <see cref="uint" /> containing the buffer size to use
/// when reading large blocks of data.
/// </value>
public static uint BufferSize => (uint)buffer_size;
#endregion
#region Constructors
/// <summary>
/// Constructs and initializes a new instance of <see
/// cref="File" /> for a specified path in the local file
/// system.
/// </summary>
/// <param name="path">
/// A <see cref="string" /> object containing the path of the
/// file to use in the new instance.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="path" /> is <see langword="null" />.
/// </exception>
protected File (string path)
{
if (path == null)
throw new ArgumentNullException (nameof (path));
file_abstraction = new LocalFileAbstraction (path);
}
/// <summary>
/// Constructs and initializes a new instance of <see
/// cref="File" /> for a specified file abstraction.
/// </summary>
/// <param name="abstraction">
/// A <see cref="IFileAbstraction" /> object to use when
/// reading from and writing to the file.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="abstraction" /> is <see langword="null"
/// />.
/// </exception>
protected File (IFileAbstraction abstraction)
{
if (abstraction == null)
throw new ArgumentNullException (nameof (abstraction));
file_abstraction = abstraction;
}
#endregion
#region Public Properties
/// <summary>
/// Gets a abstract representation of all tags stored in the
/// current instance.
/// </summary>
/// <value>
/// A <see cref="TagLib.Tag" /> object representing all tags
/// stored in the current instance.
/// </value>
/// <remarks>
/// <para>This property provides generic and general access
/// to the most common tagging features of a file. To access
/// or add a specific type of tag in the file, use <see
/// cref="GetTag(TagLib.TagTypes,bool)" />.</para>
/// </remarks>
public abstract Tag Tag { get; }
/// <summary>
/// Gets the media properties of the file represented by the
/// current instance.
/// </summary>
/// <value>
/// A <see cref="TagLib.Properties" /> object containing the
/// media properties of the file represented by the current
/// instance.
/// </value>
public abstract Properties Properties { get; }
/// <summary>
/// Gets the tag types contained in the physical file
/// represented by the current instance.
/// </summary>
/// <value>
/// A bitwise combined <see cref="TagLib.TagTypes" /> value
/// containing the tag types stored in the physical file as
/// it was read or last saved.
/// </value>
public TagTypes TagTypesOnDisk { get; protected set; } = TagTypes.None;
/// <summary>
/// Gets the tag types contained in the current instance.
/// </summary>
/// <value>
/// A bitwise combined <see cref="TagLib.TagTypes" /> value
/// containing the tag types stored in the current instance.
/// </value>
public TagTypes TagTypes => Tag?.TagTypes ?? TagTypes.None;
/// <summary>
/// Gets the name of the file as stored in its file
/// abstraction.
/// </summary>
/// <value>
/// A <see cref="string" /> object containing the name of the
/// file as stored in the <see cref="IFileAbstraction" />
/// object used to create it or the path if created with a
/// local path.
/// </value>
public string Name => file_abstraction.Name;
/// <summary>
/// Gets the mime-type of the file as determined by <see
/// cref="Create(IFileAbstraction,string,ReadStyle)" /> if
/// that method was used to create the current instance.
/// </summary>
/// <value>
/// A <see cref="string" /> object containing the mime-type
/// used to create the file or <see langword="null" /> if <see
/// cref="Create(IFileAbstraction,string,ReadStyle)" /> was
/// not used to create the current instance.
/// </value>
public string MimeType { get; internal set; }
/// <summary>
/// Gets the seek position in the internal stream used by the
/// current instance.
/// </summary>
/// <value>
/// A <see cref="long" /> value representing the seek
/// position, or 0 if the file is not open for reading.
/// </value>
public long Tell => (Mode == AccessMode.Closed) ? 0 : file_stream.Position;
/// <summary>
/// Gets the length of the file represented by the current
/// instance.
/// </summary>
/// <value>
/// A <see cref="long" /> value representing the size of the
/// file, or 0 if the file is not open for reading.
/// </value>
public long Length => (Mode == AccessMode.Closed) ? 0 : file_stream.Length;
/// <summary>
/// Gets the position at which the invariant portion of the
/// current instance begins.
/// </summary>
/// <value>
/// A <see cref="long" /> value representing the seek
/// position at which the file's invariant (media) data
/// section begins. If the value could not be determined,
/// <c>-1</c> is returned.
/// </value>
public long InvariantStartPosition { get; protected set; } = -1;
/// <summary>
/// Gets the position at which the invariant portion of the
/// current instance ends.
/// </summary>
/// <value>
/// A <see cref="long" /> value representing the seek
/// position at which the file's invariant (media) data
/// section ends. If the value could not be determined,
/// <c>-1</c> is returned.
/// </value>
public long InvariantEndPosition { get; protected set; } = -1;
/// <summary>
/// Gets and sets the file access mode in use by the current
/// instance.
/// </summary>
/// <value>
/// A <see cref="AccessMode" /> value describing the features
/// of stream currently in use by the current instance.
/// </value>
/// <remarks>
/// Changing the value will cause the stream currently in use
/// to be closed, except when a change is made from <see
/// cref="AccessMode.Write" /> to <see cref="AccessMode.Read"
/// /> which has no effect.
/// </remarks>
public AccessMode Mode {
get {
if (file_stream == null)
return AccessMode.Closed;
if (file_stream.CanWrite)
return AccessMode.Write;
return AccessMode.Read;
}
set {
if (Mode == value || (Mode == AccessMode.Write && value == AccessMode.Read))
return;
if (file_stream != null)
file_abstraction.CloseStream (file_stream);
file_stream = null;
if (value == AccessMode.Read)
file_stream = file_abstraction.ReadStream;
else if (value == AccessMode.Write)
file_stream = file_abstraction.WriteStream;
Mode = value;
}
}
/// <summary>
/// Gets the <see cref="IFileAbstraction"/> representing the file.
/// </summary>
public IFileAbstraction FileAbstraction => file_abstraction;
/// <summary>
/// Indicates if tags can be written back to the current file or not
/// </summary>
/// <value>
/// A <see cref="bool" /> which is true if tags can be written to the
/// current file, otherwise false.
/// </value>
public virtual bool Writeable => !PossiblyCorrupt;
/// <summary>
/// Indicates whether or not this file may be corrupt.
/// </summary>
/// <value>
/// <c>true</c> if possibly corrupt; otherwise, <c>false</c>.
/// </value>
/// <remarks>
/// Files with unknown corruptions should not be written.
/// </remarks>
public bool PossiblyCorrupt => corruption_reasons != null;
/// <summary>
/// The reasons for which this file is marked as corrupt.
/// </summary>
public IEnumerable<string> CorruptionReasons => corruption_reasons;
#endregion
#region Public Methods
/// <summary>
/// Mark the file as corrupt.
/// </summary>
/// <param name="reason">
/// The reason why this file is considered to be corrupt.
/// </param>
internal void MarkAsCorrupt (string reason)
{
if (corruption_reasons == null)
corruption_reasons = new List<string> ();
corruption_reasons.Add (reason);
}
/// <summary>
/// Dispose the current file. Equivalent to setting the
/// mode to closed
/// </summary>
public void Dispose ()
{
Mode = AccessMode.Closed;
}
/// <summary>
/// Saves the changes made in the current instance to the
/// file it represents.
/// </summary>
public abstract void Save ();
/// <summary>
/// Removes a set of tag types from the current instance.
/// </summary>
/// <param name="types">
/// A bitwise combined <see cref="TagLib.TagTypes" /> value
/// containing tag types to be removed from the file.
/// </param>
/// <remarks>
/// In order to remove all tags from a file, pass <see
/// cref="TagTypes.AllTags" /> as <paramref name="types" />.
/// </remarks>
public abstract void RemoveTags (TagTypes types);
/// <summary>
/// Gets a tag of a specified type from the current instance,
/// optionally creating a new tag if possible.
/// </summary>
/// <param name="type">
/// A <see cref="TagLib.TagTypes" /> value indicating the
/// type of tag to read.
/// </param>
/// <param name="create">
/// A <see cref="bool" /> value specifying whether or not to
/// try and create the tag if one is not found.
/// </param>
/// <returns>
/// A <see cref="Tag" /> object containing the tag that was
/// found in or added to the current instance. If no
/// matching tag was found and none was created, <see
/// langword="null" /> is returned.
/// </returns>
/// <remarks>
/// <para>Passing <see langword="true" /> to <paramref
/// name="create" /> does not guarantee the tag will be
/// created. For example, trying to create an ID3v2 tag on an
/// OGG Vorbis file will always fail.</para>
/// <para>It is safe to assume that if <see langword="null"
/// /> is not returned, the returned tag can be cast to the
/// appropriate type.</para>
/// </remarks>
/// <example>
/// <para>The following example sets the mood of a file to
/// several tag types.</para>
/// <code lang="C#">string [] SetMoods (TagLib.File file, params string[] moods)
///{
/// TagLib.Id3v2.Tag id3 = file.GetTag (TagLib.TagTypes.Id3v2, true);
/// if (id3 != null)
/// id3.SetTextFrame ("TMOO", moods);
///
/// TagLib.Asf.Tag asf = file.GetTag (TagLib.TagTypes.Asf, true);
/// if (asf != null)
/// asf.SetDescriptorStrings (moods, "WM/Mood", "Mood");
///
/// TagLib.Ape.Tag ape = file.GetTag (TagLib.TagTypes.Ape);
/// if (ape != null)
/// ape.SetValue ("MOOD", moods);
///
/// // Whatever tag types you want...
///}</code>
/// </example>
public abstract Tag GetTag (TagTypes type, bool create);
/// <summary>
/// Gets a tag of a specified type from the current instance.
/// </summary>
/// <param name="type">
/// A <see cref="TagLib.TagTypes" /> value indicating the
/// type of tag to read.
/// </param>
/// <returns>
/// A <see cref="Tag" /> object containing the tag that was
/// found in the current instance. If no matching tag
/// was found, <see langword="null" /> is returned.
/// </returns>
/// <remarks>
/// <para>This class merely accesses the tag if it exists.
/// <see cref="GetTag(TagTypes,bool)" /> provides the option
/// of adding the tag to the current instance if it does not
/// exist.</para>
/// <para>It is safe to assume that if <see langword="null"
/// /> is not returned, the returned tag can be cast to the
/// appropriate type.</para>
/// </remarks>
/// <example>
/// <para>The following example reads the mood of a file from
/// several tag types.</para>
/// <code lang="C#">static string [] GetMoods (TagLib.File file)
///{
/// TagLib.Id3v2.Tag id3 = file.GetTag (TagLib.TagTypes.Id3v2);
/// if (id3 != null) {
/// TextIdentificationFrame f = TextIdentificationFrame.Get (this, "TMOO");
/// if (f != null)
/// return f.FieldList.ToArray ();
/// }
///
/// TagLib.Asf.Tag asf = file.GetTag (TagLib.TagTypes.Asf);
/// if (asf != null) {
/// string [] value = asf.GetDescriptorStrings ("WM/Mood", "Mood");
/// if (value.Length > 0)
/// return value;
/// }
///
/// TagLib.Ape.Tag ape = file.GetTag (TagLib.TagTypes.Ape);
/// if (ape != null) {
/// Item item = ape.GetItem ("MOOD");
/// if (item != null)
/// return item.ToStringArray ();
/// }
///
/// // Whatever tag types you want...
///
/// return new string [] {};
///}</code>
/// </example>
public Tag GetTag (TagTypes type)
{
return GetTag (type, false);
}
/// <summary>
/// Reads a specified number of bytes at the current seek
/// position from the current instance.
/// </summary>
/// <param name="length">
/// A <see cref="int" /> value specifying the number of bytes
/// to read.
/// </param>
/// <returns>
/// A <see cref="ByteVector" /> object containing the data
/// read from the current instance.
/// </returns>
/// <remarks>
/// <para>This method reads the block of data at the current
/// seek position. To change the seek position, use <see
/// cref="Seek(long,SeekOrigin)" />.</para>
/// </remarks>
/// <exception cref="ArgumentException">
/// <paramref name="length" /> is less than zero.
/// </exception>
public ByteVector ReadBlock (int length)
{
if (length < 0)
throw new ArgumentException ("Length must be non-negative", nameof (length));
if (length == 0)
return new ByteVector ();
Mode = AccessMode.Read;
byte[] buffer = new byte[length];
int count = 0, read = 0, needed = length;
do {
count = file_stream.Read (buffer, read, needed);
read += count;
needed -= count;
} while (needed > 0 && count != 0);
return new ByteVector (buffer, read);
}
/// <summary>
/// Writes a block of data to the file represented by the
/// current instance at the current seek position.
/// </summary>
/// <param name="data">
/// A <see cref="ByteVector" /> object containing data to be
/// written to the current instance.
/// </param>
/// <remarks>
/// This will overwrite any existing data at the seek
/// position and append new data to the file if writing past
/// the current end.
/// </remarks>
/// <exception cref="ArgumentNullException">
/// <paramref name="data" /> is <see langword="null" />.
/// </exception>
public void WriteBlock (ByteVector data)
{
if (data == null)
throw new ArgumentNullException (nameof (data));
Mode = AccessMode.Write;
file_stream.Write (data.Data, 0, data.Count);
}
/// <summary>
/// Searches forwards through a file for a specified
/// pattern, starting at a specified offset.
/// </summary>
/// <param name="pattern">
/// A <see cref="ByteVector" /> object containing a pattern
/// to search for in the current instance.
/// </param>
/// <param name="startPosition">
/// A <see cref="int" /> value specifying at what
/// seek position to start searching.
/// </param>
/// <param name="before">
/// A <see cref="ByteVector" /> object specifying a pattern
/// that the searched for pattern must appear before. If this
/// pattern is found first, -1 is returned.
/// </param>
/// <returns>
/// A <see cref="long" /> value containing the index at which
/// the value was found. If not found, -1 is returned.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="pattern" /> is <see langword="null" />.
/// </exception>
public long Find (ByteVector pattern, long startPosition, ByteVector before)
{
if (pattern == null)
throw new ArgumentNullException (nameof (pattern));
Mode = AccessMode.Read;
if (pattern.Count > buffer_size)
return -1;
// The position in the file that the current buffer
// starts at.
long buffer_offset = startPosition;
long original_position = file_stream.Position;
try {
// Start the search at the offset.
file_stream.Position = startPosition;
for (var buffer = ReadBlock (buffer_size); buffer.Count > 0; buffer = ReadBlock (buffer_size)) {
var location = buffer.Find (pattern);
if (before != null) {
var beforeLocation = buffer.Find (before);
if (beforeLocation < location)
return -1;
}
if (location >= 0)
return buffer_offset + location;
// Ensure that we always rewind the stream a little so we never have a partial
// match where our data exists between the end of read A and the start of read B.
buffer_offset += buffer_size - pattern.Count;
if (before != null && before.Count > pattern.Count)
buffer_offset -= before.Count - pattern.Count;
file_stream.Position = buffer_offset;
}
return -1;
} finally {
file_stream.Position = original_position;
}
}
/// <summary>
/// Searches forwards through a file for a specified
/// pattern, starting at a specified offset.
/// </summary>
/// <param name="pattern">
/// A <see cref="ByteVector" /> object containing a pattern
/// to search for in the current instance.
/// </param>
/// <param name="startPosition">
/// A <see cref="int" /> value specifying at what
/// seek position to start searching.
/// </param>
/// <returns>
/// A <see cref="long" /> value containing the index at which
/// the value was found. If not found, -1 is returned.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="pattern" /> is <see langword="null" />.
/// </exception>
public long Find (ByteVector pattern, long startPosition)
{
return Find (pattern, startPosition, null);
}
/// <summary>
/// Searches forwards through a file for a specified
/// pattern, starting at the beginning of the file.
/// </summary>
/// <param name="pattern">
/// A <see cref="ByteVector" /> object containing a pattern
/// to search for in the current instance.
/// </param>
/// <returns>
/// A <see cref="long" /> value containing the index at which
/// the value was found. If not found, -1 is returned.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="pattern" /> is <see langword="null" />.
/// </exception>
public long Find (ByteVector pattern)
{
return Find (pattern, 0);
}
/// <summary>
/// Searches backwards through a file for a specified
/// pattern, starting at a specified offset.
/// </summary>
/// <param name="pattern">
/// A <see cref="ByteVector" /> object containing a pattern
/// to search for in the current instance.
/// </param>
/// <param name="startPosition">
/// A <see cref="int" /> value specifying at what
/// seek position to start searching.
/// </param>
/// <param name="after">
/// A <see cref="ByteVector" /> object specifying a pattern
/// that the searched for pattern must appear after. If this
/// pattern is found first, -1 is returned.
/// </param>
/// <returns>
/// A <see cref="long" /> value containing the index at which
/// the value was found. If not found, -1 is returned.
/// </returns>
/// <remarks>
/// Searching for <paramref name="after" /> is not yet
/// implemented.
/// </remarks>
/// <exception cref="ArgumentNullException">
/// <paramref name="pattern" /> is <see langword="null" />.
/// </exception>
long RFind (ByteVector pattern, long startPosition, ByteVector after)
{
if (pattern == null)
throw new ArgumentNullException (nameof (pattern));
Mode = AccessMode.Read;
if (pattern.Count > buffer_size)
return -1;
// The position in the file that the current buffer
// starts at.
ByteVector buffer;
// These variables are used to keep track of a partial
// match that happens at the end of a buffer.
/*
int previous_partial_match = -1;
int after_previous_partial_match = -1;
*/
// Save the location of the current read pointer. We
// will restore the position using Seek() before all
// returns.
long original_position = file_stream.Position;
// Start the search at the offset.
long buffer_offset = Length - startPosition;
int read_size = buffer_size;
read_size = (int)Math.Min (buffer_offset, buffer_size);
buffer_offset -= read_size;
file_stream.Position = buffer_offset;
// See the notes in find() for an explanation of this
// algorithm.
for (buffer = ReadBlock (read_size); buffer.Count > 0; buffer = ReadBlock (read_size)) {
// TODO: (1) previous partial match
// (2) pattern contained in current buffer
long location = buffer.RFind (pattern);
if (location >= 0) {
file_stream.Position = original_position;
return buffer_offset + location;
}
if (after != null && buffer.RFind (after) >= 0) {
file_stream.Position = original_position;
return -1;
}
read_size = (int)Math.Min (buffer_offset, buffer_size);
buffer_offset -= read_size;
if (read_size + pattern.Count > buffer_size)
buffer_offset += pattern.Count;
file_stream.Position = buffer_offset;
}
// Since we hit the end of the file, reset the status
// before continuing.
file_stream.Position = original_position;
return -1;
}
/// <summary>
/// Searches backwards through a file for a specified
/// pattern, starting at a specified offset.
/// </summary>
/// <param name="pattern">
/// A <see cref="ByteVector" /> object containing a pattern
/// to search for in the current instance.
/// </param>
/// <param name="startPosition">
/// A <see cref="int" /> value specifying at what
/// seek position to start searching.
/// </param>
/// <returns>
/// A <see cref="long" /> value containing the index at which
/// the value was found. If not found, -1 is returned.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="pattern" /> is <see langword="null" />.
/// </exception>
public long RFind (ByteVector pattern, long startPosition)
{
return RFind (pattern, startPosition, null);
}
/// <summary>
/// Searches backwards through a file for a specified
/// pattern, starting at the end of the file.
/// </summary>
/// <param name="pattern">
/// A <see cref="ByteVector" /> object containing a pattern
/// to search for in the current instance.
/// </param>
/// <returns>
/// A <see cref="long" /> value containing the index at which
/// the value was found. If not found, -1 is returned.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="pattern" /> is <see langword="null" />.
/// </exception>
public long RFind (ByteVector pattern)
{
return RFind (pattern, 0);
}
/// <summary>
/// Inserts a specifed block of data into the file repesented
/// by the current instance at a specified location,
/// replacing a specified number of bytes.
/// </summary>
/// <param name="data">
/// A <see cref="ByteVector" /> object containing the data to
/// insert into the file.
/// </param>
/// <param name="start">
/// A <see cref="long" /> value specifying at which point to
/// insert the data.
/// </param>
/// <param name="replace">
/// A <see cref="long" /> value specifying the number of
/// bytes to replace. Typically this is the original size of
/// the data block so that a new block will replace the old
/// one.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="data" /> is <see langword="null" />.
/// </exception>
public void Insert (ByteVector data, long start, long replace)
{
if (data == null)
throw new ArgumentNullException (nameof (data));
Insert (data, data.Count, start, replace);
}
/// <summary>
/// Inserts a specified block of data into the file repesented
/// by the current instance at a specified location.
/// </summary>
/// <param name="data">
/// A <see cref="ByteVector" /> object containing the data to
/// insert into the file.
/// </param>
/// <param name="start">
/// A <see cref="long" /> value specifying at which point to
/// insert the data.
/// </param>
/// <remarks>
/// This method inserts a new block of data into the file. To
/// replace an existing block, ie. replacing an existing
/// tag with a new one of different size, use <see
/// cref="Insert(ByteVector,long,long)" />.
/// </remarks>
/// <exception cref="ArgumentNullException">
/// <paramref name="data" /> is <see langword="null" />.
/// </exception>
public void Insert (ByteVector data, long start)
{
Insert (data, start, 0);
}
/// <summary>
/// Inserts a specified block-size into the file repesented
/// by the current instance at a specified location. Former
/// data at this location is not overwriten and may then
/// contain random content.
/// </summary>
/// <param name="size">
/// A <see cref="long" /> value specifying the size in bytes
/// of the block to be inserted (reserved).
/// </param>