Support adapting a C# MemoryStream as a Dafny.Sequence #2067
Labels
area: performance
Performance issues
kind: enhancement
Enhancements, feature requests, etc. These are NOT bugs, but ways we can improve Dafny
lang: c#
Dafny's C# transpiler and its runtime
part: runtime
Happens in Dafny's runtime (Add a `lang` tag if relevant)
priority: not yet
Will reconsider working on this when we're looking for work
This would be similar to the existing optimization in the Java runtime to allow adapting a
java.lang.String
as aDafnySequence
using theStringDafnySequence
adaptor class. In both cases the motivation is similar: avoiding having to copy values when they cross the FFI between native target language code and cross-compiled Dafny code.This would selectively introduce a soundness risk, and to a greater degree than wrapping a string.
MemoryStream
exposes aCanWrite
property, which if false means that it is not possible to mutate the underlying data through theMemoryStream
API. However, you can create a newMemoryStream
that wraps (a range of) an arbitrarybyte[]
value, which is intentionally not copied in the constructor. That means it will be possible to accidentally mutate a sequence's data, which obviously breaks the semantics of Dafny and leads to undefined behavior. Wrapping ajava.lang.String
is substantially safer, as that datatype DOES copy values on construction and does not mutate or expose its underlyingbyte[]
.Also note that as per the name,
MemoryStream
is designed to be more of a "sequential stream backed by a byte array" rather than a "random-access sequence of bytes". It is possible to read a single byte at an arbitrary index in O(n) time, but the constant factor will be higher than ideal, and the code will not be thread-safe unless we apply additional synchronization, as it will look something like the snippet below. This could be avoided by requiring that the wrapped stream also supportsGetBuffer()
, which exposes the internal array, but that would be an even bigger soundness risk.It will be worth considering supporting more sequential access of sequences in Dafny itself, so that we can leverage the more efficient access patterns abstractions like
MemoryStream
(or its supertypeStream
for that matter). dafny-lang/libraries#37 and dafny-lang/rfcs#9 both aim to progress towards supporting implementations of sequences that do not necessarily support efficient random access.The text was updated successfully, but these errors were encountered: