/
file_impl.dart
1095 lines (962 loc) · 32 KB
/
file_impl.dart
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
// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
part of dart.io;
// Read the file in blocks of size 64k.
const int _blockSize = 64 * 1024;
class _FileStream extends Stream<List<int>> {
// Stream controller.
StreamController<Uint8List> _controller;
// Information about the underlying file.
String _path;
RandomAccessFile _openedFile;
int _position;
int _end;
final Completer _closeCompleter = new Completer();
// Has the stream been paused or unsubscribed?
bool _unsubscribed = false;
// Is there a read currently in progress?
bool _readInProgress = true;
bool _closed = false;
bool _atEnd = false;
_FileStream(this._path, this._position, this._end) {
_position ??= 0;
}
_FileStream.forStdin() : _position = 0;
StreamSubscription<Uint8List> listen(void onData(Uint8List event),
{Function onError, void onDone(), bool cancelOnError}) {
_setupController();
return _controller.stream.listen(onData,
onError: onError, onDone: onDone, cancelOnError: cancelOnError);
}
void _setupController() {
_controller = new StreamController<Uint8List>(
sync: true,
onListen: _start,
onResume: _readBlock,
onCancel: () {
_unsubscribed = true;
return _closeFile();
});
}
Future _closeFile() {
if (_readInProgress || _closed) {
return _closeCompleter.future;
}
_closed = true;
void done() {
_closeCompleter.complete();
_controller.close();
}
_openedFile.close().catchError(_controller.addError).whenComplete(done);
return _closeCompleter.future;
}
void _readBlock() {
// Don't start a new read if one is already in progress.
if (_readInProgress) return;
if (_atEnd) {
_closeFile();
return;
}
_readInProgress = true;
int readBytes = _blockSize;
if (_end != null) {
readBytes = min(readBytes, _end - _position);
if (readBytes < 0) {
_readInProgress = false;
if (!_unsubscribed) {
_controller.addError(new RangeError("Bad end position: $_end"));
_closeFile();
_unsubscribed = true;
}
return;
}
}
_openedFile.read(readBytes).then((block) {
_readInProgress = false;
if (_unsubscribed) {
_closeFile();
return;
}
_position += block.length;
if (block.length < readBytes || (_end != null && _position == _end)) {
_atEnd = true;
}
if (!_atEnd && !_controller.isPaused) {
_readBlock();
}
_controller.add(block);
if (_atEnd) {
_closeFile();
}
}).catchError((e, s) {
if (!_unsubscribed) {
_controller.addError(e, s);
_closeFile();
_unsubscribed = true;
}
});
}
void _start() {
if (_position < 0) {
_controller.addError(new RangeError("Bad start position: $_position"));
_controller.close();
_closeCompleter.complete();
return;
}
void onReady(RandomAccessFile file) {
_openedFile = file;
_readInProgress = false;
_readBlock();
}
void onOpenFile(RandomAccessFile file) {
if (_position > 0) {
file.setPosition(_position).then(onReady, onError: (e, s) {
_controller.addError(e, s);
_readInProgress = false;
_closeFile();
});
} else {
onReady(file);
}
}
void openFailed(error, stackTrace) {
_controller.addError(error, stackTrace);
_controller.close();
_closeCompleter.complete();
}
if (_path != null) {
new File(_path)
.open(mode: FileMode.read)
.then(onOpenFile, onError: openFailed);
} else {
try {
onOpenFile(_File._openStdioSync(0));
} catch (e, s) {
openFailed(e, s);
}
}
}
}
class _FileStreamConsumer extends StreamConsumer<List<int>> {
File _file;
Future<RandomAccessFile> _openFuture;
_FileStreamConsumer(this._file, FileMode mode) {
_openFuture = _file.open(mode: mode);
}
_FileStreamConsumer.fromStdio(int fd) {
_openFuture = new Future.value(_File._openStdioSync(fd));
}
Future<File> addStream(Stream<List<int>> stream) {
Completer<File> completer = new Completer<File>.sync();
_openFuture.then((openedFile) {
var _subscription;
void error(e, [StackTrace stackTrace]) {
_subscription.cancel();
openedFile.close();
completer.completeError(e, stackTrace);
}
_subscription = stream.listen((d) {
_subscription.pause();
try {
openedFile
.writeFrom(d, 0, d.length)
.then((_) => _subscription.resume(), onError: error);
} catch (e, stackTrace) {
error(e, stackTrace);
}
}, onDone: () {
completer.complete(_file);
}, onError: error, cancelOnError: true);
}).catchError(completer.completeError);
return completer.future;
}
Future<File> close() =>
_openFuture.then((openedFile) => openedFile.close()).then((_) => _file);
}
// Class for encapsulating the native implementation of files.
class _File extends FileSystemEntity implements File {
String _path;
Uint8List _rawPath;
_File(String path) {
ArgumentError.checkNotNull(path, 'path');
_path = path;
_rawPath = FileSystemEntity._toUtf8Array(path);
}
_File.fromRawPath(Uint8List rawPath) {
ArgumentError.checkNotNull(rawPath, 'rawPath');
_rawPath = FileSystemEntity._toNullTerminatedUtf8Array(rawPath);
_path = FileSystemEntity._toStringFromUtf8Array(rawPath);
}
String get path => _path;
// WARNING:
// Calling this function will increase the reference count on the native
// namespace object. It should only be called to pass the pointer to the
// IOService, which will decrement the reference count when it is finished
// with it.
static int _namespacePointer() => _Namespace._namespacePointer;
static Future _dispatchWithNamespace(int request, List data) {
data[0] = _namespacePointer();
return _IOService._dispatch(request, data);
}
Future<bool> exists() {
return _dispatchWithNamespace(_IOService.fileExists, [null, _rawPath])
.then((response) {
if (_isErrorResponse(response)) {
throw _exceptionFromResponse(response, "Cannot check existence", path);
}
return response;
});
}
external static _exists(_Namespace namespace, Uint8List rawPath);
bool existsSync() {
var result = _exists(_Namespace._namespace, _rawPath);
throwIfError(result, "Cannot check existence of file", path);
return result;
}
File get absolute => new File(_absolutePath);
Future<File> create({bool recursive: false}) {
var result =
recursive ? parent.create(recursive: true) : new Future.value(null);
return result
.then((_) =>
_dispatchWithNamespace(_IOService.fileCreate, [null, _rawPath]))
.then((response) {
if (_isErrorResponse(response)) {
throw _exceptionFromResponse(response, "Cannot create file", path);
}
return this;
});
}
external static _create(_Namespace namespace, Uint8List rawPath);
external static _createLink(
_Namespace namespace, Uint8List rawPath, String target);
external static _linkTarget(_Namespace namespace, Uint8List rawPath);
void createSync({bool recursive: false}) {
if (recursive) {
parent.createSync(recursive: true);
}
var result = _create(_Namespace._namespace, _rawPath);
throwIfError(result, "Cannot create file", path);
}
Future<File> _delete({bool recursive: false}) {
if (recursive) {
return new Directory(path).delete(recursive: true).then((_) => this);
}
return _dispatchWithNamespace(_IOService.fileDelete, [null, _rawPath])
.then((response) {
if (_isErrorResponse(response)) {
throw _exceptionFromResponse(response, "Cannot delete file", path);
}
return this;
});
}
external static _deleteNative(_Namespace namespace, Uint8List rawPath);
external static _deleteLinkNative(_Namespace namespace, Uint8List rawPath);
void _deleteSync({bool recursive: false}) {
if (recursive) {
return new Directory.fromRawPath(_rawPath).deleteSync(recursive: true);
}
var result = _deleteNative(_Namespace._namespace, _rawPath);
throwIfError(result, "Cannot delete file", path);
}
Future<File> rename(String newPath) {
return _dispatchWithNamespace(
_IOService.fileRename, [null, _rawPath, newPath]).then((response) {
if (_isErrorResponse(response)) {
throw _exceptionFromResponse(
response, "Cannot rename file to '$newPath'", path);
}
return new File(newPath);
});
}
external static _rename(
_Namespace namespace, Uint8List oldPath, String newPath);
external static _renameLink(
_Namespace namespace, Uint8List oldPath, String newPath);
File renameSync(String newPath) {
var result = _rename(_Namespace._namespace, _rawPath, newPath);
throwIfError(result, "Cannot rename file to '$newPath'", path);
return new File(newPath);
}
Future<File> copy(String newPath) {
return _dispatchWithNamespace(
_IOService.fileCopy, [null, _rawPath, newPath]).then((response) {
if (_isErrorResponse(response)) {
throw _exceptionFromResponse(
response, "Cannot copy file to '$newPath'", path);
}
return new File(newPath);
});
}
external static _copy(
_Namespace namespace, Uint8List oldPath, String newPath);
File copySync(String newPath) {
var result = _copy(_Namespace._namespace, _rawPath, newPath);
throwIfError(result, "Cannot copy file to '$newPath'", path);
return new File(newPath);
}
Future<RandomAccessFile> open({FileMode mode: FileMode.read}) {
if (mode != FileMode.read &&
mode != FileMode.write &&
mode != FileMode.append &&
mode != FileMode.writeOnly &&
mode != FileMode.writeOnlyAppend) {
return new Future.error(
new ArgumentError('Invalid file mode for this operation'));
}
return _dispatchWithNamespace(
_IOService.fileOpen, [null, _rawPath, mode._mode]).then((response) {
if (_isErrorResponse(response)) {
throw _exceptionFromResponse(response, "Cannot open file", path);
}
return new _RandomAccessFile(response, path);
});
}
Future<int> length() {
return _dispatchWithNamespace(
_IOService.fileLengthFromPath, [null, _rawPath]).then((response) {
if (_isErrorResponse(response)) {
throw _exceptionFromResponse(
response, "Cannot retrieve length of file", path);
}
return response;
});
}
external static _lengthFromPath(_Namespace namespace, Uint8List rawPath);
int lengthSync() {
var result = _lengthFromPath(_Namespace._namespace, _rawPath);
throwIfError(result, "Cannot retrieve length of file", path);
return result;
}
Future<DateTime> lastAccessed() {
return _dispatchWithNamespace(_IOService.fileLastAccessed, [null, _rawPath])
.then((response) {
if (_isErrorResponse(response)) {
throw _exceptionFromResponse(
response, "Cannot retrieve access time", path);
}
return new DateTime.fromMillisecondsSinceEpoch(response);
});
}
external static _lastAccessed(_Namespace namespace, Uint8List rawPath);
DateTime lastAccessedSync() {
var ms = _lastAccessed(_Namespace._namespace, _rawPath);
throwIfError(ms, "Cannot retrieve access time", path);
return new DateTime.fromMillisecondsSinceEpoch(ms);
}
Future setLastAccessed(DateTime time) {
int millis = time.millisecondsSinceEpoch;
return _dispatchWithNamespace(
_IOService.fileSetLastAccessed, [null, _rawPath, millis])
.then((response) {
if (_isErrorResponse(response)) {
throw _exceptionFromResponse(response, "Cannot set access time", path);
}
return null;
});
}
external static _setLastAccessed(
_Namespace namespace, Uint8List rawPath, int millis);
void setLastAccessedSync(DateTime time) {
int millis = time.millisecondsSinceEpoch;
var result = _setLastAccessed(_Namespace._namespace, _rawPath, millis);
if (result is OSError) {
throw new FileSystemException(
"Failed to set file access time", path, result);
}
}
Future<DateTime> lastModified() {
return _dispatchWithNamespace(_IOService.fileLastModified, [null, _rawPath])
.then((response) {
if (_isErrorResponse(response)) {
throw _exceptionFromResponse(
response, "Cannot retrieve modification time", path);
}
return new DateTime.fromMillisecondsSinceEpoch(response);
});
}
external static _lastModified(_Namespace namespace, Uint8List rawPath);
DateTime lastModifiedSync() {
var ms = _lastModified(_Namespace._namespace, _rawPath);
throwIfError(ms, "Cannot retrieve modification time", path);
return new DateTime.fromMillisecondsSinceEpoch(ms);
}
Future setLastModified(DateTime time) {
int millis = time.millisecondsSinceEpoch;
return _dispatchWithNamespace(
_IOService.fileSetLastModified, [null, _rawPath, millis])
.then((response) {
if (_isErrorResponse(response)) {
throw _exceptionFromResponse(
response, "Cannot set modification time", path);
}
return null;
});
}
external static _setLastModified(
_Namespace namespace, Uint8List rawPath, int millis);
void setLastModifiedSync(DateTime time) {
int millis = time.millisecondsSinceEpoch;
var result = _setLastModified(_Namespace._namespace, _rawPath, millis);
if (result is OSError) {
throw new FileSystemException(
"Failed to set file modification time", path, result);
}
}
external static _open(_Namespace namespace, Uint8List rawPath, int mode);
RandomAccessFile openSync({FileMode mode: FileMode.read}) {
if (mode != FileMode.read &&
mode != FileMode.write &&
mode != FileMode.append &&
mode != FileMode.writeOnly &&
mode != FileMode.writeOnlyAppend) {
throw new ArgumentError('Invalid file mode for this operation');
}
var id = _open(_Namespace._namespace, _rawPath, mode._mode);
throwIfError(id, "Cannot open file", path);
return new _RandomAccessFile(id, _path);
}
external static int _openStdio(int fd);
static RandomAccessFile _openStdioSync(int fd) {
var id = _openStdio(fd);
if (id == 0) {
throw new FileSystemException("Cannot open stdio file for: $fd");
}
return new _RandomAccessFile(id, "");
}
Stream<List<int>> openRead([int start, int end]) {
return new _FileStream(path, start, end);
}
IOSink openWrite({FileMode mode: FileMode.write, Encoding encoding: utf8}) {
if (mode != FileMode.write &&
mode != FileMode.append &&
mode != FileMode.writeOnly &&
mode != FileMode.writeOnlyAppend) {
throw new ArgumentError('Invalid file mode for this operation');
}
var consumer = new _FileStreamConsumer(this, mode);
return new IOSink(consumer, encoding: encoding);
}
Future<Uint8List> readAsBytes() {
Future<Uint8List> readDataChunked(RandomAccessFile file) {
var builder = new BytesBuilder(copy: false);
var completer = new Completer<Uint8List>();
void read() {
file.read(_blockSize).then((data) {
if (data.length > 0) {
builder.add(data);
read();
} else {
completer.complete(builder.takeBytes());
}
}, onError: completer.completeError);
}
read();
return completer.future;
}
return open().then((file) {
return file.length().then((length) {
if (length == 0) {
// May be character device, try to read it in chunks.
return readDataChunked(file);
}
return file.read(length);
}).whenComplete(file.close);
});
}
Uint8List readAsBytesSync() {
var opened = openSync();
try {
Uint8List data;
var length = opened.lengthSync();
if (length == 0) {
// May be character device, try to read it in chunks.
var builder = new BytesBuilder(copy: false);
do {
data = opened.readSync(_blockSize);
if (data.length > 0) builder.add(data);
} while (data.length > 0);
data = builder.takeBytes();
} else {
data = opened.readSync(length);
}
return data;
} finally {
opened.closeSync();
}
}
String _tryDecode(List<int> bytes, Encoding encoding) {
try {
return encoding.decode(bytes);
} catch (_) {
throw new FileSystemException(
"Failed to decode data using encoding '${encoding.name}'", path);
}
}
Future<String> readAsString({Encoding encoding: utf8}) {
// TODO(dart:io): If the change in async semantics to run synchronously
// until await lands, this is as efficient as
// return _tryDecode(await readAsBytes(), encoding);
var stack = StackTrace.current;
return readAsBytes().then((bytes) {
try {
return _tryDecode(bytes, encoding);
} catch (e) {
return new Future.error(e, stack);
}
});
}
String readAsStringSync({Encoding encoding: utf8}) =>
_tryDecode(readAsBytesSync(), encoding);
Future<List<String>> readAsLines({Encoding encoding: utf8}) =>
readAsString(encoding: encoding).then(const LineSplitter().convert);
List<String> readAsLinesSync({Encoding encoding: utf8}) =>
const LineSplitter().convert(readAsStringSync(encoding: encoding));
Future<File> writeAsBytes(List<int> bytes,
{FileMode mode: FileMode.write, bool flush: false}) {
return open(mode: mode).then((file) {
return file.writeFrom(bytes, 0, bytes.length).then<File>((_) {
if (flush) return file.flush().then((_) => this);
return this;
}).whenComplete(file.close);
});
}
void writeAsBytesSync(List<int> bytes,
{FileMode mode: FileMode.write, bool flush: false}) {
RandomAccessFile opened = openSync(mode: mode);
try {
opened.writeFromSync(bytes, 0, bytes.length);
if (flush) opened.flushSync();
} finally {
opened.closeSync();
}
}
Future<File> writeAsString(String contents,
{FileMode mode: FileMode.write,
Encoding encoding: utf8,
bool flush: false}) {
try {
return writeAsBytes(encoding.encode(contents), mode: mode, flush: flush);
} catch (e) {
return new Future.error(e);
}
}
void writeAsStringSync(String contents,
{FileMode mode: FileMode.write,
Encoding encoding: utf8,
bool flush: false}) {
writeAsBytesSync(encoding.encode(contents), mode: mode, flush: flush);
}
String toString() => "File: '$path'";
static throwIfError(Object result, String msg, String path) {
if (result is OSError) {
throw new FileSystemException(msg, path, result);
}
}
}
abstract class _RandomAccessFileOps {
external factory _RandomAccessFileOps(int pointer);
int getPointer();
int close();
readByte();
read(int bytes);
readInto(List<int> buffer, int start, int end);
writeByte(int value);
writeFrom(List<int> buffer, int start, int end);
position();
setPosition(int position);
truncate(int length);
length();
flush();
lock(int lock, int start, int end);
}
class _RandomAccessFile implements RandomAccessFile {
static bool _connectedResourceHandler = false;
final String path;
bool _asyncDispatched = false;
SendPort _fileService;
_FileResourceInfo _resourceInfo;
_RandomAccessFileOps _ops;
_RandomAccessFile(int pointer, this.path) {
_ops = new _RandomAccessFileOps(pointer);
_resourceInfo = new _FileResourceInfo(this);
_maybeConnectHandler();
}
void _maybePerformCleanup() {
if (closed) {
_FileResourceInfo.FileClosed(_resourceInfo);
}
}
_maybeConnectHandler() {
if (!_connectedResourceHandler) {
// TODO(ricow): We probably need to set these in some initialization code.
// We need to make sure that these are always available from the
// observatory even if no files (or sockets for the socket ones) are
// open.
registerExtension(
'ext.dart.io.getOpenFiles', _FileResourceInfo.getOpenFiles);
registerExtension(
'ext.dart.io.getFileByID', _FileResourceInfo.getFileInfoMapByID);
_connectedResourceHandler = true;
}
}
Future<void> close() {
return _dispatch(_IOService.fileClose, [null], markClosed: true)
.then((result) {
if (result == -1) {
throw new FileSystemException("Cannot close file", path);
}
closed = closed || (result == 0);
_maybePerformCleanup();
});
}
void closeSync() {
_checkAvailable();
var id = _ops.close();
if (id == -1) {
throw new FileSystemException("Cannot close file", path);
}
closed = closed || (id == 0);
_maybePerformCleanup();
}
Future<int> readByte() {
return _dispatch(_IOService.fileReadByte, [null]).then((response) {
if (_isErrorResponse(response)) {
throw _exceptionFromResponse(response, "readByte failed", path);
}
_resourceInfo.addRead(1);
return response;
});
}
int readByteSync() {
_checkAvailable();
var result = _ops.readByte();
if (result is OSError) {
throw new FileSystemException("readByte failed", path, result);
}
_resourceInfo.addRead(1);
return result;
}
Future<Uint8List> read(int bytes) {
ArgumentError.checkNotNull(bytes, 'bytes');
return _dispatch(_IOService.fileRead, [null, bytes]).then((response) {
if (_isErrorResponse(response)) {
throw _exceptionFromResponse(response, "read failed", path);
}
_resourceInfo.addRead(response[1].length);
Uint8List result = response[1];
return result;
});
}
Uint8List readSync(int bytes) {
_checkAvailable();
ArgumentError.checkNotNull(bytes, 'bytes');
var result = _ops.read(bytes);
if (result is OSError) {
throw new FileSystemException("readSync failed", path, result);
}
_resourceInfo.addRead(result.length);
return result;
}
Future<int> readInto(List<int> buffer, [int start = 0, int end]) {
if ((buffer is! List) ||
((start != null) && (start is! int)) ||
((end != null) && (end is! int))) {
throw new ArgumentError();
}
end = RangeError.checkValidRange(start, end, buffer.length);
if (end == start) {
return new Future.value(0);
}
int length = end - start;
return _dispatch(_IOService.fileReadInto, [null, length]).then((response) {
if (_isErrorResponse(response)) {
throw _exceptionFromResponse(response, "readInto failed", path);
}
int read = response[1];
List<int> data = response[2];
buffer.setRange(start, start + read, data);
_resourceInfo.addRead(read);
return read;
});
}
int readIntoSync(List<int> buffer, [int start = 0, int end]) {
_checkAvailable();
if ((buffer is! List) ||
((start != null) && (start is! int)) ||
((end != null) && (end is! int))) {
throw new ArgumentError();
}
end = RangeError.checkValidRange(start, end, buffer.length);
if (end == start) {
return 0;
}
var result = _ops.readInto(buffer, start, end);
if (result is OSError) {
throw new FileSystemException("readInto failed", path, result);
}
_resourceInfo.addRead(result);
return result;
}
Future<RandomAccessFile> writeByte(int value) {
ArgumentError.checkNotNull(value, 'value');
return _dispatch(_IOService.fileWriteByte, [null, value]).then((response) {
if (_isErrorResponse(response)) {
throw _exceptionFromResponse(response, "writeByte failed", path);
}
_resourceInfo.addWrite(1);
return this;
});
}
int writeByteSync(int value) {
_checkAvailable();
ArgumentError.checkNotNull(value, 'value');
var result = _ops.writeByte(value);
if (result is OSError) {
throw new FileSystemException("writeByte failed", path, result);
}
_resourceInfo.addWrite(1);
return result;
}
Future<RandomAccessFile> writeFrom(List<int> buffer,
[int start = 0, int end]) {
if ((buffer is! List) ||
((start != null) && (start is! int)) ||
((end != null) && (end is! int))) {
throw new ArgumentError("Invalid arguments to writeFrom");
}
end = RangeError.checkValidRange(start, end, buffer.length);
if (end == start) {
return new Future.value(this);
}
_BufferAndStart result;
try {
result = _ensureFastAndSerializableByteData(buffer, start, end);
} catch (e) {
return new Future.error(e);
}
List request = new List(4);
request[0] = null;
request[1] = result.buffer;
request[2] = result.start;
request[3] = end - (start - result.start);
return _dispatch(_IOService.fileWriteFrom, request).then((response) {
if (_isErrorResponse(response)) {
throw _exceptionFromResponse(response, "writeFrom failed", path);
}
_resourceInfo.addWrite(end - (start - result.start));
return this;
});
}
void writeFromSync(List<int> buffer, [int start = 0, int end]) {
_checkAvailable();
if ((buffer is! List) ||
((start != null) && (start is! int)) ||
((end != null) && (end is! int))) {
throw new ArgumentError("Invalid arguments to writeFromSync");
}
end = RangeError.checkValidRange(start, end, buffer.length);
if (end == start) {
return;
}
_BufferAndStart bufferAndStart =
_ensureFastAndSerializableByteData(buffer, start, end);
var result = _ops.writeFrom(bufferAndStart.buffer, bufferAndStart.start,
end - (start - bufferAndStart.start));
if (result is OSError) {
throw new FileSystemException("writeFrom failed", path, result);
}
_resourceInfo.addWrite(end - (start - bufferAndStart.start));
}
Future<RandomAccessFile> writeString(String string,
{Encoding encoding: utf8}) {
ArgumentError.checkNotNull(encoding, 'encoding');
var data = encoding.encode(string);
return writeFrom(data, 0, data.length);
}
void writeStringSync(String string, {Encoding encoding: utf8}) {
ArgumentError.checkNotNull(encoding, 'encoding');
var data = encoding.encode(string);
writeFromSync(data, 0, data.length);
}
Future<int> position() {
return _dispatch(_IOService.filePosition, [null]).then((response) {
if (_isErrorResponse(response)) {
throw _exceptionFromResponse(response, "position failed", path);
}
return response;
});
}
int positionSync() {
_checkAvailable();
var result = _ops.position();
if (result is OSError) {
throw new FileSystemException("position failed", path, result);
}
return result;
}
Future<RandomAccessFile> setPosition(int position) {
return _dispatch(_IOService.fileSetPosition, [null, position])
.then((response) {
if (_isErrorResponse(response)) {
throw _exceptionFromResponse(response, "setPosition failed", path);
}
return this;
});
}
void setPositionSync(int position) {
_checkAvailable();
var result = _ops.setPosition(position);
if (result is OSError) {
throw new FileSystemException("setPosition failed", path, result);
}
}
Future<RandomAccessFile> truncate(int length) {
return _dispatch(_IOService.fileTruncate, [null, length]).then((response) {
if (_isErrorResponse(response)) {
throw _exceptionFromResponse(response, "truncate failed", path);
}
return this;
});
}
void truncateSync(int length) {
_checkAvailable();
var result = _ops.truncate(length);
if (result is OSError) {
throw new FileSystemException("truncate failed", path, result);
}
}
Future<int> length() {
return _dispatch(_IOService.fileLength, [null]).then((response) {
if (_isErrorResponse(response)) {
throw _exceptionFromResponse(response, "length failed", path);
}
return response;
});
}
int lengthSync() {
_checkAvailable();
var result = _ops.length();
if (result is OSError) {
throw new FileSystemException("length failed", path, result);
}
return result;
}
Future<RandomAccessFile> flush() {
return _dispatch(_IOService.fileFlush, [null]).then((response) {
if (_isErrorResponse(response)) {
throw _exceptionFromResponse(response, "flush failed", path);
}
return this;
});
}
void flushSync() {
_checkAvailable();
var result = _ops.flush();
if (result is OSError) {
throw new FileSystemException("flush failed", path, result);
}
}
static const int lockUnlock = 0;
// static const int lockShared = 1;
// static const int lockExclusive = 2;
// static const int lockBlockingShared = 3;
// static const int lockBlockingExclusive = 4;
int _fileLockValue(FileLock fl) => fl._type;
Future<RandomAccessFile> lock(
[FileLock mode = FileLock.exclusive, int start = 0, int end = -1]) {
if ((mode is! FileLock) || (start is! int) || (end is! int)) {
throw new ArgumentError();
}
if ((start < 0) || (end < -1) || ((end != -1) && (start >= end))) {
throw new ArgumentError();
}