// Copyright (c) 2026, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'dart:_internal' show patch;
import 'dart:convert' show Encoding, utf8, latin1, ascii;

@patch
class _Uri {
  @patch
  static String _uriEncode(
    int canonicalMask,
    String text,
    Encoding encoding,
    bool spaceToPlus,
  ) {
    // First check if the text will be changed by encoding.
    int i = 0;
    if (identical(encoding, utf8) ||
        identical(encoding, latin1) ||
        identical(encoding, ascii)) {
      // Encoding is compatible with the original string.
      // Find first character that needs encoding.
      for (; i < text.length; i++) {
        var char = text.codeUnitAt(i);
        if (char >= 128 || _charTables.codeUnitAt(char) & canonicalMask == 0) {
          break;
        }
      }
    }
    if (i == text.length) return text;

    // Encode the string into bytes then generate an ASCII only string
    // by percent encoding selected bytes.
    StringBuffer result = StringBuffer();
    for (int j = 0; j < i; j++) {
      result.writeCharCode(text.codeUnitAt(j));
    }

    // TODO(lrn): Is there a way to only encode from index i and forwards.
    var bytes = encoding.encode(text);
    for (; i < bytes.length; i++) {
      int byte = bytes[i];
      if (byte < 128 && ((_charTables.codeUnitAt(byte) & canonicalMask) != 0)) {
        result.writeCharCode(byte);
      } else if (spaceToPlus && byte == _SPACE) {
        result.writeCharCode(_PLUS);
      } else {
        const String hexDigits = '0123456789ABCDEF';
        result
          ..writeCharCode(_PERCENT)
          ..writeCharCode(hexDigits.codeUnitAt(byte >> 4))
          ..writeCharCode(hexDigits.codeUnitAt(byte & 0x0f));
      }
    }
    return result.toString();
  }

  @patch
  static String _makeQueryFromParameters(
    Map<String, dynamic /*String?|Iterable<String>*/> queryParameters,
  ) {
    return _makeQueryFromParametersDefault(queryParameters);
  }
}
