acceptedQuality function

double acceptedQuality(
  1. String header,
  2. String coding
)

The q of coding (lower case) in the Accept-Encoding value header: 0 when the client does not accept it. A coding that is not in the list gets the q of *, or 0 with no * (RFC 9110).

Implementation

double acceptedQuality(String header, String coding) {
  double? any;
  for (String part in header.split(',')) {
    List<String> fields = part.split(';');
    String name = fields.first.trim().toLowerCase();

    /// `x-gzip` is the same coding as `gzip` (RFC 9110)
    if (name == 'x-gzip') name = 'gzip';
    if (name != coding && name != '*') continue;
    double q = 1;
    for (int i = 1; i < fields.length; i++) {
      String field = fields[i].trim().toLowerCase();
      if (field.startsWith('q=')) {
        /// a `q` that is not a number from 0 to 1 means "not accepted"
        double? given = double.tryParse(field.substring(2).trim());
        q = given != null && given >= 0 && given <= 1 ? given : 0;
      }
    }
    if (name == coding) return q;
    any = q;
  }
  return any ?? 0;
}