Skip to content

Instantly share code, notes, and snippets.

@sassman
Last active November 29, 2022 19:58
Show Gist options
  • Save sassman/db1841614f0b7f5f9efdf6be7aad3e77 to your computer and use it in GitHub Desktop.
Save sassman/db1841614f0b7f5f9efdf6be7aad3e77 to your computer and use it in GitHub Desktop.
Dart IO and Streams the right way
library io_testing;
import 'dart:async';
import 'dart:io';
import 'dart:convert';
class UpperCaseConverter extends Converter<String, String> {
@override
String convert(String input) => input.toUpperCase();
@override
Sink<String> startChunkedConversion(Sink<String> sink) {
return StringEventConverterSink(sink, this);
}
}
class StringEventConverterSink extends StringConversionSinkBase {
EventSink<String> innerSink;
Converter<String, String> converter;
StringEventConverterSink(Sink<String> sink, Converter<String, String> converter) {
this.innerSink = sink;
this.converter = converter;
}
@override
void addSlice(String str, int start, int end, bool isLast) {
innerSink.add(converter.convert(str));
}
@override
void close() {
innerSink.close();
}
}
Future main() async {
var config = File(Platform.script.toFilePath());
Stream<List<int>> inputStream = config.openRead();
var lines = inputStream
.transform(utf8.decoder)
.transform(LineSplitter())
.transform(UpperCaseConverter());
try {
await for (var line in lines) {
print('Got ${line.length} characters from stream');
print(line);
}
print('file is now closed');
} catch (e) {
print(e);
}
}
library io_expedition;
import 'dart:async';
import 'dart:io';
import 'dart:convert';
class StringConverter extends Converter<String, String> {
String Function(String x) convertFunction;
StringConverter(this.convertFunction);
@override
String convert(String input) => convertFunction(input);
@override
Sink<String> startChunkedConversion(Sink<String> sink) => StringEventConverterSink(sink, this);
}
class UpperCaseConverter extends Converter<String, String> {
@override
String convert(String input) => input.toUpperCase();
@override
Sink<String> startChunkedConversion(Sink<String> sink) => StringEventConverterSink(sink, this);
}
class StringEventConverterSink extends StringConversionSinkBase {
EventSink<String> innerSink;
Converter<String, String> converter;
StringEventConverterSink(this.innerSink, this.converter);
@override
void addSlice(String str, int start, int end, bool isLast) => innerSink.add(converter.convert(str));
@override
void close() => innerSink.close();
}
Future main() async {
var config = File(Platform.script.toFilePath());
Stream<List<int>> inputStream = config.openRead();
var lines = inputStream
.transform(utf8.decoder)
.transform(LineSplitter())
.transform(StringConverter((String x) => x.toUpperCase()));
try {
await for (var line in lines) {
print('Got ${line.length} characters from stream');
print(line);
}
print('file is now closed');
} catch (e) {
print(e);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment