Created
July 19, 2023 12:10
-
-
Save osa1/ceb8cf290a009ee2ba8aacf8146893c6 to your computer and use it in GitHub Desktop.
Strange Dart 10
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:typed_data'; | |
void main() { | |
final Int32List list = Int32List.fromList([1, 2, 3, 4, 5, 6]); | |
// Create a view, list without the first and last elements. | |
final Int32List view = Int32List.sublistView(list, 1, 5); | |
print(view); // [2, 3, 4, 5, 6] | |
// Do the same, this time using the `ByteBuffer` object. | |
final Int32List viewView = view.buffer.asInt32List( | |
1 * Int32List.bytesPerElement, // skip one element (offset in bytes) | |
3 // include 3 elements | |
); | |
print(viewView); // Guess the output... | |
final Int32List viewViewCorrect = Int32List.sublistView(view, 1, 3); | |
print(viewViewCorrect); // [3, 4], as expected | |
// This behavior also allows you to get a larger list from a smaller list! | |
print(viewViewCorrect.buffer.asInt32List(0, 6)); // prints the original list | |
// In general, `ByteBuffer` type should be avoided. When you need views use | |
// `sublistView` factories. | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment