toBytes method

(BuBytes, FloatLength) toBytes(
  1. FloatLength? decodFloatType, {
  2. Endian? endianness,
  3. bool allowFloat16 = true,
})

Encodes value into bytes using decodFloatType, or (if null) the smallest format it fits without loss. Returns the encoded bytes together with the format actually used.

allowFloat16: when picking the format automatically (i.e. decodFloatType is null), whether float16 is allowed as that choice.

Throws CborException if decodFloatType is explicitly given as float16 or float32 but value doesn't fit that format exactly.

Implementation

(BuBytes, FloatLength) toBytes(
  FloatLength? decodFloatType, {
  Endian? endianness,
  bool allowFloat16 = true,
}) {
  if (decodFloatType == null) {
    if (allowFloat16 && isLessThan16) {
      return (_encodeFloat16(endianness), FloatLength.bytes16);
    } else if (isLessThan32) {
      return (_encodeFloat32(endianness), FloatLength.bytes32);
    }
    return (_encodeFloat64(endianness), FloatLength.bytes64);
  }
  final BuBytes bytes;
  switch (decodFloatType) {
    case FloatLength.bytes16:
      if (!isLessThan16) {
        throw BuError(
          DefaultErrorType.badCbor,
          "Float value is larger than float16.",
        );
      }
      bytes = _encodeFloat16(endianness);
      break;
    case FloatLength.bytes32:
      if (!isLessThan32) {
        throw BuError(
          DefaultErrorType.badCbor,
          "Float value is larger than float32.",
        );
      }
      bytes = _encodeFloat32(endianness);
      break;
    case FloatLength.bytes64:
      bytes = _encodeFloat64(endianness);
      break;
  }
  return (bytes, decodFloatType);
}