Florian Levis
05/30/2024, 4:01 PMFilipp Zhinkin
05/31/2024, 7:41 AMval source: Source = ...
val buffer = Buffer()
source.transferTo(buffer) // that will consume the source
println(buffer.size)
Florian Levis
05/31/2024, 9:12 AMFilipp Zhinkin
05/31/2024, 9:36 AMhow does the C# do?By providing an interface whose implementations would, in general, throw
NotSupportedException
on an attempt to get the length 🙂
Not every source can have a length. It's easy to find it for in-memory buffers and regular files, but for sources like network streams there's not such a property.
The intended way of transforming incoming data in kotlinx-io is by wrapping one source into another. Once it's done, even if the underlying source was a file, it's no longer possible to guess the length.
As an example, consider reading a gzipped file. To do so, one may open a file source and wrap it into gzip-decoding-source. The file source definitely has a length (assuming that's a regular file), but there's no way to find decompressed data length until it's read in full.
C# folks decided to throw an exception when the length could not be retrieved, for Okio and kotlinx-io the decision was to abstain from providing such a property.
If you're working with files, the length could be checked by calling FileSystem::metadaOrNull(path)?.size
[kdoc]. And for in memory sources, a.k.a. Buffers, the size property is already there.Florian Levis
05/31/2024, 10:01 AM