Byte array representation in Dart 2

1,818 views
Skip to first unread message

Denis Portnov

unread,
Jun 11, 2018, 7:34:25 PM6/11/18
to Dart Misc
Hi all, 

What is idiomatic way in Dart 2 for representing byte array? What type to use?

I see that io, convert, crypto etc. all require or produce byte arrays as List<int>
It's not very convenient for library author as it requires either to check/truncate individual ints from List, or use Uint8List.fromList() everywhere.


So let's say I'm doing library for IP address, UUID, hash, or any structure with underlying byte array. 

Is it fine to have this


  class
IPAddress {
    IPAddress.fromBytes(Uint8List bytes) {}
 
    Uint8List get bytes;
  }

  class SomeBinaryEncoder extends Converter<Uint8List, Uint8List> {

    
Uint8List convert(Uint8List input) {}
 
  }


Thanks
Denis

Florian Loitsch

unread,
Jun 12, 2018, 5:22:47 AM6/12/18
to mi...@dartlang.org
Yes.
It's perfectly fine to stick to Uint8Lists if that's what you use internally, and if you expect most users of your API to be comfortable with it.
dart:io, ... would probably now switch to explicit `Uint8List` as well.

Alternatively, you can take `List<int>` and create a function `ensureUint8List` that does an `is` check and only converts the list if it isn't already one.

--
For more ways to connect visit https://www.dartlang.org/community
---
You received this message because you are subscribed to the Google Groups "Dart Misc" group.
To unsubscribe from this group and stop receiving emails from it, send an email to misc+uns...@dartlang.org.
To view this discussion on the web visit https://groups.google.com/a/dartlang.org/d/msgid/misc/478c312b-8066-4e22-9bc3-9ed524e5016b%40dartlang.org.

Istvan Soos

unread,
Jun 12, 2018, 6:16:31 AM6/12/18
to General Dart Discussion, deni...@gmail.com
Both should work in most cases just fine, however I have a slight
preference on the least restrictive inputs. E.g. when a method expects
bytes as input, I'd prefer to have it as List<int>, but when it
returns these values, it is could be nicer if it returns them as
Uint8List, if/when the implementation will use that anyway.

As Florian suggested, you can easily convert it to Uint8List
internally if that is important for the implementation logic.

Also, for some byte-concatenation tasks, CombinedListView from
package:collection can be useful.

Cheers,
Istvan

Denis Portnov

unread,
Jun 12, 2018, 10:04:49 PM6/12/18
to mi...@dartlang.org
Florian, Istvan, Than your for your comments. 
Btw, is that the right assumption that on  VM/dart-js level typed_data collections are more optimal in terms of processing compared to List<int>?
Thanks
Denis
Reply all
Reply to author
Forward
0 new messages